Skip to content

Write HTML. Render video. Built for agents.

feat(lint): flag nested structure, missing timing and caption tracks on the root composition (#4146)

Miguel Ángelb44f1f85dcf0
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index fa8fec379a..9ec912a770 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -451,14 +451,14 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
return cachedProjectSignature;
},
- async lint(html: string, opts?: { filePath?: string }) {
+ async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {
const { lintHyperframeHtml } = await import("@hyperframes/lint");
- return await lintHyperframeHtml(html, opts);
+ return await lintHyperframeHtml(html, { ...opts, host: "studio" });
},
async lintProject(dir: string) {
const { lintProject } = await import("@hyperframes/lint");
- return await lintProject(dir);
+ return await lintProject(dir, undefined, { host: "studio" });
},
runtimeUrl: "/api/runtime.js",
diff --git a/packages/lint/src/hyperframeLinter.ts b/packages/lint/src/hyperframeLinter.ts
index ae6aade898..68e9028a1d 100644
--- a/packages/lint/src/hyperframeLinter.ts
+++ b/packages/lint/src/hyperframeLinter.ts
@@ -17,6 +17,7 @@ import { adapterRules } from "./rules/adapters";
import { textureRules } from "./rules/textures";
import { fontRules } from "./rules/fonts";
import { slideshowRules } from "./rules/slideshow";
+import { structureRules } from "./rules/structure";
// Rules are grouped by source module so a timing can be attributed to
// something a human can act on. Individual rules stay anonymous: an
@@ -43,6 +44,7 @@ const RULE_GROUPS: ReadonlyArray<{
{ group: "textures", rules: textureRules },
{ group: "fonts", rules: fontRules },
{ group: "slideshow", rules: slideshowRules },
+ { group: "structure", rules: structureRules },
];
/**
diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.ts
index 563e7fbad8..b3d5e8fd36 100644
--- a/packages/lint/src/project.ts
+++ b/packages/lint/src/project.ts
@@ -21,7 +21,11 @@ import {
lintVideoMediaStartPastEof,
} from "./hevcPreviewLint.js";
import { lintHyperframeHtml } from "./hyperframeLinter.js";
-import type { HyperframeLintFinding, HyperframeLintResult } from "./types.js";
+import type {
+ HyperframeLintFinding,
+ HyperframeLintResult,
+ HyperframeLinterOptions,
+} from "./types.js";
import type { ParsableDocumentLike } from "@hyperframes/parsers/sub-composition-validity";
import { mediaSrcTagRe } from "./utils";
@@ -162,6 +166,7 @@ function resolveCssAssetCandidates(
export async function lintProject(
projectDir: string,
entryFile?: string,
+ hostOptions: Pick<HyperframeLinterOptions, "host"> = {},
): Promise<ProjectLintResult> {
const indexPath = entryFile ? resolve(entryFile) : resolve(projectDir, "index.html");
if (entryFile && !isWithinProjectRoot(projectDir, indexPath)) {
@@ -176,6 +181,7 @@ export async function lintProject(
const rootHtml = readFileSync(indexPath, "utf-8");
const rootResult = await lintHyperframeHtml(rootHtml, {
+ ...hostOptions,
filePath: indexPath,
externalStyles: collectExternalStyles(projectDir, rootHtml, rootCompSrcPath),
});
@@ -215,6 +221,7 @@ export async function lintProject(
// inlines snippet markup (or mentions the token in text) is still linted.
if (isSnippetFragment(html)) continue;
const result = await lintHyperframeHtml(html, {
+ ...hostOptions,
filePath,
isSubComposition: true,
externalStyles: collectExternalStyles(projectDir, html, compSrcPath),
diff --git a/packages/lint/src/rules/structure.catalog.test.ts b/packages/lint/src/rules/structure.catalog.test.ts
new file mode 100644
index 0000000000..08b26a7b46
--- /dev/null
+++ b/packages/lint/src/rules/structure.catalog.test.ts
@@ -0,0 +1,45 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+import { lintHyperframeHtml } from "../hyperframeLinter";
+
+const REPO_ROOT = resolve(__dirname, "../../../..");
+const STRUCTURE_CODES = new Set([
+ "nested_structure_needs_subcomposition",
+ "timeline_element_missing_timing",
+ "media_missing_duration",
+ "caption_track_kind_missing",
+ "multiple_caption_tracks",
+]);
+
+function htmlFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) return entry.name === "node_modules" ? [] : htmlFiles(path);
+ return entry.name.endsWith(".html") ? [path] : [];
+ });
+}
+
+describe("structure rules on the shipped catalog and skills", () => {
+ it("report nothing for any registry item or skill example", async () => {
+ const files = [
+ ...htmlFiles(join(REPO_ROOT, "registry")),
+ ...htmlFiles(join(REPO_ROOT, "skills")),
+ ];
+ const hits: string[] = [];
+ let roots = 0;
+ for (const file of files) {
+ const isRoot = file.endsWith("/index.html");
+ roots += isRoot ? 1 : 0;
+ const { findings } = await lintHyperframeHtml(readFileSync(file, "utf8"), {
+ host: "studio",
+ filePath: file,
+ isSubComposition: !isRoot,
+ });
+ for (const f of findings.filter((x) => STRUCTURE_CODES.has(x.code)))
+ hits.push(`${file}: ${f.code}`);
+ }
+ expect(roots).toBeGreaterThan(30);
+ expect(hits).toEqual([]);
+ }, 120_000);
+});
diff --git a/packages/lint/src/rules/structure.test.ts b/packages/lint/src/rules/structure.test.ts
new file mode 100644
index 0000000000..9f3392d7c0
--- /dev/null
+++ b/packages/lint/src/rules/structure.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from "vitest";
+import { lintHyperframeHtml } from "../hyperframeLinter";
+import type { HyperframeLinterOptions } from "../types";
+
+const page = (body: string) =>
+ `<html><body><div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="10">${body}</div><script>window.__timelines={main:gsap.timeline({paused:true})};</script></body></html>`;
+
+async function codes(body: string, options: HyperframeLinterOptions = {}) {
+ const { findings } = await lintHyperframeHtml(page(body), options);
+ return findings.filter((f) => STRUCTURE.has(f.code));
+}
+const STRUCTURE = new Set([
+ "nested_structure_needs_subcomposition",
+ "timeline_element_missing_timing",
+ "media_missing_duration",
+ "caption_track_kind_missing",
+ "multiple_caption_tracks",
+]);
+const has = (found: Awaited<ReturnType<typeof codes>>, code: string) =>
+ found.some((f) => f.code === code);
+
+describe("nested_structure_needs_subcomposition", () => {
+ it("flags a timed div that contains another div", async () => {
+ const found = await codes(
+ '<div id="card" class="clip" data-start="0" data-duration="3"><div>inner</div></div>',
+ );
+ expect(has(found, "nested_structure_needs_subcomposition")).toBe(true);
+ });
+ it("leaves layout free inside a sub-composition file", async () => {
+ const found = await codes(
+ '<div class="clip" data-start="0" data-duration="3"><div>inner</div></div>',
+ { isSubComposition: true },
+ );
+ expect(found).toEqual([]);
+ });
+ it("passes a timed leaf with inline text, media, and a sub-composition host", async () => {
+ const found = await codes(
+ '<div class="clip" data-start="0" data-duration="3">hello <b>world</b><br></div>' +
+ '<video src="a.mp4" data-start="0" data-duration="3"></video>' +
+ '<div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="3" data-duration="2"><div>ignored</div></div>',
+ );
+ expect(has(found, "nested_structure_needs_subcomposition")).toBe(false);
+ });
+ it("ignores style, script and template content inside a timed element", async () => {
+ const found = await codes(
+ '<div class="clip" data-start="0" data-duration="3">hi<style>.a{}</style><script>1</script><template><div></div></template></div>',
+ );
+ expect(has(found, "nested_structure_needs_subcomposition")).toBe(false);
+ });
+ it("descends an untimed wrapper to reach the timed element", async () => {
+ const found = await codes(
+ '<div id="stage"><div class="clip" data-start="0" data-duration="3"><p>x</p></div></div>',
+ );
+ expect(has(found, "nested_structure_needs_subcomposition")).toBe(true);
+ });
+});
+
+describe("severity follows the host", () => {
+ const body = '<div class="clip" data-start="0" data-duration="3"><div>inner</div></div>';
+ it("is a warning for the CLI and an error for Studio", async () => {
+ expect((await codes(body))[0]?.severity).toBe("warning");
+ expect((await codes(body, { host: "cli" }))[0]?.severity).toBe("warning");
+ expect((await codes(body, { host: "studio" }))[0]?.severity).toBe("error");
+ });
+});
+
+describe("timeline_element_missing_timing", () => {
+ it("flags a timed element with no duration, passes one with a duration and a sub-composition host without one", async () => {
+ expect(
+ has(
+ await codes('<div class="clip" data-start="0">x</div>'),
+ "timeline_element_missing_timing",
+ ),
+ ).toBe(true);
+ expect(
+ has(
+ await codes('<div data-composition-id="a" data-start="0"></div>'),
+ "timeline_element_missing_timing",
+ ),
+ ).toBe(false);
+ expect(
+ has(
+ await codes('<div class="clip" data-start="0" data-duration="2">x</div>'),
+ "timeline_element_missing_timing",
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("legacy data-end", () => {
+ it("counts data-end as the clip's length", async () => {
+ const found = await codes('<div class="clip" data-start="0" data-end="3">x</div>');
+ expect(has(found, "timeline_element_missing_timing")).toBe(false);
+ });
+});
+
+describe("media_missing_duration", () => {
+ it("flags img, video and audio without data-duration and passes them with one", async () => {
+ for (const tag of ["img", "video", "audio"]) {
+ expect(
+ has(await codes(`<${tag} src="a" data-start="0"></${tag}>`), "media_missing_duration"),
+ ).toBe(true);
+ expect(
+ has(
+ await codes(`<${tag} src="a" data-start="0" data-duration="3"></${tag}>`),
+ "media_missing_duration",
+ ),
+ ).toBe(false);
+ }
+ });
+});
+
+describe("static media", () => {
+ it("does not flag a bare img with no timing attributes", async () => {
+ expect(has(await codes('<img src="bg.svg" alt="" />'), "media_missing_duration")).toBe(false);
+ });
+});
+
+describe("caption rules", () => {
+ const cap = (extra: string) =>
+ `<div data-composition-src="compositions/captions.html" data-start="0" data-duration="5" ${extra}></div>`;
+ it("asks a legacy captions host to add data-track-kind, and passes an explicit one", async () => {
+ const legacy =
+ '<div data-composition-id="captions" data-composition-src="compositions/captions.html" data-start="0" data-duration="5"></div>';
+ expect(has(await codes(legacy), "caption_track_kind_missing")).toBe(true);
+ expect(
+ has(
+ await codes(cap('data-track-kind="captions" data-track-index="5"')),
+ "caption_track_kind_missing",
+ ),
+ ).toBe(false);
+ });
+ it("flags captions on two lanes and passes captions sharing one lane", async () => {
+ const two =
+ cap('data-track-kind="captions" data-track-index="5"') +
+ cap('data-track-kind="captions" data-track-index="6"');
+ const one =
+ cap('data-track-kind="captions" data-track-index="5"') +
+ cap('data-track-kind="captions" data-track-index="5"');
+ expect(has(await codes(two), "multiple_caption_tracks")).toBe(true);
+ expect(has(await codes(one), "multiple_caption_tracks")).toBe(false);
+ });
+ it("does not count a caption row without a lane as a second track", async () => {
+ const mixed =
+ cap('data-track-kind="captions" data-track-index="5"') + cap('data-track-kind="captions"');
+ expect(has(await codes(mixed), "multiple_caption_tracks")).toBe(false);
+ });
+});
diff --git a/packages/lint/src/rules/structure.ts b/packages/lint/src/rules/structure.ts
new file mode 100644
index 0000000000..7273ee09a0
--- /dev/null
+++ b/packages/lint/src/rules/structure.ts
@@ -0,0 +1,193 @@
+import type { LintContext, HyperframeLintFinding, OpenTag } from "../context";
+import { readDecodedAttr } from "../utils";
+import {
+ isSubCompositionHost,
+ topLevelElements,
+ trackKindOf,
+ type StructureNode,
+} from "@hyperframes/parsers/top-level-elements";
+
+interface TagNode extends StructureNode<TagNode> {
+ children: TagNode[];
+ open: OpenTag;
+}
+
+// Text-level tags may sit inside a timed element without being "nested structure".
+const INLINE_TEXT_TAGS = new Set([
+ "br",
+ "wbr",
+ "b",
+ "i",
+ "u",
+ "s",
+ "em",
+ "strong",
+ "small",
+ "sub",
+ "sup",
+ "mark",
+ "span",
+ "a",
+ "code",
+ "abbr",
+]);
+// Their content is one drawn object, so their children are not layout.
+const OPAQUE_TAGS = new Set([
+ "svg",
+ "canvas",
+ "picture",
+ "video",
+ "audio",
+ "select",
+ "textarea",
+ "iframe",
+ "object",
+]);
+// Never layout: their content is code or inert markup.
+const NON_LAYOUT_TAGS = new Set(["style", "script", "template", "noscript"]);
+const MEDIA_TAGS = new Set(["img", "video", "audio"]);
+const NODE_ATTRS = [
+ "id",
+ "class",
+ "data-start",
+ "data-duration",
+ "data-end",
+ "data-track",
+ "data-track-index",
+ "data-track-kind",
+ "data-composition-id",
+ "data-composition-src",
+];
+
+function toNode(open: OpenTag): TagNode {
+ const attrs: Record<string, string | undefined> = {};
+ for (const name of NODE_ATTRS) attrs[name] = readDecodedAttr(open.raw, name) ?? undefined;
+ return { tag: open.name, attrs, children: [], open };
+}
+
+type OpenNode = { node: TagNode; end: number };
+
+/** The innermost still-open node at `index`; closes nodes the index has passed. */
+function enclosing(stack: OpenNode[], root: TagNode, index: number): TagNode {
+ let top = stack.at(-1);
+ while (top && stack.length > 1 && index >= top.end) {
+ stack.pop();
+ top = stack.at(-1);
+ }
+ return top?.node ?? root;
+}
+
+/** Rebuilds nesting from the flat tag list using each tag's close index. */
+function buildTree(ctx: LintContext): TagNode | null {
+ const { rootTag } = ctx;
+ const rootEnd = rootTag?.closeIndex;
+ if (!rootTag || rootEnd == null) return null;
+ const root = toNode(rootTag);
+ const stack: OpenNode[] = [{ node: root, end: rootEnd }];
+ for (const tag of ctx.tags.filter((t) => t.index > rootTag.index && t.index < rootEnd)) {
+ const node = toNode(tag);
+ enclosing(stack, root, tag.index).children.push(node);
+ if (tag.closeIndex != null) stack.push({ node, end: tag.closeIndex });
+ }
+ return root;
+}
+
+function hasNestedStructure(node: TagNode): TagNode | null {
+ if (OPAQUE_TAGS.has(node.tag)) return null;
+ for (const child of node.children) {
+ if (NON_LAYOUT_TAGS.has(child.tag)) continue;
+ if (!INLINE_TEXT_TAGS.has(child.tag)) return child;
+ const deeper = hasNestedStructure(child);
+ if (deeper) return deeper;
+ }
+ return null;
+}
+
+const describe = (node: TagNode) => `<${node.tag}${node.attrs.id ? ` id="${node.attrs.id}"` : ""}>`;
+
+type Severity = HyperframeLintFinding["severity"];
+
+function nestedStructureFindings(rows: TagNode[], severity: Severity): HyperframeLintFinding[] {
+ return rows.flatMap((row) => {
+ const nested = isSubCompositionHost(row) ? null : hasNestedStructure(row);
+ if (!nested) return [];
+ return [
+ {
+ code: "nested_structure_needs_subcomposition",
+ severity,
+ message: `${describe(row)} is a timeline element that contains nested ${describe(nested)}. The timeline shows one row per top-level element, and the root composition is built only from sub-compositions.`,
+ elementId: row.attrs.id,
+ fixHint: `Move ${describe(row)} and its contents into a sub-composition file and mount it with data-composition-src.`,
+ },
+ ];
+ });
+}
+
+function missingDurationFindings(rows: TagNode[], severity: Severity): HyperframeLintFinding[] {
+ // A bare media element with no timing is a static layer, not a timeline clip.
+ const intendedClip = (row: TagNode) =>
+ !MEDIA_TAGS.has(row.tag) ||
+ row.attrs["data-start"] !== undefined ||
+ row.attrs["data-track-index"] !== undefined;
+ return rows
+ .filter(
+ (row) =>
+ row.attrs["data-duration"] === undefined &&
+ row.attrs["data-end"] === undefined &&
+ !isSubCompositionHost(row) &&
+ intendedClip(row),
+ )
+ .map((row) => {
+ const isMedia = MEDIA_TAGS.has(row.tag);
+ return {
+ code: isMedia ? "media_missing_duration" : "timeline_element_missing_timing",
+ severity,
+ message: isMedia
+ ? `${describe(row)} is media on the timeline without data-duration, so its clip has no length.`
+ : `${describe(row)} is a timeline element without data-duration, so the timeline cannot draw where it ends.`,
+ elementId: row.attrs.id,
+ fixHint: `Add data-duration (in seconds) to ${describe(row)}.`,
+ };
+ });
+}
+
+function captionFindings(rows: TagNode[], severity: Severity): HyperframeLintFinding[] {
+ const captionRows = rows.filter((row) => trackKindOf(row).kind === "captions");
+ const findings: HyperframeLintFinding[] = captionRows
+ .filter((row) => trackKindOf(row).source === "legacy-captions")
+ .map((row) => ({
+ code: "caption_track_kind_missing",
+ severity,
+ message: `${describe(row)} looks like captions but is not marked as such, so the timeline cannot group it on the caption track.`,
+ elementId: row.attrs.id,
+ fixHint: `Add data-track-kind="captions" to ${describe(row)}.`,
+ }));
+ const lanes = new Set(
+ captionRows.flatMap((row) => row.attrs["data-track-index"] ?? row.attrs["data-track"] ?? []),
+ );
+ if (lanes.size > 1) {
+ findings.push({
+ code: "multiple_caption_tracks",
+ severity,
+ message: `Captions are spread across ${lanes.size} timeline tracks. Keep all captions on one track.`,
+ fixHint: "Give every caption element the same data-track-index.",
+ });
+ }
+ return findings;
+}
+
+export const structureRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
+ (ctx) => {
+ // The timeline shows the root composition's rows; a sub-composition file is the leaf where layout lives.
+ if (ctx.options.isSubComposition) return [];
+ const root = buildTree(ctx);
+ if (!root) return [];
+ const severity = ctx.options.host === "studio" ? "error" : "warning";
+ const rows = topLevelElements(root);
+ return [
+ ...nestedStructureFindings(rows, severity),
+ ...missingDurationFindings(rows, severity),
+ ...captionFindings(rows, severity),
+ ];
+ },
+];
diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.ts
index 3b92152d0f..bb9d988fe9 100644
--- a/packages/lint/src/types.ts
+++ b/packages/lint/src/types.ts
@@ -46,6 +46,8 @@ export type HyperframeLinterOptions = {
* render time — the font will silently fall back to whatever the OS provides.
*/
distributed?: boolean;
+ /** Who is running the lint: Studio raises the structure rules to errors, the CLI keeps them warnings. */
+ host?: "studio" | "cli";
};
// A rule is a function: receives parsed context, returns zero or more findings.
diff --git a/packages/studio-server/src/routes/lint.test.ts b/packages/studio-server/src/routes/lint.test.ts
index 500ca57e5e..e7d134aff3 100644
--- a/packages/studio-server/src/routes/lint.test.ts
+++ b/packages/studio-server/src/routes/lint.test.ts
@@ -141,6 +141,7 @@ describe("registerLintRoutes — dot-directory exclusion (#1384)", () => {
expect(singleFileLint).toHaveBeenCalledTimes(1);
expect(singleFileLint).toHaveBeenCalledWith("<html><body>intro</body></html>", {
filePath: "scenes/intro.html",
+ isSubComposition: true,
});
expect(payload.findings).toContainEqual(
expect.objectContaining({ code: "scene_finding", file: "scenes/intro.html" }),
diff --git a/packages/studio-server/src/routes/lint.ts b/packages/studio-server/src/routes/lint.ts
index deaad93ed3..4e1c99251e 100644
--- a/packages/studio-server/src/routes/lint.ts
+++ b/packages/studio-server/src/routes/lint.ts
@@ -34,7 +34,7 @@ async function lintUncoveredHtml(
for (const file of htmlFiles) {
if (coveredFiles.has(file)) continue;
const content = readFileSync(join(projectDir, file), "utf-8");
- const result = await adapter.lint(content, { filePath: file });
+ const result = await adapter.lint(content, { filePath: file, isSubComposition: true });
for (const finding of result?.findings ?? []) {
findings.push({ ...finding, file });
}
diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.ts
index 1344b90701..3280a8638b 100644
--- a/packages/studio-server/src/types.ts
+++ b/packages/studio-server/src/types.ts
@@ -113,7 +113,10 @@ export interface StudioApiAdapter {
getProjectSignature?: (projectDir: string) => string;
/** Lint a single HTML string. */
- lint(html: string, opts?: { filePath?: string }): Promise<LintResult> | LintResult;
+ lint(
+ html: string,
+ opts?: { filePath?: string; isSubComposition?: boolean },
+ ): Promise<LintResult> | LintResult;
/**
* Lint the complete project, including relationships between files. Official
diff --git a/packages/studio/vite.adapter.ts b/packages/studio/vite.adapter.ts
index 13017fc6ca..261573b42c 100644
--- a/packages/studio/vite.adapter.ts
+++ b/packages/studio/vite.adapter.ts
@@ -255,14 +255,14 @@ export function createViteAdapter(
return signatureCache.get(projectDir);
},
- async lint(html: string, opts?: { filePath?: string }) {
+ async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {
const mod = await server.ssrLoadModule("@hyperframes/core/lint");
- return await mod.lintHyperframeHtml(html, opts);
+ return await mod.lintHyperframeHtml(html, { ...opts, host: "studio" });
},
async lintProject(projectDir: string) {
const mod = await server.ssrLoadModule("@hyperframes/core/lint");
- return await mod.lintProject(projectDir);
+ return await mod.lintProject(projectDir, undefined, { host: "studio" });
},
runtimeUrl: "/api/runtime.js",