Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
import type { LintContext, HyperframeLintFinding } from "../context";
import postcss from "postcss";
import selectorParser from "postcss-selector-parser";
import {
HTML_BODY_CSS_WIDTH_FIRST_RE,
HTML_BODY_CSS_HEIGHT_FIRST_RE,
VIEWPORT_META_SIZE_RE,
} from "@hyperframes/parsers/composition";
import {
readAttr,
readDecodedAttr,
truncateSnippet,
stripJsComments,
stripStringLiterals,
blankInlinedGsapLibrary,
extractCompositionIdsFromCss,
extractTimelineRegistryKeys,
getInlineScriptSyntaxError,
hasUnquotedLessThan,
TIMELINE_REGISTRY_INIT_PATTERN,
TIMELINE_REGISTRY_ASSIGN_PATTERN,
TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN,
INVALID_SCRIPT_CLOSE_PATTERN,
} from "../utils";
const SCRIPT_SYNTAX_EXEMPT_TYPES = new Set([
"application/json",
"application/hyperframes-slideshow+json",
"importmap",
"module",
]);
function repeatedDescendantId(selector: string): string | null {
let repeated: string | null = null;
const requiredPseudoIds = (pseudo: selectorParser.Pseudo): Set<string> => {
if (![":is", ":where"].includes(pseudo.value.toLowerCase()) || pseudo.nodes.length === 0) {
return new Set<string>();
}
const optionIdSets: Set<string>[] = [];
for (const option of pseudo.nodes) {
// Only promote ids from a single compound. For selector-list branches with
// combinators, determining which compound is the subject requires fuller
// selector semantics; skipping them avoids false positives.
if (option.nodes.some((node) => node.type === "combinator")) return new Set<string>();
const optionIds = new Set<string>(
option.nodes.filter((node) => node.type === "id").map((node) => node.value),
);
optionIdSets.push(optionIds);
}
const [firstOptionIds, ...remainingOptionIds] = optionIdSets;
return new Set<string>(
[...(firstOptionIds ?? [])].filter((id) =>
remainingOptionIds.every((optionIds) => optionIds.has(id)),
),
);
};
try {
selectorParser((root) => {
root.each((selectorNode) => {
const firstCompoundById = new Map<string, number>();
let compound = 0;
selectorNode.each((node) => {
if (repeated) return;
if (node.type === "combinator") {
compound += 1;
return;
}
const requiredIds =
node.type === "id"
? [node.value]
: node.type === "pseudo"
? [...requiredPseudoIds(node)]
: [];
for (const id of requiredIds) {
const firstCompound = firstCompoundById.get(id);
if (firstCompound !== undefined && firstCompound !== compound) {
repeated = id;
return;
}
firstCompoundById.set(id, compound);
}
});
});
}).processSync(selector);
} catch {
return null;
}
return repeated;
}
// Unescaped `#<digit...>` id selectors: what querySelector and GSAP reject. `#\31 -x` is valid and skipped.
function addUnescapedDigitIds(selector: string, ids: Set<string>): void {
try {
selectorParser((root) => {
root.walkIds((node) => {
if (/^#\d/.test(node.toString().trim())) ids.add(node.value);
});
}).processSync(selector);
} catch {
// An unparseable selector targets nothing we can name.
}
}
const SELECTOR_CALL_PATTERN =
/(?:\.(?:querySelector(?:All)?|closest|matches|to|from|fromTo|set|toArray)\s*\(|(?<![\w$-])(?:trigger|endTrigger|pin|scrollTrigger|scroller|pinnedContainer|pinSpacer)["']?\s*:)\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/g;
function digitIdsTargetedBySelectors(
styles: LintContext["styles"],
scripts: LintContext["scripts"],
): Set<string> {
const ids = new Set<string>();
for (const style of styles) {
try {
postcss.parse(style.content).walkRules((rule) => {
for (const selector of rule.selectors) addUnescapedDigitIds(selector, ids);
});
} catch {
// css_parse_error reports this block.
}
}
for (const script of scripts) {
for (const match of stripJsComments(script.content).matchAll(SELECTOR_CALL_PATTERN)) {
addUnescapedDigitIds(match[2] ?? "", ids);
}
}
return ids;
}
function resolvedRuleSelectors(rule: postcss.Rule): string[] {
let ancestor: postcss.AnyNode | undefined = rule.parent;
while (ancestor && ancestor.type !== "rule") ancestor = ancestor.parent;
if (!ancestor || ancestor.type !== "rule") return rule.selectors;
const parentSelectors = resolvedRuleSelectors(ancestor);
return parentSelectors.flatMap((parentSelector) =>
rule.selectors.map((childSelector) => {
const nestingToken = /(^|[\s>+~,(])&/g;
if (nestingToken.test(childSelector)) {
return childSelector.replace(
nestingToken,
(_, separator: string) => separator + parentSelector,
);
}
return `${parentSelector} ${childSelector}`;
}),
);
}
// The rightmost compound: the nodes that match the styled element itself.
function rightmostCompoundNodes(selectorNode: selectorParser.Selector): selectorParser.Node[] {
const subject: selectorParser.Node[] = [];
selectorNode.each((node) => {
if (node.type === "combinator") subject.length = 0;
else subject.push(node);
});
return subject;
}
function selectorAliasesRuntimeHiddenStyle(selector: string): boolean {
let unsafe = false;
try {
selectorParser((root) => {
root.each((selectorNode) => {
const subject = rightmostCompoundNodes(selectorNode);
const hostScoped = subject.some(
(node) =>
node.type === "attribute" &&
["data-composition-src", "data-composition-file"].includes(
node.attribute.toLowerCase(),
),
);
if (hostScoped) return;
if (
subject.some((node) => {
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "style") return false;
if (node.operator !== "*=" || !node.value) return false;
const needle = node.insensitive ? node.value.toLowerCase() : node.value;
if (!needle.includes("visibility") && !needle.includes("hidden")) return false;
return "visibility: hidden !important;".includes(needle);
})
) {
unsafe = true;
}
});
}).processSync(selector);
} catch {
return false;
}
return unsafe;
}
const POSITION_PROPERTIES = new Set(["left", "top", "right", "bottom", "inset"]);
function weakIdOf(node: selectorParser.Node): string | null {
if (node.type === "attribute" && node.attribute.toLowerCase() === "id") {
return node.operator === "=" && node.value ? node.value : null;
}
if (node.type !== "pseudo" || node.value.toLowerCase() !== ":where") return null;
const inner = node.nodes.flatMap((option) => option.nodes).find((n) => n.type === "id");
return inner ? inner.value : null;
}
// The id a subject targets only via `[id="x"]` or `:where(#x)`, which carry class-level or zero specificity
// and so lose to a compound class rule like `.parent .row`. A bare `#id` never does.
function reducedSpecificityId(selector: string): string | null {
let matched: string | null = null;
try {
selectorParser((root) => {
root.each((selectorNode) => {
const subject = rightmostCompoundNodes(selectorNode);
if (subject.some((node) => node.type === "id")) return;
for (const node of subject) matched = weakIdOf(node) ?? matched;
});
}).processSync(selector);
} catch {
return null;
}
return matched;
}
// `#id` with the characters a bare id selector cannot hold (a leading digit, punctuation) hex-escaped.
function cssIdSelector(id: string): string {
return `#${id.replace(/[^a-zA-Z0-9_-]|^-?\d/g, (match) =>
Array.from(match, (char) => `\\${char.codePointAt(0)?.toString(16)} `).join(""),
)}`;
}
function reducedSpecificityIdFindings(
rule: postcss.Rule,
reported: Set<string>,
): HyperframeLintFinding[] {
const positionProps = rule.nodes.flatMap((node) =>
node.type === "decl" && !node.important && POSITION_PROPERTIES.has(node.prop.toLowerCase())
? [node.prop]
: [],
);
if (positionProps.length === 0) return [];
const findings: HyperframeLintFinding[] = [];
for (const selector of resolvedRuleSelectors(rule)) {
const id = reported.has(selector) ? null : reducedSpecificityId(selector);
if (id === null) continue;
reported.add(selector);
findings.push({
code: "id_override_reduced_specificity",
severity: "warning",
message: `Selector "${selector}" sets ${positionProps.join("/")} through [id=...] or :where(#id), which has class-level or zero specificity, so a compound class rule (e.g. ".parent .row") on the same element can silently win over this override.`,
selector,
fixHint: `Use \`${cssIdSelector(id)}\` instead; id specificity beats any selector built only from classes.`,
snippet: truncateSnippet(rule.toString()),
});
}
return findings;
}
function ruleForcesOpacityZero(rule: postcss.Rule): boolean {
let forcesOpacityZero = false;
rule.walkDecls(/^opacity$/i, (declaration) => {
if (Number(declaration.value.trim()) === 0) forcesOpacityZero = true;
});
return forcesOpacityZero;
}
const CSS_TRANSITION_PROPERTY_PATTERN = /^(?:-webkit-)?transition(?:-[a-z][a-z-]*)?$/i;
const TRANSITION_NONE_PROPERTIES = new Set(["transition", "transition-property"]);
const TRANSITION_TIME_PROPERTIES = new Set([
"transition",
"transition-duration",
"transition-delay",
]);
// All-zero times (the reduced-motion / render-lock reset) never run on the browser clock.
function hasNonZeroTime(value: string): boolean {
const times = value.match(/[+-]?(?:\d*\.)?\d+m?s\b/g) ?? [];
return value.includes("var(") || times.some((time) => Number.parseFloat(time) !== 0);
}
function isSeekUnsafeTransition(declaration: postcss.Declaration): boolean {
const property = declaration.prop.trim().toLowerCase();
if (!CSS_TRANSITION_PROPERTY_PATTERN.test(property)) return false;
const name = property.replace(/^-webkit-/, "");
const value = declaration.value.trim().toLowerCase();
if (value === "none" && TRANSITION_NONE_PROPERTIES.has(name)) return false;
return !TRANSITION_TIME_PROPERTIES.has(name) || hasNonZeroTime(value);
}
function cssTransitionFinding(
declaration: postcss.Declaration,
details: Pick<HyperframeLintFinding, "selector" | "elementId" | "snippet">,
): HyperframeLintFinding {
return {
code: "css_transition_used",
severity: "warning",
message: `CSS declaration \`${declaration.prop}: ${declaration.value}\` runs on the browser clock and cannot be seeked deterministically across render workers.`,
fixHint:
"Keep the class or attribute swap for state; put the visual change on the paused GSAP timeline.",
...details,
};
}
function isStudioTimelineElement(tag: { raw: string; name: string }): boolean {
if (["script", "style", "link", "meta", "template", "noscript"].includes(tag.name)) {
return false;
}
return Boolean(
readAttr(tag.raw, "data-start") ||
readAttr(tag.raw, "data-track-index") ||
readAttr(tag.raw, "data-track") ||
readAttr(tag.raw, "data-composition-src") ||
readAttr(tag.raw, "data-composition-file"),
);
}
function describeStudioElement(tag: { raw: string; name: string }): string {
const parts = [`<${tag.name}`];
const className = readAttr(tag.raw, "class");
const compositionId = readDecodedAttr(tag.raw, "data-composition-id");
const dataStart = readAttr(tag.raw, "data-start");
const dataTrack = readAttr(tag.raw, "data-track-index") ?? readAttr(tag.raw, "data-track");
if (className) {
const primaryClass = className
.split(/\s+/)
.map((value) => value.trim())
.find((value) => value && value !== "clip");
if (primaryClass) parts.push(` class="${primaryClass}"`);
}
if (compositionId) parts.push(` data-composition-id="${compositionId}"`);
if (dataStart) parts.push(` data-start="${dataStart}"`);
if (dataTrack) parts.push(` data-track-index="${dataTrack}"`);
parts.push(">");
return parts.join("");
}
const VISIBLE_MARKUP_COMMENT_PATTERN = /\/\*[\s\S]*?\*\//g;
const VISIBLE_MARKUP_COMMENT_PROTECTED_BLOCK_PATTERN =
/<(style|script|template|title|noscript|pre|code|textarea|text)\b[^>]*>[\s\S]*?<\/\1(?:\s[^>]*)?>/gi;
interface SourceRange {
start: number;
end: number;
}
function findProtectedVisibleMarkupRanges(source: string): SourceRange[] {
const ranges: SourceRange[] = [];
for (const match of source.matchAll(VISIBLE_MARKUP_COMMENT_PROTECTED_BLOCK_PATTERN)) {
ranges.push({ start: match.index, end: match.index + match[0].length });
}
return ranges;
}
function isInsideSourceRange(index: number, ranges: SourceRange[]): boolean {
return ranges.some((range) => range.start <= index && index < range.end);
}
function isInsideHtmlTag(source: string, index: number): boolean {
let inTag = false;
let quote: '"' | "'" | null = null;
for (let i = 0; i < index; i++) {
const char = source[i];
if (!inTag) {
if (char === "<") inTag = true;
continue;
}
if (quote) {
if (char === quote) quote = null;
continue;
}
if (char === '"' || char === "'") {
quote = char;
} else if (char === ">") {
inTag = false;
}
}
return inTag;
}
function findVisibleMarkupCommentLeak(source: string): string | null {
const protectedRanges = findProtectedVisibleMarkupRanges(source);
for (const match of source.matchAll(VISIBLE_MARKUP_COMMENT_PATTERN)) {
if (isInsideHtmlTag(source, match.index)) continue;
if (isInsideSourceRange(match.index, protectedRanges)) continue;
return match[0];
}
return null;
}
type ScaffoldSize = { width: string; height: string };
// Groups 1 and 3 are prefix text for applyResolutionPreset's in-place
// replace; lint only reads the digit groups (2 and 4).
function readHtmlBodyCssSize(source: string): ScaffoldSize | null {
const widthFirst = source.match(HTML_BODY_CSS_WIDTH_FIRST_RE);
if (widthFirst) {
const [, , width = "", , height = ""] = widthFirst;
return { width, height };
}
const heightFirst = source.match(HTML_BODY_CSS_HEIGHT_FIRST_RE);
if (heightFirst) {
const [, , height = "", , width = ""] = heightFirst;
return { width, height };
}
return null;
}
function readViewportMetaSize(source: string): ScaffoldSize | null {
const match = source.match(VIEWPORT_META_SIZE_RE);
if (!match) return null;
const [, , width = "", , height = ""] = match;
return { width, height };
}
function describeSizeMismatch(
label: string,
size: ScaffoldSize | null,
dataWidth: string,
dataHeight: string,
): string | null {
if (!size || (size.width === dataWidth && size.height === dataHeight)) return null;
return `${label} is ${size.width}x${size.height}`;
}
// Only html/body CSS actually clips the root; the CDP viewport comes from
// data-width/data-height, not `<meta viewport>` — so a viewport-only drift gets distinct wording.
function describeRootDimensionsDrift(
source: string,
dataWidth: string,
dataHeight: string,
): { message: string; fixHint: string } | null {
const bodyCssMismatch = describeSizeMismatch(
"html/body CSS",
readHtmlBodyCssSize(source),
dataWidth,
dataHeight,
);
const viewportMismatch = describeSizeMismatch(
"the viewport meta",
readViewportMetaSize(source),
dataWidth,
dataHeight,
);
if (!bodyCssMismatch && !viewportMismatch) return null;
const declared = `Root composition declares data-width="${dataWidth}" data-height="${dataHeight}"`;
if (!bodyCssMismatch) {
return {
message: `${declared}, but ${viewportMismatch}. The viewport meta has no effect on capture (the renderer sizes the viewport from the root's own data-width/data-height), so this is stale metadata, not a clipping risk.`,
fixHint:
"update the meta viewport to match, or scaffold with `hyperframes init --resolution portrait`",
};
}
const mismatches = viewportMismatch
? `${bodyCssMismatch} and ${viewportMismatch}`
: bodyCssMismatch;
return {
message: `${declared}, but ${mismatches}. The scaffolded body clips the composition at its old size.`,
fixHint:
"update html/body CSS and the meta viewport to match, or scaffold with `hyperframes init --resolution portrait`",
};
}
export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// id_requires_css_escape
({ tags, styles, scripts }) => {
const findings: HyperframeLintFinding[] = [];
let targeted: Set<string> | undefined;
for (const tag of tags) {
const id = readAttr(tag.raw, "id");
if (!id || !/^\d/.test(id)) continue;
targeted ??= digitIdsTargetedBySelectors(styles, scripts);
const used = targeted.has(id);
findings.push({
code: "id_requires_css_escape",
severity: used ? "error" : "warning",
message: used
? `id="${id}" starts with a digit, and the selector \`#${id}\` used in this composition is invalid: querySelector and GSAP throw a SyntaxError, and CSS drops the rule.`
: `id="${id}" starts with a digit, so the common selector \`#${id}\` throws a SyntaxError in querySelector().`,
elementId: id,
fixHint:
"Rename the id to start with a letter (recommended), or build selectors with `#${CSS.escape(id)}` at runtime.",
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// root_missing_composition_id + root_missing_dimensions
// fallow-ignore-next-line complexity
({ rootTag, options }) => {
const findings: HyperframeLintFinding[] = [];
if (!rootTag || !readDecodedAttr(rootTag.raw, "data-composition-id")) {
findings.push({
code: "root_missing_composition_id",
severity: "error",
message: "Root composition is missing `data-composition-id`.",
elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
fixHint: "Add a stable `data-composition-id` to the entry composition wrapper.",
snippet: truncateSnippet(rootTag?.raw || ""),
});
}
if (
!options.isSubComposition &&
(!rootTag || !readAttr(rootTag.raw, "data-width") || !readAttr(rootTag.raw, "data-height"))
) {
findings.push({
code: "root_missing_dimensions",
severity: "error",
message: "Root composition is missing `data-width` or `data-height`.",
elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
fixHint: "Set numeric `data-width` and `data-height` on the entry composition root.",
snippet: truncateSnippet(rootTag?.raw || ""),
});
}
return findings;
},
// root_dimensions_mismatch
//
// Render size and the runtime's forced #root size both read the root's own
// data-width/data-height, so they stay correct. But editing only those two
// attributes — rather than scaffolding with `hyperframes init --resolution`,
// which rewrites the scaffold's other copies of the resolution too — leaves
// the `html, body` CSS and the `<meta viewport>` at the old value, and a
// stale body with `overflow: hidden` visually clips the correctly-sized
// root. `hyperframes check`'s layout audits can't see it: they measure
// against the root's own (already-correct) rect, not the body's.
//
// Sub-compositions are exempt: loadCompositions (packages/core/src/
// runtime/compositionLoader.ts) mounts only the matched <template>/<body>
// subtree, so a sub-comp's own <html>/<head>/<meta viewport> never reach
// the rendering document, even when it's a full standalone document.
({ rootTag, source, options }) => {
if (!rootTag || options.isSubComposition) return [];
const dataWidth = readAttr(rootTag.raw, "data-width");
const dataHeight = readAttr(rootTag.raw, "data-height");
if (!dataWidth || !dataHeight) return [];
const drift = describeRootDimensionsDrift(source, dataWidth, dataHeight);
if (!drift) return [];
return [
{
code: "root_dimensions_mismatch",
severity: "warning",
message: drift.message,
elementId: readAttr(rootTag.raw, "id") || undefined,
fixHint: drift.fixHint,
snippet: truncateSnippet(rootTag.raw),
},
];
},
// unbalanced_style_tags
({ source }) => {
let opens = 0;
let closes = 0;
let firstTag = "";
for (const match of source.matchAll(
/<script\b[\s\S]*?<\/script[^>]*>|<style\b|<\/style\s*>/gi,
)) {
const token = match[0].toLowerCase();
if (token.startsWith("<script")) continue;
if (token.startsWith("</style")) closes += 1;
else opens += 1;
if (!firstTag) firstTag = match[0];
}
if (opens === closes) return [];
return [
{
code: "unbalanced_style_tags",
severity: "error",
message:
opens > closes
? "A <style> block is never closed, so following markup is parsed as CSS and disappears from the frame."
: "An extra </style> closes the stylesheet early, so trailing CSS renders as visible on-screen text.",
fixHint: "Keep <style> and </style> paired. One extra closer dumps CSS into the body.",
snippet: truncateSnippet(firstTag || "<style>"),
},
];
},
// visible_markup_comment
({ source }) => {
const snippet = findVisibleMarkupCommentLeak(source);
if (!snippet) return [];
return [
{
code: "visible_markup_comment",
severity: "error",
message:
"CSS/JS block comment syntax (`/* ... */`) appears in visible HTML markup. HTML only treats `<!-- ... -->` as comments, so this renders as on-screen text.",
fixHint:
"Remove the text or convert it to a real HTML comment (`<!-- ... -->`). Keep CSS comments inside `<style>` and JS comments inside `<script>`.",
snippet: truncateSnippet(snippet),
},
];
},
// missing_timeline_registry
// fallow-ignore-next-line complexity
({ source, rawSource, rootTag, options }) => {
// Sub-compositions inherit window.__timelines from the host composition
if (options.isSubComposition || rawSource.trimStart().toLowerCase().startsWith("<template")) {
return [];
}
if (/(?:^|\s)data-no-timeline(?=[\s=/]|$)/i.test(rootTag?.attrs || "")) return [];
const findings: HyperframeLintFinding[] = [];
if (
!TIMELINE_REGISTRY_INIT_PATTERN.test(source) &&
!TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source) &&
!TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(source)
) {
findings.push({
code: "missing_timeline_registry",
severity: "error",
message: "Missing `window.__timelines` registration.",
fixHint: "Register each composition timeline on `window.__timelines[compositionId]`.",
});
}
// `timeline_registry_missing_init` used to fire here, demanding
// `window.__timelines = window.__timelines || {}` before any assignment.
// The runtime already owns that invariant: runtime/entry.ts creates the
// registry at script-evaluation time, before any inline composition script
// runs, and both injection paths put the runtime bundle in <head> ahead of
// the body scripts that build timelines. Verified by rendering a
// composition whose only registration is a bare
// `window.__timelines["main"] = gsap.timeline(...)`: it renders and
// animates correctly. The rule made a working file fail lint, and a lint
// ERROR also suppresses the layout and contrast audits in `check`, so it
// cost far more than the line it was protecting.
return findings;
},
// timeline_id_mismatch
({ source, compositionIds }) => {
const findings: HyperframeLintFinding[] = [];
const htmlCompIds = new Set(compositionIds);
const timelineRegKeys = new Set<string>();
for (const key of extractTimelineRegistryKeys(source)) {
timelineRegKeys.add(key);
}
for (const key of timelineRegKeys) {
if (!htmlCompIds.has(key)) {
findings.push({
code: "timeline_id_mismatch",
severity: "error",
message: `Timeline registered as "${key}" but no element has data-composition-id="${key}". The runtime cannot auto-nest this timeline.`,
fixHint: `Change window.__timelines["${key}"] to match the data-composition-id attribute, or vice versa.`,
});
}
}
return findings;
},
// css_transition_used
({ styles, tags }) => {
const findings: HyperframeLintFinding[] = [];
for (const style of styles) {
if (!/transition/i.test(style.content)) continue;
let root: postcss.Root;
try {
root = postcss.parse(style.content);
} catch {
// The CSS syntax rule reports malformed style blocks separately.
continue;
}
root.walkDecls((declaration) => {
if (!isSeekUnsafeTransition(declaration)) return;
const selector =
declaration.parent?.type === "rule" ? declaration.parent.selector : undefined;
findings.push(
cssTransitionFinding(declaration, {
selector,
snippet: truncateSnippet(declaration.toString()),
}),
);
});
}
for (const tag of tags) {
const inlineStyle = readDecodedAttr(tag.raw, "style");
if (!inlineStyle || !/transition/i.test(inlineStyle)) continue;
let root: postcss.Root;
try {
root = postcss.parse(inlineStyle);
} catch {
continue;
}
root.walkDecls((declaration) => {
if (!isSeekUnsafeTransition(declaration)) return;
findings.push(
cssTransitionFinding(declaration, {
elementId: readDecodedAttr(tag.raw, "id") || undefined,
snippet: truncateSnippet(tag.raw),
}),
);
});
}
return findings;
},
// CSS selector safety
({ styles, locate }) => {
const findings: HyperframeLintFinding[] = [];
const reportedRepeatedIds = new Set<string>();
const reportedHiddenStyleSelectors = new Set<string>();
const reportedReducedIdSelectors = new Set<string>();
for (const style of styles) {
let root: postcss.Root;
try {
root = postcss.parse(style.content);
} catch (error) {
findings.push({
...locate(
style,
error instanceof postcss.CssSyntaxError
? cssErrorOffset(style.content, error)
: undefined,
),
code: "css_parse_error",
severity: "error",
message: `CSS parse error: ${error instanceof Error ? error.message : "unknown"}`,
});
continue;
}
root.walkRules((rule) => {
const forcesOpacityZero = ruleForcesOpacityZero(rule);
findings.push(...reducedSpecificityIdFindings(rule, reportedReducedIdSelectors));
for (const selector of resolvedRuleSelectors(rule)) {
const repeatedId = repeatedDescendantId(selector);
if (repeatedId && !reportedRepeatedIds.has(repeatedId)) {
reportedRepeatedIds.add(repeatedId);
findings.push({
code: "repeated_id_descendant_selector",
severity: "error",
message: `Selector "${selector}" requires #${repeatedId} to be nested inside another #${repeatedId}. IDs must be unique, so this selector cannot match a valid composition.`,
selector,
fixHint: `Remove the duplicate ancestor: change \`#${repeatedId} #${repeatedId}\` to \`#${repeatedId}\`.`,
});
}
if (
!forcesOpacityZero ||
reportedHiddenStyleSelectors.has(selector) ||
!selectorAliasesRuntimeHiddenStyle(selector)
) {
continue;
}
reportedHiddenStyleSelectors.add(selector);
findings.push({
code: "runtime_hidden_style_opacity",
severity: "error",
message: `Selector "${selector}" observes HyperFrames' runtime-owned hidden style and forces opacity to zero. The renderer hides each native video before copying its computed opacity to the visible replacement frame, so this rule makes both transparent.`,
selector,
fixHint:
'Restrict the guard to sub-composition hosts, for example `[data-composition-src][style*="visibility: hidden"]` and `[data-composition-file][style*="visibility: hidden"]`. Do not derive arbitrary element or media opacity from runtime-owned inline visibility.',
snippet: truncateSnippet(rule.toString()),
});
}
});
}
return findings;
},
// unclosed_tag_swallowed_element
({ tags }) => {
const findings: HyperframeLintFinding[] = [];
for (const tag of tags) {
if (!hasUnquotedLessThan(tag.attrs)) continue;
findings.push({
code: "unclosed_tag_swallowed_element",
severity: "error",
message: `<${tag.name}> is missing its closing \`>\` before the next \`<\`, so the following element is swallowed as bogus attribute text and never becomes a real node.`,
fixHint: "Close the previous tag's `>` before opening the next element.",
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// invalid_inline_script_syntax (malformed close tag)
({ source }) => {
if (!INVALID_SCRIPT_CLOSE_PATTERN.test(source)) return [];
return [
{
code: "invalid_inline_script_syntax",
severity: "error",
message: "Detected malformed inline `<script>` closing syntax.",
fixHint: "Close inline scripts with a valid `</script>` tag.",
},
];
},
// invalid_inline_script_syntax (JS parse error)
({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
for (const script of scripts) {
const type = readDecodedAttr(script.raw, "type")?.trim().toLowerCase() ?? "";
if (readDecodedAttr(script.raw, "src") !== null || SCRIPT_SYNTAX_EXEMPT_TYPES.has(type))
continue;
const syntaxError = getInlineScriptSyntaxError(script.content);
if (!syntaxError) continue;
findings.push({
...locate(script, syntaxError.offset),
code: "invalid_inline_script_syntax",
severity: "error",
message: `Inline script has invalid syntax: ${syntaxError.message}`,
fixHint: "Fix the inline script syntax before render verification.",
snippet: truncateSnippet(script.content),
});
}
return findings;
},
// host_missing_composition_id
({ tags }) => {
const findings: HyperframeLintFinding[] = [];
for (const tag of tags) {
const src = readAttr(tag.raw, "data-composition-src");
if (!src) continue;
if (readDecodedAttr(tag.raw, "data-composition-id")) continue;
findings.push({
code: "host_missing_composition_id",
severity: "error",
message: `Composition host for "${src}" is missing \`data-composition-id\`.`,
elementId: readAttr(tag.raw, "id") || undefined,
fixHint: "Set `data-composition-id` on every `data-composition-src` host element.",
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// scoped_css_missing_wrapper
({ styles, compositionIds }) => {
const findings: HyperframeLintFinding[] = [];
const scopedCssCompositionIds = new Set<string>();
for (const style of styles) {
for (const compId of extractCompositionIdsFromCss(style.content)) {
scopedCssCompositionIds.add(compId);
}
}
for (const compId of scopedCssCompositionIds) {
if (compositionIds.has(compId)) continue;
findings.push({
code: "scoped_css_missing_wrapper",
severity: "warning",
message: `Scoped CSS targets composition "${compId}" but no matching wrapper exists in this HTML.`,
selector: `[data-composition-id="${compId}"]`,
fixHint:
"Preserve the matching composition wrapper or align the CSS scope to an existing wrapper.",
});
}
return findings;
},
// studio_missing_editable_id
({ tags, rootTag }) => {
const findings: HyperframeLintFinding[] = [];
for (const tag of tags) {
if (rootTag && tag.index === rootTag.index) continue;
if (!isStudioTimelineElement(tag)) continue;
if (readAttr(tag.raw, "id")) continue;
const descriptor = describeStudioElement(tag);
findings.push({
code: "studio_missing_editable_id",
severity: "warning",
message: `${descriptor} has no id, so Studio cannot use a stable edit target for its timeline and canvas controls.`,
selector: readDecodedAttr(tag.raw, "data-composition-id")
? `[data-composition-id="${readDecodedAttr(tag.raw, "data-composition-id")}"]`
: undefined,
fixHint:
'Add a stable, human-readable id such as id="hero-title" or id="scene-1-card" to every timeline-visible element you want agents or Studio to edit.',
snippet: truncateSnippet(tag.raw),
});
}
return findings;
},
// non_deterministic_code
({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
const patterns: Array<{
pattern: RegExp;
label: string;
hint: string;
/** Match against raw source, because the value being matched is a string GSAP parses. */
scansStrings?: boolean;
}> = [
{
pattern: /Math\.random\s*\(/,
label: "Math.random()",
hint: "Use a seeded PRNG (e.g. a simple mulberry32) so renders are deterministic across frames.",
},
{
pattern: /Date\.now\s*\(/,
label: "Date.now()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
// Zero-arg only. `new Date(<fixed timestamp>)` is fully deterministic and is how
// a composition labels a fixed date on an axis or card; the hint ("remove
// time-dependent code") cannot be applied to it without deleting the label.
pattern: /new\s+Date\s*\(\s*\)/,
label: "new Date()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
pattern: /performance\.now\s*\(/,
label: "performance.now()",
hint: "Remove time-dependent code. Use GSAP timeline position instead of wall-clock time.",
},
{
pattern: /crypto\.getRandomValues\s*\(/,
label: "crypto.getRandomValues()",
hint: "Use a seeded PRNG (e.g. a simple mulberry32) so renders are deterministic across frames.",
},
{
pattern: /gsap\.utils\.random\s*\(/,
label: "gsap.utils.random()",
hint: "Each render worker initializes independently, so random values diverge across chunks. Use a seeded PRNG or fixed values.",
},
{
// GSAP string form: "random(...)" / "+=random(...)" — re-rolls at tween init.
// `scansStrings` because here the string IS the executed value: GSAP parses it.
// Every other pattern above matches executable code, so a match inside a string
// literal is inert text and must not be reported.
pattern: /["'`](?:[+-]=)?random\(\s*[-\d[]/,
scansStrings: true,
label: '"random(...)" tween value',
hint: "GSAP random string values re-roll at tween init and each render worker initializes independently. Use fixed values or precompute with a seeded PRNG.",
},
];
for (const script of scripts) {
const withoutComments = stripJsComments(blankInlinedGsapLibrary(script.content));
// Strings are content, not code. A composition that DISPLAYS source (the
// code-snippet blocks) carries `Math.random()` inside a string
// literal it never executes, and reported itself non-deterministic with no
// way to clear the error while still rendering the snippet.
const executable = stripStringLiterals(withoutComments);
for (const { pattern, label, hint, scansStrings } of patterns) {
const match = pattern.exec(scansStrings ? withoutComments : executable);
if (match) {
findings.push({
...locate(script, match.index),
code: "non_deterministic_code",
severity: "error",
message: `Script contains \`${label}\` which produces non-deterministic output. Renders may differ between frames or runs.`,
fixHint: hint,
snippet: truncateSnippet(script.content),
});
}
}
}
return findings;
},
];
function cssErrorOffset(source: string, error: postcss.CssSyntaxError): number | undefined {
// Current PostCSS supplies offsets, but its declaration type omits this field.
if (error.input && "offset" in error.input && typeof error.input.offset === "number")
return error.input.offset;
const { line, column } = error;
if (line === undefined || column === undefined) return undefined;
let offset = 0;
let currentLine = 1;
// PostCSS counts LF only; sourcePosition subsequently handles HTML newline conventions.
for (const match of source.matchAll(/\n/g)) {
if (currentLine >= line) break;
offset = match.index + 1;
currentLine++;
}
return currentLine === line ? offset + column - 1 : undefined;
}