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: let modules say what their values mean and look like
rpone191cfa1967e5
diff --git a/.gitignore b/.gitignoreindex d2ca30d7..49823f17 100644--- a/.gitignore+++ b/.gitignore@@ -14,3 +14,6 @@ services/whisperx/src/*.egg-info/services/image-opencv/.venv/services/image-opencv/**/__pycache__/services/media-lambda/build/++# macOS Finder metadata+.DS_Storediff --git a/packages/broll/src/author.ts b/packages/broll/src/author.tsindex e8ed4aef..07e67ef3 100644--- a/packages/broll/src/author.ts+++ b/packages/broll/src/author.ts@@ -27,6 +27,29 @@ export function sealBrollItemSpec(value: BrollItemSpec): BrollItemSpec {return canonicalize(value) as unknown as BrollItemSpec;}+/**+ * One inset card, for anything that must place B-roll before an author has+ * styled it.+ *+ * A spec and not an Item: media is the caller's, and a package that shipped a+ * default clip would be answering a question nobody asked it. Everything a+ * package can honestly decide — where the card sits, how it is cropped, how it+ * arrives and leaves — is decided here, once.+ */+export function defaultBrollItemSpec(id = "broll-item"): BrollItemSpec {+ return sealBrollItemSpec({+ contract: "svml.broll-item-spec@1",+ id,+ z: 40,+ box: { xPercent: 8, yPercent: 20, widthPercent: 84, heightPercent: 48 },+ fit: "contain",+ backgroundColor: "#111116",+ borderRadiusPx: 28,+ enter: { operator: "slide-up", durationFrames: 8 },+ exit: { operator: "fade", durationFrames: 6 },+ });+}+export function assertBrollItemSpec(value: BrollItemSpec): void {assert(value.contract === "svml.broll-item-spec@1" && value.id.length > 0, "BrollItemSpec identity is invalid");assert(Number.isSafeInteger(value.z), "BrollItemSpec z must be an integer");diff --git a/packages/broll/src/index.ts b/packages/broll/src/index.tsindex 4a24edf3..2a809aa0 100644--- a/packages/broll/src/index.ts+++ b/packages/broll/src/index.ts@@ -19,9 +19,19 @@ export {createBrollSetImplementationDigest,finalizeBrollProgram,finalizeBrollProgramImplementationDigest,+ defaultBrollItemSpec,sealBrollItemSpec,sealBrollTrackSpec,} from "./author.js";+export {+ assertBrollAppearanceRecipe,+ brollAppearanceFromRecipe,+ brollAppearanceRecipeKeys,+ brollItemSpecFromRecipe,+ brollRecipeMotion,+ defaultBrollAppearanceRecipe,+} from "./recipe.js";+export type { BrollAppearance } from "./recipe.js";export {brollManifest,brollManifestDigest,diff --git a/packages/broll/src/manifest.ts b/packages/broll/src/manifest.tsindex 617aa4f4..1c7b66d1 100644--- a/packages/broll/src/manifest.ts+++ b/packages/broll/src/manifest.ts@@ -13,6 +13,7 @@ import { svsManifest, svsModuleRef } from "@narratage/svs";import {appendBrollItemImplementationDigest,createBrollSetImplementationDigest,+ defaultBrollItemSpec,finalizeBrollProgramImplementationDigest,} from "./author.js";@@ -40,6 +41,7 @@ export const brollProducers = {} satisfies Record<string, ProducerRef>;const string = { kind: "string", minLength: 1 } as const;+const color = { kind: "string", minLength: 1, format: "color" } as const;const number = { kind: "number" } as const;const unsignedInteger = { kind: "number", integer: true, minimum: 0 } as const;const signedInteger = { kind: "number", integer: true } as const;@@ -77,7 +79,7 @@ const item = object({audioGain: { schema: number, optional: true },enter: { schema: motion, optional: true },exit: { schema: motion, optional: true },- backgroundColor: { schema: string, optional: true },+ backgroundColor: { schema: color, optional: true },borderRadiusPx: { schema: number, optional: true },});const itemSpec = object({@@ -86,7 +88,7 @@ const itemSpec = object({z: { schema: signedInteger },box: { schema: box },fit: { schema: { kind: "string", enum: ["contain", "cover"] } },- backgroundColor: { schema: string, optional: true },+ backgroundColor: { schema: color, optional: true },borderRadiusPx: { schema: number, optional: true },enter: { schema: motion, optional: true },exit: { schema: motion, optional: true },@@ -147,7 +149,10 @@ export const brollManifest: ModuleManifest = {{ name: brollTypes.program.name, schema: brollProgramSchema },{ name: brollTypes.product.name, schema: brollProductSchema },{ name: brollTypes.trackSpec.name, schema: brollTrackSpecSchema },- { name: brollTypes.itemSpec.name, schema: brollItemSpecSchema },+ // BrollProgram has no default: an Item carries a content-addressed+ // Artifact, and this module has no bytes to point at. The appearance it can+ // honestly decide is declared on the item spec instead.+ { name: brollTypes.itemSpec.name, schema: brollItemSpecSchema, default: defaultBrollItemSpec() },{ name: brollTypes.set.name, schema: brollSetSchema },],capabilities: [],diff --git a/packages/broll/src/recipe.ts b/packages/broll/src/recipe.tsnew file mode 100644index 00000000..98568c33--- /dev/null+++ b/packages/broll/src/recipe.ts@@ -0,0 +1,96 @@+import type { SvsRecipe } from "@narratage/svs";++import type { BrollBox, BrollItemSpec, BrollMotion } from "./types.js";++/**+ * The B-roll appearance Recipe: what a stylesheet may say about an inset.+ *+ * Held apart from the Surface handler so a stylesheet reads the same whoever is+ * reading it. Media and timing come from the graph; this is only the look.+ */++export type BrollAppearance = {+ readonly z: number;+ readonly box: BrollBox;+ readonly fit: "contain" | "cover";+ readonly backgroundColor: string;+ readonly borderRadiusPx: number;+ readonly enter: BrollMotion;+ readonly exit: BrollMotion;+};++/** One inset card. Its keys are the Recipe's required property set. */+export const defaultBrollAppearanceRecipe: Readonly<Record<string, string | number>> = {+ background: "#111116",+ enter: "slide-up 8f",+ exit: "fade 6f",+ fit: "contain",+ height: 0.48,+ radius: 28,+ "stack-order": 40,+ width: 0.84,+ x: 0.08,+ y: 0.2,+};++export const brollAppearanceRecipeKeys: readonly string[] =+ Object.keys(defaultBrollAppearanceRecipe);++function number(properties: SvsRecipe["properties"], name: string): number {+ const property = properties[name];+ if (typeof property !== "number" || !Number.isFinite(property)) {+ throw new Error(`B-roll Recipe ${name} must be a number`);+ }+ return property;+}++function string(properties: SvsRecipe["properties"], name: string): string {+ const property = properties[name];+ if (typeof property !== "string" || !property.trim()) {+ throw new Error(`B-roll Recipe ${name} must be a string`);+ }+ return property.trim();+}++/** SVS writes motion as `<operator> <frames>f`, e.g. `slide-up 8f`. */+export function brollRecipeMotion(value: string): BrollMotion {+ const found = /^(fade|pop|slide-up|slide-down)\s+([1-9][0-9]*)f$/u.exec(value.trim());+ if (found === null) throw new Error(`B-roll motion ${value} is invalid`);+ return { operator: found[1] as BrollMotion["operator"], durationFrames: Number(found[2]) };+}++export function assertBrollAppearanceRecipe(properties: SvsRecipe["properties"]): void {+ const actual = Object.keys(properties).sort().join(" ");+ const expected = [...brollAppearanceRecipeKeys].sort().join(" ");+ if (actual !== expected) {+ throw new Error(`B-roll Recipe requires exactly ${[...brollAppearanceRecipeKeys].sort().join(", ")}`);+ }+}++export function brollAppearanceFromRecipe(properties: SvsRecipe["properties"]): BrollAppearance {+ assertBrollAppearanceRecipe(properties);+ const fit = string(properties, "fit");+ if (fit !== "contain" && fit !== "cover") throw new Error("B-roll Recipe fit is invalid");+ return {+ z: number(properties, "stack-order"),+ box: {+ xPercent: number(properties, "x") * 100,+ yPercent: number(properties, "y") * 100,+ widthPercent: number(properties, "width") * 100,+ heightPercent: number(properties, "height") * 100,+ },+ fit,+ backgroundColor: string(properties, "background"),+ borderRadiusPx: number(properties, "radius"),+ enter: brollRecipeMotion(string(properties, "enter")),+ exit: brollRecipeMotion(string(properties, "exit")),+ };+}++/** The appearance a Recipe describes, as the spec an Item is built from. */+export function brollItemSpecFromRecipe(+ id: string,+ properties: SvsRecipe["properties"],+): BrollItemSpec {+ return { contract: "svml.broll-item-spec@1", id, ...brollAppearanceFromRecipe(properties) };+}diff --git a/packages/broll/src/surface.ts b/packages/broll/src/surface.tsindex f9007cac..4ee4ce6a 100644--- a/packages/broll/src/surface.ts+++ b/packages/broll/src/surface.ts@@ -17,6 +17,7 @@ import type { StructuredElement, StructuredSurfaceHandler, SurfaceResolvedRefereimport { sealBrollItemSpec, sealBrollTrackSpec } from "./author.js";import { brollProducers, brollTypes } from "./manifest.js";+import { brollItemSpecFromRecipe } from "./recipe.js";import type { BrollMotion, BrollSurfaceItemInput } from "./types.js";const input = (name: string) => ({ kind: "fragment-input" as const, name });@@ -127,21 +128,13 @@ export const decodeBrollTrackSurface: StructuredSurfaceHandler = ({ element, resconst source = ref(child, "source", artifactTypes.blob, resolveReference);const selection = ref(child, "during", narrativeTypes.selection, resolveReference);const appearance = recipe(ref(child, "appearance", svsRecipeType, resolveReference));- const expected = ["background", "enter", "exit", "fit", "height", "radius", "stack-order", "width", "x", "y"];- if (Object.keys(appearance.properties).sort().join("\0") !== expected.sort().join("\0")) throw new Error(`B-roll Recipe requires exactly ${expected.join(", ")}`);- const fit = str(appearance, "fit");- if (fit !== "contain" && fit !== "cover") throw new Error("B-roll Recipe fit is invalid");const suffix = String(itemIndex).padStart(4, "0");const specId = `${id}.item.${suffix}.spec`;records.push({id: specId, type: brollTypes.itemSpec,- value: { kind: "inline", value: sealBrollItemSpec({- contract: "svml.broll-item-spec@1", id: `${id}.item.${suffix}`, z: num(appearance, "stack-order"),- box: { xPercent: num(appearance, "x") * 100, yPercent: num(appearance, "y") * 100,- widthPercent: num(appearance, "width") * 100, heightPercent: num(appearance, "height") * 100 },- fit, backgroundColor: str(appearance, "background"), borderRadiusPx: num(appearance, "radius"),- enter: motion(str(appearance, "enter")), exit: motion(str(appearance, "exit")),- }) }, range: child.range,+ value: { kind: "inline", value: sealBrollItemSpec(+ brollItemSpecFromRecipe(`${id}.item.${suffix}`, appearance.properties),+ ) }, range: child.range,});return [{ suffix, source, selection, specId, range: child.range,input: { mediaName: `item-${suffix}-media`, selectionName: `item-${suffix}-selection`, specName: `item-${suffix}-spec` } }];diff --git a/packages/caption/src/index.ts b/packages/caption/src/index.tsindex 38cbdc7c..9aa6b86a 100644--- a/packages/caption/src/index.ts+++ b/packages/caption/src/index.ts@@ -1,4 +1,12 @@export { CaptionProjectionError } from "./error.js";+export {+ assertCaptionAppearanceRecipe,+ captionAppearanceFromRecipe,+ captionAppearanceRecipeKeys,+ captionRecipePadding,+ defaultCaptionAppearanceRecipe,+} from "./recipe.js";+export type { CaptionAppearance } from "./recipe.js";export { captionDisplayAtoms, displayAtomMatchesSelection, displayTextForAtoms } from "./display.js";export { captionComponent } from "./component.js";export { captionTrackSurfaceFragment, plannedCaptionTrackSurfaceFragment } from "./fragment.js";@@ -40,6 +48,7 @@ export {assertCaptionTrackProgram,assertTimedCaptionProjection,defaultCaptionTrackProgram,+ defaultTimedCaptionProjection,renderCaptionTrack,renderCaptionProgram,renderCaptionTrackImplementationDigest,diff --git a/packages/caption/src/manifest.ts b/packages/caption/src/manifest.tsindex 70597b66..97ce2584 100644--- a/packages/caption/src/manifest.ts+++ b/packages/caption/src/manifest.ts@@ -7,6 +7,8 @@ import { digestOf } from "@narratage/protocol";import type { ModuleManifest, ProducerRef, TypeRef, ValueSchema } from "@narratage/protocol";import {+ defaultCaptionTrackProgram,+ defaultTimedCaptionProjection,renderCaptionProgramImplementationDigest,renderCaptionTrackImplementationDigest,} from "./track.js";@@ -41,6 +43,7 @@ export const captionProgramSurfaceImplementationDigest = digestOf("@narratage/caconst string = { kind: "string", minLength: 1 } as const;const number = { kind: "number", minimum: 0 } as const;const integer = { kind: "number", integer: true, minimum: 0 } as const;+const seconds = { kind: "number", minimum: 0, format: "duration" } as const;const object = (fields: Readonly<Record<string, { readonly schema: ValueSchema; readonly optional?: boolean }>>,): ValueSchema => ({ kind: "object", fields });@@ -59,12 +62,12 @@ const timedCaptionRegion = object({id: { schema: string },runId: { schema: string, optional: true },styleId: { schema: string, optional: true },- display: { schema: { kind: "string" } },+ display: { schema: { kind: "string", format: "multiline" } },segmentId: { schema: string },kind: { schema: { kind: "string", enum: ["identity", "alias", "hidden"] } },sourceTokenIds: { schema: { kind: "array", items: string } },- startSec: { schema: number },- endSec: { schema: number },+ startSec: { schema: seconds },+ endSec: { schema: seconds },refinements: { schema: { kind: "array", items: timedCaptionRefinement } },fields: { schema: { kind: "array", items: object({declarationId: { schema: string },@@ -93,24 +96,28 @@ export const captionPlanSchema: ValueSchema = object({});export const timedCaptionProjectionSchema: ValueSchema = object({contract: { schema: { kind: "literal", value: "svml.timed-caption-projection@1" } },- text: { schema: { kind: "string" } },+ text: { schema: { kind: "string", format: "multiline" } },regions: { schema: { kind: "array", items: timedCaptionRegion } },});+const color = { kind: "string", minLength: 1, format: "color" } as const;+/** Percent of a canvas dimension. Not a unit fraction: these run 0 to 100. */+const percent = { kind: "number", minimum: 0, maximum: 100 } as const;+const captionTrackStyleSchema = object({fontFamily: { schema: string },fontSizePx: { schema: number },fontWeight: { schema: number },- color: { schema: string },- backgroundColor: { schema: string, optional: true },+ color: { schema: color },+ backgroundColor: { schema: color, optional: true },paddingXPx: { schema: number },paddingYPx: { schema: number },borderRadiusPx: { schema: number },- bottomPercent: { schema: number },- maxWidthPercent: { schema: number },- leftPercent: { schema: number, optional: true },- topPercent: { schema: number, optional: true },- widthPercent: { schema: number, optional: true },+ bottomPercent: { schema: percent },+ maxWidthPercent: { schema: percent },+ leftPercent: { schema: percent, optional: true },+ topPercent: { schema: percent, optional: true },+ widthPercent: { schema: percent, optional: true },lineHeight: { schema: number, optional: true },textAlign: { schema: { kind: "string", enum: ["left", "center", "right"] } },});@@ -217,6 +224,7 @@ export const captionManifest: ModuleManifest = {{name: captionTypes.timedProjection.name,schema: timedCaptionProjectionSchema,+ default: defaultTimedCaptionProjection(),validator: {abi: "svml.type-validator@1",implementation: {@@ -229,6 +237,7 @@ export const captionManifest: ModuleManifest = {{name: captionTypes.trackProgram.name,schema: captionTrackProgramSchema,+ default: defaultCaptionTrackProgram(),validator: {abi: "svml.type-validator@1",implementation: {diff --git a/packages/caption/src/recipe.ts b/packages/caption/src/recipe.tsnew file mode 100644index 00000000..8d9da0b8Binary files /dev/null and b/packages/caption/src/recipe.ts differdiff --git a/packages/caption/src/surface.ts b/packages/caption/src/surface.tsindex 6c65d3c3..9de685db 100644--- a/packages/caption/src/surface.ts+++ b/packages/caption/src/surface.ts@@ -13,6 +13,7 @@ import type {import { captionTrackSurfaceFragment, plannedCaptionTrackSurfaceFragment } from "./fragment.js";import { captionTypes } from "./manifest.js";+import { captionAppearanceFromRecipe } from "./recipe.js";import { sealCaptionTrackProgram } from "./track.js";import { resolveCaptionProgram, sealCaptionStyle } from "./style.js";import type { CaptionStyleApplication } from "./style.js";@@ -147,35 +148,9 @@ function fieldValue(element: StructuredElement): CaptionFieldValueSchema {throw new Error(`${element.name}.type must be boolean, enum or number`);}+/** Element attributes are this handler's; the Recipe belongs to ./recipe.ts. */function captionAppearance(element: StructuredElement, value: SvsRecipe) {- const expected = ["align", "background", "fill", "font", "line-height", "padding", "radius", "size", "stack-order", "weight", "width", "x", "y"];- if (Object.keys(value.properties).sort().join("\u0000") !== expected.sort().join("\u0000")) {- throw new Error(`Caption Recipe requires exactly ${expected.join(", ")}`);- }- const align = string(value, "align");- if (align !== "left" && align !== "center" && align !== "right") throw new Error("Caption Recipe align is invalid");- const pad = padding(string(value, "padding"));- return {- mode: mode(element),- stackingOrder: integer(value, "stack-order"),- style: {- fontFamily: string(value, "font"),- fontSizePx: number(value, "size"),- fontWeight: integer(value, "weight"),- color: string(value, "fill"),- backgroundColor: string(value, "background"),- paddingXPx: pad.x,- paddingYPx: pad.y,- borderRadiusPx: number(value, "radius"),- bottomPercent: 0,- maxWidthPercent: number(value, "width") * 100,- leftPercent: number(value, "x") * 100,- topPercent: number(value, "y") * 100,- widthPercent: number(value, "width") * 100,- lineHeight: number(value, "line-height"),- textAlign: align,- },- } as const;+ return { mode: mode(element), ...captionAppearanceFromRecipe(value.properties) } as const;}export const decodeCaptionStyleSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {diff --git a/packages/caption/src/track.ts b/packages/caption/src/track.tsindex f74309ca..41f7034e 100644--- a/packages/caption/src/track.ts+++ b/packages/caption/src/track.ts@@ -80,6 +80,33 @@ export function assertCaptionTrackProgram(program: CaptionTrackProgram): void {}}+/**+ * Two cues, for anything that must show captions before speech has been+ * aligned. The regions carry no source tokens and no refinements because there+ * is no alignment behind them — which is exactly what every presentation mode+ * falls back to when a real Build has none either.+ */+export function defaultTimedCaptionProjection(): TimedCaptionProjection {+ const cues: readonly (readonly [string, number, number])[] = [+ ["This is the first caption cue.", 0, 1.8],+ ["And this one follows it.", 1.8, 4],+ ];+ return {+ contract: "svml.timed-caption-projection@1",+ text: cues.map(([display]) => display).join(" "),+ regions: cues.map(([display, startSec, endSec], index) => ({+ id: `cue-${index + 1}`,+ display,+ segmentId: "default",+ kind: "identity",+ sourceTokenIds: [],+ startSec,+ endSec,+ refinements: [],+ })),+ };+}+export function assertTimedCaptionProjection(projection: TimedCaptionProjection): void {if (projection.contract !== "svml.timed-caption-projection@1") {throw new Error("Unsupported TimedCaptionProjection contract.");diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.tsindex 3199e11c..c7a94a81 100644--- a/packages/core/src/schema.ts+++ b/packages/core/src/schema.ts@@ -59,6 +59,16 @@ function validateInline(value: CanonicalValue, schema: ValueSchema, path: stringif (schema.maxLength !== undefined && [...value].length > schema.maxLength) {fail(path, `must contain at most ${schema.maxLength} characters`);}+ // A format that nothing checks drifts from what values actually hold, in+ // the same way a duplicated constant does. The two with an exact shape+ // are checked here so a module states the rule once instead of asserting+ // it again in every consumer.+ if (schema.format === "color" && !/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/iu.test(value)) {+ fail(path, "must be #RRGGBB or #RRGGBBAA");+ }+ if (schema.format === "digest" && !/^sha256:[0-9a-f]{64}$/u.test(value)) {+ fail(path, "must be a sha256 digest");+ }return;case "literal":if (canonicalStringify(value) !== canonicalStringify(schema.value)) {diff --git a/packages/core/test/schema.test.ts b/packages/core/test/schema.test.tsnew file mode 100644index 00000000..ebab0702--- /dev/null+++ b/packages/core/test/schema.test.ts@@ -0,0 +1,41 @@+import assert from "node:assert/strict";+import test from "node:test";++import { validateStoredValue } from "../src/index.js";+import type { ValueSchema } from "@narratage/protocol";++function inline(value: unknown): { kind: "inline"; value: never } {+ return { kind: "inline", value: value as never };+}++test("a colour format admits both opaque and alpha hex, and nothing else", () => {+ const schema: ValueSchema = { kind: "string", format: "color" };+ assert.doesNotThrow(() => validateStoredValue(inline("#09090B"), schema));+ assert.doesNotThrow(() => validateStoredValue(inline("#09090bcc"), schema));+ assert.throws(() => validateStoredValue(inline("black"), schema), /#RRGGBB/u);+ assert.throws(() => validateStoredValue(inline("#09090"), schema), /#RRGGBB/u);+ // Three-digit shorthand is a CSS convenience the video contract does not take.+ assert.throws(() => validateStoredValue(inline("#abc"), schema), /#RRGGBB/u);+});++test("a digest format admits only a full sha256 identity", () => {+ const schema: ValueSchema = { kind: "string", format: "digest" };+ assert.doesNotThrow(() => validateStoredValue(inline(`sha256:${"a1".repeat(32)}`), schema));+ assert.throws(() => validateStoredValue(inline("sha256:abc"), schema), /sha256/u);+ assert.throws(() => validateStoredValue(inline("a1".repeat(32)), schema), /sha256/u);+});++test("a format describes a value without narrowing what its type already allows", () => {+ // unit-fraction, duration and multiline carry no shape of their own: bounds+ // are the schema's job, and stating them twice would let the two disagree.+ const fraction: ValueSchema = { kind: "number", format: "unit-fraction", minimum: 0, maximum: 1 };+ assert.doesNotThrow(() => validateStoredValue(inline(0.84), fraction));+ assert.throws(() => validateStoredValue(inline(1.5), fraction), /<= 1/u);++ const prose: ValueSchema = { kind: "string", format: "multiline" };+ assert.doesNotThrow(() => validateStoredValue(inline("two\nlines"), prose));+});++test("an unformatted string is still just a string", () => {+ assert.doesNotThrow(() => validateStoredValue(inline("#zzz"), { kind: "string" }));+});diff --git a/packages/film/src/index.ts b/packages/film/src/index.tsindex 6d2adbe2..6a46a276 100644--- a/packages/film/src/index.ts+++ b/packages/film/src/index.ts@@ -21,7 +21,15 @@ export {compileFilmCompositionImplementationDigest,createFilmTrackSet,createFilmTrackSetImplementationDigest,+ defaultFilmProgram,sealFilmProgram,} from "./program.js";+export {+ assertFilmRecipe,+ defaultFilmRecipe,+ filmCanvasFromRecipe,+ filmRecipeKeys,+} from "./recipe.js";+export type { FilmCanvas } from "./recipe.js";export { decodeFilmSurface } from "./surface.js";export type * from "./types.js";diff --git a/packages/film/src/manifest.ts b/packages/film/src/manifest.tsindex d689976c..c182395b 100644--- a/packages/film/src/manifest.ts+++ b/packages/film/src/manifest.ts@@ -9,6 +9,7 @@ import {appendFilmVisualTrackImplementationDigest,compileFilmCompositionImplementationDigest,createFilmTrackSetImplementationDigest,+ defaultFilmProgram,} from "./program.js";export const filmModuleRef = { name: "@narratage/film", version: "0.0.0-dev" } as const;@@ -34,7 +35,7 @@ const object = (fields: Readonly<Record<string, { readonly schema: ValueSchema;const canvasSchema = object({width: { schema: integer },height: { schema: integer },- clearColor: { schema: string },+ clearColor: { schema: { kind: "string", minLength: 1, format: "color" } },});const frameRateSchema = object({numerator: { schema: integer },@@ -68,7 +69,7 @@ export const filmManifest: ModuleManifest = {{ module: svsModuleRef, digest: digestOf(svsManifest) },],types: [- { name: filmTypes.program.name, schema: filmProgramSchema },+ { name: filmTypes.program.name, schema: filmProgramSchema, default: defaultFilmProgram() },{ name: filmTypes.trackSet.name, schema: filmTrackSetSchema },],capabilities: [],diff --git a/packages/film/src/program.ts b/packages/film/src/program.tsindex 92bb7270..cbb20ec7 100644--- a/packages/film/src/program.ts+++ b/packages/film/src/program.ts@@ -37,6 +37,23 @@ function filmTrackSetContent(value: FilmTrackSet): FilmTrackSet {};}+/**+ * One vertical frame at 30, for anything that must choose a canvas before an+ * author has declared a Film.+ *+ * The package that defines what a frame is decides what an undeclared one+ * looks like. Anything else picking its own numbers would be a second, silent+ * answer.+ */+export function defaultFilmProgram(id = "film"): FilmProgram {+ return sealFilmProgram({+ contract: "svml.film-program@1",+ id,+ frameRate: { numerator: 30, denominator: 1 },+ canvas: { width: 1080, height: 1920, clearColor: "#09090b" },+ });+}+export function sealFilmProgram(value: FilmProgram): FilmProgram {return filmProgramContent(value);}diff --git a/packages/film/src/recipe.ts b/packages/film/src/recipe.tsnew file mode 100644index 00000000..d437d7d6--- /dev/null+++ b/packages/film/src/recipe.ts@@ -0,0 +1,57 @@+import type { SvsRecipe } from "@narratage/svs";++import type { FilmProgram } from "./types.js";++/**+ * The Film Recipe: what a stylesheet says about the frame itself.+ *+ * Not an appearance among others — a Film Recipe is where a canvas comes from,+ * so anything that has to choose a frame size before compiling reads it here.+ */++export type FilmCanvas = {+ readonly frameRate: FilmProgram["frameRate"];+ readonly canvas: FilmProgram["canvas"];+};++/** One vertical frame at 30. Its keys are the Recipe's required property set. */+export const defaultFilmRecipe: Readonly<Record<string, string | number>> = {+ background: "#09090b",+ "frame-rate": 30,+ height: 1920,+ width: 1080,+};++export const filmRecipeKeys: readonly string[] = Object.keys(defaultFilmRecipe);++function number(properties: SvsRecipe["properties"], name: string): number {+ const property = properties[name];+ if (typeof property !== "number" || !Number.isFinite(property)) {+ throw new Error(`Film Recipe ${name} must be a number`);+ }+ return property;+}++export function assertFilmRecipe(properties: SvsRecipe["properties"]): void {+ const actual = Object.keys(properties).sort().join(" ");+ const expected = [...filmRecipeKeys].sort().join(" ");+ if (actual !== expected) {+ throw new Error(`Film Recipe requires exactly ${[...filmRecipeKeys].sort().join(", ")}`);+ }+}++export function filmCanvasFromRecipe(properties: SvsRecipe["properties"]): FilmCanvas {+ assertFilmRecipe(properties);+ const background = properties["background"];+ if (typeof background !== "string" || !background.trim()) {+ throw new Error("Film Recipe background must be a string");+ }+ return {+ frameRate: { numerator: number(properties, "frame-rate"), denominator: 1 },+ canvas: {+ width: number(properties, "width"),+ height: number(properties, "height"),+ clearColor: background.trim(),+ },+ };+}diff --git a/packages/film/src/surface.ts b/packages/film/src/surface.tsindex 0f2bee19..75d067cc 100644--- a/packages/film/src/surface.ts+++ b/packages/film/src/surface.ts@@ -15,6 +15,7 @@ import type {import { createFilmAssemblyFragment } from "./fragment.js";import { filmTypes } from "./manifest.js";import { sealFilmProgram } from "./program.js";+import { filmCanvasFromRecipe } from "./recipe.js";function localName(value: string): string {return value.includes(":") ? value.slice(value.lastIndexOf(":") + 1) : value;@@ -117,22 +118,12 @@ export const decodeFilmSurface: StructuredSurfaceHandler = ({ element, resolveRe}const appearanceReference = requiredReference(element, "appearance", resolveReference);const appearance = recipe(appearanceReference, `${element.name}.appearance`);- const expectedProperties = ["background", "frame-rate", "height", "width"];- const actualProperties = Object.keys(appearance.properties).sort();- if (actualProperties.join("\u0000") !== expectedProperties.join("\u0000")) {- throw new Error(`Film Recipe requires exactly ${expectedProperties.join(", ")}`);- }const programId = `${id}.program`;const program = sealFilmProgram({contract: "svml.film-program@1",id,- frameRate: { numerator: numberProperty(appearance, "frame-rate"), denominator: 1 },- canvas: {- width: numberProperty(appearance, "width"),- height: numberProperty(appearance, "height"),- clearColor: colorProperty(appearance, "background"),- },+ ...filmCanvasFromRecipe(appearance.properties),});const tracks = trackChildren(element).map((child) => {diff --git a/packages/media/src/schema.ts b/packages/media/src/schema.tsindex 1a99b8ed..d270496d 100644--- a/packages/media/src/schema.ts+++ b/packages/media/src/schema.ts@@ -1,10 +1,13 @@import type { ValueSchema } from "@narratage/protocol";const string = { kind: "string", minLength: 1 } as const;const number = { kind: "number", minimum: 0 } as const;+const seconds = { kind: "number", minimum: 0, format: "duration" } as const;const integer = { kind: "number", integer: true, minimum: 0 } as const;-const digest = { kind: "string", minLength: 71, maxLength: 71 } as const;+// 71 is `sha256:` plus 64 hex characters. The format states the shape the+// length was only ever approximating.+const digest = { kind: "string", minLength: 71, maxLength: 71, format: "digest" } as const;const object = (fields: Readonly<Record<string, { readonly schema: ValueSchema; readonly optional?: boolean }>>): ValueSchema => ({ kind: "object", fields });-export const mediaArtifactSchema = object({ digest: { schema: digest }, size: { schema: integer }, mediaType: { schema: string }, durationSec: { schema: number } });+export const mediaArtifactSchema = object({ digest: { schema: digest }, size: { schema: integer }, mediaType: { schema: string }, durationSec: { schema: seconds } });const blobArtifactSchema = (mediaTypes?: readonly string[]): ValueSchema => object({kind: { schema: { kind: "literal", value: "blob" } }, digest: { schema: digest }, size: { schema: integer },mediaType: { schema: mediaTypes === undefined ? string : { kind: "string", enum: mediaTypes } },diff --git a/packages/program-space/src/index.ts b/packages/program-space/src/index.tsindex c0423d4a..bae90c16 100644--- a/packages/program-space/src/index.ts+++ b/packages/program-space/src/index.ts@@ -11,7 +11,7 @@ export const programSpaceModuleRef = { name: "@narratage/program-space", versionexport const programSpaceTypes = {programSpace: { module: programSpaceModuleRef, name: "ProgramSpace" },} satisfies Record<string, TypeRef>;-const number = { kind: "number", minimum: 0 } as const;+const number = { kind: "number", minimum: 0, format: "duration" } as const;const integer = { kind: "number", integer: true, minimum: 0 } as const;export const programSpaceSchema: ValueSchema = {kind: "object",@@ -25,13 +25,29 @@ export const programSpaceSchema: ValueSchema = {};export const programSpaceManifest: ModuleManifest = {format: "svml.module@1", name: programSpaceModuleRef.name, version: programSpaceModuleRef.version,- dependencies: [], types: [{ name: programSpaceTypes.programSpace.name, schema: programSpaceSchema }],+ dependencies: [], types: [{+ name: programSpaceTypes.programSpace.name,+ schema: programSpaceSchema,+ default: { contract: "svml.program-space@1", durationSec: 4, frameRate: { numerator: 30, denominator: 1 } },+ }],capabilities: [], surfaces: [], producers: [],};export const programSpaceManifestDigest = digestOf(programSpaceManifest);export const programSpaceDependency = { module: programSpaceModuleRef, digest: programSpaceManifestDigest } as const;export function sealProgramSpace(value: ProgramSpace): ProgramSpace { return structuredClone(value); }++/**+ * Four seconds at 30, for anything that must have a frame domain before a+ * Build has measured one.+ */+export function defaultProgramSpace(): ProgramSpace {+ return sealProgramSpace({+ contract: "svml.program-space@1",+ durationSec: 4,+ frameRate: { numerator: 30, denominator: 1 },+ });+}export function programSpaceFrameCount(programSpace: ProgramSpace): number {const frames = programSpace.durationSec * programSpace.frameRate.numerator / programSpace.frameRate.denominator;const rounded = Math.round(frames);diff --git a/packages/protocol/src/module.ts b/packages/protocol/src/module.tsindex 515ba3ce..8f724008 100644--- a/packages/protocol/src/module.ts+++ b/packages/protocol/src/module.ts@@ -1,5 +1,5 @@import type { CapabilityRef, Digest, ModuleRef, ProducerRef, TypeRef } from "./identity.js";-import type { ValueSchema } from "./value.js";+import type { CanonicalValue, ValueSchema } from "./value.js";export type ModuleDependency = {readonly module: ModuleRef;@@ -12,6 +12,17 @@ export type TypeDeclaration = {readonly description?: string;/** Optional package-owned semantic refinement beyond the structural Schema. */readonly validator?: TypeValidatorDeclaration;+ /**+ * One value of this type, for anything that must show or exercise it before a+ * Build has produced one.+ *+ * The module that defines a type is the only place that knows what an+ * unspecified one should look like. Without this, every consumer invents its+ * own and they drift apart with nothing to notice. Omitted where no honest+ * default exists — a type carrying content-addressed media cannot have one,+ * because the module has no bytes to point at.+ */+ readonly default?: CanonicalValue;};export type TypeValidatorDeclaration = {diff --git a/packages/protocol/src/value.ts b/packages/protocol/src/value.tsindex 54303d7f..72ad03f0 100644--- a/packages/protocol/src/value.ts+++ b/packages/protocol/src/value.ts@@ -22,6 +22,32 @@ export type StoredValue =}| BlobRef;+/**+ * What a value means beyond its type.+ *+ * `kind` says a value is a string; `format` says the string is a colour rather+ * than a font family, or that a number is a fraction of a dimension rather than+ * a count. Two values with one type and different meanings are indistinguishable+ * without it, so anything reading a schema to present, diagnose or document a+ * value has to be told the difference somewhere — and a module's own type+ * declaration is where the difference is actually known.+ *+ * Deliberately closed and small. A format is a claim about the value, never an+ * instruction to a renderer: a Host decides that a `color` is best edited with a+ * swatch, and nothing here says so.+ */+export type ValueFormat =+ /** `#RRGGBB` or `#RRGGBBAA`. */+ | "color"+ /** A fraction of a containing dimension, normally 0 to 1. */+ | "unit-fraction"+ /** Prose that may contain line breaks and is read rather than matched. */+ | "multiline"+ /** Seconds. */+ | "duration"+ /** A content-addressed `sha256:` identity. */+ | "digest";+export type ValueSchema =| { readonly kind: "null" }| { readonly kind: "boolean" }@@ -30,12 +56,14 @@ export type ValueSchema =readonly integer?: boolean;readonly minimum?: number;readonly maximum?: number;+ readonly format?: ValueFormat;}| {readonly kind: "string";readonly enum?: readonly string[];readonly minLength?: number;readonly maxLength?: number;+ readonly format?: ValueFormat;}| {readonly kind: "literal";diff --git a/packages/text-track/src/index.ts b/packages/text-track/src/index.tsindex 3bccb82d..3a6ab0b7 100644--- a/packages/text-track/src/index.ts+++ b/packages/text-track/src/index.ts@@ -21,6 +21,7 @@ export {assertTextTrackSet,createTextTrackSet,createTextTrackSetImplementationDigest,+ defaultTextTrackProgram,finalizeTextTrack,finalizeTextTrackImplementationDigest,assertTextTrackSpec,@@ -34,4 +35,11 @@ export {sealTextTrackSpec,} from "./program.js";export { decodeTextTrackSurface } from "./surface.js";+export {+ assertTextAppearanceRecipe,+ defaultTextAppearanceRecipe,+ textAppearanceFromRecipe,+ textAppearanceRecipeKeys,+} from "./recipe.js";+export type { TextItemAppearance } from "./recipe.js";export type * from "./types.js";diff --git a/packages/text-track/src/manifest.ts b/packages/text-track/src/manifest.tsindex 7a6ab79b..4e71c5b1 100644--- a/packages/text-track/src/manifest.ts+++ b/packages/text-track/src/manifest.ts@@ -11,6 +11,7 @@ import {appendSelectedTextItemImplementationDigest,compileTextTrackImplementationDigest,createTextTrackSetImplementationDigest,+ defaultTextTrackProgram,finalizeTextTrackImplementationDigest,renderTextTrackImplementationDigest,} from "./program.js";@@ -42,15 +43,17 @@ const object = (fields: Readonly<Record<string, { readonly schema: ValueSchema;fields,});+const color = { kind: "string", minLength: 1, format: "color" } as const;+const textAppearanceSchema = object({- color: { schema: string },+ color: { schema: color },fontSizePx: { schema: positiveNumber },fontFamily: { schema: string, optional: true },fontWeight: { schema: { kind: "number", integer: true, minimum: 1, maximum: 1000 }, optional: true },lineHeight: { schema: positiveNumber, optional: true },align: { schema: { kind: "string", enum: ["left", "center", "right"] }, optional: true },verticalAlign: { schema: { kind: "string", enum: ["top", "center", "bottom"] }, optional: true },- backgroundColor: { schema: string, optional: true },+ backgroundColor: { schema: color, optional: true },borderRadiusPx: { schema: { kind: "number", minimum: 0 }, optional: true },paddingPx: { schema: { kind: "number", minimum: 0 }, optional: true },letterSpacingPx: { schema: number, optional: true },@@ -58,7 +61,7 @@ const textAppearanceSchema = object({const textItemSchema = object({id: { schema: string },- text: { schema: string },+ text: { schema: { kind: "string", format: "multiline" } },span: { schema: object({startFrame: { schema: unsignedInteger },endFrameExclusive: { schema: unsignedInteger },@@ -131,7 +134,7 @@ export const textTrackManifest: ModuleManifest = {compositionDependency,],types: [- { name: textTrackTypes.program.name, schema: textTrackProgramSchema },+ { name: textTrackTypes.program.name, schema: textTrackProgramSchema, default: defaultTextTrackProgram() },{ name: textTrackTypes.spec.name, schema: textTrackSpecSchema },{ name: textTrackTypes.header.name, schema: textTrackHeaderSchema },{ name: textTrackTypes.itemSpec.name, schema: textItemSpecSchema },diff --git a/packages/text-track/src/program.ts b/packages/text-track/src/program.tsindex f4b40fe7..291a651b 100644--- a/packages/text-track/src/program.ts+++ b/packages/text-track/src/program.ts@@ -4,7 +4,7 @@ import type { ProgramSpace } from "@narratage/program-space";import { assertCompleteSemanticMapIdentity, assertNarrativeSelectionIdentity, selectionFrameSpans } from "@narratage/semantic-map";import type { CompleteSemanticMap } from "@narratage/semantic-map";import { assertVisualTrackIdentity, sealVisualTrack } from "@narratage/composition";-import type { VisualStyleDeclaration, VisualTrack } from "@narratage/composition";+import type { FrameSpan, VisualStyleDeclaration, VisualTrack } from "@narratage/composition";import { canonicalize, digestOf } from "@narratage/protocol";import type {@@ -61,6 +61,40 @@ export function sealTextTrackProgram(value: TextTrackProgram): TextTrackProgramreturn textTrackProgramContent(value);}+/**+ * One legible overlay, for anything that must show a Text Track before an+ * author has written one — a preview, a diagnostic, a document.+ *+ * The package owning the type owns what it looks like by default. A consumer+ * that invented its own would be a second answer to the same question, free to+ * drift from this one without anything noticing.+ */+export function defaultTextTrackProgram(+ id = "text",+ span: FrameSpan = { startFrame: 0, endFrameExclusive: 30 },+): TextTrackProgram {+ return sealTextTrackProgram({+ contract: "svml.text-track-program@1",+ id,+ items: [{+ id: "item-0001",+ text: "A title card",+ span,+ z: 90,+ tieBreak: `${id}:item-0001`,+ box: { xPercent: 8, yPercent: 12, widthPercent: 84, heightPercent: 20 },+ appearance: {+ color: "#ffffff",+ fontSizePx: 96,+ fontFamily: "Inter, system-ui, sans-serif",+ fontWeight: 800,+ letterSpacingPx: -2,+ align: "left",+ },+ }],+ });+}+function assertAppearance(appearance: TextAppearance, label: string): void {assertNonEmpty(appearance.color, `${label} color`);assertFinite(appearance.fontSizePx, `${label} fontSizePx`);diff --git a/packages/text-track/src/recipe.ts b/packages/text-track/src/recipe.tsnew file mode 100644index 00000000..fe65d009--- /dev/null+++ b/packages/text-track/src/recipe.ts@@ -0,0 +1,84 @@+import type { SvsRecipe } from "@narratage/svs";++import type { TextAppearance, TextBox } from "./types.js";++/**+ * The Text appearance Recipe: what a stylesheet may say about an overlay.+ *+ * Held apart from the Surface handler so a stylesheet reads the same whoever is+ * reading it. The handler owns element attributes and timing; this owns the+ * Recipe.+ */++export type TextItemAppearance = {+ readonly z: number;+ readonly box: TextBox;+ readonly appearance: TextAppearance;+};++/** One legible overlay. Its keys are the Recipe's required property set. */+export const defaultTextAppearanceRecipe: Readonly<Record<string, string | number>> = {+ align: "left",+ fill: "#ffffff",+ font: "Inter, system-ui, sans-serif",+ height: 0.2,+ size: 96,+ "stack-order": 90,+ tracking: -2,+ weight: 800,+ width: 0.84,+ x: 0.08,+ y: 0.12,+};++export const textAppearanceRecipeKeys: readonly string[] =+ Object.keys(defaultTextAppearanceRecipe);++function number(properties: SvsRecipe["properties"], name: string): number {+ const property = properties[name];+ if (typeof property !== "number" || !Number.isFinite(property)) {+ throw new Error(`Text Recipe ${name} must be a number`);+ }+ return property;+}++function string(properties: SvsRecipe["properties"], name: string): string {+ const property = properties[name];+ if (typeof property !== "string" || !property.trim()) {+ throw new Error(`Text Recipe ${name} must be a string`);+ }+ return property.trim();+}++export function assertTextAppearanceRecipe(properties: SvsRecipe["properties"]): void {+ const actual = Object.keys(properties).sort().join(" ");+ const expected = [...textAppearanceRecipeKeys].sort().join(" ");+ if (actual !== expected) {+ throw new Error(`Text Recipe requires exactly ${[...textAppearanceRecipeKeys].sort().join(", ")}`);+ }+}++export function textAppearanceFromRecipe(properties: SvsRecipe["properties"]): TextItemAppearance {+ assertTextAppearanceRecipe(properties);+ const align = string(properties, "align");+ if (align !== "left" && align !== "center" && align !== "right") {+ throw new Error("Text Recipe align is invalid");+ }+ return {+ z: number(properties, "stack-order"),+ box: {+ xPercent: number(properties, "x") * 100,+ yPercent: number(properties, "y") * 100,+ widthPercent: number(properties, "width") * 100,+ heightPercent: number(properties, "height") * 100,+ },+ appearance: {+ color: string(properties, "fill"),+ fontSizePx: number(properties, "size"),+ fontFamily: string(properties, "font"),+ fontWeight: number(properties, "weight"),+ letterSpacingPx: number(properties, "tracking"),+ align,+ },+ };+}diff --git a/packages/text-track/src/surface.ts b/packages/text-track/src/surface.tsindex cb9515b1..02ef1d23 100644--- a/packages/text-track/src/surface.ts+++ b/packages/text-track/src/surface.ts@@ -11,6 +11,7 @@ import type { StructuredElement, StructuredSurfaceHandler, SurfaceResolvedRefereimport { textTrackProducers, textTrackTypes } from "./manifest.js";import { sealTextItemSpec, sealTextTrackHeader } from "./program.js";+import { textAppearanceFromRecipe } from "./recipe.js";import type { TextItemSpec } from "./types.js";const input = (name: string) => ({ kind: "fragment-input" as const, name });@@ -143,27 +144,13 @@ export const decodeTextTrackSurface: StructuredSurfaceHandler = ({ element, reso})(): ref(child, "during", narrativeTypes.selection, resolveReference);const appearance = recipe(ref(child, "appearance", svsRecipeType, resolveReference));- const expected = ["align", "fill", "font", "height", "size", "stack-order", "tracking", "weight", "width", "x", "y"];- if (Object.keys(appearance.properties).sort().join("\0") !== expected.sort().join("\0")) throw new Error(`Text Recipe requires exactly ${expected.join(", ")}`);- const align = propString(appearance, "align");- if (align !== "left" && align !== "center" && align !== "right") throw new Error("Text Recipe align is invalid");- const textAlign = align as "left" | "center" | "right";const suffix = String(itemIndex).padStart(4, "0");const specId = `${id}.item.${suffix}.spec`;const spec = sealTextItemSpec({contract: "svml.text-item-spec@1",id: `item-${suffix}`,text: text(child, "text"),- z: propNumber(appearance, "stack-order"),- box: {- xPercent: propNumber(appearance, "x") * 100, yPercent: propNumber(appearance, "y") * 100,- widthPercent: propNumber(appearance, "width") * 100, heightPercent: propNumber(appearance, "height") * 100,- },- appearance: {- color: propString(appearance, "fill"), fontSizePx: propNumber(appearance, "size"),- fontFamily: propString(appearance, "font"), fontWeight: propNumber(appearance, "weight"),- letterSpacingPx: propNumber(appearance, "tracking"), align: textAlign,- },+ ...textAppearanceFromRecipe(appearance.properties),});records.push({ id: specId, type: textTrackTypes.itemSpec, value: { kind: "inline", value: spec }, range: child.range });return [{diff --git a/test/playground-discover.test.ts b/test/playground-discover.test.tsdeleted file mode 100644index 913c2c21..00000000--- a/test/playground-discover.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import test from "node:test";--import { discover } from "../tools/playground/src/svs/discover.js";-import { within } from "../tools/playground/src/server/browse.js";--const repoRoot = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/u, "");-const golden = readFileSync(- fileURLToPath(new URL("../examples/talking-film-golden/studio.svs", import.meta.url)),- "utf8",-);--test("a stylesheet is read as a list of things to preview", () => {- const found = discover("studio.svs", golden);- assert.equal(found.sheetId, "studio");-- // A Film Recipe is not a preview subject: it says how big the frame is.- assert.deepEqual(found.canvases, [{- path: "film.vertical", width: 1080, height: 1920, fps: 30, clearColor: "#09090B",- }]);-- assert.deepEqual(- found.subjects.map((subject) => [subject.path, subject.component.id]),- [- ["broll.product", "broll"],- ["caption.dialogue", "caption"],- ["caption.alice", "caption"],- ["caption.bob", "caption"],- ["text.title", "text-track"],- ],- );-- // Reported rather than dropped. These are real Recipes with no preview, and- // naming them is the difference between a gap and a silent omission.- //- // speech.full is here for a reason worth knowing: no Surface in the compiler- // reads it. projectSpeechVisual takes no appearance at all, so the Recipe is- // declared and unused, and the playground cannot honour what nothing honours.- assert.deepEqual(- found.unmatched.map((entry) => entry.path),- ["font.inter-semibold", "font.inter-black", "speech.full", "caption.short-cues"],- );-});--test("Recipes sharing a path prefix are told apart by their shape", () => {- const found = discover("studio.svs", golden);- // caption.dialogue previews; caption.short-cues is Gemini planning config.- assert.ok(found.subjects.some((subject) => subject.path === "caption.dialogue"));- assert.ok(found.unmatched.some((entry) => entry.path === "caption.short-cues"));-});--test("each Recipe carries its own draft, so like-shaped ones stay distinct", () => {- const subjects = discover("studio.svs", golden).subjects;- assert.equal(new Set(subjects.map((subject) => subject.key)).size, subjects.length);- const alice = subjects.find((subject) => subject.path === "caption.alice")!;- const bob = subjects.find((subject) => subject.path === "caption.bob")!;- const fill = (value: unknown) => (value as Record<string, unknown>)["fill"];- assert.equal(fill(alice.parameters), "#73FBD3");- assert.notEqual(fill(alice.parameters), fill(bob.parameters));-});--test("a source that is not a stylesheet is refused by name", () => {- assert.throws(- () => discover("main.svml", '<?svml using="@narratage/text@1"?>\n<svml/>\n'),- /not a stylesheet/u,- );-});--test("browsing cannot leave the repository", () => {- assert.equal(within(repoRoot, "examples"), `${repoRoot}/examples`);- assert.equal(within(repoRoot, "."), repoRoot);- // Containment is checked on the resolved path, so traversal is refused- // however it is spelled.- assert.equal(within(repoRoot, ".."), undefined);- assert.equal(within(repoRoot, "examples/../.."), undefined);- assert.equal(within(repoRoot, "/etc/passwd"), undefined);- // A sibling directory whose name merely starts with the root is not inside it.- assert.equal(within("/srv/app", "/srv/app-secrets/key"), undefined);-});diff --git a/test/playground-discovery.test.ts b/test/playground-discovery.test.tsnew file mode 100644index 00000000..5034e37b--- /dev/null+++ b/test/playground-discovery.test.ts@@ -0,0 +1,103 @@+import assert from "node:assert/strict";+import { readdirSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { assertHyperframesDocument, compileHyperframesDocument } from "@narratage/hyperframes";+import { sealComposition } from "@narratage/composition";+import { sealProgramSpace } from "@narratage/program-space";++import { discoverPreviewProducers } from "../tools/playground/src/discovery/producers.js";+import type { PreviewSources } from "../tools/playground/src/discovery/producers.js";++/**+ * The playground lists no components. It finds them, by asking the manifests+ * which modules declare a Producer that outputs a VisualTrack.+ *+ * These tests run that discovery over the real workspace, so a module that+ * gains or loses a visual Producer changes the result here without anybody+ * editing a list — which is the property the whole arrangement exists for.+ */++const packages = fileURLToPath(new URL("../packages", import.meta.url));++function workspace(): PreviewSources {+ const entries: Record<string, () => Promise<unknown>> = {};+ const components: Record<string, () => Promise<unknown>> = {};+ for (const dir of readdirSync(packages, { withFileTypes: true })) {+ if (!dir.isDirectory()) continue;+ // A small module states its manifest in its entry rather than in a file of+ // its own, and a Producer taking one of its types still needs the schema.+ entries[`${dir.name}/manifest`] = async () => await import(`${packages}/${dir.name}/src/manifest.ts`);+ entries[`${dir.name}/index`] = async () => await import(`${packages}/${dir.name}/src/index.ts`);+ components[dir.name] = async () => await import(`${packages}/${dir.name}/src/component.ts`);+ }+ return { manifests: entries, components };+}++const programSpace = sealProgramSpace({+ contract: "svml.program-space@1",+ durationSec: 4,+ frameRate: { numerator: 30, denominator: 1 },+});+const canvas = { width: 1080, height: 1920, clearColor: "#09090b" };++test("previewable modules are the ones declaring a VisualTrack Producer", async () => {+ const found = await discoverPreviewProducers(workspace());+ assert.deepEqual(+ [...new Set(found.map((producer) => producer.moduleName))].sort(),+ ["@narratage/broll", "@narratage/caption", "@narratage/speech-basis", "@narratage/text-track"],+ );+});++test("each producer carries its inputs' declared schemas", async () => {+ for (const producer of await discoverPreviewProducers(workspace())) {+ assert.ok(producer.inputs.length > 0, `${producer.id} declares no inputs`);+ for (const input of producer.inputs) {+ assert.notEqual(input.schema, undefined,+ `${producer.id} input ${input.name} has no schema, so no form can be built for it`);+ }+ }+});++test("a producer whose inputs all carry defaults renders without anything being typed", async () => {+ const found = await discoverPreviewProducers(workspace());+ const ready = found.filter((producer) =>+ producer.inputs.every((input) => input.initial !== undefined));++ // The modules that can answer for themselves entirely: caption and text.+ // B-roll and speech take content-addressed media, which no module can default.+ assert.ok(ready.length >= 2, "at least two producers should be fully defaulted");++ for (const producer of ready) {+ const values = Object.fromEntries(producer.inputs.map((input) =>+ [input.name, input.type.name === "ProgramSpace" ? programSpace : input.initial]));+ const track = producer.invoke(values as never);+ const document = compileHyperframesDocument(sealComposition({+ contract: "svml.composition@1",+ id: producer.moduleName,+ canvas,+ tracks: [track as never],+ }), programSpace);+ assert.doesNotThrow(() => assertHyperframesDocument(document),+ `${producer.id} produced an illegal document from its own declared defaults`);+ assert.match(document.html, /class="clip svml-visual-present"/u);+ }+});++test("a module offering no default for a media input says so rather than inventing one", async () => {+ const found = await discoverPreviewProducers(workspace());+ // B-roll and speech both take a value carrying a content-addressed Artifact,+ // and a module has no bytes to point at, so neither offers a default. Saying+ // nothing is the honest answer; a stub digest would be rejected downstream.+ for (const moduleName of ["@narratage/broll", "@narratage/speech-basis"]) {+ const producer = found.find((entry) => entry.moduleName === moduleName)!;+ assert.ok(producer.inputs.some((input) => input.initial === undefined),+ `${moduleName} should decline to default its media-bearing input`);+ }+});++test("each producer is discovered once, however many files re-export its module", async () => {+ const found = await discoverPreviewProducers(workspace());+ assert.equal(new Set(found.map((producer) => producer.id)).size, found.length);+});diff --git a/test/playground-preview.test.ts b/test/playground-preview.test.tsdeleted file mode 100644index 4e55d652..00000000--- a/test/playground-preview.test.ts+++ /dev/null@@ -1,180 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";--import { assertHyperframesDocument, compileHyperframesDocument } from "@narratage/hyperframes";-import { sealComposition } from "@narratage/composition";-import { sealProgramSpace } from "@narratage/program-space";--import { REGISTRY, matchRecipe } from "../tools/playground/src/registry/index.js";-import { registerArtifact } from "../tools/playground/src/preview/artifacts.js";--/**- * Every adapter, through the whole compiler path it will run in the browser.- *- * The playground has no schema validator by design — the packages' own seal and- * assert functions are the judge. That makes this the test that matters: if an- * adapter's defaults cannot reach a legal HyperFrames document here, the- * playground cannot show it there.- */--const programSpace = sealProgramSpace({- contract: "svml.program-space@1",- durationSec: 4,- frameRate: { numerator: 30, denominator: 1 },-});-const canvas = { width: 1080, height: 1920, clearColor: "#09090b" };--/** A named Artifact with no bytes — enough to build with, not to draw. */-const VIDEO = registerArtifact({- digest: `sha256:${"a1".repeat(32)}`,- size: 1024,- mediaType: "video/mp4",- durationSec: 4,-} as Parameters<typeof registerArtifact>[0]);--/**- * Fills in whatever media a component needs.- *- * Components that draw supplied footage contribute nothing until they have- * some — an empty picker is not an error — so their defaults have to be- * completed before there is a document to judge.- */-function withMedia(content: unknown): unknown {- const bag = structuredClone(content) as Record<string, unknown>;- for (const value of Object.values(bag)) {- if (!Array.isArray(value)) continue;- for (const entry of value as Record<string, unknown>[]) {- if ("media" in entry) entry["media"] = VIDEO.digest;- }- }- return bag;-}--for (const component of REGISTRY) {- test(`${component.id} compiles its defaults into a legal document`, () => {- const { parameters, content } = component.defaults();- const tracks = component.build({- parameters,- content: withMedia(content) as typeof content,- programSpace,- canvas,- });- assert.ok(tracks.length > 0, "an adapter must contribute at least one Track");- const document = compileHyperframesDocument(sealComposition({- contract: "svml.composition@1",- id: component.id,- canvas,- tracks,- }), programSpace);- assert.doesNotThrow(() => assertHyperframesDocument(document));- assert.match(document.html, /class="clip svml-visual-present"/u);- });-- test(`${component.id} survives a duration shorter than its content`, () => {- // Dragging the duration down must clamp spans, not throw: the Presents an- // adapter derives from seconds would otherwise fall outside the program.- const short = sealProgramSpace({- contract: "svml.program-space@1",- durationSec: 0.5,- frameRate: { numerator: 30, denominator: 1 },- });- const { parameters, content } = component.defaults();- assert.doesNotThrow(() => {- compileHyperframesDocument(sealComposition({- contract: "svml.composition@1",- id: component.id,- canvas,- tracks: component.build({- parameters,- content: withMedia(content) as typeof content,- programSpace: short,- canvas,- }),- }), short);- });- });-- test(`${component.id} draws nothing rather than failing before its media arrives`, () => {- // An empty picker is a state to pass through, not an error to report.- const { parameters, content } = component.defaults();- assert.doesNotThrow(() => component.build({ parameters, content, programSpace, canvas }));- });-}--test("a Recipe is matched by its exact property key set, not its path prefix", () => {- const caption = REGISTRY.find((component) => component.id === "caption")!;- const properties = Object.fromEntries((caption.recipeKeys ?? []).map((key) => [key, "0"]));- assert.equal(matchRecipe(properties)?.id, "caption");-- // caption.short-cues shares the prefix and is a different shape entirely.- assert.equal(matchRecipe({ model: "x", "max-words": 6, "max-lines": 2 }), undefined);- // A near miss is a miss: one extra key means a different contract.- assert.equal(matchRecipe({ ...properties, extra: 1 }), undefined);-});--test("filling from a Recipe leaves no parameter unset", () => {- // The bug this catches is a Recipe key that gains a mapping in the schema but- // not in fromRecipe, which would silently hand the form an undefined field.- for (const component of REGISTRY) {- if (component.recipeKeys === undefined) continue;- assert.equal(typeof component.fromRecipe, "function",- `${component.id} declares recipeKeys so it must accept a Recipe`);- const properties = Object.fromEntries(component.recipeKeys.map((key) => [key, "0"]));- const filled = component.fromRecipe!(properties) as Record<string, unknown>;- const declared = component.parameters.kind === "object"- ? Object.keys(component.parameters.fields)- : [];- for (const name of declared) {- assert.notEqual(filled[name], undefined,- `${component.id}.fromRecipe left ${name} unset`);- }- }-});--/** Verbatim from examples/talking-film-golden/studio.svs. */-const GOLDEN: Readonly<Record<string, Readonly<Record<string, string>>>> = {- caption: {- "stack-order": "70", x: "0.08", y: "0.76", width: "0.84",- font: "inter-semibold", weight: "600", size: "58", "line-height": "0.96",- align: "center", fill: "#FFFFFF", background: "#09090BCC",- padding: "16 24", radius: "18",- },- "text-track": {- "stack-order": "90", x: "0.08", y: "0.12", width: "0.84", height: "0.2",- font: "inter-black", weight: "800", size: "96", tracking: "-2",- align: "left", fill: "#FFFFFF",- },-};--test("a real Recipe renders through the component it describes", () => {- for (const [id, properties] of Object.entries(GOLDEN)) {- const component = REGISTRY.find((entry) => entry.id === id)!;- assert.deepEqual(- Object.keys(properties).sort(),- [...(component.recipeKeys ?? [])].sort(),- `the ${id} fixture must carry exactly the Recipe's keys`,- );- assert.equal(matchRecipe(properties)?.id, id);- const document = compileHyperframesDocument(sealComposition({- contract: "svml.composition@1",- id,- canvas,- tracks: component.build({- parameters: component.fromRecipe!(properties),- content: component.defaults().content,- programSpace,- canvas,- }),- }), programSpace);- assert.doesNotThrow(() => assertHyperframesDocument(document));- }-});--test("padding carries y first, and one value covers both axes", () => {- const caption = REGISTRY.find((entry) => entry.id === "caption")!;- const of = (padding: string) => caption.fromRecipe!({- ...GOLDEN["caption"]!, padding,- }) as Record<string, unknown>;- assert.deepEqual([of("16 24")["paddingY"], of("16 24")["paddingX"]], [16, 24]);- assert.deepEqual([of("12")["paddingY"], of("12")["paddingX"]], [12, 12]);-});diff --git a/tools/playground-registry.test.mjs b/tools/playground-registry.test.mjsdeleted file mode 100644index 2029d179..00000000--- a/tools/playground-registry.test.mjs+++ /dev/null@@ -1,57 +0,0 @@-import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import { fileURLToPath } from "node:url";--import { REGISTRY } from "./playground/src/registry/index.ts";--/**- * The playground copies each component's SVS Recipe key set, because the- * compiler states it only as a literal inside its Surface handler and there is- * no shared declaration to import yet.- *- * A copy that can drift silently is worse than no copy: the playground would- * quietly stop matching a Recipe it still claims to preview. This reads the- * literal back out of the Surface source and pins the two together, so adding a- * property to a Recipe breaks the build until the playground follows.- *- * Delete this once the key sets move into the packages' manifests and the- * playground can import them.- */--const SURFACES = {- caption: "../packages/caption/src/surface.ts",- "text-track": "../packages/text-track/src/surface.ts",- broll: "../packages/broll/src/surface.ts",-};--/** Pulls the `expected` array literal a Surface compares Recipe keys against. */-function declaredKeys(source) {- const found = /const expected = \[([^\]]*)\]/u.exec(source);- assert.notEqual(found, null, "the Surface must declare an expected Recipe key list");- return [...found[1].matchAll(/"([^"]+)"/gu)].map((match) => match[1]).sort();-}--for (const [id, relative] of Object.entries(SURFACES)) {- test(`the ${id} Recipe key set matches its Surface`, () => {- const source = readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");- const component = REGISTRY.find((entry) => entry.id === id);- assert.notEqual(component, undefined, `the registry must carry ${id}`);- assert.deepEqual(- [...component.recipeKeys].sort(),- declaredKeys(source),- `${id} drifted from ${relative}; update tools/playground/src/registry/${id}.ts`,- );- });-}--test("no two components claim the same Recipe shape", () => {- const seen = new Map();- for (const component of REGISTRY) {- if (component.recipeKeys === undefined) continue;- const key = [...component.recipeKeys].sort().join(" ");- assert.equal(seen.get(key), undefined,- `${component.id} and ${seen.get(key)} match the same Recipe, so discovery would be arbitrary`);- seen.set(key, component.id);- }-});diff --git a/tools/playground/README.md b/tools/playground/README.mdindex 679f84f8..ca83b58a 100644--- a/tools/playground/README.md+++ b/tools/playground/README.md@@ -6,22 +6,30 @@ Look at a visual component without running a Build.pnpm playground```-Pick a component, fill in its parameters, and it renders on a canvas of the size-you choose. Or browse to a `.svs` stylesheet: every Recipe in it becomes its own-preview, and the `film` Recipe fills in the frame size.+Pick a producer, fill in its inputs, and it renders on a canvas of the size you+choose. Browse to a `.svs` stylesheet and its Film Recipe fills in the frame.-## What it actually renders+## It lists nothing-The real thing. Each adapter converts form values into its package's own Program-type and calls that package's renderer — `renderCaptionTrack`,-`renderTextTrack`, `compileBrollProduct`, `projectSpeechVisual` — then-`compileHyperframesDocument` produces the same document a Build would render.-Those functions are pure and import nothing from `node:`, which is what lets-them run in a browser at all.+There is no registry here, and no per-component code. Everything comes from+what the compiler already declares about itself:-Nothing here validates. The packages' own `seal*` and `assert*` functions are-the judge, because they are what a real Build runs. A rejected value shows the-compiler's own message beside the form and leaves the last good frame up.+| Question | Answered by |+|---|---|+| Which modules can be previewed | manifests declaring a Producer whose output type is `@narratage/composition.VisualTrack` |+| What each needs | that Producer's `inputs`, each a `TypeRef` |+| What shape each input has | the declaring module's `TypeDeclaration.schema` |+| What a control should look like | `ValueSchema.format` — `color`, `unit-fraction`, `multiline`, `digest`, `duration` |+| What to start from | `TypeDeclaration.default`, given by the module that owns the type |+| How to run it | the module's `component.producers[].handler` |++A module that gains a visual Producer appears here on its own. One that loses+it disappears. Neither requires editing anything in this directory.++Nothing here validates, either: `validateStoredValue` and the modules' own+`seal*` and `assert*` functions are the judge, because they are what a real+Build runs. A rejected value shows the compiler's own message beside the form+and leaves the last good frame up.## Two things a Build supplies that the document does not@@ -37,17 +45,16 @@ self-sufficient — a real render supplies a producer for the rest. The shim in`getAnimations()` plus an explicit `currentTime` — the same technique theproduction renderer uses.-## Adding a component+## Making a module previewable-One file in `src/registry/`, one entry in `src/registry/index.ts`. Declare the-parameters as a `ValueSchema` and the form is generated; return `Track[]` from-`build` and the shell owns the canvas, the ProgramSpace and the seal.+Nothing to add here. In the module: declare a Producer that outputs a+`VisualTrack`, give each input type a `schema`, and give it a `default` where+you honestly can. A type carrying content-addressed media has no default — say+nothing rather than inventing a digest, and the playground will ask the operator+for a file instead.-If the component reads an SVS Recipe, copy its key set from the Surface handler-and add the pair to `tools/playground-registry.test.mjs`, which reads the-literal back out of the source and fails if the two drift. Recipes are matched-by exact property key set, never by path prefix — `caption.dialogue` and-`caption.short-cues` share a prefix and describe unrelated things.+Annotate a field with `format` where its type alone is ambiguous: a colour and+a font family are both strings, and only the module knows which is which.## Known divergences from a real render@@ -55,5 +62,5 @@ by exact property key set, never by path prefix — `caption.dialogue` and`FontArtifactRef` path with hashed `@font-face` families is not exercised,because `renderCaptionTrack` and `renderTextTrack` do not attach one.- Audio tracks are not played.-- `speech.full` in the golden stylesheet has no preview because no Surface in- the compiler reads it; `projectSpeechVisual` takes no appearance at all.+- The frame domain is the shell's, not the form's: a `ProgramSpace` input is+ filled from the canvas controls, so there is only one place to change it.diff --git a/tools/playground/src/discovery/producers.ts b/tools/playground/src/discovery/producers.tsnew file mode 100644index 00000000..2075300a--- /dev/null+++ b/tools/playground/src/discovery/producers.ts@@ -0,0 +1,174 @@+import type {+ CanonicalValue,+ ModuleManifest,+ ProducerDeclaration,+ TypeRef,+ ValueSchema,+} from "../svml.js";++/**+ * What the compiler already says about itself.+ *+ * Nothing here lists components. A module is previewable because it declares a+ * Producer that outputs a VisualTrack — that is what "puts pixels on the frame"+ * means, and the manifests already say it. A module added tomorrow appears here+ * without this file changing, and one that stops emitting a VisualTrack+ * disappears without anybody remembering to remove it.+ */++const VISUAL_TRACK = { module: "@narratage/composition", name: "VisualTrack" } as const;++type BoundProducer = {+ readonly producer: { readonly name: string };+ readonly handler: (invocation: {+ readonly inputs: Readonly<Record<string, { readonly value: unknown } | undefined>>;+ }) => { readonly outputs: Readonly<Record<string, { readonly value: unknown }>> };+};++type ComponentModule = {+ readonly name: string;+ readonly producers: readonly BoundProducer[];+};++export type PreviewInput = {+ readonly name: string;+ readonly type: TypeRef;+ readonly schema: ValueSchema | undefined;+ /** The declaring module's own default, where it has one it can honestly give. */+ readonly initial: CanonicalValue | undefined;+};++export type PreviewProducer = {+ readonly id: string;+ readonly label: string;+ readonly moduleName: string;+ readonly inputs: readonly PreviewInput[];+ readonly outputName: string;+ readonly invoke: (values: Readonly<Record<string, CanonicalValue>>) => unknown;+};++function typeKey(ref: TypeRef): string {+ return `${ref.module.name}::${ref.name}`;+}++function outputsVisualTrack(producer: ProducerDeclaration): boolean {+ return producer.outputs.some((port) =>+ port.type.name === VISUAL_TRACK.name && port.type.module.name === VISUAL_TRACK.module);+}++/**+ * Names a producer by its module, and by itself only when its module offers a+ * choice.+ *+ * A producer name alone is often meaningless out of context — `project-visual`+ * says nothing — while a module name alone is ambiguous where one module emits+ * more than one Track.+ */+function label(moduleName: string, producer: ProducerDeclaration, siblings: number): string {+ const short = moduleName.replace(/^@narratage\//u, "");+ if (siblings < 2) return short;+ const rest = producer.name+ .replace(/^(?:render|project|compile)-/u, "")+ .replace(new RegExp(`^${short}-`, "u"), "");+ return `${short} · ${rest}`;+}++/**+ * Loads every workspace module and keeps the ones a browser can run.+ *+ * A module whose manifest or component cannot be imported here — because it+ * reaches for a filesystem, a process or a network — is simply not previewable.+ * That is a fact about the module, not a list to maintain, so it is discovered+ * rather than declared.+ */+export type ModuleLoader = () => Promise<unknown>;++export type PreviewSources = {+ readonly manifests: Readonly<Record<string, ModuleLoader>>;+ readonly components: Readonly<Record<string, ModuleLoader>>;+};++export async function discoverPreviewProducers(+ sources: PreviewSources,+): Promise<readonly PreviewProducer[]> {+ // Keyed by module name: an entry file re-exports its own manifest, so the+ // same module arrives more than once and must be counted once.+ const byName = new Map<string, ModuleManifest>();+ for (const load of Object.values(sources.manifests)) {+ try {+ const module = await load() as Record<string, unknown>;+ for (const value of Object.values(module)) {+ if (isManifest(value) && !byName.has(value.name)) byName.set(value.name, value);+ }+ } catch {+ /* Not loadable here, therefore not previewable here. */+ }+ }+ const manifests = [...byName.values()];++ // Input types belong to whichever module declares them, which is often not+ // the module that produces the Track — a ProgramSpace comes from elsewhere.+ const types = new Map<string, { schema: ValueSchema; default?: CanonicalValue }>();+ for (const manifest of manifests) {+ for (const declaration of manifest.types) {+ types.set(`${manifest.name}::${declaration.name}`, declaration);+ }+ }++ const components = new Map<string, ComponentModule>();+ for (const load of Object.values(sources.components)) {+ try {+ const module = await load() as Record<string, unknown>;+ for (const value of Object.values(module)) {+ if (isComponent(value) && !components.has(value.name)) components.set(value.name, value);+ }+ } catch {+ /* Same: a component that cannot load here cannot be previewed here. */+ }+ }++ const found: PreviewProducer[] = [];+ for (const manifest of manifests) {+ const visual = manifest.producers.filter(outputsVisualTrack);+ for (const declaration of visual) {+ const bound = components.get(manifest.name)+ ?.producers.find((entry) => entry.producer.name === declaration.name);+ // A declared Producer with no bound handler is declared but not runnable.+ if (bound === undefined) continue;+ const outputName = declaration.outputs.find((port) =>+ port.type.name === VISUAL_TRACK.name)!.name;++ found.push({+ id: `${manifest.name}#${declaration.name}`,+ label: label(manifest.name, declaration, visual.length),+ moduleName: manifest.name,+ outputName,+ inputs: declaration.inputs.map((port) => {+ const declared = types.get(typeKey(port.type));+ return {+ name: port.name,+ type: port.type,+ schema: declared?.schema,+ initial: declared?.default,+ };+ }),+ invoke: (values) => bound.handler({+ inputs: Object.fromEntries(Object.entries(values)+ .map(([name, value]) => [name, { value: { kind: "inline", value } }])),+ }).outputs[outputName]?.value,+ });+ }+ }+ return found.sort((left, right) => left.label.localeCompare(right.label));+}++function isManifest(value: unknown): value is ModuleManifest {+ return value !== null && typeof value === "object"+ && (value as { format?: unknown }).format === "svml.module@1";+}++function isComponent(value: unknown): value is ComponentModule {+ return value !== null && typeof value === "object"+ && typeof (value as { name?: unknown }).name === "string"+ && Array.isArray((value as { producers?: unknown }).producers);+}diff --git a/tools/playground/src/discovery/workspace.ts b/tools/playground/src/discovery/workspace.tsnew file mode 100644index 00000000..e7e53d12--- /dev/null+++ b/tools/playground/src/discovery/workspace.ts@@ -0,0 +1,24 @@+/// <reference types="vite/client" />++import { discoverPreviewProducers } from "./producers.js";+import type { PreviewProducer } from "./producers.js";++/**+ * Every workspace module, handed to the discovery as loaders.+ *+ * The glob is the only part of discovery that is Vite's rather than the+ * compiler's, so it is the only part kept here — which also leaves the+ * discovery itself runnable, and testable, outside a browser.+ */+export async function workspacePreviewProducers(): Promise<readonly PreviewProducer[]> {+ return await discoverPreviewProducers({+ // Both, because a small module states its manifest in its entry rather than+ // in a file of its own — ProgramSpace is one, and a Producer that takes one+ // needs its schema to build a form.+ manifests: {+ ...import.meta.glob("../../../../packages/*/src/manifest.ts"),+ ...import.meta.glob("../../../../packages/*/src/index.ts"),+ },+ components: import.meta.glob("../../../../packages/*/src/component.ts"),+ });+}diff --git a/tools/playground/src/main.ts b/tools/playground/src/main.tsindex 03f7c865..629e3dee 100644--- a/tools/playground/src/main.ts+++ b/tools/playground/src/main.ts@@ -1,3 +1,3 @@import { mountShell } from "./ui/shell.js";-mountShell(document.querySelector<HTMLElement>("#app")!);+void mountShell(document.querySelector<HTMLElement>("#app")!);diff --git a/tools/playground/src/registry/broll.ts b/tools/playground/src/registry/broll.tsdeleted file mode 100644index 6b229ac6..00000000--- a/tools/playground/src/registry/broll.ts+++ /dev/null@@ -1,172 +0,0 @@-import { artifactRef } from "../preview/artifacts.js";-import { compileBrollProduct, programSpaceFrameCount, sealBrollProgram } from "../svml.js";-import type { BrollItem, BrollMotion, CanonicalValue } from "../svml.js";-import { fields, list, number, text } from "./types.js";-import type { PreviewComponent } from "./types.js";--/**- * The B-roll Recipe key set, copied from packages/broll/src/surface.ts.- * tools/playground-registry.test.mjs fails if the two ever diverge.- */-const RECIPE_KEYS = [- "background", "enter", "exit", "fit", "height",- "radius", "stack-order", "width", "x", "y",-] as const;--const OPERATORS = ["fade", "pop", "slide-up", "slide-down"] as const;--function numeric(properties: Readonly<Record<string, CanonicalValue>>, key: string): number {- const value = Number(properties[key]);- return Number.isFinite(value) ? value : 0;-}--/** SVS writes motion as `<operator> <frames>f`, e.g. `slide-up 8f`. */-function parseMotion(value: CanonicalValue | undefined): { operator: string; frames: number } {- const found = /^(fade|pop|slide-up|slide-down)\s+([1-9][0-9]*)f$/u.exec(String(value ?? "").trim());- return found === null- ? { operator: "fade", frames: 6 }- : { operator: found[1]!, frames: Number(found[2]) };-}--function motion(operator: string, frames: number): BrollMotion | undefined {- if (frames <= 0) return undefined;- return { operator: operator as BrollMotion["operator"], durationFrames: frames };-}--export const brollComponent: PreviewComponent = {- id: "broll",- label: "B-roll",- recipeKeys: RECIPE_KEYS,-- parameters: {- kind: "object",- fields: {- stackOrder: { schema: { kind: "number", integer: true, minimum: 0 } },- x: { schema: { kind: "number", minimum: 0, maximum: 1 } },- y: { schema: { kind: "number", minimum: 0, maximum: 1 } },- width: { schema: { kind: "number", minimum: 0, maximum: 1 } },- height: { schema: { kind: "number", minimum: 0, maximum: 1 } },- fit: { schema: { kind: "string", enum: ["contain", "cover"] } },- background: { schema: { kind: "string" } },- radius: { schema: { kind: "number", minimum: 0 } },- enterOperator: { schema: { kind: "string", enum: [...OPERATORS] } },- enterFrames: { schema: { kind: "number", integer: true, minimum: 0 } },- exitOperator: { schema: { kind: "string", enum: [...OPERATORS] } },- exitFrames: { schema: { kind: "number", integer: true, minimum: 0 } },- },- },-- content: {- kind: "object",- fields: {- items: {- schema: {- kind: "array",- minItems: 1,- items: {- kind: "object",- fields: {- media: { schema: { kind: "blob", mediaTypes: ["image/*", "video/*"] } },- startSec: { schema: { kind: "number", minimum: 0 } },- endSec: { schema: { kind: "number", minimum: 0 } },- },- },- },- },- },- },-- hints: {- background: "color",- x: "unit-fraction",- y: "unit-fraction",- width: "unit-fraction",- height: "unit-fraction",- },-- defaults: () => ({- parameters: {- stackOrder: 40,- x: 0.08, y: 0.2, width: 0.84, height: 0.48,- fit: "contain",- background: "#111116",- radius: 28,- enterOperator: "slide-up", enterFrames: 8,- exitOperator: "fade", exitFrames: 6,- },- content: {- items: [{ media: "", startSec: 0, endSec: 4 }],- },- }),-- fromRecipe: (properties) => {- const enter = parseMotion(properties["enter"]);- const exit = parseMotion(properties["exit"]);- return {- stackOrder: numeric(properties, "stack-order"),- x: numeric(properties, "x"),- y: numeric(properties, "y"),- width: numeric(properties, "width"),- height: numeric(properties, "height"),- fit: String(properties["fit"] ?? "contain"),- background: String(properties["background"] ?? "#00000000"),- radius: numeric(properties, "radius"),- enterOperator: enter.operator, enterFrames: enter.frames,- exitOperator: exit.operator, exitFrames: exit.frames,- };- },-- build: ({ parameters, content, programSpace }) => {- const p = fields(parameters);- const totalFrames = programSpaceFrameCount(programSpace);- const fps = programSpace.frameRate.numerator / programSpace.frameRate.denominator;- const enter = motion(text(p["enterOperator"], "enterOperator"), number(p["enterFrames"], "enterFrames"));- const exit = motion(text(p["exitOperator"], "exitOperator"), number(p["exitFrames"], "exitFrames"));-- const items: BrollItem[] = list(fields(content)["items"], "items").flatMap((entry, index) => {- const item = fields(entry);- const digest = item["media"];- const artifact = artifactRef(typeof digest === "string" && digest !== "" ? digest : undefined);- // An Item with no media yet is skipped rather than faked: compileBroll- // would reject a stub digest, and a stand-in would misreport the frame.- if (artifact === undefined) return [];- const startFrame = Math.max(0, Math.min(totalFrames - 1, Math.round(number(item["startSec"], "startSec") * fps)));- const endFrameExclusive = Math.max(- startFrame + 1,- Math.min(totalFrames, Math.round(number(item["endSec"], "endSec") * fps)),- );- const span = endFrameExclusive - startFrame;- return [{- id: `item-${index + 1}`,- artifact,- span: { startFrame, endFrameExclusive },- z: number(p["stackOrder"], "stackOrder"),- tieBreak: `broll:${index + 1}`,- box: {- xPercent: number(p["x"], "x") * 100,- yPercent: number(p["y"], "y") * 100,- widthPercent: number(p["width"], "width") * 100,- heightPercent: number(p["height"], "height") * 100,- },- fit: text(p["fit"], "fit") as "contain" | "cover",- // Not a choice: B-roll requires freeze for a still and forbids it for a- // moving one, so the media decides and a control would only offer a way- // to be wrong.- playback: artifact.mediaType.startsWith("image/") ? "freeze" : "native",- backgroundColor: text(p["background"], "background"),- borderRadiusPx: number(p["radius"], "radius"),- // Motion must fit inside the Present it decorates.- ...(enter !== undefined && enter.durationFrames < span ? { enter } : {}),- ...(exit !== undefined && exit.durationFrames < span ? { exit } : {}),- }];- });-- if (items.length === 0) return [];- return [compileBrollProduct(programSpace, sealBrollProgram({- contract: "svml.broll-program@1",- id: "broll",- items,- transitions: [],- })).visualTrack];- },-};diff --git a/tools/playground/src/registry/caption.ts b/tools/playground/src/registry/caption.tsdeleted file mode 100644index cf6188b0..00000000--- a/tools/playground/src/registry/caption.ts+++ /dev/null@@ -1,198 +0,0 @@-import {- renderCaptionTrack,- sealCaptionTrackProgram,-} from "../svml.js";-import type {- CanonicalValue,- CaptionPresentationMode,- TimedCaptionProjection,- TimedCaptionRegion,-} from "../svml.js";-import { fields, list, number, text } from "./types.js";-import type { PreviewComponent } from "./types.js";--/**- * The Caption Recipe key set, copied from packages/caption/src/surface.ts.- * tools/playground-registry.test.mjs fails if the two ever diverge.- */-const RECIPE_KEYS = [- "align", "background", "fill", "font", "line-height", "padding",- "radius", "size", "stack-order", "weight", "width", "x", "y",-] as const;--const MODES: readonly CaptionPresentationMode[] = ["whole", "proportional-word", "character-flow"];--/** SVS writes padding as "y" or "y x" — the y value comes first. */-function padding(value: CanonicalValue): { y: number; x: number } {- const parts = String(value).trim().split(/\s+/u).map(Number);- const y = parts[0];- if (y === undefined || !Number.isFinite(y)) return { y: 0, x: 0 };- const x = parts[1];- return { y, x: x !== undefined && Number.isFinite(x) ? x : y };-}--function numeric(properties: Readonly<Record<string, CanonicalValue>>, key: string): number {- const value = Number(properties[key]);- return Number.isFinite(value) ? value : 0;-}--export const captionComponent: PreviewComponent = {- id: "caption",- label: "Caption",- recipeKeys: RECIPE_KEYS,-- parameters: {- kind: "object",- fields: {- mode: { schema: { kind: "string", enum: [...MODES] } },- stackOrder: { schema: { kind: "number", integer: true, minimum: 0 } },- font: { schema: { kind: "string" } },- size: { schema: { kind: "number", minimum: 1 } },- weight: { schema: { kind: "number", integer: true, minimum: 100, maximum: 900 } },- lineHeight: { schema: { kind: "number", minimum: 0 } },- fill: { schema: { kind: "string" } },- background: { schema: { kind: "string" } },- paddingY: { schema: { kind: "number", minimum: 0 } },- paddingX: { schema: { kind: "number", minimum: 0 } },- radius: { schema: { kind: "number", minimum: 0 } },- align: { schema: { kind: "string", enum: ["left", "center", "right"] } },- x: { schema: { kind: "number", minimum: 0, maximum: 1 } },- y: { schema: { kind: "number", minimum: 0, maximum: 1 } },- width: { schema: { kind: "number", minimum: 0, maximum: 1 } },- },- },-- content: {- kind: "object",- fields: {- cues: {- schema: {- kind: "array",- minItems: 1,- items: {- kind: "object",- fields: {- text: { schema: { kind: "string" } },- startSec: { schema: { kind: "number", minimum: 0 } },- endSec: { schema: { kind: "number", minimum: 0 } },- },- },- },- },- },- },-- hints: {- fill: "color",- background: "color",- x: "unit-fraction",- y: "unit-fraction",- width: "unit-fraction",- "cues[].text": "multiline",- },-- defaults: () => ({- parameters: {- mode: "whole",- stackOrder: 70,- font: "Inter, system-ui, sans-serif",- size: 58,- weight: 600,- lineHeight: 1.25,- fill: "#ffffff",- background: "#000000cc",- paddingY: 14,- paddingX: 26,- radius: 18,- align: "center",- x: 0.08,- y: 0.76,- width: 0.84,- },- content: {- cues: [- { text: "This is the first caption cue.", startSec: 0, endSec: 1.8 },- { text: "And this one follows it.", startSec: 1.8, endSec: 4 },- ],- },- }),-- fromRecipe: (properties) => {- const pad = padding(properties["padding"] ?? "0");- return {- mode: "whole",- stackOrder: numeric(properties, "stack-order"),- font: String(properties["font"] ?? ""),- size: numeric(properties, "size"),- weight: numeric(properties, "weight"),- lineHeight: numeric(properties, "line-height"),- fill: String(properties["fill"] ?? "#ffffff"),- background: String(properties["background"] ?? "#00000000"),- paddingY: pad.y,- paddingX: pad.x,- radius: numeric(properties, "radius"),- align: String(properties["align"] ?? "center"),- x: numeric(properties, "x"),- y: numeric(properties, "y"),- width: numeric(properties, "width"),- };- },-- build: ({ parameters, content, programSpace }) => {- const p = fields(parameters);- const mode = text(p["mode"], "mode") as CaptionPresentationMode;-- // The compiler's own conversion, from packages/caption/src/surface.ts:- // SVS geometry is a 0–1 fraction and the style carries percentages.- const program = sealCaptionTrackProgram({- contract: "svml.caption-track-program@1",- id: "caption",- mode,- stacking: { order: number(p["stackOrder"], "stackOrder"), tieBreak: "caption" },- style: {- fontFamily: text(p["font"], "font"),- fontSizePx: number(p["size"], "size"),- fontWeight: number(p["weight"], "weight"),- color: text(p["fill"], "fill"),- backgroundColor: text(p["background"], "background"),- paddingXPx: number(p["paddingX"], "paddingX"),- paddingYPx: number(p["paddingY"], "paddingY"),- borderRadiusPx: number(p["radius"], "radius"),- bottomPercent: 0,- maxWidthPercent: number(p["width"], "width") * 100,- leftPercent: number(p["x"], "x") * 100,- topPercent: number(p["y"], "y") * 100,- widthPercent: number(p["width"], "width") * 100,- lineHeight: number(p["lineHeight"], "lineHeight"),- textAlign: text(p["align"], "align") as "left" | "center" | "right",- },- });-- // A projection the playground synthesises. planCaptionPresentation reads- // only display text and timing, so an empty token list and no refinements- // are honest here rather than a stub: every mode, including- // proportional-word, distributes time the same way it does without- // alignment refinements in a real Build.- const cues = list(fields(content)["cues"], "cues");- const regions: TimedCaptionRegion[] = cues.map((cue, index) => {- const item = fields(cue);- return {- id: `cue-${index + 1}`,- display: text(item["text"], "cue text"),- segmentId: "playground",- kind: "identity",- sourceTokenIds: [],- startSec: number(item["startSec"], "startSec"),- endSec: number(item["endSec"], "endSec"),- refinements: [],- };- });- const projection: TimedCaptionProjection = {- contract: "svml.timed-caption-projection@1",- text: regions.map((region) => region.display).join(" "),- regions,- };-- return [renderCaptionTrack(projection, program, programSpace)];- },-};diff --git a/tools/playground/src/registry/index.ts b/tools/playground/src/registry/index.tsdeleted file mode 100644index 4606bb89..00000000--- a/tools/playground/src/registry/index.ts+++ /dev/null@@ -1,40 +0,0 @@-import type { CanonicalValue } from "../svml.js";-import { brollComponent } from "./broll.js";-import { captionComponent } from "./caption.js";-import { speechComponent } from "./speech.js";-import { textTrackComponent } from "./text-track.js";-import type { PreviewComponent } from "./types.js";--export type { BuildInput, FieldHint, PreviewComponent } from "./types.js";--/** Every component that puts pixels on the frame. */-export const REGISTRY: readonly PreviewComponent[] = [- captionComponent,- textTrackComponent,- brollComponent,- speechComponent,-];--export function componentById(id: string): PreviewComponent | undefined {- return REGISTRY.find((component) => component.id === id);-}--/** Joined on a separator no CSS-like property name can contain. */-function keySet(names: readonly string[]): string {- return [...names].sort().join("\u0000");-}--/**- * Finds the component a Recipe describes.- *- * By exact property key set, which is what every Surface handler in the- * compiler matches on. A Recipe's dotted path is a label: `caption.dialogue`- * and `caption.short-cues` share a prefix and describe unrelated things.- */-export function matchRecipe(- properties: Readonly<Record<string, CanonicalValue>>,-): PreviewComponent | undefined {- const wanted = keySet(Object.keys(properties));- return REGISTRY.find((component) =>- component.recipeKeys !== undefined && keySet(component.recipeKeys) === wanted);-}diff --git a/tools/playground/src/registry/speech.ts b/tools/playground/src/registry/speech.tsdeleted file mode 100644index dcc072ac..00000000--- a/tools/playground/src/registry/speech.ts+++ /dev/null@@ -1,89 +0,0 @@-import { artifactRef } from "../preview/artifacts.js";-import { projectSpeechVisual } from "../svml.js";-import type { MediaArtifactRef, SpeechBasis } from "../svml.js";-import { fields, list, number } from "./types.js";-import type { PreviewComponent } from "./types.js";--/**- * The speaker's own footage, full bleed.- *- * `projectSpeechVisual` takes no appearance at all — it always emits a- * full-frame `object-fit: cover` element at stacking order 0. So this component- * has clips and nothing else, which is the honest shape: `speech.full` exists in- * the golden stylesheet but no Surface reads it, and inventing knobs here would- * imply a control the compiler does not have.- */-export const speechComponent: PreviewComponent = {- id: "speech",- label: "Speaker footage",-- parameters: { kind: "object", fields: {} },-- content: {- kind: "object",- fields: {- clips: {- schema: {- kind: "array",- minItems: 1,- items: {- kind: "object",- fields: {- media: { schema: { kind: "blob", mediaTypes: ["image/*", "video/*"] } },- startSec: { schema: { kind: "number", minimum: 0 } },- endSec: { schema: { kind: "number", minimum: 0 } },- },- },- },- },- },- },-- defaults: () => ({- parameters: {},- content: { clips: [{ media: "", startSec: 0, endSec: 4 }] },- }),-- build: ({ content, programSpace }) => {- type Clip = SpeechBasis["visualTrack"]["clips"][number];- const clips: Clip[] = list(fields(content)["clips"], "clips").flatMap((entry, index): Clip[] => {- const clip = fields(entry);- const digest = clip["media"];- const artifact = artifactRef(typeof digest === "string" && digest !== "" ? digest : undefined);- // A clip with no media yet contributes nothing rather than a stub digest,- // which projectSpeechVisual would reject.- if (artifact === undefined) return [];- const startSec = number(clip["startSec"], "startSec");- const endSec = Math.min(- programSpace.durationSec,- Math.max(startSec + 1 / 30, number(clip["endSec"], "endSec")),- );- // Indexed by position, not by how many survived: two clips must never- // share a segment id, or their Presents collide.- return [{ segmentId: `segment-${index + 1}`, artifact, startSec, endSec }];- });- if (clips.length === 0) return [];-- // assertSpeechBasisIdentity requires an audio Artifact whose duration equals- // the ProgramSpace's. projectSpeechVisual never reads it — only the visual- // clips and the segments — so the first clip's own digest stands in at the- // program's duration rather than a fabricated one.- const audio: MediaArtifactRef = {- ...clips[0]!.artifact,- durationSec: programSpace.durationSec,- };-- const basis: SpeechBasis = {- contract: "svml.speech-basis@1",- programSpace,- audio,- visualTrack: { clips },- segments: clips.map((clip) => ({- segmentId: clip.segmentId,- startSec: clip.startSec,- endSec: clip.endSec,- })),- };- return [projectSpeechVisual(basis)];- },-};diff --git a/tools/playground/src/registry/text-track.ts b/tools/playground/src/registry/text-track.tsdeleted file mode 100644index 133f6959..00000000--- a/tools/playground/src/registry/text-track.ts+++ /dev/null@@ -1,147 +0,0 @@-import { programSpaceFrameCount, renderTextTrack, sealTextTrackProgram } from "../svml.js";-import type { CanonicalValue, TextItem } from "../svml.js";-import { fields, list, number, text } from "./types.js";-import type { PreviewComponent } from "./types.js";--/**- * The Text Recipe key set, copied from packages/text-track/src/surface.ts.- * tools/playground-registry.test.mjs fails if the two ever diverge.- */-const RECIPE_KEYS = [- "align", "fill", "font", "height", "size",- "stack-order", "tracking", "weight", "width", "x", "y",-] as const;--function numeric(properties: Readonly<Record<string, CanonicalValue>>, key: string): number {- const value = Number(properties[key]);- return Number.isFinite(value) ? value : 0;-}--export const textTrackComponent: PreviewComponent = {- id: "text-track",- label: "Text overlay",- recipeKeys: RECIPE_KEYS,-- parameters: {- kind: "object",- fields: {- stackOrder: { schema: { kind: "number", integer: true, minimum: 0 } },- font: { schema: { kind: "string" } },- size: { schema: { kind: "number", minimum: 1 } },- weight: { schema: { kind: "number", integer: true, minimum: 100, maximum: 900 } },- tracking: { schema: { kind: "number" } },- fill: { schema: { kind: "string" } },- align: { schema: { kind: "string", enum: ["left", "center", "right"] } },- x: { schema: { kind: "number", minimum: 0, maximum: 1 } },- y: { schema: { kind: "number", minimum: 0, maximum: 1 } },- width: { schema: { kind: "number", minimum: 0, maximum: 1 } },- height: { schema: { kind: "number", minimum: 0, maximum: 1 } },- },- },-- content: {- kind: "object",- fields: {- items: {- schema: {- kind: "array",- minItems: 1,- items: {- kind: "object",- fields: {- text: { schema: { kind: "string" } },- startSec: { schema: { kind: "number", minimum: 0 } },- endSec: { schema: { kind: "number", minimum: 0 } },- },- },- },- },- },- },-- hints: {- fill: "color",- x: "unit-fraction",- y: "unit-fraction",- width: "unit-fraction",- height: "unit-fraction",- "items[].text": "multiline",- },-- defaults: () => ({- parameters: {- stackOrder: 90,- font: "Inter, system-ui, sans-serif",- size: 96,- weight: 800,- tracking: -2,- fill: "#ffffff",- align: "left",- x: 0.08,- y: 0.12,- width: 0.84,- height: 0.2,- },- content: {- items: [{ text: "A title card", startSec: 0, endSec: 4 }],- },- }),-- fromRecipe: (properties) => ({- stackOrder: numeric(properties, "stack-order"),- font: String(properties["font"] ?? ""),- size: numeric(properties, "size"),- weight: numeric(properties, "weight"),- tracking: numeric(properties, "tracking"),- fill: String(properties["fill"] ?? "#ffffff"),- align: String(properties["align"] ?? "left"),- x: numeric(properties, "x"),- y: numeric(properties, "y"),- width: numeric(properties, "width"),- height: numeric(properties, "height"),- }),-- build: ({ parameters, content, programSpace }) => {- const p = fields(parameters);- const totalFrames = programSpaceFrameCount(programSpace);- const fps = programSpace.frameRate.numerator / programSpace.frameRate.denominator;-- const items: TextItem[] = list(fields(content)["items"], "items").map((entry, index) => {- const item = fields(entry);- const startFrame = Math.max(0, Math.min(totalFrames - 1, Math.round(number(item["startSec"], "startSec") * fps)));- // assertTextTrackProgramIdentity requires every span inside the program- // space, so shortening the duration must clamp rather than throw.- const endFrameExclusive = Math.max(- startFrame + 1,- Math.min(totalFrames, Math.round(number(item["endSec"], "endSec") * fps)),- );- return {- id: `item-${index + 1}`,- text: text(item["text"], "item text"),- span: { startFrame, endFrameExclusive },- z: number(p["stackOrder"], "stackOrder"),- tieBreak: `text:${index + 1}`,- box: {- xPercent: number(p["x"], "x") * 100,- yPercent: number(p["y"], "y") * 100,- widthPercent: number(p["width"], "width") * 100,- heightPercent: number(p["height"], "height") * 100,- },- appearance: {- color: text(p["fill"], "fill"),- fontSizePx: number(p["size"], "size"),- fontFamily: text(p["font"], "font"),- fontWeight: number(p["weight"], "weight"),- letterSpacingPx: number(p["tracking"], "tracking"),- align: text(p["align"], "align") as "left" | "center" | "right",- },- };- });-- return [renderTextTrack(programSpace, sealTextTrackProgram({- contract: "svml.text-track-program@1",- id: "text",- items,- }))];- },-};diff --git a/tools/playground/src/registry/types.ts b/tools/playground/src/registry/types.tsdeleted file mode 100644index d61c4b1f..00000000--- a/tools/playground/src/registry/types.ts+++ /dev/null@@ -1,71 +0,0 @@-import type { CanonicalValue, ProgramSpace, Track, ValueSchema } from "../svml.js";--/**- * What a control needs to know that `ValueSchema` cannot say.- *- * `ValueSchema` describes what a value *is*, not how it should be typed in. SVS- * geometry is normalized 0–1, which a slider edits far better than a number box,- * and colours may carry alpha, which `<input type=color>` cannot express.- */-export type FieldHint = "color" | "multiline" | "unit-fraction";--export type BuildInput = {- readonly parameters: CanonicalValue;- readonly content: CanonicalValue;- readonly programSpace: ProgramSpace;- readonly canvas: { readonly width: number; readonly height: number };-};--/**- * One previewable component.- *- * `build` returns Tracks rather than a Composition: the shell owns the canvas,- * the ProgramSpace and the seal, so adding a component is one file and one entry- * in the registry array. Everything a component states about itself — its- * parameters, its sample content, how a Recipe fills it in — lives here, and the- * form is generated from it rather than written per component.- */-export type PreviewComponent = {- readonly id: string;- readonly label: string;- /**- * The exact SVS property key set this component's Recipe carries. Absent means- * the component is not discoverable from a stylesheet. Matching is by key set- * because that is what the compiler itself matches on — a Recipe's dotted path- * is a label, and `caption.dialogue` and `caption.short-cues` are different- * shapes under one prefix.- */- readonly recipeKeys?: readonly string[];- readonly parameters: ValueSchema;- readonly content: ValueSchema;- readonly hints?: Readonly<Record<string, FieldHint>>;- readonly defaults: () => { parameters: CanonicalValue; content: CanonicalValue };- /** Fills the parameter form from a Recipe. The form stays the source of truth. */- readonly fromRecipe?: (properties: Readonly<Record<string, CanonicalValue>>) => CanonicalValue;- readonly build: (input: BuildInput) => readonly Track[];-};--/** Narrows a form value to the object every component's parameters and content are. */-export function fields(value: CanonicalValue): Readonly<Record<string, CanonicalValue>> {- if (value === null || typeof value !== "object" || Array.isArray(value)) {- throw new Error("Expected an object of fields.");- }- return value as Readonly<Record<string, CanonicalValue>>;-}--export function text(value: CanonicalValue | undefined, name: string): string {- if (typeof value !== "string") throw new Error(`${name} must be a string.`);- return value;-}--export function number(value: CanonicalValue | undefined, name: string): number {- if (typeof value !== "number" || !Number.isFinite(value)) {- throw new Error(`${name} must be a number.`);- }- return value;-}--export function list(value: CanonicalValue | undefined, name: string): readonly CanonicalValue[] {- if (!Array.isArray(value)) throw new Error(`${name} must be a list.`);- return value;-}diff --git a/tools/playground/src/svml.ts b/tools/playground/src/svml.tsindex 17e08e05..b9ecf831 100644--- a/tools/playground/src/svml.ts+++ b/tools/playground/src/svml.ts@@ -7,8 +7,9 @@* 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.+ * Only the render path is named here. Components are not: they are discovered+ * from the manifests at run time, and a list of them in this file would be the+ * very coupling the discovery exists to avoid.*/export {@@ -18,52 +19,32 @@ export {} 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 { sealComposition } from "@narratage/composition";+export type { Composition, Track, VisualTrack } from "@narratage/composition";-export { programSpaceFrameCount, sealProgramSpace } from "@narratage/program-space";+export {+ defaultProgramSpace,+ programSpaceFrameCount,+ sealProgramSpace,+} from "@narratage/program-space";export type { ProgramSpace } from "@narratage/program-space";-export type { CanonicalValue, ValueSchema } from "@narratage/protocol";+export { validateStoredValue } from "@narratage/core";-// Component lowering. These are the real renderers the compiler runs, so what-// the playground shows is the production visual result and not a lookalike.-export {- renderCaptionTrack,- sealCaptionTrackProgram,-} from "@narratage/caption";export type {- CaptionPresentationMode,- CaptionTrackProgram,- TimedCaptionProjection,- TimedCaptionRegion,-} from "@narratage/caption";+ CanonicalValue,+ ModuleManifest,+ ProducerDeclaration,+ TypeRef,+ ValueFormat,+ ValueSchema,+} from "@narratage/protocol";-export { renderTextTrack, sealTextTrackProgram } from "@narratage/text-track";-export type { TextItem, TextTrackProgram } from "@narratage/text-track";+export type { MediaArtifactRef } from "@narratage/media";+// Stylesheets are read to fill a form, never to decide what a component is.export { parseSvs } from "@narratage/svs";-export type { ParsedSvsSheet, SvsRecipe } from "@narratage/svs";-+export type { SvsRecipe } from "@narratage/svs";export { maskSourceHeader, parseSourceHeader } from "@narratage/source";-export type { SourceHeader } from "@narratage/source";--export type { MediaArtifactRef } from "@narratage/media";--export { compileBrollProduct, sealBrollProgram } from "@narratage/broll";-export type { BrollItem, BrollMotion, BrollProgram } from "@narratage/broll";-export { projectSpeechVisual } from "@narratage/speech-basis";-export type { SpeechBasis } from "@narratage/speech";+export { defaultFilmProgram, filmCanvasFromRecipe, filmRecipeKeys } from "@narratage/film";diff --git a/tools/playground/src/svs/discover.ts b/tools/playground/src/svs/discover.tsdeleted file mode 100644index 25ee4495..00000000--- a/tools/playground/src/svs/discover.ts+++ /dev/null@@ -1,100 +0,0 @@-import { matchRecipe } from "../registry/index.js";-import type { PreviewComponent } from "../registry/index.js";-import { maskSourceHeader, parseSourceHeader, parseSvs } from "../svml.js";-import type { CanonicalValue } from "../svml.js";--/** The Film Recipe key set, from packages/film/src/surface.ts. */-const FILM_KEYS = ["background", "frame-rate", "height", "width"];--export type CanvasOffer = {- readonly path: string;- readonly width: number;- readonly height: number;- readonly fps: number;- readonly clearColor: string;-};--export type PreviewSubject = {- readonly key: string;- readonly path: string;- readonly component: PreviewComponent;- readonly parameters: CanonicalValue;- readonly content: CanonicalValue;-};--export type Discovery = {- readonly sheetId: string | undefined;- readonly subjects: readonly PreviewSubject[];- /** Film Recipes are not previewable; they say how big the frame is. */- readonly canvases: readonly CanvasOffer[];- /** Everything else, named so the gaps are visible rather than silent. */- readonly unmatched: readonly { readonly path: string; readonly keys: readonly string[] }[];-};--function keySet(names: readonly string[]): string {- return [...names].sort().join("\u0000");-}--function numberOf(value: CanonicalValue | undefined, fallback: number): number {- const parsed = Number(value);- return Number.isFinite(parsed) ? parsed : fallback;-}--/**- * Reads a stylesheet as a list of things to preview.- *- * A sheet is a discovery source, never a dependency: what it produces is form- * values, and from that point the form is the only source of truth. An- * unmatched Recipe is reported rather than dropped — `font.*` and- * `caption.short-cues` are real Recipes the playground simply cannot draw, and- * saying so is more useful than showing nothing.- */-export function discover(name: string, source: string): Discovery {- // The Source Header is mandatory and is not the sheet. Masking it rather than- // slicing it is what the compiler does: every offset a Recipe reports still- // points at the right place in the file the author is looking at.- const header = parseSourceHeader(name, source);- if (!header.using.startsWith("@narratage/svs@")) {- throw new Error(`${name} is a ${header.using} source, not a stylesheet.`);- }- const sheet = parseSvs(name, maskSourceHeader(source, header));- const subjects: PreviewSubject[] = [];- const canvases: CanvasOffer[] = [];- const unmatched: { path: string; keys: readonly string[] }[] = [];-- for (const [index, parsed] of sheet.recipes.entries()) {- const recipe = parsed.value;- const keys = Object.keys(recipe.properties);-- if (keySet(keys) === keySet(FILM_KEYS)) {- canvases.push({- path: recipe.path,- width: numberOf(recipe.properties["width"], 1080),- height: numberOf(recipe.properties["height"], 1920),- fps: numberOf(recipe.properties["frame-rate"], 30),- clearColor: String(recipe.properties["background"] ?? "#000000"),- });- continue;- }-- const component = matchRecipe(recipe.properties);- if (component === undefined || component.fromRecipe === undefined) {- unmatched.push({ path: recipe.path, keys: [...keys].sort() });- continue;- }- subjects.push({- key: `${index}:${recipe.path}`,- path: recipe.path,- component,- parameters: component.fromRecipe(recipe.properties),- content: component.defaults().content,- });- }-- return {- ...(sheet.id === undefined ? { sheetId: undefined } : { sheetId: sheet.id }),- subjects,- canvases,- unmatched,- };-}diff --git a/tools/playground/src/ui/form.ts b/tools/playground/src/ui/form.tsindex 31a28f75..22ab9dfc 100644--- a/tools/playground/src/ui/form.ts+++ b/tools/playground/src/ui/form.ts@@ -1,10 +1,9 @@import { artifactLabel, registerFile } from "../preview/artifacts.js";import type { CanonicalValue, ValueSchema } from "../svml.js";-import type { FieldHint } from "../registry/index.js";export const FORM_CSS = `.form { display: flex; flex-direction: column; gap: 2px; }-.form-row { display: grid; grid-template-columns: 96px 1fr; gap: 8px; align-items: center; padding: 3px 0; }+.form-row { display: grid; grid-template-columns: 108px 1fr; gap: 8px; align-items: center; padding: 3px 0; }.form-row > label { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; }.form-control { display: flex; gap: 6px; align-items: center; min-width: 0; }.form-control input[type=text], .form-control input[type=number], .form-control select, .form-control textarea {@@ -15,7 +14,7 @@ export const FORM_CSS = `.form-control input[type=range] { flex: 1; min-width: 0; accent-color: var(--accent); }.form-control input[type=color] { width: 28px; height: 24px; padding: 0; border: 1px solid var(--line); background: none; border-radius: 4px; }.form-control .narrow { flex: 0 0 68px; }-.form-control .form-file { flex: 0 0 auto; font-size: 11px; color: var(--muted); max-width: 130px; }+.form-control .form-file { flex: 0 0 auto; font-size: 11px; color: var(--muted); max-width: 118px; }.form-control .form-file::file-selector-button {border: 1px solid var(--line); border-radius: 5px; background: #1c1c21;color: var(--text); font: inherit; font-size: 11px; padding: 2px 7px; margin-right: 6px; cursor: pointer;@@ -32,16 +31,17 @@ export const FORM_CSS = `}.form-actions button:hover:not(:disabled) { border-color: #3a3a42; }.form-actions button:disabled { opacity: .4; cursor: default; }+.form-fixed { color: var(--muted); font-size: 12px; font-family: ui-monospace, monospace; }`;type Emit = () => void;-function row(label: string, control: HTMLElement): HTMLElement {+function row(name: string, control: HTMLElement): HTMLElement {const element = document.createElement("div");element.className = "form-row";const caption = document.createElement("label");- caption.textContent = label;- caption.title = label;+ caption.textContent = name;+ caption.title = name;const holder = document.createElement("div");holder.className = "form-control";holder.append(control);@@ -49,7 +49,12 @@ function row(label: string, control: HTMLElement): HTMLElement {return element;}-/** `#RRGGBB` or `#RRGGBBAA`; `<input type=color>` can only carry the first six. */+/**+ * A colour, edited as text with a swatch beside it.+ *+ * The text is authoritative: `format: "color"` admits `#RRGGBBAA` and+ * `<input type=color>` cannot carry the alpha byte.+ */function colorControl(value: string, onChange: (next: string) => void): HTMLElement {const holder = document.createElement("div");holder.className = "form-control";@@ -59,7 +64,6 @@ function colorControl(value: string, onChange: (next: string) => void): HTMLElemconst exact = document.createElement("input");exact.type = "text";exact.value = value;- // The text box is the source of truth: alpha survives only there.swatch.addEventListener("input", () => {const alpha = exact.value.length === 9 ? exact.value.slice(7) : "";exact.value = swatch.value + alpha;@@ -97,38 +101,82 @@ function fractionControl(return holder;}+/**+ * Media, addressed by digest.+ *+ * A `format: "digest"` field is content-addressed, so the control produces one+ * by hashing the chosen file. The form value stays the digest; the bytes live+ * in the Artifact registry.+ */+function digestControl(+ current: CanonicalValue | undefined,+ onChange: (next: CanonicalValue) => void,+): HTMLElement {+ const holder = document.createElement("div");+ holder.className = "form-control";+ const picker = document.createElement("input");+ picker.type = "file";+ picker.className = "form-file";+ const label = document.createElement("span");+ label.className = "form-file-label";+ label.textContent = artifactLabel(typeof current === "string" && current !== "" ? current : undefined);+ picker.addEventListener("change", () => {+ const file = picker.files?.[0];+ if (file === undefined) return;+ label.textContent = "hashing…";+ void registerFile(file).then((ref) => {+ label.textContent = artifactLabel(ref.digest);+ onChange(ref.digest);+ }).catch((error: unknown) => {+ label.textContent = error instanceof Error ? error.message : String(error);+ });+ });+ holder.append(picker, label);+ return holder;+}+/*** Builds controls from a ValueSchema.*- * Nothing here validates. The schema shapes and coerces the input; the packages'- * own seal and assert functions decide whether a value is legal, because they- * are what a real Build would run and their messages are already good. A form- * that pre-judged would only disagree with them.+ * Every choice here comes from the schema: `enum` becomes a list, `format`+ * decides between a colour, a slider, a prose box and a file, bounds become+ * limits. Nothing is keyed on a field's name, so a module that declares a new+ * field gets a usable control without this file knowing it exists.+ *+ * Nothing here validates. `validateStoredValue` and the packages' own assert+ * functions are the judge — they are what a real Build runs.*/export function buildForm(schema: ValueSchema,value: CanonicalValue,- hints: Readonly<Record<string, FieldHint>>,emit: Emit,- path = "",): HTMLElement {const container = document.createElement("div");container.className = "form";-if (schema.kind !== "object") {- container.textContent = "Unsupported top-level schema.";+ container.append(row("value", scalarControl(schema, value, (next) => {+ // A non-object input is replaced wholesale by its caller.+ (emit as Emit & { replace?: (v: CanonicalValue) => void }).replace?.(next);+ emit();+ })));return container;}const bag = value as Record<string, CanonicalValue>;-for (const [name, field] of Object.entries(schema.fields)) {- const here = path ? `${path}.${name}` : name;- const hint = hints[here] ?? hints[name];const current = bag[name];+ if (field.schema.kind === "literal") {+ // A literal is the contract tag: shown so the shape is legible, never+ // offered, because changing it would only ever be wrong.+ const fixed = document.createElement("span");+ fixed.className = "form-fixed";+ fixed.textContent = String(field.schema.value);+ container.append(row(name, fixed));+ continue;+ }if (field.schema.kind === "array") {- container.append(arrayGroup(name, here, field.schema, bag, hints, emit));+ container.append(arrayGroup(name, field.schema, bag, emit));continue;}if (field.schema.kind === "object") {@@ -136,11 +184,12 @@ export function buildForm(group.className = "form-group";const legend = document.createElement("legend");legend.textContent = name;- group.append(legend, buildForm(field.schema, current ?? {}, hints, emit, here));+ if (bag[name] === undefined) bag[name] = {};+ group.append(legend, buildForm(field.schema, bag[name], emit));container.append(group);continue;}- container.append(row(name, scalarControl(field.schema, current, hint, (next) => {+ container.append(row(name, scalarControl(field.schema, current, (next) => {bag[name] = next;emit();})));@@ -151,7 +200,6 @@ export function buildForm(function scalarControl(schema: ValueSchema,current: CanonicalValue | undefined,- hint: FieldHint | undefined,onChange: (next: CanonicalValue) => void,): HTMLElement {if (schema.kind === "boolean") {@@ -163,7 +211,7 @@ function scalarControl(}if (schema.kind === "number") {- if (hint === "unit-fraction") {+ if (schema.format === "unit-fraction") {return fractionControl(typeof current === "number" ? current : 0, schema, onChange);}const input = document.createElement("input");@@ -171,7 +219,7 @@ function scalarControl(if (schema.minimum !== undefined) input.min = String(schema.minimum);if (schema.maximum !== undefined) input.max = String(schema.maximum);input.step = schema.integer === true ? "1" : "any";- input.value = String(typeof current === "number" ? current : 0);+ input.value = String(typeof current === "number" ? current : schema.minimum ?? 0);input.addEventListener("input", () => {if (input.value !== "") onChange(Number(input.value));});@@ -191,10 +239,11 @@ function scalarControl(select.addEventListener("input", () => onChange(select.value));return select;}- if (hint === "color") {+ if (schema.format === "color") {return colorControl(typeof current === "string" ? current : "#ffffff", onChange);}- if (hint === "multiline") {+ if (schema.format === "digest") return digestControl(current, onChange);+ if (schema.format === "multiline") {const area = document.createElement("textarea");area.value = typeof current === "string" ? current : "";area.addEventListener("input", () => onChange(area.value));@@ -207,68 +256,31 @@ function scalarControl(return input;}- if (schema.kind === "blob") return blobControl(current, schema.mediaTypes, onChange);-const unsupported = document.createElement("span");+ unsupported.className = "form-fixed";unsupported.textContent = `(${schema.kind})`;return unsupported;}-/**- * Media picker.- *- * The form value is the digest, and the bytes stay in the Artifact registry, so- * a component's parameters remain a plain canonical value that a test can build- * without a browser.- */-function blobControl(- current: CanonicalValue | undefined,- mediaTypes: readonly string[] | undefined,- onChange: (next: CanonicalValue) => void,-): HTMLElement {- const holder = document.createElement("div");- holder.className = "form-control";- const picker = document.createElement("input");- picker.type = "file";- picker.className = "form-file";- if (mediaTypes !== undefined) picker.accept = mediaTypes.join(",");- const label = document.createElement("span");- label.className = "form-file-label";- label.textContent = artifactLabel(typeof current === "string" && current !== "" ? current : undefined);- picker.addEventListener("change", () => {- const file = picker.files?.[0];- if (file === undefined) return;- label.textContent = "hashing…";- void registerFile(file).then((ref) => {- label.textContent = artifactLabel(ref.digest);- onChange(ref.digest);- }).catch((error: unknown) => {- label.textContent = error instanceof Error ? error.message : String(error);- });- });- holder.append(picker, label);- return holder;-}--function blank(schema: ValueSchema): CanonicalValue {+export function blankValue(schema: ValueSchema): CanonicalValue {if (schema.kind === "object") {return Object.fromEntries(Object.entries(schema.fields).filter(([, field]) => field.optional !== true)- .map(([name, field]) => [name, blank(field.schema)]));+ .map(([name, field]) => [name, blankValue(field.schema)]));}+ if (schema.kind === "literal") return schema.value;if (schema.kind === "array") return [];if (schema.kind === "number") return schema.minimum ?? 0;if (schema.kind === "string") return schema.enum?.[0] ?? "";if (schema.kind === "boolean") return false;+ if (schema.kind === "oneOf") return blankValue(schema.variants[0] ?? { kind: "null" });return null;}function arrayGroup(name: string,- path: string,schema: ValueSchema & { kind: "array" },bag: Record<string, CanonicalValue>,- hints: Readonly<Record<string, FieldHint>>,emit: Emit,): HTMLElement {const group = document.createElement("fieldset");@@ -282,23 +294,16 @@ function arrayGroup(const minItems = schema.minItems ?? 0;const rebuild = (): void => {- // Adding or removing an entry changes the control tree, so this subtree is- // rebuilt rather than patched. Scalar edits never come through here.- const replacement = arrayGroup(name, path, schema, bag, hints, emit);- group.replaceWith(replacement);+ // Adding or removing changes the control tree, so this subtree is rebuilt.+ // Scalar edits never come through here.+ group.replaceWith(arrayGroup(name, schema, bag, emit));emit();};entries.forEach((entry, index) => {const item = document.createElement("div");item.className = "form-item";- item.append(buildForm(- schema.items,- entry,- hints,- emit,- `${path}[]`,- ));+ item.append(buildForm(schema.items, entry, emit));const actions = document.createElement("div");actions.className = "form-actions";const remove = document.createElement("button");@@ -316,7 +321,7 @@ function arrayGroup(const add = document.createElement("button");add.type = "button";add.textContent = "Add";- add.addEventListener("click", () => { entries.push(blank(schema.items)); rebuild(); });+ add.addEventListener("click", () => { entries.push(blankValue(schema.items)); rebuild(); });actions.append(add);group.append(actions);return group;diff --git a/tools/playground/src/ui/gallery.ts b/tools/playground/src/ui/gallery.tsdeleted file mode 100644index 5c304662..00000000--- a/tools/playground/src/ui/gallery.ts+++ /dev/null@@ -1,138 +0,0 @@-import { renderPreview } from "../preview/render.js";-import type { PreviewSubject } from "../svs/discover.js";-import { sealProgramSpace } from "../svml.js";--export const GALLERY_CSS = `-.gallery { flex: 1; min-width: 0; overflow-y: auto; background: #0d0d10; padding: 18px; }-.gallery-grid { display: flex; flex-wrap: wrap; gap: 18px; align-content: flex-start; }-.tile { display: flex; flex-direction: column; gap: 7px; cursor: pointer; }-.tile-frame {- position: relative; overflow: hidden; background: #000;- box-shadow: 0 0 0 1px var(--line); border-radius: 3px;-}-.tile:hover .tile-frame { box-shadow: 0 0 0 1px var(--accent); }-.tile-frame iframe { position: absolute; top: 0; left: 0; border: 0; transform-origin: top left; }-.tile-name { font-size: 12px; font-family: ui-monospace, monospace; }-.tile-kind { font-size: 11px; color: var(--muted); }-.tile-error {- position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;- padding: 10px; color: var(--danger); font-size: 11px; text-align: center;- font-family: ui-monospace, monospace; background: #2a1416;-}-.gallery-note { color: var(--muted); font-size: 12px; margin: 22px 0 7px; }-.gallery-unmatched { display: flex; flex-direction: column; gap: 3px; }-.gallery-unmatched code { font-size: 11px; color: var(--muted); font-family: ui-monospace, monospace; }-.gallery-unmatched b { color: var(--text); font-weight: 500; }-`;--const TILE_WIDTH = 250;--export type GalleryInput = {- readonly subjects: readonly PreviewSubject[];- readonly unmatched: readonly { readonly path: string; readonly keys: readonly string[] }[];- readonly canvas: { readonly width: number; readonly height: number; readonly clearColor: string };- readonly fps: number;- readonly durationSec: number;- readonly onFocus: (subject: PreviewSubject) => void;-};--/**- * Every Recipe in a sheet, previewed side by side.- *- * Each tile is an independent document at composition scale, shrunk by- * transform. Tiles hold one representative frame rather than a scrubber: the- * gallery answers "what is in this stylesheet", and a Recipe you want to work- * on gets focused into the single stage.- */-export function renderGallery(input: GalleryInput): HTMLElement {- const element = document.createElement("div");- element.className = "gallery";- const grid = document.createElement("div");- grid.className = "gallery-grid";- element.append(grid);-- const scale = TILE_WIDTH / input.canvas.width;- const height = Math.round(input.canvas.height * scale);-- for (const subject of input.subjects) {- const tile = document.createElement("div");- tile.className = "tile";- const frame = document.createElement("div");- frame.className = "tile-frame";- frame.style.width = `${TILE_WIDTH}px`;- frame.style.height = `${height}px`;-- try {- const programSpace = sealProgramSpace({- contract: "svml.program-space@1",- durationSec: input.durationSec,- frameRate: { numerator: input.fps, denominator: 1 },- });- const preview = renderPreview({- id: subject.component.id,- canvas: input.canvas,- programSpace,- tracks: subject.component.build({- parameters: subject.parameters,- content: subject.content,- programSpace,- canvas: input.canvas,- }),- });- const view = document.createElement("iframe");- view.title = subject.path;- view.style.width = `${input.canvas.width}px`;- view.style.height = `${input.canvas.height}px`;- view.style.transform = `scale(${scale})`;- view.srcdoc = preview.srcdoc;- // A third of the way in shows a Present that has settled rather than one- // still animating in from nothing.- const at = Math.floor(preview.frameCount / 3);- view.addEventListener("load", () => {- (view.contentWindow as { __svmlSeekFrame?: (frame: number) => void } | null)- ?.__svmlSeekFrame?.(at);- });- frame.append(view);- } catch (error) {- const failed = document.createElement("div");- failed.className = "tile-error";- failed.textContent = error instanceof Error ? error.message : String(error);- frame.append(failed);- }-- const name = document.createElement("div");- name.className = "tile-name";- name.textContent = subject.path;- const kind = document.createElement("div");- kind.className = "tile-kind";- kind.textContent = subject.component.label;- tile.append(frame, name, kind);- tile.addEventListener("click", () => input.onFocus(subject));- grid.append(tile);- }-- if (input.subjects.length === 0) {- const empty = document.createElement("div");- empty.className = "gallery-note";- empty.textContent = "This stylesheet declares nothing the playground can draw yet.";- element.append(empty);- }-- if (input.unmatched.length > 0) {- const note = document.createElement("div");- note.className = "gallery-note";- note.textContent = `${input.unmatched.length} Recipe(s) have no preview — their property sets match no component:`;- const list = document.createElement("div");- list.className = "gallery-unmatched";- for (const entry of input.unmatched) {- const line = document.createElement("code");- const path = document.createElement("b");- path.textContent = entry.path;- line.append(path, document.createTextNode(` { ${entry.keys.join(", ")} }`));- list.append(line);- }- element.append(note, list);- }-- return element;-}diff --git a/tools/playground/src/ui/shell.ts b/tools/playground/src/ui/shell.tsindex 15997c79..b6c98279 100644--- a/tools/playground/src/ui/shell.ts+++ b/tools/playground/src/ui/shell.ts@@ -1,18 +1,24 @@-import { REGISTRY, componentById } from "../registry/index.js";-import type { PreviewComponent } from "../registry/index.js";+import type { PreviewProducer } from "../discovery/producers.js";+import { workspacePreviewProducers } from "../discovery/workspace.js";import { renderPreview } from "../preview/render.js";-import { discover } from "../svs/discover.js";-import type { Discovery, PreviewSubject } from "../svs/discover.js";-import { sealProgramSpace } from "../svml.js";-import type { CanonicalValue } from "../svml.js";+import {+ defaultFilmProgram,+ defaultProgramSpace,+ filmCanvasFromRecipe,+ filmRecipeKeys,+ maskSourceHeader,+ parseSourceHeader,+ parseSvs,+ sealProgramSpace,+} from "../svml.js";+import type { CanonicalValue, ProgramSpace, Track } from "../svml.js";import { BROWSE_CSS, createBrowser, readSheet } from "./browse.js";-import { FORM_CSS, buildForm } from "./form.js";-import { GALLERY_CSS, renderGallery } from "./gallery.js";+import { FORM_CSS, blankValue, buildForm } from "./form.js";import { createStage } from "./stage.js";const CSS = `.rail {- width: 340px; flex: 0 0 340px; border-right: 1px solid var(--line);+ width: 356px; flex: 0 0 356px; border-right: 1px solid var(--line);background: var(--panel); display: flex; flex-direction: column; min-height: 0;}.rail-head { padding: 12px 14px; border-bottom: 1px solid var(--line); }@@ -20,28 +26,21 @@ const CSS = `.rail-body { flex: 1; min-height: 0; overflow-y: auto; padding: 10px 14px 24px; }.rail select, .rail input[type=number] {background: #1c1c21; color: var(--text); border: 1px solid var(--line);- border-radius: 5px; padding: 4px 7px; font: inherit; font-size: 12px; min-width: 0;+ border-radius: 5px; padding: 4px 7px; font: inherit; font-size: 12px; min-width: 0; width: 100%;}.rail-canvas { display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 6px; align-items: center; margin-top: 9px; }.rail-canvas span { color: var(--muted); font-size: 11px; }.section { color: var(--accent); font-size: 11px; letter-spacing: .05em;- text-transform: uppercase; margin: 14px 0 4px; display: flex; justify-content: space-between; align-items: baseline; }+ text-transform: uppercase; margin: 15px 0 4px; }.section:first-child { margin-top: 0; }-.section button {- border: 0; background: none; color: var(--muted); cursor: pointer;- font: inherit; font-size: 11px; text-transform: none; letter-spacing: 0; padding: 0;-}-.section button:hover { color: var(--text); }-.sheet-note { color: var(--muted); font-size: 12px; margin-top: 6px; }+.module { color: var(--muted); font-size: 11px; font-family: ui-monospace, monospace; margin-top: 4px; }+.sheet-note { color: var(--muted); font-size: 12px; margin-top: 7px; }.sheet-note b { color: var(--accent); font-weight: 500; }${BROWSE_CSS}${FORM_CSS}-${GALLERY_CSS}`;-type Draft = { parameters: CanonicalValue; content: CanonicalValue };--export function mountShell(root: HTMLElement): void {+export async function mountShell(root: HTMLElement): Promise<void> {const style = document.createElement("style");style.textContent = CSS;document.head.append(style);@@ -51,7 +50,8 @@ export function mountShell(root: HTMLElement): void {rail.innerHTML = `<div class="rail-head"><h1>Component playground</h1>- <select data-component></select>+ <select data-producer></select>+ <div class="module" data-module></div><div class="rail-canvas"><span>W</span><input type="number" data-width min="16" step="2" /><span>H</span><input type="number" data-height min="16" step="2" />@@ -62,53 +62,80 @@ export function mountShell(root: HTMLElement): void {<div class="rail-body"></div>`;- const picker = rail.querySelector<HTMLSelectElement>("[data-component]")!;+ const picker = rail.querySelector<HTMLSelectElement>("[data-producer]")!;+ const moduleLine = rail.querySelector<HTMLElement>("[data-module]")!;const body = rail.querySelector<HTMLElement>(".rail-body")!;const widthInput = rail.querySelector<HTMLInputElement>("[data-width]")!;const heightInput = rail.querySelector<HTMLInputElement>("[data-height]")!;const fpsInput = rail.querySelector<HTMLInputElement>("[data-fps]")!;const durationInput = rail.querySelector<HTMLInputElement>("[data-duration]")!;- for (const component of REGISTRY) {+ const stage = createStage();+ root.append(rail, stage.element);++ const producers = await workspacePreviewProducers();+ if (producers.length === 0) {+ stage.showError("No module declares a Producer that outputs a VisualTrack.");+ return;+ }+ for (const producer of producers) {const option = document.createElement("option");- option.value = component.id;- option.textContent = component.label;+ option.value = producer.id;+ option.textContent = producer.label;picker.append(option);}- const stage = createStage();- let main: HTMLElement = stage.element;- root.append(rail, main);+ // The Film module owns what an undeclared frame looks like, so the canvas+ // starts as whatever it says rather than as numbers chosen here.+ const film = defaultFilmProgram();+ const canvas = { ...film.canvas };+ const space = {+ fps: film.frameRate.numerator / film.frameRate.denominator,+ durationSec: defaultProgramSpace().durationSec,+ };- const canvas = { width: 1080, height: 1920, clearColor: "#09090b" };- const space = { fps: 30, durationSec: 4 };- widthInput.value = String(canvas.width);- heightInput.value = String(canvas.height);- fpsInput.value = String(space.fps);- durationInput.value = String(space.durationSec);+ /**+ * Values a ProgramSpace input must agree with.+ *+ * Producers take a ProgramSpace as an ordinary input, but the canvas controls+ * and the scrubber describe the same thing, so the shell owns it and the form+ * does not offer a second copy to disagree with.+ */+ function programSpace(): ProgramSpace {+ return sealProgramSpace({+ contract: "svml.program-space@1",+ durationSec: space.durationSec,+ frameRate: { numerator: space.fps, denominator: 1 },+ });+ }- // Mode B keeps one draft per component; mode A keeps one per Recipe, so- // switching between two captions from a sheet does not merge their edits.- const drafts = new Map<string, Draft>();- let active: PreviewComponent = REGISTRY[0]!;- let activeKey = active.id;- let sheet: { name: string; discovery: Discovery } | undefined;+ const drafts = new Map<string, Record<string, CanonicalValue>>();+ // Open on something that draws. A producer whose inputs its own modules can+ // all supply shows a frame immediately; one waiting on media would greet the+ // operator with a failure they have not caused yet.+ let active: PreviewProducer = producers.find((producer) =>+ producer.inputs.every((input) => input.initial !== undefined)) ?? producers[0]!;+ picker.value = active.id;- function draft(key: string, make: () => Draft): Draft {- const existing = drafts.get(key);+ function draft(producer: PreviewProducer): Record<string, CanonicalValue> {+ const existing = drafts.get(producer.id);if (existing !== undefined) return existing;- const created = make();- drafts.set(key, created);+ const created: Record<string, CanonicalValue> = {};+ for (const input of producer.inputs) {+ // Whatever the declaring module says one of these looks like. Where it+ // declines — because the value carries media it has no bytes for — the+ // schema still says what shape the operator has to fill in.+ created[input.name] = input.initial !== undefined+ ? structuredClone(input.initial) as CanonicalValue+ : input.schema === undefined ? null : blankValue(input.schema);+ }+ drafts.set(producer.id, created);return created;}- function currentDraft(): Draft {- return draft(activeKey, () => active.defaults());- }-- function swapMain(next: HTMLElement): void {- main.replaceWith(next);- main = next;+ function isProgramSpace(name: string, producer: PreviewProducer): boolean {+ return producer.inputs.some((input) =>+ input.name === name && input.type.name === "ProgramSpace");}let queued = 0;@@ -117,129 +144,106 @@ export function mountShell(root: HTMLElement): void {queued = window.setTimeout(render, 120);}- function programSpace() {- return sealProgramSpace({- contract: "svml.program-space@1",- durationSec: space.durationSec,- frameRate: { numerator: space.fps, denominator: 1 },- });- }-function render(): void {- if (main !== stage.element) swapMain(stage.element);- const current = currentDraft();+ const values = { ...draft(active) };try {const resolved = programSpace();+ for (const input of active.inputs) {+ if (isProgramSpace(input.name, active)) values[input.name] = resolved as never;+ }+ const track = active.invoke(values) as Track;stage.show(renderPreview({- id: active.id,+ id: active.moduleName,canvas,programSpace: resolved,- tracks: active.build({- parameters: current.parameters,- content: current.content,- programSpace: resolved,- canvas,- }),+ tracks: [track],}));} catch (error) {- // The compiler's own message, verbatim. The last good frame stays up.+ // The compiler's own message. The last good frame stays up.stage.showError(error instanceof Error ? error.message : String(error));}}- function showGallery(): void {- if (sheet === undefined) return;- swapMain(renderGallery({- subjects: sheet.discovery.subjects,- unmatched: sheet.discovery.unmatched,- canvas,- fps: space.fps,- durationSec: space.durationSec,- onFocus: focusSubject,- }));- }-- function focusSubject(subject: PreviewSubject): void {- active = subject.component;- activeKey = subject.key;- picker.value = subject.component.id;- draft(subject.key, () => ({ parameters: subject.parameters, content: subject.content }));- renderRail();- render();- }-function loadSheet(path: string): void {void readSheet(path).then((source) => {- const discovery = discover(path, source);- sheet = { name: path, discovery };- // A Film Recipe is not a preview subject; it says how big the frame is.- const offer = discovery.canvases[0];- if (offer !== undefined) {- canvas.width = offer.width;- canvas.height = offer.height;- canvas.clearColor = offer.clearColor;- space.fps = offer.fps;- widthInput.value = String(offer.width);- heightInput.value = String(offer.height);- fpsInput.value = String(offer.fps);+ const header = parseSourceHeader(path, source);+ if (!header.using.startsWith("@narratage/svs@")) {+ throw new Error(`${path} is a ${header.using} source, not a stylesheet.`);+ }+ const sheet = parseSvs(path, maskSourceHeader(source, header));+ const filmShape = [...filmRecipeKeys].sort().join(" ");+ const found = sheet.recipes.find((recipe) =>+ Object.keys(recipe.value.properties).sort().join(" ") === filmShape);+ if (found === undefined) {+ note.textContent = "This stylesheet declares no Film Recipe, so the canvas is unchanged.";+ return;}- renderRail();- showGallery();+ const read = filmCanvasFromRecipe(found.value.properties);+ canvas.width = read.canvas.width;+ canvas.height = read.canvas.height;+ canvas.clearColor = read.canvas.clearColor;+ space.fps = read.frameRate.numerator / read.frameRate.denominator;+ widthInput.value = String(canvas.width);+ heightInput.value = String(canvas.height);+ fpsInput.value = String(space.fps);+ note.replaceChildren(document.createTextNode("Canvas from "));+ const which = document.createElement("b");+ which.textContent = found.value.path;+ note.append(which);+ render();}).catch((error: unknown) => {- sheet = undefined;- renderRail();- stage.showError(error instanceof Error ? error.message : String(error));+ note.textContent = error instanceof Error ? error.message : String(error);});}const browser = createBrowser(loadSheet);+ const note = document.createElement("div");+ note.className = "sheet-note";- function section(title: string, action?: { label: string; run: () => void }): HTMLElement {+ function section(title: string): HTMLElement {const element = document.createElement("div");element.className = "section";- const caption = document.createElement("span");- caption.textContent = title;- element.append(caption);- if (action !== undefined) {- const button = document.createElement("button");- button.type = "button";- button.textContent = action.label;- button.addEventListener("click", action.run);- element.append(button);- }+ element.textContent = title;return element;}function renderRail(): void {- const current = currentDraft();- body.replaceChildren();+ const values = draft(active);+ moduleLine.textContent = active.moduleName;+ body.replaceChildren(section("Canvas from a stylesheet"), browser.element, note);- body.append(section("Stylesheet"), browser.element);- if (sheet !== undefined) {- const note = document.createElement("div");- note.className = "sheet-note";- const count = sheet.discovery.subjects.length;- note.append(document.createTextNode(`${count} previewable Recipe(s) in `));- const id = document.createElement("b");- id.textContent = sheet.discovery.sheetId ?? sheet.name;- note.append(id);- body.append(note, section("", { label: "Show all", run: showGallery }));+ for (const input of active.inputs) {+ // The shell owns the frame domain; offering it again would be a second+ // answer free to disagree with the canvas controls.+ if (isProgramSpace(input.name, active)) continue;+ body.append(section(input.name));+ if (input.schema === undefined) {+ const missing = document.createElement("div");+ missing.className = "sheet-note";+ missing.textContent = `${input.type.module.name} declares no schema for ${input.type.name}.`;+ body.append(missing);+ continue;+ }+ if (values[input.name] === null || values[input.name] === undefined) {+ const empty = document.createElement("div");+ empty.className = "sheet-note";+ empty.textContent = `${input.type.module.name} offers no default for ${input.type.name}.`;+ body.append(empty);+ }+ body.append(buildForm(input.schema, values[input.name] ?? {}, schedule));}-- body.append(section("Parameters"));- body.append(buildForm(active.parameters, current.parameters, active.hints ?? {}, schedule));- body.append(section("Content"));- body.append(buildForm(active.content, current.content, active.hints ?? {}, schedule));}picker.addEventListener("input", () => {- active = componentById(picker.value) ?? active;- // Choosing from the list leaves any focused Recipe behind.- activeKey = active.id;+ active = producers.find((entry) => entry.id === picker.value) ?? active;renderRail();render();});+ widthInput.value = String(canvas.width);+ heightInput.value = String(canvas.height);+ fpsInput.value = String(space.fps);+ durationInput.value = String(space.durationSec);for (const [input, apply] of [[widthInput, (n: number) => { canvas.width = n; }],[heightInput, (n: number) => { canvas.height = n; }],diff --git a/tools/recipe-defaults.test.mjs b/tools/recipe-defaults.test.mjsnew file mode 100644index 00000000..35241803--- /dev/null+++ b/tools/recipe-defaults.test.mjs@@ -0,0 +1,78 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ captionAppearanceFromRecipe,+ captionAppearanceRecipeKeys,+ defaultCaptionAppearanceRecipe,+} from "../packages/caption/src/index.ts";+import {+ brollAppearanceFromRecipe,+ brollAppearanceRecipeKeys,+ defaultBrollAppearanceRecipe,+} from "../packages/broll/src/index.ts";+import {+ defaultFilmRecipe,+ filmCanvasFromRecipe,+ filmRecipeKeys,+} from "../packages/film/src/index.ts";+import {+ defaultTextAppearanceRecipe,+ textAppearanceFromRecipe,+ textAppearanceRecipeKeys,+} from "../packages/text-track/src/index.ts";++/**+ * A module's default Recipe has to be a Recipe its own Surface would admit.+ *+ * The default and the required key set used to be stated twice — once as a+ * literal in the Surface handler and once wherever a consumer needed one — and+ * a copy that can drift silently is worse than no copy. Now the default is the+ * declaration and the key set is read off it, so the only thing left to check+ * is that the default actually survives the mapping it describes.+ */+const MODULES = [+ {+ name: "caption",+ keys: captionAppearanceRecipeKeys,+ recipe: defaultCaptionAppearanceRecipe,+ read: captionAppearanceFromRecipe,+ },+ {+ name: "text-track",+ keys: textAppearanceRecipeKeys,+ recipe: defaultTextAppearanceRecipe,+ read: textAppearanceFromRecipe,+ },+ {+ name: "broll",+ keys: brollAppearanceRecipeKeys,+ recipe: defaultBrollAppearanceRecipe,+ read: brollAppearanceFromRecipe,+ },+ { name: "film", keys: filmRecipeKeys, recipe: defaultFilmRecipe, read: filmCanvasFromRecipe },+];++for (const module of MODULES) {+ test(`the ${module.name} default Recipe is one its own reader admits`, () => {+ assert.deepEqual([...module.keys].sort(), Object.keys(module.recipe).sort(),+ "the key set must be read off the default, not restated");+ assert.doesNotThrow(() => module.read(module.recipe));+ });++ test(`the ${module.name} reader refuses a Recipe with the wrong shape`, () => {+ const { [module.keys[0]]: _dropped, ...missing } = module.recipe;+ assert.throws(() => module.read(missing), /requires exactly/u);+ assert.throws(() => module.read({ ...module.recipe, unexpected: 1 }), /requires exactly/u);+ });+}++test("no two modules claim the same Recipe shape", () => {+ const seen = new Map();+ for (const module of MODULES) {+ const shape = [...module.keys].sort().join(" ");+ assert.equal(seen.get(shape), undefined,+ `${module.name} and ${seen.get(shape)} are indistinguishable to a reader matching on shape`);+ seen.set(shape, module.name);+ }+});