Skip to content

Code-first video & image, rendered natively on WebGPU.

rm cli refs

okanasl8cb97c6c65ba
diff --git a/.changeset/ff-cli.md b/.changeset/ff-cli.md
deleted file mode 100644
index e17f4ea6..00000000
--- a/.changeset/ff-cli.md
+++ /dev/null
@@ -1,8 +0,0 @@
----
-"framefields": minor
----
-
-Add `framefields.json`, the project manifest.
-
-- `framefields/project`: `loadProject`, `resolveComposition` and `buildComposition` read a project's compositions from `framefields.json` (or the implicit `src/film.ts#buildFilm`); the JSON Schema ships as `framefields/schemas/project.v1.json`.
-- `startPreview({ project, composition })` previews a project's composition, and the page switches between its compositions.
diff --git a/examples/24_audio_capabilities/framefields.json b/examples/24_audio_capabilities/framefields.json
deleted file mode 100644
index f9947067..00000000
--- a/examples/24_audio_capabilities/framefields.json
+++ /dev/null
@@ -1,55 +0,0 @@
-{
- "$schema": "https://framefields.dev/schemas/project.v1.json",
- "version": 1,
- "compositions": {
- "showcase": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildAudioShowcase",
- "title": "Audio showcase",
- "default": true
- },
- "step-1": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep1InitialAudio",
- "title": "Initial audio",
- "group": "Steps",
- "description": "Clean baseline soundtrack without DSP"
- },
- "step-2": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep2FadedAudio",
- "title": "Fade in/out",
- "group": "Steps"
- },
- "step-3": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep3FadedReverbAudio",
- "title": "Fade + reverb",
- "group": "Steps"
- },
- "step-4": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep4DelayAudio",
- "title": "Delay",
- "group": "Steps"
- },
- "step-5": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep5ParametricEqAudio",
- "title": "Parametric EQ",
- "group": "Steps"
- },
- "step-6": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep6CompressorAudio",
- "title": "Compressor",
- "group": "Steps"
- },
- "step-7": {
- "entry": "src/audio-pipeline.ts",
- "export": "buildStep7StereoPanningAudio",
- "title": "Stereo panning",
- "group": "Steps"
- }
- }
-}
diff --git a/packages/framefields/package.json b/packages/framefields/package.json
index 13bdabb6..b88dcb95 100644
--- a/packages/framefields/package.json
+++ b/packages/framefields/package.json
@@ -71,21 +71,13 @@
"development": "./src/preview/index.ts",
"import": "./dist/preview/index.mjs",
"default": "./dist/preview/index.mjs"
- },
- "./project": {
- "types": "./dist/project/index.d.mts",
- "development": "./src/project/index.ts",
- "import": "./dist/project/index.mjs",
- "default": "./dist/project/index.mjs"
- },
- "./schemas/project.v1.json": "./schemas/project.v1.json"
+ }
},
"files": [
- "dist/**",
- "schemas/**"
+ "dist/**"
],
"scripts": {
- "build": "tsdown && node scripts/generate-project-schema.mjs && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs",
+ "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs",
"dev": "tsdown --watch",
"clean": "rm -rf dist .turbo",
"prepack": "node ../../scripts/sync-readme.mjs",
diff --git a/packages/framefields/schemas/project.v1.json b/packages/framefields/schemas/project.v1.json
deleted file mode 100644
index 49ef0596..00000000
--- a/packages/framefields/schemas/project.v1.json
+++ /dev/null
@@ -1,82 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "type": "object",
- "properties": {
- "$schema": {
- "type": "string"
- },
- "version": {
- "default": 1,
- "type": "number",
- "const": 1
- },
- "compositions": {
- "type": "object",
- "propertyNames": {
- "type": "string",
- "pattern": "^[a-z0-9][a-z0-9-]{0,62}$"
- },
- "additionalProperties": {
- "type": "object",
- "properties": {
- "entry": {
- "type": "string",
- "minLength": 1
- },
- "export": {
- "default": "default",
- "type": "string",
- "pattern": "^[A-Za-z_$][\\w$]*$"
- },
- "title": {
- "type": "string",
- "maxLength": 120
- },
- "description": {
- "type": "string",
- "maxLength": 500
- },
- "group": {
- "type": "string",
- "maxLength": 60
- },
- "default": {
- "type": "boolean"
- }
- },
- "required": [
- "entry"
- ],
- "additionalProperties": {}
- }
- },
- "assets": {
- "type": "object",
- "properties": {
- "directory": {
- "type": "string",
- "minLength": 1
- },
- "exclude": {
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1
- }
- }
- },
- "additionalProperties": {}
- },
- "output": {
- "type": "string",
- "minLength": 1
- }
- },
- "required": [
- "compositions"
- ],
- "additionalProperties": {},
- "$id": "https://framefields.dev/schemas/project.v1.json",
- "title": "framefields.json",
- "description": "Framefields project manifest: the project's compositions, by stable id."
-}
diff --git a/packages/framefields/scripts/generate-project-schema.mjs b/packages/framefields/scripts/generate-project-schema.mjs
deleted file mode 100644
index 4e07573b..00000000
--- a/packages/framefields/scripts/generate-project-schema.mjs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Writes schemas/project.v1.json, the JSON Schema for framefields.json, from
-// the zod schema in src/project so editors validate the manifest. Runs after
-// tsdown, against the built module.
-import { mkdirSync, writeFileSync } from "node:fs";
-import { z } from "zod";
-import {
- MANIFEST_SCHEMA_URL,
- projectManifestSchema,
-} from "../dist/project/index.mjs";
-
-const schema = {
- ...z.toJSONSchema(projectManifestSchema, { io: "input" }),
- $id: MANIFEST_SCHEMA_URL,
- title: "framefields.json",
- description:
- "Framefields project manifest: the project's compositions, by stable id.",
-};
-
-mkdirSync("schemas", { recursive: true });
-writeFileSync(
- "schemas/project.v1.json",
- `${JSON.stringify(schema, null, "\t")}\n`,
-);
-console.log("schemas/project.v1.json");
diff --git a/packages/framefields/src/preview/index.ts b/packages/framefields/src/preview/index.ts
index 36e30f36..26b3c324 100644
--- a/packages/framefields/src/preview/index.ts
+++ b/packages/framefields/src/preview/index.ts
@@ -7,11 +7,6 @@ import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { VirtualMediaData } from "@framefields/core";
import { encodeStereoWav } from "../audio/index.js";
-import {
- type Project,
- type ResolvedComposition,
- resolveComposition,
-} from "../project/index.js";
import { HeadlessMediaRenderer } from "../renderer/index.js";
import {
bundleProject,
@@ -23,11 +18,8 @@ import {
import { describeNote, type NewNote, NoteStore } from "./notes.js";
import { previewPage } from "./page.js";
-/** Where the composition comes from: the module that builds it, or a project's composition. */
-export type PreviewSource = PreviewEntrySource | PreviewProjectSource;
-
-/** The module that builds the composition. */
-export interface PreviewEntrySource {
+/** Where the composition comes from: the module that builds it. */
+export interface PreviewSource {
/** Path or file URL of the module, e.g. `new URL("./film.ts", import.meta.url)`. */
entry: string | URL;
/**
@@ -37,16 +29,6 @@ export interface PreviewEntrySource {
export?: string;
}
-/**
- * A composition of a project (see `framefields/project`). The page can switch
- * between the project's compositions.
- */
-export interface PreviewProjectSource {
- project: Project;
- /** A composition id, `file#export`, or undefined for the default. */
- composition?: string;
-}
-
/** What the server needs from the composition: its size, timing and soundtrack. */
interface PreviewTarget {
toVirtualMedia?(): VirtualMediaData;
@@ -127,10 +109,6 @@ export interface PreviewSession {
interface PreviewMeta {
session: string;
- /** The composition shown, when previewing a project. */
- composition: string | null;
- /** The project's compositions, for the page's picker. */
- compositions: { id: string; title: string; group: string | null }[];
/** Where notes are kept; null when they are off. */
notesDir: string | null;
title: string;
@@ -166,42 +144,18 @@ export async function startPreview(
source: PreviewSource,
options: PreviewOptions = {},
): Promise<PreviewSession> {
- const project = "project" in source ? source.project : undefined;
- const pick = (ref?: string): Picked => {
- if (!project) {
- const s = source as PreviewEntrySource;
- const entry =
- s.entry instanceof URL || String(s.entry).startsWith("file:")
- ? fileURLToPath(s.entry)
- : path.resolve(String(s.entry));
- return { id: null, entry, exportName: s.export ?? "default" };
- }
- const c = resolveComposition(project, ref);
- return {
- id: c.id,
- entry: path.join(project.root, c.entry),
- exportName: c.export,
- composition: c,
- };
- };
- let current = pick("project" in source ? source.composition : undefined);
- const compositions = project
- ? [
- ...project.compositions,
- ...(current.composition &&
- !project.compositions.includes(current.composition)
- ? [current.composition]
- : []),
- ].map((c) => ({ id: c.id, title: c.title, group: c.group }))
- : [];
- const baseDir = project?.root ?? path.dirname(current.entry);
+ const entry =
+ source.entry instanceof URL || String(source.entry).startsWith("file:")
+ ? fileURLToPath(source.entry)
+ : path.resolve(String(source.entry));
+ const exportName = source.export ?? "default";
// Vision nodes load their cached models, and onnxruntime-web's files when
// the project has it installed.
const modelsDir = visionModelsDir();
- const ort = onnxRuntimeWeb(baseDir);
+ const ort = onnxRuntimeWeb(path.dirname(entry));
const roots = [
...(options.root === undefined
- ? [repoRoot(baseDir)]
+ ? [repoRoot(path.dirname(entry))]
: Array.isArray(options.root)
? options.root
: [options.root]),
@@ -213,8 +167,8 @@ export async function startPreview(
const sseClients = new Set<http.ServerResponse>();
const idleCloseMs = options.idleCloseMs ?? 5000;
let idleTimer: NodeJS.Timeout | undefined;
- const titleFor = (p: Picked) =>
- options.title ?? p.composition?.title ?? "framefields preview";
+ const title = options.title ?? "framefields preview";
+ const session = randomUUID();
const log =
options.log === false
? () => {}
@@ -224,34 +178,25 @@ export async function startPreview(
const reported = new Set<string>();
let pageOpened = false;
- // Several compositions keep their notes apart, one folder each.
- const notesFor = (p: Picked) =>
+ const notes =
options.notesDir === false
? undefined
: new NoteStore(
path.resolve(
options.notesDir ??
path.join(process.cwd(), ".framefields", "preview-notes"),
- compositions.length > 1 && p.id ? p.id : "",
),
);
- let notes = notesFor(current);
// Changes run one at a time: each reads and rewrites notes.json.
let noteQueue: Promise<unknown> = Promise.resolve();
- const describe = (target: PreviewTarget, p: Picked) =>
- resolveMeta(target, titleFor(p), randomUUID(), notes?.dir ?? null, {
- composition: p.id,
- compositions,
- });
- let target = await loadTarget(current.entry, current.exportName);
- let meta = await describe(target, current);
+ const target = await loadTarget(entry, exportName);
+ const meta = await resolveMeta(target, title, session, notes?.dir ?? null);
// The project's own code, bundled against the browser engine; the engine
// itself is prebuilt (or built once, running from source).
let bundle: Promise<string> | undefined;
const playerBundle = () => {
if (!bundle) {
- const { entry, exportName } = current;
const built = bundleProject({
entry,
exportName,
@@ -277,9 +222,6 @@ export async function startPreview(
state: options.audio === false ? "none" : "mixing",
};
let audioWav: Buffer | undefined;
- // Bumped on each switch, so a soundtrack still mixing for the last
- // composition is dropped.
- let generation = 0;
function broadcast(event: string, data: unknown) {
for (const client of sseClients) {
@@ -299,16 +241,13 @@ export async function startPreview(
return;
}
const renderer = options.renderer ?? new HeadlessMediaRenderer();
- const mixing = generation;
- const { fps } = meta;
(async () => {
const vm = target.toVirtualMediaAsync
? await target.toVirtualMediaAsync()
: (target.toVirtualMedia as () => VirtualMediaData)();
- return renderer.renderAudio(vm, { fps });
+ return renderer.renderAudio(vm, { fps: meta.fps });
})().then(
({ channels, sampleRate }) => {
- if (mixing !== generation) return;
const left = channels[0] ?? new Float32Array(0);
const right = channels[1] ?? left;
const peaks = computePeaks(left, right, PEAK_BINS);
@@ -324,7 +263,6 @@ export async function startPreview(
});
},
(err: unknown) => {
- if (mixing !== generation) return;
setAudio({
state: "error",
error: err instanceof Error ? err.message : String(err),
@@ -452,30 +390,6 @@ export async function startPreview(
});
return;
}
- // The page's composition picker: load the other composition, then
- // say hello with a new session so open tabs reload into it.
- if (
- project &&
- req.method === "POST" &&
- url.pathname === "/@framefields/composition" &&
- req.headers["content-type"] === "application/json"
- ) {
- const { id } = JSON.parse(await readBody(req, 4096)) as {
- id?: unknown;
- };
- if (typeof id !== "string" || !compositions.some((c) => c.id === id)) {
- sendJson(res, 404, { error: "no such composition" });
- return;
- }
- try {
- await switchTo(id);
- } catch (err) {
- sendJson(res, 422, { error: errorText(err) });
- return;
- }
- sendJson(res, 200, { ok: true, session: meta.session });
- return;
- }
// A newer preview of the same project wants this port. The custom
// header keeps web pages from triggering it (it forces a CORS preflight).
if (
@@ -510,10 +424,9 @@ export async function startPreview(
res.writeHead(204).end();
return;
}
- const store = notes;
- if (store && url.pathname === "/@framefields/notes") {
+ if (notes && url.pathname === "/@framefields/notes") {
if (req.method === "GET") {
- sendJson(res, 200, await store.list());
+ sendJson(res, 200, await notes.list());
return;
}
if (
@@ -528,11 +441,11 @@ export async function startPreview(
note?: NewNote;
};
const change = noteQueue.then(() =>
- changeNote(store, body, meta.fps, say),
+ changeNote(notes, body, meta.fps, say),
);
noteQueue = change.catch(() => {});
const note = await change;
- broadcast("notes", await store.list());
+ broadcast("notes", await notes.list());
sendJson(res, note ? 200 : 404, note ?? { error: "no such note" });
return;
}
@@ -589,25 +502,6 @@ export async function startPreview(
}
});
- async function switchTo(id: string) {
- if (id === current.id) return;
- const next = pick(id);
- const nextTarget = await loadTarget(next.entry, next.exportName);
- current = next;
- target = nextTarget;
- notes = notesFor(next);
- meta = await describe(nextTarget, next);
- bundle = undefined;
- generation++;
- audioWav = undefined;
- audio = { state: options.audio === false ? "none" : "mixing" };
- reported.clear();
- say(`switched to ${id}`);
- void playerBundle().catch(() => {});
- startAudio();
- broadcast("hello", { session: meta.session });
- }
-
let onClient: (() => void) | undefined;
const host = options.host ?? "127.0.0.1";
const port = options.port ?? stablePort();
@@ -834,27 +728,17 @@ async function sendFile(
fs.createReadStream(file, { start, end }).pipe(res);
}
-/** The composition being previewed. */
-interface Picked {
- id: string | null;
- entry: string;
- exportName: string;
- composition?: ResolvedComposition;
-}
-
async function resolveMeta(
target: PreviewTarget,
title: string,
session: string,
notesDir: string | null,
- project: Pick<PreviewMeta, "composition" | "compositions">,
): Promise<PreviewMeta> {
const fps = target.fps ?? 24;
const durationMs =
target.durationMs ?? (await target.computeDuration?.()) ?? 5000;
return {
session,
- ...project,
notesDir,
title,
fps,
diff --git a/packages/framefields/src/preview/page.ts b/packages/framefields/src/preview/page.ts
index 13974b51..3fa752e7 100644
--- a/packages/framefields/src/preview/page.ts
+++ b/packages/framefields/src/preview/page.ts
@@ -62,12 +62,6 @@ export const previewPage = /* html */ `<!doctype html>
.sep { width: 1px; height: 18px; background: var(--line-2); flex: none; margin: 0 2px; }
.top h1 { font-size: 14px; font-weight: 600; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.spec { color: var(--ink-3); font-size: 12px; white-space: nowrap; }
- .comp {
- height: 28px; max-width: 260px; padding: 0 8px; border: 1px solid var(--line); border-radius: 8px;
- background: var(--surface); color: var(--ink); font: inherit; font-size: 12.5px; flex: none; cursor: pointer;
- }
- .comp:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
- .comp:disabled { opacity: .6; cursor: progress; }
@media (max-width: 640px) { .spec { display: none; } }
.chip {
display: inline-flex; align-items: center; gap: 8px; height: 26px; padding: 0 10px; white-space: nowrap;
@@ -292,7 +286,6 @@ export const previewPage = /* html */ `<!doctype html>
<svg class="logo" viewBox="0 0 512 512" aria-label="framefields" role="img"><g fill="none" stroke="currentColor" stroke-linecap="round"><path d="M184 56H86q-30 0-30 30v98M328 56h98q30 0 30 30v98M184 456H86q-30 0-30-30v-98M328 456h98q30 0 30-30v-98" stroke-width="34" stroke-linejoin="round"/><path d="M176 182v148m0-148c0 74 60 74 100 74" stroke-width="28"/></g><g fill="currentColor"><circle cx="176" cy="172" r="32"/><circle cx="176" cy="340" r="32"/><path d="M284 200l78 56-78 56z" stroke="currentColor" stroke-width="34" stroke-linejoin="round"/></g></svg>
<span class="sep" aria-hidden="true"></span>
<h1 id="title">framefields preview</h1>
- <select class="comp" id="comp" aria-label="Composition" title="Composition" hidden></select>
<span class="grow"></span>
<span class="spec tnum" id="spec"></span>
<span class="chip" id="chip" data-state="mixing" role="status" aria-live="polite"><span class="spinner"></span><span>Mixing audio</span></span>
@@ -1168,51 +1161,11 @@ export const previewPage = /* html */ `<!doctype html>
$("title").textContent = m.title;
$("spec").textContent = m.width + "×" + m.height + " · " + m.fps + " fps · " + fmt(last());
$("tcDur").textContent = fmt(last());
- renderPicker(m);
stage.style.setProperty("--ar", m.width + " / " + m.height);
stage.style.setProperty("--ar-n", String(m.width / m.height));
renderRuler();
}
- // A project's compositions: switching asks the server to load the other one,
- // and its hello with a new session reloads this tab into it.
- function renderPicker(m) {
- var sel = $("comp"), list = m.compositions || [];
- sel.hidden = list.length < 2;
- if (sel.hidden) return;
- sel.textContent = "";
- var groups = {};
- list.forEach(function (c) {
- var opt = document.createElement("option");
- opt.value = c.id;
- opt.textContent = c.title === c.id ? c.id : c.title + " (" + c.id + ")";
- opt.selected = c.id === m.composition;
- if (!c.group) { sel.appendChild(opt); return; }
- if (!groups[c.group]) {
- groups[c.group] = document.createElement("optgroup");
- groups[c.group].label = c.group;
- sel.appendChild(groups[c.group]);
- }
- groups[c.group].appendChild(opt);
- });
- }
- $("comp").addEventListener("change", function () {
- var sel = $("comp");
- sel.disabled = true;
- fetch("/@framefields/composition", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ id: sel.value })
- }).then(function (r) { return r.json().then(function (b) { return [r.ok, b]; }); }).then(function (res) {
- if (!res[0]) throw new Error(res[1].error || "could not switch");
- location.reload();
- }).catch(function (err) {
- sel.disabled = false;
- sel.value = meta.composition;
- showError(err);
- });
- });
-
new ResizeObserver(function () {
if (!meta) return;
renderRuler();
diff --git a/packages/framefields/src/project/index.ts b/packages/framefields/src/project/index.ts
deleted file mode 100644
index e6b6a18a..00000000
--- a/packages/framefields/src/project/index.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-/**
- * `framefields.json`, the project manifest: names a project's compositions so
- * tools (the `ff` CLI, the preview, Framefields Cloud, agents) can tell what is
- * previewable without running code. Each composition is the `{ entry, export }`
- * pair `startPreview` already takes, under a stable id.
- *
- * This module only reads JSON and imports entries on request; it never loads
- * the engine itself, so the CLI can bundle it.
- */
-import fs from "node:fs";
-import path from "node:path";
-import { pathToFileURL } from "node:url";
-import { z } from "zod";
-import type { Composition } from "../index.js";
-
-export const MANIFEST_FILE = "framefields.json";
-export const MANIFEST_SCHEMA_URL =
- "https://framefields.dev/schemas/project.v1.json";
-
-/** Used when a project has no manifest: the layout `ff init` scaffolds. */
-export const DEFAULT_COMPOSITION = {
- id: "film",
- entry: "src/film.ts",
- export: "buildFilm",
-} as const;
-
-const COMPOSITION_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
-const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
-const ENTRY_EXT = /\.(ts|tsx|mts|js|mjs)$/;
-
-const isInsidePath = (p: string) =>
- !p.startsWith("/") &&
- !/^[A-Za-z]:/.test(p) &&
- !p.split(/[\\/]/).includes("..");
-
-const entryPath = z
- .string()
- .min(1)
- .refine(isInsidePath, "entry must be a path inside the project")
- .regex(ENTRY_EXT, "entry must be a .ts, .tsx, .mts, .js or .mjs file");
-
-const compositionSchema = z.looseObject({
- entry: entryPath,
- export: z
- .string()
- .regex(IDENTIFIER, "export must be a JavaScript identifier")
- .default("default"),
- title: z.string().max(120).optional(),
- description: z.string().max(500).optional(),
- /** Groups compositions in pickers, e.g. "Steps" or "Scenes". */
- group: z.string().max(60).optional(),
- /** The composition opened and rendered when none is named. At most one. */
- default: z.boolean().optional(),
-});
-
-const assetsSchema = z.looseObject({
- directory: z
- .string()
- .min(1)
- .refine(isInsidePath, "assets.directory must be inside the project")
- .optional(),
- exclude: z.array(z.string().min(1)).optional(),
-});
-
-export const projectManifestSchema = z.looseObject({
- $schema: z.string().optional(),
- version: z.literal(1).default(1),
- compositions: z
- .record(
- z
- .string()
- .regex(
- COMPOSITION_ID,
- "composition ids are lowercase letters, digits and dashes (max 63)",
- ),
- compositionSchema,
- )
- .refine(
- (c) => Object.keys(c).length > 0,
- "declare at least one composition",
- )
- .refine(
- (c) => Object.values(c).filter((x) => x.default).length <= 1,
- "only one composition can be the default",
- ),
- assets: assetsSchema.optional(),
- output: z
- .string()
- .min(1)
- .refine(isInsidePath, "output must be inside the project")
- .optional(),
-});
-
-export type ProjectManifest = z.input<typeof projectManifestSchema>;
-
-export interface ResolvedComposition {
- id: string;
- entry: string;
- export: string;
- title: string;
- description: string | null;
- group: string | null;
- default: boolean;
-}
-
-export interface Project {
- /** Directory containing framefields.json (or package.json). */
- root: string;
- source: "manifest" | "default";
- compositions: ResolvedComposition[];
- defaultId: string;
- assets: { directory: string; exclude: string[] };
- output: string;
-}
-
-export type ProjectErrorKind =
- /** No framefields.json or package.json above the directory. */
- | "not-found"
- /** framefields.json is not valid JSON or breaks a rule. */
- | "invalid"
- /** A `<composition>` reference names nothing in the project. */
- | "unknown-composition"
- /** The entry could not be imported, or its export isn't a composition. */
- | "build";
-
-/** A problem with a project, its manifest or a composition reference. */
-export class ProjectError extends Error {
- override name = "ProjectError";
- constructor(
- message: string,
- readonly kind: ProjectErrorKind,
- /** The file the problem is in, when there is one. */
- readonly path?: string,
- /** A follow-up the user can run or check. */
- readonly hint?: string,
- ) {
- super(message);
- }
-}
-
-/** `step-1` → `Step 1`. */
-export const humanize = (id: string) =>
- id.replace(/-+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
-
-/**
- * Parses manifest JSON (already decoded) into a project at `root`. Exposed for
- * readers that get the file from elsewhere, such as a git tree.
- */
-export function resolveManifest(json: unknown, root: string): Project {
- const file = path.join(root, MANIFEST_FILE);
- const parsed = projectManifestSchema.safeParse(json);
- if (!parsed.success) {
- const issue = parsed.error.issues[0];
- const where = issue?.path.length ? ` at ${issue.path.join(".")}` : "";
- throw new ProjectError(
- `${MANIFEST_FILE}${where}: ${issue?.message ?? "invalid"}`,
- "invalid",
- file,
- );
- }
- const data = parsed.data;
- const entries = Object.entries(data.compositions);
- const defaultId =
- entries.find(([, c]) => c.default)?.[0] ?? (entries[0]?.[0] as string);
- return {
- root,
- source: "manifest",
- defaultId,
- compositions: entries.map(([id, c]) => ({
- id,
- entry: normalizeEntry(c.entry),
- export: c.export,
- title: c.title ?? humanize(id),
- description: c.description ?? null,
- group: c.group ?? null,
- default: id === defaultId,
- })),
- assets: {
- directory: data.assets?.directory ?? "assets",
- exclude: data.assets?.exclude ?? ["**/.DS_Store"],
- },
- output: data.output ?? "output",
- };
-}
-
-/** The project of a directory with no manifest: one composition, `film`. */
-export function defaultProject(root: string): Project {
- const c = DEFAULT_COMPOSITION;
- return {
- root,
- source: "default",
- defaultId: c.id,
- compositions: [
- {
- ...c,
- title: humanize(c.id),
- description: null,
- group: null,
- default: true,
- },
- ],
- assets: { directory: "assets", exclude: ["**/.DS_Store"] },
- output: "output",
- };
-}
-
-/**
- * Finds the project root from `cwd` upwards and resolves its manifest. The
- * root is the nearest directory holding `framefields.json` or `package.json`;
- * a package without a manifest gets the default `film` composition.
- */
-export async function loadProject(cwd = process.cwd()): Promise<Project> {
- const start = path.resolve(cwd);
- for (let dir = start; ; dir = path.dirname(dir)) {
- const manifest = path.join(dir, MANIFEST_FILE);
- if (fs.existsSync(manifest)) {
- const raw = await fs.promises.readFile(manifest, "utf8");
- let json: unknown;
- try {
- json = JSON.parse(raw);
- } catch (err) {
- throw new ProjectError(
- `${MANIFEST_FILE} is not valid JSON: ${(err as Error).message}`,
- "invalid",
- manifest,
- );
- }
- return resolveManifest(json, dir);
- }
- if (fs.existsSync(path.join(dir, "package.json")))
- return defaultProject(dir);
- if (path.dirname(dir) === dir) break;
- }
- throw new ProjectError(
- `no framefields project found in ${start} or any parent directory`,
- "not-found",
- undefined,
- "ff init",
- );
-}
-
-/** True when `ref` is a `file#export` or file reference rather than an id. */
-export function isFileReference(ref: string): boolean {
- const file = ref.split("#")[0] ?? "";
- return ref.includes("#") || ENTRY_EXT.test(file) || file.includes("/");
-}
-
-/**
- * Resolves `<composition>` (an id, `file#export`, a bare file, or undefined
- * for the default) against a project.
- */
-export function resolveComposition(
- project: Project,
- ref?: string,
-): ResolvedComposition {
- if (ref === undefined || ref === "") {
- const found = project.compositions.find((c) => c.id === project.defaultId);
- if (found) return found;
- throw new ProjectError("the project has no default composition", "invalid");
- }
- if (isFileReference(ref)) return adHocComposition(project, ref);
- const found = project.compositions.find((c) => c.id === ref);
- if (found) return found;
- throw new ProjectError(
- `unknown composition '${ref}'`,
- "unknown-composition",
- undefined,
- `compositions${project.source === "manifest" ? ` in ${MANIFEST_FILE}` : ""}: ${listIds(project)} (ff ls)`,
- );
-}
-
-/** `a, b, c` or `a, b … h` for long lists. */
-function listIds(project: Project): string {
- const ids = project.compositions.map((c) => c.id);
- return ids.length > 4
- ? `${ids.slice(0, 2).join(", ")} … ${ids[ids.length - 1]}`
- : ids.join(", ");
-}
-
-function adHocComposition(project: Project, ref: string): ResolvedComposition {
- const hash = ref.indexOf("#");
- const file = hash === -1 ? ref : ref.slice(0, hash);
- const exportName = hash === -1 ? "default" : ref.slice(hash + 1);
- const abs = path.resolve(project.root, file);
- const entry = normalizeEntry(path.relative(project.root, abs));
- if (entry.startsWith("..") || path.isAbsolute(entry)) {
- throw new ProjectError(
- `'${file}' is outside the project (${project.root})`,
- "unknown-composition",
- );
- }
- if (!ENTRY_EXT.test(entry)) {
- throw new ProjectError(
- `'${file}' is not a .ts, .tsx, .mts, .js or .mjs file`,
- "unknown-composition",
- );
- }
- if (!IDENTIFIER.test(exportName)) {
- throw new ProjectError(
- `'${exportName}' is not a JavaScript identifier`,
- "unknown-composition",
- );
- }
- const listed = project.compositions.find(
- (c) => c.entry === entry && c.export === exportName,
- );
- if (listed) return listed;
- const base = path
- .basename(entry)
- .replace(ENTRY_EXT, "")
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-");
- const suffix =
- exportName === "default"
- ? ""
- : `-${exportName
- .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")}`;
- const id =
- `${base}${suffix}`.replace(/^-+|-+$/g, "").slice(0, 63) || "composition";
- return {
- id,
- entry,
- export: exportName,
- title: `${entry}#${exportName}`,
- description: null,
- group: null,
- default: false,
- };
-}
-
-function normalizeEntry(entry: string): string {
- return entry.split(path.sep).join("/").replace(/^\.\//, "");
-}
-
-/**
- * Imports the entry and calls the export: the one place that turns a
- * reference into a Composition. TypeScript entries need a loader (tsx, or a
- * Node that strips types); the `ff` CLI registers one.
- */
-export async function buildComposition(
- project: Project,
- ref?: string,
-): Promise<Composition> {
- const target = resolveComposition(project, ref);
- const file = path.join(project.root, target.entry);
- const where = `${target.entry}#${target.export}`;
- if (!fs.existsSync(file)) {
- throw new ProjectError(
- `${target.entry} does not exist (composition '${target.id}')`,
- "build",
- file,
- project.source === "default"
- ? `create it, or list your compositions in ${MANIFEST_FILE}`
- : undefined,
- );
- }
- let mod: Record<string, unknown>;
- try {
- mod = (await import(pathToFileURL(file).href)) as Record<string, unknown>;
- } catch (err) {
- throw new ProjectError(
- `could not import ${target.entry}: ${errorMessage(err)}`,
- "build",
- file,
- );
- }
- const exported = mod[target.export];
- if (exported === undefined) {
- const names = Object.keys(mod).filter((k) => typeof mod[k] === "function");
- throw new ProjectError(
- `${target.entry} has no export named '${target.export}'`,
- "build",
- file,
- names.length ? `function exports: ${names.join(", ")}` : undefined,
- );
- }
- let value: unknown;
- try {
- value =
- typeof exported === "function"
- ? await (exported as () => unknown)()
- : exported;
- } catch (err) {
- const error = new ProjectError(
- `${where} threw: ${errorMessage(err)}`,
- "build",
- file,
- );
- error.cause = err;
- throw error;
- }
- if (!isComposition(value)) {
- throw new ProjectError(
- `${where} did not return a Composition`,
- "build",
- file,
- );
- }
- return value as Composition;
-}
-
-function isComposition(value: unknown): boolean {
- return (
- typeof value === "object" &&
- value !== null &&
- typeof (value as { toSpec?: unknown }).toSpec === "function" &&
- typeof (value as { renderFrame?: unknown }).renderFrame === "function"
- );
-}
-
-function errorMessage(err: unknown): string {
- return err instanceof Error ? err.message : String(err);
-}
diff --git a/packages/framefields/src/project/project.test.ts b/packages/framefields/src/project/project.test.ts
deleted file mode 100644
index 99d10da0..00000000
--- a/packages/framefields/src/project/project.test.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
-import {
- buildComposition,
- humanize,
- loadProject,
- ProjectError,
- resolveComposition,
- resolveManifest,
-} from "./index.js";
-
-const dirs: string[] = [];
-function tmp(files: Record<string, string>): string {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ff-project-"));
- dirs.push(dir);
- for (const [file, content] of Object.entries(files)) {
- fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
- fs.writeFileSync(path.join(dir, file), content);
- }
- return dir;
-}
-afterEach(() => {
- for (const d of dirs.splice(0))
- fs.rmSync(d, { recursive: true, force: true });
-});
-
-const manifest = (compositions: unknown, extra: object = {}) => ({
- version: 1,
- compositions,
- ...extra,
-});
-
-function invalid(json: unknown): string {
- try {
- resolveManifest(json, "/p");
- } catch (err) {
- expect(err).toBeInstanceOf(ProjectError);
- expect((err as ProjectError).kind).toBe("invalid");
- return (err as Error).message;
- }
- throw new Error("expected the manifest to be rejected");
-}
-
-describe("resolveManifest (§3.1 rules)", () => {
- it("resolves defaults: export, title, group, description, assets, output", () => {
- const p = resolveManifest(
- manifest({ "step-1": { entry: "src/a.ts" } }),
- "/p",
- );
- expect(p).toEqual({
- root: "/p",
- source: "manifest",
- defaultId: "step-1",
- compositions: [
- {
- id: "step-1",
- entry: "src/a.ts",
- export: "default",
- title: "Step 1",
- description: null,
- group: null,
- default: true,
- },
- ],
- assets: { directory: "assets", exclude: ["**/.DS_Store"] },
- output: "output",
- });
- });
-
- it("keeps insertion order and honours an explicit default", () => {
- const p = resolveManifest(
- manifest({
- b: { entry: "src/b.ts" },
- a: { entry: "src/a.ts", default: true, group: "Steps", title: "A!" },
- }),
- "/p",
- );
- expect(p.compositions.map((c) => c.id)).toEqual(["b", "a"]);
- expect(p.defaultId).toBe("a");
- expect(p.compositions.map((c) => c.default)).toEqual([false, true]);
- expect(p.compositions[1]).toMatchObject({ title: "A!", group: "Steps" });
- });
-
- it("version is optional and must be 1", () => {
- expect(() =>
- resolveManifest({ compositions: { a: { entry: "a.ts" } } }, "/p"),
- ).not.toThrow();
- expect(
- invalid({ version: 2, compositions: { a: { entry: "a.ts" } } }),
- ).toMatch(/version/);
- });
-
- it("requires at least one composition", () => {
- expect(invalid(manifest({}))).toMatch(/at least one/);
- expect(invalid({ version: 1 })).toMatch(/compositions/);
- });
-
- it("validates ids", () => {
- for (const id of ["Step1", "-a", "a_b", "a".repeat(64), ""]) {
- expect(invalid(manifest({ [id]: { entry: "a.ts" } }))).toMatch(
- /composition ids|compositions/,
- );
- }
- expect(() =>
- resolveManifest(manifest({ ["a".repeat(63)]: { entry: "a.ts" } }), "/p"),
- ).not.toThrow();
- });
-
- it("validates entries", () => {
- expect(invalid(manifest({ a: { entry: "../x.ts" } }))).toMatch(/inside/);
- expect(invalid(manifest({ a: { entry: "/abs/x.ts" } }))).toMatch(/inside/);
- expect(invalid(manifest({ a: { entry: "src/x.json" } }))).toMatch(/\.ts/);
- for (const ext of ["ts", "tsx", "mts", "js", "mjs"]) {
- expect(() =>
- resolveManifest(manifest({ a: { entry: `src/x.${ext}` } }), "/p"),
- ).not.toThrow();
- }
- });
-
- it("validates exports, lengths and the single default", () => {
- expect(
- invalid(manifest({ a: { entry: "a.ts", export: "not-ok" } })),
- ).toMatch(/identifier/);
- expect(
- invalid(manifest({ a: { entry: "a.ts", title: "x".repeat(121) } })),
- ).toMatch(/title/);
- expect(
- invalid(manifest({ a: { entry: "a.ts", description: "x".repeat(501) } })),
- ).toMatch(/description/);
- expect(
- invalid(manifest({ a: { entry: "a.ts", group: "x".repeat(61) } })),
- ).toMatch(/group/);
- expect(
- invalid(
- manifest({
- a: { entry: "a.ts", default: true },
- b: { entry: "b.ts", default: true },
- }),
- ),
- ).toMatch(/only one/);
- });
-
- it("preserves and ignores unknown keys", () => {
- const p = resolveManifest(
- manifest(
- { a: { entry: "a.ts", posterFrame: 12 } },
- { chapters: [], assets: { directory: "media", exclude: [], extra: 1 } },
- ),
- "/p",
- );
- expect(p.assets).toEqual({ directory: "media", exclude: [] });
- });
-});
-
-describe("loadProject", () => {
- it("reads framefields.json from the nearest parent", async () => {
- const root = tmp({
- "framefields.json": JSON.stringify(
- manifest({ show: { entry: "src/show.ts", export: "build" } }),
- ),
- "src/nested/x.txt": "",
- });
- const p = await loadProject(path.join(root, "src", "nested"));
- expect(p.root).toBe(root);
- expect(p.source).toBe("manifest");
- expect(p.defaultId).toBe("show");
- });
-
- it("falls back to the implicit film composition beside package.json", async () => {
- const root = tmp({ "package.json": "{}" });
- const p = await loadProject(root);
- expect(p.source).toBe("default");
- expect(p.compositions).toEqual([
- {
- id: "film",
- entry: "src/film.ts",
- export: "buildFilm",
- title: "Film",
- description: null,
- group: null,
- default: true,
- },
- ]);
- });
-
- it("reports invalid JSON with the file path", async () => {
- const root = tmp({ "framefields.json": "{ nope" });
- const err = await loadProject(root).catch((e: unknown) => e);
- expect(err).toBeInstanceOf(ProjectError);
- expect(err).toMatchObject({
- kind: "invalid",
- path: path.join(root, "framefields.json"),
- });
- });
-});
-
-describe("resolveComposition", () => {
- const project = resolveManifest(
- manifest({
- showcase: {
- entry: "src/audio.ts",
- export: "buildShowcase",
- default: true,
- },
- "step-1": { entry: "src/audio.ts", export: "buildStep1" },
- }),
- "/p",
- );
-
- it("resolves the default, ids and listed file refs", () => {
- expect(resolveComposition(project).id).toBe("showcase");
- expect(resolveComposition(project, "step-1").export).toBe("buildStep1");
- expect(resolveComposition(project, "src/audio.ts#buildStep1").id).toBe(
- "step-1",
- );
- });
-
- it("resolves ad-hoc file#export references", () => {
- expect(resolveComposition(project, "scratch/probe.ts#buildProbe")).toEqual({
- id: "probe-build-probe",
- entry: "scratch/probe.ts",
- export: "buildProbe",
- title: "scratch/probe.ts#buildProbe",
- description: null,
- group: null,
- default: false,
- });
- expect(resolveComposition(project, "./src/probe.ts")).toMatchObject({
- id: "probe",
- entry: "src/probe.ts",
- export: "default",
- });
- });
-
- it("rejects unknown ids with a hint listing the compositions", () => {
- try {
- resolveComposition(project, "step-9");
- expect.unreachable();
- } catch (err) {
- expect(err).toMatchObject({
- kind: "unknown-composition",
- message: "unknown composition 'step-9'",
- hint: "compositions in framefields.json: showcase, step-1 (ff ls)",
- });
- }
- });
-
- it("rejects refs outside the project or with bad exports", () => {
- expect(() => resolveComposition(project, "../x.ts")).toThrow(/outside/);
- expect(() => resolveComposition(project, "src/x.ts#not-ok")).toThrow(
- /identifier/,
- );
- expect(() => resolveComposition(project, "src/x.json#a")).toThrow(/\.ts/);
- });
-});
-
-describe("buildComposition", () => {
- const comp = `export function build() { return { toSpec() { return {}; }, renderFrame() {} }; }
-export default async function () { return build(); }
-export function notComp() { return 42; }
-export function boom() { throw new Error("kaput"); }
-`;
-
- it("imports the entry and calls the export", async () => {
- const root = tmp({
- "framefields.json": JSON.stringify(
- manifest({ a: { entry: "src/a.mjs", export: "build" } }),
- ),
- "src/a.mjs": comp,
- });
- const project = await loadProject(root);
- const built = await buildComposition(project);
- expect(typeof built.toSpec).toBe("function");
- expect(typeof (await buildComposition(project, "src/a.mjs")).toSpec).toBe(
- "function",
- );
- });
-
- it("explains missing files, missing exports, throws and non-compositions", async () => {
- const root = tmp({
- "framefields.json": JSON.stringify(
- manifest({ a: { entry: "src/a.mjs", export: "build" } }),
- ),
- "src/a.mjs": comp,
- });
- const project = await loadProject(root);
- await expect(buildComposition(project, "src/missing.mjs")).rejects.toThrow(
- /does not exist/,
- );
- await expect(buildComposition(project, "src/a.mjs#nope")).rejects.toThrow(
- /no export named 'nope'/,
- );
- await expect(buildComposition(project, "src/a.mjs#boom")).rejects.toThrow(
- /threw: kaput/,
- );
- await expect(
- buildComposition(project, "src/a.mjs#notComp"),
- ).rejects.toThrow(/did not return a Composition/);
- });
-});
-
-it("humanize", () => {
- expect(humanize("step-1")).toBe("Step 1");
- expect(humanize("film")).toBe("Film");
-});
diff --git a/packages/framefields/tsdown.config.ts b/packages/framefields/tsdown.config.ts
index b4d69a88..0e278c86 100644
--- a/packages/framefields/tsdown.config.ts
+++ b/packages/framefields/tsdown.config.ts
@@ -10,7 +10,6 @@ export default defineConfig({
"src/renderer/index.ts",
"src/fonts/index.ts",
"src/preview/index.ts",
- "src/project/index.ts",
],
format: ["esm"],
clean: true,