Code-first video & image, rendered natively on WebGPU.
feat(cli): named renders in framefields.json
okanasl66ecdae80b93
diff --git a/.changeset/render-manifest.md b/.changeset/render-manifest.mdnew file mode 100644index 00000000..217173e8--- /dev/null+++ b/.changeset/render-manifest.md@@ -0,0 +1,5 @@+---+"framefields": minor+---++Named renders in `framefields.json`: `renders.<name>` points at a module and export with its title, description and render defaults (workers, codec, quality, output). `framefields render <name> --cloud`, `framefields check <name>` (no name checks every render), `framefields renders` and `renderCloud({ render })` pick them by name, and the dashboard lists them so nobody selects files. `init` records a `film` render and its scripts use it.diff --git a/CLAUDE.md b/CLAUDE.mdindex 833bf4cb..32b4a8ea 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ Code-first video engine on native WebGPU (Dawn) in Node, no browser. pnpm + turb- Keep this file current when structure or dev patterns change but do not bloat it.## Repo map-- `packages/framefields`: public SDK. `Composition`, `Layer.*`, `LayerAnimation`, `Signal`, effects (`src/effects/classes.ts`), `FontManager`, `renderFrameGrid`. `src/index.ts` is the export surface. CLI in `src/cli/` (`init`, `add`, `list`, `fonts add|list`, `check`, `render --cloud`); `framefields/cloud` (`renderCloud`) is the GPU-free client for api.framefields.dev; `init` never prompts or overwrites, and its file templates are strings in `templates.ts` (a test parses them).+- `packages/framefields`: public SDK. `Composition`, `Layer.*`, `LayerAnimation`, `Signal`, effects (`src/effects/classes.ts`), `FontManager`, `renderFrameGrid`. `src/index.ts` is the export surface. CLI in `src/cli/` (`init`, `add`, `list`, `fonts add|list`, `check`, `renders`, `render --cloud`); `framefields.json` (`cli/config.ts`) holds the components folder, fonts and named `renders` that the CLI, `renderCloud` and the dashboard pick by name; `framefields/cloud` (`renderCloud`) is the GPU-free client for api.framefields.dev; `init` never prompts or overwrites, and its file templates are strings in `templates.ts` (a test parses them).- `packages/components`: the component registry `framefields add` copies into user projects (shadcn-style). `defineComponent`/`bind` contract in `src/core/contract.ts`, shared helpers in `src/core/` (keys, color, layout, surface, theme). Components import only `framefields` and `../core`. Registry items declare font needs (e.g. emoji); CLI fonts are pinned by URL, size and SHA-256 in `cli/fonts.ts`. Prop docs in `components.json` are generated (drift test). Tree-shake size budgets are tested.- `packages/compositions`: Yoga layout (`utils/layout/resolve-layout.ts`), program schema (`program/schema.ts`), lint (`program/lint.ts`), animation/evaluator.- `packages/webgpu-renderers`: WGSL shaders, 2D/3D pipelines, Slug text (`src/slug/`), audio DSP.diff --git a/packages/framefields/src/cli.ts b/packages/framefields/src/cli.tsindex 07222f48..afb6147a 100644--- a/packages/framefields/src/cli.ts+++ b/packages/framefields/src/cli.ts@@ -7,10 +7,11 @@* npx framefields list the components you can add* npx framefields fonts add <role...> install fonts (emoji)* npx framefields fonts list the fonts you can install- * npx framefields render <entry> --cloud render on api.framefields.dev+ * npx framefields renders the renders named in framefields.json+ * npx framefields render <name> --cloud render on api.framefields.dev*/import { readFileSync } from "node:fs";-import { relative, resolve } from "node:path";+import { join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { parseArgs } from "node:util";import { type AddReport, add } from "./cli/add.js";@@ -39,8 +40,11 @@ const HELP = `Usage: framefields <command> [options]Commands:api JSON reference generated from timing, grid and check types.- check <entry> Build, validate and lint a composition; --render also writes a- representative frame and grid. --export defaults to buildFilm.+ check [name|entry]+ Build, validate and lint a composition; --render also writes a+ representative frame and grid. A render named in+ framefields.json, or a module (--export defaults to+ buildFilm); with neither, every named render.init [dir] Start a framefields project in dir (default: here), or addframefields to the project there: package.json, tsconfig,src/theme.ts, film.ts, render.ts, assets/, .gitignore,@@ -53,10 +57,14 @@ Commands:Install fonts (pinned, hash-checked, with their license)and register them in the generated <components>/fonts.ts.fonts list List the fonts you can install.- render <entry> --cloud+ renders List the renders named in framefields.json.+ render [name|entry] --cloudRender on api.framefields.dev from the pushed commit ofthis git repo, and download the video. Needs- FRAMEFIELDS_API_KEY. --export defaults to buildFilm.+ FRAMEFIELDS_API_KEY. A render named in framefields.json+ (its fields are the defaults; flags override them), or a+ module (--export defaults to buildFilm). Without either,+ the project's only named render.Options for check:--export <name> Composition or builder export (default buildFilm).@@ -73,7 +81,7 @@ Options for render --cloud:--max-workers <n> Upper bound for auto.--plan Measure and plan only: prints workers, time and theestimated cost, renders nothing.- --output <file> Where the video goes (default output/<entry>.mp4).+ --output <file> Where the video goes (default output/<name>.mp4).--codec <codec> h264 (default) or vp9.--quality <q> very_low, low, high or very_high (default).--select <name> When the export returns several compositions.@@ -107,7 +115,7 @@ Examples:npx framefields init my-film --installnpx framefields add mouse-pointer focus-zoomnpx framefields fonts add emoji- npx framefields render src/film.ts --cloud --workers auto --plan+ npx framefields render film --cloud --plan`;async function main(argv: string[]): Promise<number> {@@ -165,37 +173,12 @@ async function main(argv: string[]): Promise<number> {log(JSON.stringify({ ...catalog, sdkVersion: ownVersion() }));return 0;}- if (command === "check") {- if (names.length !== 1) {- process.stderr.write(- "Usage: framefields check <entry> [--export buildFilm] [--render] [--json]\n",- );- return 2;- }- const report = await runCheck({- entry: names[0],- exportName: values.export,- render: values.render,- outputDir: values.output,- timeoutMs:- values.timeout === undefined ? undefined : Number(values.timeout),- warningsAsErrors: values["warnings-as-errors"],- });- if (values.json) log(JSON.stringify(report));- else {- log(`Check ${report.status}: ${report.entry} (${report.exportName})`);- for (const d of report.diagnostics)- log(- `${d.severity} ${d.code}${d.path ? ` at ${d.path}` : ""}: ${d.message}`,- );- for (const file of report.artifacts) log(`Wrote ${file}`);- }- return report.status === "passed" ? 0 : 1;- }+ if (command === "check") return check(names, cwd, values, log);+ if (command === "renders") return listRenders(cwd, values.json, log);if (command === "render") {- if (names.length !== 1 || !values.cloud) {+ if (names.length > 1 || !values.cloud) {process.stderr.write(- "Usage: framefields render <entry> --cloud [--workers auto] [--plan]\nLocal renders run your project's render script (`npm run render`).\n",+ "Usage: framefields render [name|entry] --cloud [--workers auto] [--plan]\nLocal renders run your project's render script (`npm run render`).\n",);return 2;}@@ -317,6 +300,114 @@ const onDownload = (spec: FontSpec) =>);/** What `add` did about fonts, and how to use them. */+/** `check [name|entry]`: a named render, a module, or every named render. */+async function check(+ names: string[],+ cwd: string,+ values: {+ export?: string;+ render?: boolean;+ output?: string;+ timeout?: string;+ "warnings-as-errors"?: boolean;+ json?: boolean;+ },+ log: (s: string) => void,+): Promise<number> {+ const renders = readConfig(cwd).config.renders ?? {};+ const usage = () => {+ process.stderr.write(+ "Usage: framefields check [name|entry] [--export buildFilm] [--render] [--json]\n",+ );+ return 2;+ };+ if (names.length > 1) return usage();+ const targets: { name?: string; entry: string; exportName?: string }[] =+ names.length === 0+ ? Object.entries(renders).map(([name, spec]) => ({+ name,+ entry: spec.entry,+ exportName: spec.export,+ }))+ : renders[names[0]]+ ? [+ {+ name: names[0],+ entry: renders[names[0]].entry,+ exportName: values.export ?? renders[names[0]].export,+ },+ ]+ : [{ entry: names[0], exportName: values.export }];+ if (targets.length === 0) return usage();+ const reports = [];+ for (const t of targets) {+ const report = await runCheck({+ entry: t.entry,+ exportName: t.exportName,+ render: values.render,+ outputDir:+ values.output ??+ (targets.length > 1+ ? join("output", "check", t.name ?? "")+ : undefined),+ timeoutMs:+ values.timeout === undefined ? undefined : Number(values.timeout),+ warningsAsErrors: values["warnings-as-errors"],+ });+ reports.push({ ...(t.name && { name: t.name }), ...report });+ if (values.json) continue;+ log(+ `Check ${report.status}: ${t.name ? `${t.name} (${t.entry}, ${report.exportName})` : `${report.entry} (${report.exportName})`}`,+ );+ for (const d of report.diagnostics)+ log(+ `${d.severity} ${d.code}${d.path ? ` at ${d.path}` : ""}: ${d.message}`,+ );+ for (const file of report.artifacts) log(`Wrote ${file}`);+ }+ const passed = reports.every((r) => r.status === "passed");+ if (values.json)+ log(+ JSON.stringify(+ names.length === 0+ ? { status: passed ? "passed" : "failed", checks: reports }+ : reports[0],+ ),+ );+ return passed ? 0 : 1;+}++/** `renders`: what framefields.json names, as the dashboard shows it. */+function listRenders(+ cwd: string,+ json: boolean | undefined,+ log: (s: string) => void,+): number {+ const renders = readConfig(cwd).config.renders ?? {};+ if (json) {+ log(JSON.stringify({ schemaVersion: 1, renders }));+ return 0;+ }+ const entries = Object.entries(renders);+ if (entries.length === 0) {+ log(+ 'framefields.json names no renders. Add one: "renders": { "film": { "entry": "src/film.ts", "export": "buildFilm" } }',+ );+ return 0;+ }+ for (const [name, spec] of entries) {+ const title = spec.title && spec.title !== name ? ` ${spec.title}` : "";+ const opts = [+ spec.workers !== undefined && `workers ${spec.workers}`,+ spec.codec,+ ].filter(Boolean);+ log(+ `${name}${title}\n ${spec.entry} · ${spec.export ?? "buildFilm"}${spec.select ? ` · ${spec.select}` : ""}${opts.length ? ` · ${opts.join(", ")}` : ""}${spec.description ? `\n ${spec.description}` : ""}`,+ );+ }+ return 0;+}+function logFonts(report: AddReport, cwd: string, log: (s: string) => void) {for (const f of report.fonts)log(diff --git a/packages/framefields/src/cli/add.ts b/packages/framefields/src/cli/add.tsindex c9ba6645..9ddbec3c 100644--- a/packages/framefields/src/cli/add.ts+++ b/packages/framefields/src/cli/add.ts@@ -118,7 +118,7 @@ export async function add(}}if (!saved) {- writeConfig(cwd, { components: relative(cwd, dir) || "." });+ writeConfig(cwd, { ...config, components: relative(cwd, dir) || "." });report.configWritten = true;}diff --git a/packages/framefields/src/cli/cloud.ts b/packages/framefields/src/cli/cloud.tsindex 36084383..8ac8e6a8 100644--- a/packages/framefields/src/cli/cloud.ts+++ b/packages/framefields/src/cli/cloud.ts@@ -1,8 +1,11 @@/**- * `framefields render <entry> --cloud`: renders the project on- * api.framefields.dev and downloads the video. Prints one plain line per- * phase, and a progress line at most every 10 seconds while frames render.+ * `framefields render <name|entry> --cloud`: renders the project on+ * api.framefields.dev and downloads the video. `name` is a render in+ * framefields.json; a module path renders without one. Prints one plain+ * line per phase, and a progress line at most every 10 seconds while+ * frames render.*/+import { existsSync } from "node:fs";import path from "node:path";import {CloudRenderError,@@ -10,9 +13,11 @@ import {type CloudRenderStatus,renderCloud,} from "../cloud/index.js";+import { CONFIG_FILE, findRender, readConfig } from "./config.js";export interface CloudCliOptions {- entry: string;+ /** A render named in framefields.json, or a module path. Optional when framefields.json has one render. */+ entry?: string;export?: string;select?: string;workers?: string;@@ -22,6 +27,8 @@ export interface CloudCliOptions {output?: string;plan?: boolean;json?: boolean;+ /** Project folder. Default `process.cwd()`. */+ cwd?: string;}const PROGRESS_EVERY_MS = 10_000;@@ -33,8 +40,9 @@ export async function runCloudRender(options: CloudRenderOptions,) => Promise<CloudRenderStatus> = renderCloud,): Promise<number> {+ const cwd = o.cwd ?? process.cwd();const workers = parseWorkers(o.workers);- if (workers === undefined) {+ if (workers === null) {log(`--workers must be "auto" or a positive whole number, not "${o.workers}".`,);@@ -44,13 +52,23 @@ export async function runCloudRender(log(`--codec must be h264 or vp9, not "${o.codec}".`);return 2;}- const codec = (o.codec ?? "h264") as "h264" | "vp9";+ const target = pickRender(o.entry, cwd);+ if ("error" in target) {+ log(target.error);+ return 2;+ }+ const spec = target.name ? findRender(cwd, target.name) : undefined;+ const codec = (o.codec ?? spec?.codec ?? "h264") as "h264" | "vp9";const outputPath =o.output ??+ spec?.output ??path.join("output",- `${path.basename(o.entry).replace(/\.[^.]+$/, "")}.${codec === "vp9" ? "webm" : "mp4"}`,+ `${target.name ?? path.basename(target.entry ?? "").replace(/\.[^.]+$/, "")}.${codec === "vp9" ? "webm" : "mp4"}`,);+ // A plan of a one-worker render would only ever say "one worker".+ const planWorkers =+ o.plan && (workers ?? spec?.workers ?? 1) === 1 ? "auto" : workers;const controller = new AbortController();const onSigint = () => {log("Cancelling the cloud render…");@@ -61,12 +79,14 @@ export async function runCloudRender(const narrate = narrator(o.json ? () => {} : log, Date.now);try {const result = await render({- entry: o.entry,+ cwd,+ render: target.name,+ entry: target.entry,export: o.export,select: o.select,- workers: o.plan && workers === 1 ? "auto" : workers,+ workers: planWorkers,maxWorkers: o.maxWorkers ? Number(o.maxWorkers) : undefined,- codec,+ codec: o.codec as "h264" | "vp9" | undefined,quality: o.quality,dryRun: o.plan,outputPath: o.plan ? undefined : outputPath,@@ -79,7 +99,10 @@ export async function runCloudRender(return 0;}if (result.status === "planned") {- log(`Render it: ${renderCommand(o)}`);+ const planned = planWorkers === "auto" && spec?.workers !== "auto";+ log(+ `Render it: ${renderCommand({ ...o, entry: target.name ?? target.entry, workers: o.workers ?? (planned ? "auto" : undefined) })}`,+ );return 0;}const bytes = result.output?.bytes;@@ -107,23 +130,53 @@ export function renderCommand(o: CloudCliOptions): string {const flags: [string, string | undefined][] = [["--export", o.export],["--select", o.select],- ["--workers", o.workers ?? "auto"],+ ["--workers", o.workers],["--max-workers", o.maxWorkers],["--codec", o.codec],["--quality", o.quality],["--output", o.output],];return [- `framefields render ${o.entry} --cloud`,+ `framefields render ${o.entry ?? ""} --cloud`.replace(" ", " "),...flags.filter(([, v]) => v !== undefined).map(([f, v]) => `${f} ${v}`),].join(" ");}-function parseWorkers(value: string | undefined): number | "auto" | undefined {- if (value === undefined) return 1;+/**+ * What `framefields render [arg]` renders: a render named in framefields.json,+ * or a module path; with no argument, the project's only named render.+ */+export function pickRender(+ arg: string | undefined,+ cwd: string,+): { name?: string; entry?: string } | { error: string } {+ const renders = readConfig(cwd).config.renders ?? {};+ const names = Object.keys(renders);+ if (arg === undefined) {+ if (names.length === 1) return { name: names[0] };+ return {+ error: names.length+ ? `Name the render: ${names.join(", ")}. \`framefields renders\` lists them.`+ : `Name a module, e.g. \`framefields render src/film.ts --cloud\`, or add "renders" to ${CONFIG_FILE}.`,+ };+ }+ if (renders[arg]) return { name: arg };+ if (existsSync(path.resolve(cwd, arg))) return { entry: arg };+ return {+ error: names.length+ ? `"${arg}" is neither a render in ${CONFIG_FILE} (${names.join(", ")}) nor a file.`+ : `"${arg}" is not a file, and ${CONFIG_FILE} names no renders.`,+ };+}++/** --workers: undefined when not given, null when invalid. */+function parseWorkers(+ value: string | undefined,+): number | "auto" | undefined | null {+ if (value === undefined) return undefined;if (value === "auto") return "auto";const n = Number(value);- return Number.isInteger(n) && n >= 1 ? n : undefined;+ return Number.isInteger(n) && n >= 1 ? n : null;}/** Turns status polls into log lines: one per phase, throttled frame progress. */diff --git a/packages/framefields/src/cli/config.ts b/packages/framefields/src/cli/config.tsindex 69a0c6e4..206091d5 100644--- a/packages/framefields/src/cli/config.ts+++ b/packages/framefields/src/cli/config.ts@@ -1,12 +1,53 @@/*** `framefields.json` at the project root: where installed components live,- * and which fonts `framefields add` / `framefields fonts add` installed.+ * which fonts `framefields add` / `framefields fonts add` installed, and the+ * project's named renders.+ *+ * ```json+ * {+ * "components": "src/components",+ * "renders": {+ * "film": {+ * "title": "Launch film",+ * "entry": "src/film.ts",+ * "export": "buildFilm",+ * "workers": "auto"+ * }+ * }+ * }+ * ```+ *+ * A named render is what `framefields render film --cloud`, `framefields+ * check film`, `renderCloud({ render: "film" })` and the dashboard's New+ * render dialog pick, so nobody chooses files and exports by hand.*/import { existsSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";export const CONFIG_FILE = "framefields.json";+/** One renderable piece of the project: an export of a module, with its defaults. */+export interface RenderSpec {+ /** The module that builds the composition, relative to the project root. */+ entry: string;+ /** A Composition, or a function returning one. Default `buildFilm`. */+ export?: string;+ /** Shown in the dashboard and `framefields renders`. Default: the name. */+ title?: string;+ description?: string;+ /** Passed to the export when it is a function. */+ args?: unknown;+ /** When the export returns several compositions, the one to render. */+ select?: string;+ /** Cloud workers: 1, a number, or "auto" to split long films. Default 1. */+ workers?: number | "auto";+ maxWorkers?: number;+ codec?: "h264" | "vp9";+ quality?: "very_low" | "low" | "high" | "very_high";+ /** Where `framefields render <name> --cloud` writes the video. */+ output?: string;+}+export interface ProjectConfig {/** Components directory, relative to the project root. */components: string;@@ -15,34 +56,55 @@ export interface ProjectConfig {* set here counts as installed: point it at your own font to use that.*/fonts?: Partial<Record<string, string>>;+ /** Named renders, by name (letters, digits, `-`, `_`, `.`). */+ renders?: Record<string, RenderSpec>;}-/** The project's config, or the default it would get: `src/components` when there is a `src`. */+export const RENDER_NAME = /^[A-Za-z0-9][\w.-]{0,63}$/;+const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;+const QUALITIES = ["very_low", "low", "high", "very_high"];++/**+ * The project's config, or the default it would get: `src/components` when+ * there is a `src`. `saved` is whether the file records a components folder.+ */export function readConfig(cwd: string): {config: ProjectConfig;saved: boolean;} {const file = join(cwd, CONFIG_FILE);- if (existsSync(file)) {- const config = JSON.parse(- readFileSync(file, "utf8"),- ) as Partial<ProjectConfig>;- if (typeof config.components !== "string")- throw new Error(`${CONFIG_FILE}: "components" must be a directory path`);- if (- config.fonts !== undefined &&- (typeof config.fonts !== "object" ||- Object.values(config.fonts).some((v) => typeof v !== "string"))- )- throw new Error(- `${CONFIG_FILE}: "fonts" must map roles to font file paths, e.g. { "emoji": "assets/fonts/NotoColorEmoji.ttf" }`,- );- return { config: config as ProjectConfig, saved: true };- }- const components = existsSync(join(cwd, "src"))+ const fallback = existsSync(join(cwd, "src"))? "src/components": "components";- return { config: { components }, saved: false };+ if (!existsSync(file))+ return { config: { components: fallback }, saved: false };+ let raw: unknown;+ try {+ raw = JSON.parse(readFileSync(file, "utf8"));+ } catch (err) {+ throw new Error(+ `${CONFIG_FILE} is not valid JSON: ${(err as Error).message}`,+ );+ }+ if (!isRecord(raw)) throw new Error(`${CONFIG_FILE} must be a JSON object`);+ const { components, fonts, renders } = raw;+ if (components !== undefined && typeof components !== "string")+ throw new Error(`${CONFIG_FILE}: "components" must be a directory path`);+ if (+ fonts !== undefined &&+ (!isRecord(fonts) ||+ Object.values(fonts).some((v) => typeof v !== "string"))+ )+ throw new Error(+ `${CONFIG_FILE}: "fonts" must map roles to font file paths, e.g. { "emoji": "assets/fonts/NotoColorEmoji.ttf" }`,+ );+ // Other keys (a `$schema`, say) survive a rewrite.+ const config = {+ ...raw,+ components: components ?? fallback,+ ...(renders !== undefined && { renders: parseRenders(renders) }),+ } as ProjectConfig;+ return { config, saved: components !== undefined };}export function writeConfig(cwd: string, config: ProjectConfig): void {@@ -51,3 +113,74 @@ export function writeConfig(cwd: string, config: ProjectConfig): void {`${JSON.stringify(config, null, "\t")}\n`,);}++/** Validates the `renders` map; errors name the render and field at fault. */+export function parseRenders(value: unknown): Record<string, RenderSpec> {+ if (!isRecord(value))+ throw new Error(+ `${CONFIG_FILE}: "renders" must map names to renders, e.g. { "film": { "entry": "src/film.ts" } }`,+ );+ const out: Record<string, RenderSpec> = {};+ for (const [name, spec] of Object.entries(value)) {+ const fail = (message: string) => {+ throw new Error(`${CONFIG_FILE}: renders.${name} ${message}`);+ };+ if (!RENDER_NAME.test(name))+ fail("has an invalid name: use letters, digits, -, _ and . (at most 64)");+ if (!isRecord(spec)) fail("must be an object with an entry");+ const s = spec as Record<string, unknown>;+ if (!isRelativePath(s.entry))+ fail(+ 'needs "entry": the module path inside the project, e.g. "src/film.ts"',+ );+ if (+ s.export !== undefined &&+ !(typeof s.export === "string" && IDENTIFIER.test(s.export))+ )+ fail('"export" must be a JavaScript identifier');+ for (const key of ["title", "description", "select"] as const)+ if (s[key] !== undefined && typeof s[key] !== "string")+ fail(`"${key}" must be a string`);+ if (s.workers !== undefined && s.workers !== "auto" && !isCount(s.workers))+ fail('"workers" must be "auto" or a positive whole number');+ if (s.maxWorkers !== undefined && !isCount(s.maxWorkers))+ fail('"maxWorkers" must be a positive whole number');+ if (s.codec !== undefined && s.codec !== "h264" && s.codec !== "vp9")+ fail('"codec" must be "h264" or "vp9"');+ if (s.quality !== undefined && !QUALITIES.includes(s.quality as string))+ fail(`"quality" must be one of ${QUALITIES.join(", ")}`);+ if (s.output !== undefined && typeof s.output !== "string")+ fail('"output" must be a file path');+ out[name] = s as unknown as RenderSpec;+ }+ return out;+}++/**+ * The named render `name` of the project at `cwd`, or undefined when there+ * is no render by that name (an entry path, say).+ */+export function findRender(+ cwd: string,+ name: string,+): (RenderSpec & { name: string }) | undefined {+ const spec = readConfig(cwd).config.renders?.[name];+ return spec && { ...spec, name };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function isCount(value: unknown): boolean {+ return typeof value === "number" && Number.isInteger(value) && value >= 1;+}++function isRelativePath(value: unknown): boolean {+ return (+ typeof value === "string" &&+ value.length > 0 &&+ !value.startsWith("/") &&+ !value.split(/[/\\]/).includes("..")+ );+}diff --git a/packages/framefields/src/cli/init.test.ts b/packages/framefields/src/cli/init.test.tsindex 1644e082..ec783373 100644--- a/packages/framefields/src/cli/init.test.ts+++ b/packages/framefields/src/cli/init.test.ts@@ -156,6 +156,15 @@ describe("framefields init", () => {mono: "assets/fonts/mono.ttf",emoji: "assets/fonts/emoji.ttf",},+ renders: {+ film: {+ title: "My Film",+ entry: "src/film.ts",+ export: "buildFilm",+ workers: "auto",+ output: "output/film.mp4",+ },+ },});const fontsTs = read(root("src/components/fonts.ts"));expect(fontsTs).toContain(diff --git a/packages/framefields/src/cli/init.ts b/packages/framefields/src/cli/init.tsindex 8d2774af..65d55eaf 100644--- a/packages/framefields/src/cli/init.ts+++ b/packages/framefields/src/cli/init.ts@@ -14,7 +14,7 @@ import { spawn } from "node:child_process";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { basename, dirname, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";-import { readConfig, writeConfig } from "./config.js";+import { CONFIG_FILE, readConfig, writeConfig } from "./config.js";import {type Fetch,type FontInstall,@@ -24,6 +24,7 @@ import {writeFontsModule,} from "./fonts.js";import {+ defaultRenders,ENV_EXAMPLE,FILM_TS,GITATTRIBUTES,@@ -191,11 +192,15 @@ export async function init(options: InitOptions): Promise<InitReport> {] as const)record(report, path, appendLines(join(root, path), lines));- // framefields.json, then fonts (recorded there) and their module.+ // framefields.json (components folder, named renders), then fonts (recorded there) and their module.+ const configExisted = existsSync(join(root, CONFIG_FILE));const { config, saved } = readConfig(root);- if (!saved) {- writeConfig(root, config);- report.written.push("framefields.json");+ if (!saved || !config.renders) {+ writeConfig(root, {+ ...config,+ renders: config.renders ?? defaultRenders(basename(root)),+ });+ record(report, CONFIG_FILE, configExisted || "written");}const installFonts = options.fonts !== false;const installEmoji = options.emoji ?? installFonts;diff --git a/packages/framefields/src/cli/renders.test.ts b/packages/framefields/src/cli/renders.test.tsnew file mode 100644index 00000000..a6894499--- /dev/null+++ b/packages/framefields/src/cli/renders.test.ts@@ -0,0 +1,168 @@+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { CloudRenderOptions, CloudRenderStatus } from "../cloud/index.js";+import { withNamedRender } from "../cloud/index.js";+import { pickRender, runCloudRender } from "./cloud.js";+import {+ CONFIG_FILE,+ parseRenders,+ readConfig,+ writeConfig,+} from "./config.js";++let cwd: string;++beforeEach(() => {+ cwd = mkdtempSync(join(tmpdir(), "ff-renders-"));+ mkdirSync(join(cwd, "src"));+ writeFileSync(join(cwd, "src/film.ts"), "export const buildFilm = 1;\n");+});+afterEach(() => rmSync(cwd, { recursive: true, force: true }));++const manifest = (value: unknown) =>+ writeFileSync(join(cwd, CONFIG_FILE), JSON.stringify(value));++describe("framefields.json renders", () => {+ it("reads renders without a components folder, which stays unsaved", () => {+ manifest({ renders: { film: { entry: "src/film.ts", workers: "auto" } } });+ expect(readConfig(cwd)).toEqual({+ config: {+ components: "src/components",+ renders: { film: { entry: "src/film.ts", workers: "auto" } },+ },+ saved: false,+ });+ });++ it("keeps renders and unknown keys when the config is rewritten", () => {+ manifest({+ $schema: "x",+ renders: { film: { entry: "src/film.ts" } },+ });+ const { config } = readConfig(cwd);+ writeConfig(cwd, { ...config, components: "src/parts" });+ expect(JSON.parse(readFileSync(join(cwd, CONFIG_FILE), "utf8"))).toEqual({+ $schema: "x",+ components: "src/parts",+ renders: { film: { entry: "src/film.ts" } },+ });+ });++ it("names the render and field at fault", () => {+ expect(() => parseRenders({ film: {} })).toThrow(+ 'framefields.json: renders.film needs "entry"',+ );+ expect(() => parseRenders({ film: { entry: "../x.ts" } })).toThrow(+ 'renders.film needs "entry"',+ );+ expect(() => parseRenders({ film: { entry: "a.ts", workers: 0 } })).toThrow(+ 'renders.film "workers" must be "auto"',+ );+ expect(() =>+ parseRenders({ film: { entry: "a.ts", export: "build film" } }),+ ).toThrow('"export" must be a JavaScript identifier');+ expect(() => parseRenders({ "bad name": { entry: "a.ts" } })).toThrow(+ "invalid name",+ );+ expect(() => parseRenders([])).toThrow('"renders" must map names');+ });+});++describe("picking a render", () => {+ it("takes a name, a module path, or the only named render", () => {+ manifest({ renders: { film: { entry: "src/film.ts" } } });+ expect(pickRender("film", cwd)).toEqual({ name: "film" });+ expect(pickRender("src/film.ts", cwd)).toEqual({ entry: "src/film.ts" });+ expect(pickRender(undefined, cwd)).toEqual({ name: "film" });+ });++ it("asks for a name when there are several, and lists them for a typo", () => {+ manifest({+ renders: {+ film: { entry: "src/film.ts" },+ teaser: { entry: "src/film.ts", export: "teaser" },+ },+ });+ expect(pickRender(undefined, cwd)).toEqual({+ error: "Name the render: film, teaser. `framefields renders` lists them.",+ });+ expect(pickRender("flim", cwd)).toEqual({+ error:+ '"flim" is neither a render in framefields.json (film, teaser) nor a file.',+ });+ });++ it("fills the request from the named render; options override it", () => {+ manifest({+ renders: {+ teaser: {+ title: "Teaser",+ entry: "src/film.ts",+ export: "buildTeaser",+ workers: "auto",+ codec: "vp9",+ },+ },+ });+ expect(withNamedRender(cwd, { render: "teaser", codec: "h264" })).toEqual({+ render: "teaser",+ name: "teaser",+ title: "Teaser",+ entry: "src/film.ts",+ export: "buildTeaser",+ workers: "auto",+ codec: "h264",+ args: undefined,+ select: undefined,+ maxWorkers: undefined,+ quality: undefined,+ });+ expect(() => withNamedRender(cwd, { render: "nope" })).toThrow(+ 'No render named "nope" in framefields.json. Renders: teaser.',+ );+ });++ it("renders a named render from the CLI with its output and hint", async () => {+ manifest({+ renders: {+ film: { entry: "src/film.ts", output: "out/launch.mp4" },+ },+ });+ const calls: CloudRenderOptions[] = [];+ const lines: string[] = [];+ const planned: CloudRenderStatus = {+ id: "r1",+ status: "planned",+ workers: 2,+ progress: { frames: 0, totalFrames: null, etaSec: null },+ costUsd: 0,+ gpuSeconds: 0,+ };+ const code = await runCloudRender(+ { plan: true, cwd },+ (l) => lines.push(l),+ async (o) => {+ calls.push(o);+ return planned;+ },+ );+ expect(code).toBe(0);+ expect(calls[0]).toMatchObject({+ cwd,+ render: "film",+ workers: "auto",+ dryRun: true,+ });+ expect(lines.at(-1)).toBe(+ "Render it: framefields render film --cloud --workers auto",+ );+ });+});diff --git a/packages/framefields/src/cli/templates.ts b/packages/framefields/src/cli/templates.tsindex 744d3d75..b453bd37 100644--- a/packages/framefields/src/cli/templates.ts+++ b/packages/framefields/src/cli/templates.ts@@ -3,6 +3,7 @@* setup skill describes. `film.ts` only builds; `render.ts` renders frames,* a grid, the live preview or the video; `theme.ts` holds the numbers.*/+import type { RenderSpec } from "./config.js";/*** Packages with install scripts. framefields needs exactly one (skia-canvas@@ -27,16 +28,28 @@ export const DEV_DEPENDENCIES: Record<string, string> = {export const SCRIPTS: Record<string, string> = {typecheck: "tsc --noEmit -p .",- check: "tsc --noEmit -p . && framefields check src/film.ts --json",- "check:render":- "tsc --noEmit -p . && framefields check src/film.ts --render --json",+ check: "tsc --noEmit -p . && framefields check film --json",+ "check:render": "tsc --noEmit -p . && framefields check film --render --json",frames: "tsx src/render.ts frames",grid: "tsx src/render.ts grid",preview: "tsx src/render.ts preview",render: "tsx src/render.ts",- "render:cloud": "framefields render src/film.ts --cloud --workers auto",+ "render:cloud": "framefields render film --cloud",};+/** The named render `init` records in framefields.json. */+export function defaultRenders(name: string): Record<string, RenderSpec> {+ return {+ film: {+ title: name,+ entry: "src/film.ts",+ export: "buildFilm",+ workers: "auto",+ output: "output/film.mp4",+ },+ };+}+/*** The `package.json` fields a framefields project needs. npm reads* `allowScripts`, pnpm its `pnpm` block, bun `trustedDependencies`.@@ -254,6 +267,9 @@ ${run("render")} # output/output.mp4${run("render:cloud")} # on cloud GPUs, from the pushed commit\`\`\`+- \`framefields.json\` names the renders: \`film\` is \`buildFilm\` in \`src/film.ts\`. Add an+ entry under \`renders\` for each cut (a teaser, a vertical edit) and render or check it by+ name: \`npx framefields render teaser --cloud\`, \`npx framefields check teaser\`.- \`src/film.ts\` builds the composition, \`src/theme.ts\` holds sizes, colors and fonts,\`src/render.ts\` renders it.- \`npx framefields list\` shows ready-made components; \`npx framefields add <name>\` copiesdiff --git a/packages/framefields/src/cloud/cloud.test.ts b/packages/framefields/src/cloud/cloud.test.tsindex a4382e92..3d06ee2c 100644--- a/packages/framefields/src/cloud/cloud.test.ts+++ b/packages/framefields/src/cloud/cloud.test.ts@@ -361,8 +361,8 @@ describe("render --cloud output", () => {expect(renderCommand({ entry: "src/film.ts", export: "split", workers: "2" }),).toBe("framefields render src/film.ts --cloud --export split --workers 2");- expect(renderCommand({ entry: "src/film.ts" })).toBe(- "framefields render src/film.ts --cloud --workers auto",+ expect(renderCommand({ entry: "film" })).toBe(+ "framefields render film --cloud",);});diff --git a/packages/framefields/src/cloud/index.ts b/packages/framefields/src/cloud/index.tsindex 7acb084d..ddf81ead 100644--- a/packages/framefields/src/cloud/index.ts+++ b/packages/framefields/src/cloud/index.ts@@ -6,13 +6,16 @@* import { renderCloud } from "framefields/cloud";** const result = await renderCloud({- * entry: "src/film.ts",- * workers: "auto", // split a long film across GPUs; 1 (default) renders on one+ * render: "film", // a render named in framefields.json* outputPath: "output/film.mp4",* onProgress: (s) => console.log(s.status, s.progress.frames),* });* ```*+ * Without a framefields.json, name the module instead: `entry: "src/film.ts"`+ * (and `export`, `workers`, …). Options passed here override the named+ * render's.+ ** `workers: "auto"` probes the film on one worker first, then splits it into* as many chunks as stay efficient: short films stay on one worker, long ones* spread out up to `maxWorkers`. `dryRun: true` returns that plan with the@@ -25,6 +28,7 @@ import path from "node:path";import { Readable } from "node:stream";import { pipeline } from "node:stream/promises";import type { ReadableStream as WebReadableStream } from "node:stream/web";+import { CONFIG_FILE, findRender, readConfig } from "../cli/config.js";import { type CloudSource, resolveGitSource } from "./git-source.js";export { type CloudSource, resolveGitSource, toHttps } from "./git-source.js";@@ -32,8 +36,10 @@ export { type CloudSource, resolveGitSource, toHttps } from "./git-source.js";export const FRAMEFIELDS_API_URL = "https://api.framefields.dev";export interface CloudRenderOptions {- /** The module that builds the composition, relative to `cwd`. */- entry: string;+ /** A render named in `cwd`'s framefields.json; its fields are the defaults here. */+ render?: string;+ /** The module that builds the composition, relative to `cwd`. Required without `render`. */+ entry?: string;/** Its export: a Composition, or a function returning one. Default `buildFilm`. */export?: string;/** Passed to the export when it is a function. */@@ -138,9 +144,10 @@ export async function renderCloud(): Promise<CloudRenderResult> {const api = cloudClient(options);const cwd = options.cwd ?? process.cwd();+ const o = withNamedRender(cwd, options);const resolved = options.source- ? { source: options.source, entry: options.entry, warnings: [] }- : resolveGitSource(cwd, options.entry);+ ? { source: options.source, entry: o.entry, warnings: [] }+ : resolveGitSource(cwd, o.entry);const warn =options.onWarning ??((m: string) => process.stderr.write(`framefields: ${m}\n`));@@ -150,17 +157,19 @@ export async function renderCloud(source: resolved.source,target: {entry: resolved.entry,- export: options.export ?? "buildFilm",- ...(options.args !== undefined && { args: options.args }),- ...(options.select && { select: [options.select] }),+ export: o.export ?? "buildFilm",+ ...(o.args !== undefined && { args: o.args }),+ ...(o.select && { select: [o.select] }),},render: {- codec: options.codec ?? "h264",- ...(options.quality && { quality: options.quality }),+ codec: o.codec ?? "h264",+ ...(o.quality && { quality: o.quality }),},- workers: options.workers ?? 1,- ...(options.maxWorkers && { max_workers: options.maxWorkers }),+ workers: o.workers ?? 1,+ ...(o.maxWorkers && { max_workers: o.maxWorkers }),dry_run: options.dryRun ?? false,+ ...(o.name && { name: o.name }),+ ...(o.title && { title: o.title }),});options.onProgress?.(status);@@ -197,6 +206,50 @@ export async function renderCloud(return status;}+/**+ * The options with a named render's fields filled in where the caller left+ * them out, plus the name and title the dashboard shows.+ */+export function withNamedRender(+ cwd: string,+ options: CloudRenderOptions,+): CloudRenderOptions & { entry: string; name?: string; title?: string } {+ if (!options.render) {+ if (!options.entry)+ throw new CloudRenderError(+ "Name a render from framefields.json (render) or a module (entry).",+ "invalid_request",+ );+ return { ...options, entry: options.entry };+ }+ const spec = findRender(cwd, options.render);+ if (!spec) {+ const names = Object.keys(readConfig(cwd).config.renders ?? {});+ throw new CloudRenderError(+ names.length+ ? `No render named "${options.render}" in ${CONFIG_FILE}. Renders: ${names.join(", ")}.`+ : `No render named "${options.render}": ${CONFIG_FILE} has no "renders".`,+ "render_not_found",+ );+ }+ const defined = Object.fromEntries(+ Object.entries(options).filter(([, v]) => v !== undefined),+ ) as CloudRenderOptions;+ return {+ entry: spec.entry,+ export: spec.export,+ args: spec.args,+ select: spec.select,+ workers: spec.workers,+ maxWorkers: spec.maxWorkers,+ codec: spec.codec,+ quality: spec.quality,+ ...defined,+ name: spec.name,+ title: spec.title ?? spec.name,+ } as CloudRenderOptions & { entry: string; name: string; title: string };+}+/** The API calls behind `renderCloud`, for callers who track renders themselves. */export function cloudClient(options: Pick<CloudRenderOptions, "apiKey" | "apiUrl">,diff --git a/plugins/framefields/skills/framefields-render/SKILL.md b/plugins/framefields/skills/framefields-render/SKILL.mdindex 6eefe70f..f62f9975 100644--- a/plugins/framefields/skills/framefields-render/SKILL.md+++ b/plugins/framefields/skills/framefields-render/SKILL.md@@ -44,7 +44,7 @@ Typecheck the project:npx tsc --noEmit -p .```-In projects initialized with the current CLI, `pnpm check` runs typechecking and document preflight. For another entry, run `pnpm exec framefields check src/film.ts --export buildFilm --json`. The export is a `Composition` or a builder returning one; importing it executes project code, so keep rendering, generation and writes out of the builder. The CLI runs it in an isolated process, routes builder logs to stderr and writes one versioned JSON result to stdout. Errors fail the command; warnings fail with `--warnings-as-errors`. `--timeout 60000` bounds the worker lifetime.+In projects initialized with the current CLI, `pnpm check` runs typechecking and document preflight. For a named render, run `pnpm exec framefields check teaser --json`; with no argument it checks every render in `framefields.json`. For another module, `pnpm exec framefields check src/film.ts --export buildFilm --json`. The export is a `Composition` or a builder returning one; importing it executes project code, so keep rendering, generation and writes out of the builder. The CLI runs it in an isolated process, routes builder logs to stderr and writes one versioned JSON result to stdout. Errors fail the command; warnings fail with `--warnings-as-errors`. `--timeout 60000` bounds the worker lifetime.`pnpm check:render` adds GPU verification, a frame and a three-point grid under `output/check`; `--output <dir>` changes the location. This smoke check does not replace targeted pixel assertions or video QA. A failed or unavailable GPU check is reported as a failure. Use `pnpm exec framefields api` for timing, grid and preflight type declarations generated from this SDK version.@@ -192,15 +192,30 @@ await stitchChunks({ chunks: ["out/chunk-0.mp4", "out/chunk-1.mp4"], audio: "outapi.framefields.dev renders the project on framefields' GPUs and splits a long film across several. It fetches the project from git, so it renders the **pushed commit**: commit and push first; uncommitted changes are not rendered (the CLI warns), and an unpushed commit is refused. It bills the account behind `FRAMEFIELDS_API_KEY`; if authentication is required, ask the user to set it in the process environment and never print or embed it.+Renders are named in `framefields.json` (`init` writes `film`), so nobody picks files: the CLI, `renderCloud` and the dashboard's New render dialog all list them.++```json+{+ "renders": {+ "film": { "title": "Launch film", "entry": "src/film.ts", "export": "buildFilm", "workers": "auto", "output": "output/film.mp4" },+ "teaser": { "title": "15 s teaser", "description": "Vertical cut for socials", "entry": "src/film.ts", "export": "buildTeaser" }+ }+}+```++Each render takes `entry` (required, relative to the project root), `export` (default `buildFilm`), `title`, `description`, `args`, `select`, `workers`, `maxWorkers`, `codec`, `quality` and `output`. Add one per cut instead of parameterizing the render script; `npx framefields renders` lists them, `npx framefields check` checks all of them.+```bash-npx framefields render src/film.ts --cloud --workers auto --plan # workers, time and estimated cost; renders nothing-npx framefields render src/film.ts --cloud --workers auto # render, then download to output/film.mp4+npx framefields render film --cloud --plan # workers, time and estimated cost; renders nothing+npx framefields render film --cloud # render, then download to the render's output+npx framefields render src/film.ts --cloud --export buildFilm --workers auto # a module, without a manifest```-- `--workers` defaults to 1 (one GPU, no planning step). `auto` measures frame costs on one worker, then uses as many workers as stay efficient: a 5-minute film stays on one, a 3-hour film spreads to `--max-workers` (API cap 10). A number splits into that many.+- Flags override the named render's fields. With one named render, `framefields render --cloud` needs no name.+- `--workers` defaults to the render's `workers`, else 1 (one GPU, no planning step). `auto` measures frame costs on one worker, then uses as many workers as stay efficient: a 5-minute film stays on one, a 3-hour film spreads to `--max-workers` (API cap 10). A number splits into that many.- Show the user `--plan` before a long or expensive render: it prints the estimated cost.- Ctrl-C cancels the render; GPU time already used is charged. Failures print the worker's error code (e.g. `ASSET_NOT_FOUND` for an asset left out of LFS).-- From code: `renderCloud({ entry, workers: "auto", outputPath, onProgress })` from `framefields/cloud` (no GPU needed locally). The HTTP API is `POST /v1/render` (`workers`, `max_workers`, `dry_run`), `GET` and `DELETE /v1/render/:id`.+- From code: `renderCloud({ render: "film", outputPath, onProgress })` (or `{ entry, export, workers }`) from `framefields/cloud` (no GPU needed locally). The HTTP API is `POST /v1/render` (`workers`, `max_workers`, `dry_run`), `GET` and `DELETE /v1/render/:id`.---diff --git a/plugins/framefields/skills/framefields/SKILL.md b/plugins/framefields/skills/framefields/SKILL.mdindex 52d28ebd..e928c993 100644--- a/plugins/framefields/skills/framefields/SKILL.md+++ b/plugins/framefields/skills/framefields/SKILL.md@@ -226,7 +226,18 @@ Add scripts to `package.json`:"grid": "tsx src/render.ts grid","preview": "tsx src/render.ts preview","render": "tsx src/render.ts",- "render:cloud": "framefields render src/film.ts --cloud --workers auto"+ "render:cloud": "framefields render film --cloud"+}+```++`framefields.json` names what the project renders; `film` is the scaffold's. Add an entry per cut (teaser, vertical edit) so the CLI, `framefields check` and the dashboard pick it by name:++```json+{+ "components": "src/components",+ "renders": {+ "film": { "title": "Launch film", "entry": "src/film.ts", "export": "buildFilm", "workers": "auto", "output": "output/film.mp4" }+ }}```@@ -403,7 +414,7 @@ npx framefields add mouse-pointer focus-zoom # writes src/components/<name>/npx framefields fonts add emoji # color emoji (chat-thread and captions add it themselves)```-The generated project also has `check` (TypeScript plus schema/lint/timeline preflight) and `check:render` (adds a GPU frame/grid smoke check) scripts. They produce versioned JSON for agents and terminate with a failure code on errors. For a custom entry, use `framefields check src/film.ts --export buildFilm --json`; add `--render` to write inspection artifacts under `output/check`. Keep the builder free of generation, rendering and writes, because preflight imports and executes it.+The generated project also has `check` (TypeScript plus schema/lint/timeline preflight) and `check:render` (adds a GPU frame/grid smoke check) scripts. They produce versioned JSON for agents and terminate with a failure code on errors. For another named render, use `framefields check teaser --json` (no name checks them all); for a module without one, `framefields check src/film.ts --export buildFilm --json`; add `--render` to write inspection artifacts under `output/check`. Keep the builder free of generation, rendering and writes, because preflight imports and executes it.```typescriptimport { MousePointer } from "./components/mouse-pointer/index.js";