Skip to content

Write HTML. Render video. Built for agents.

fix(lint): map parser diagnostics to exact source positions (#4360)

Miguel Ángel7977b926d205
diff --git a/bun.lock b/bun.lock
index 279120a05e..dd3edec0fb 100644
--- a/bun.lock
+++ b/bun.lock
@@ -177,6 +177,8 @@
"version": "0.8.62",
"dependencies": {
"@hyperframes/parsers": "workspace:*",
+ "acorn": "^8.17.0",
+ "acorn-walk": "^8.3.5",
"htmlparser2": "^10.1.0",
"linkedom": "^0.18.12",
"postcss": "^8.5.8",
diff --git a/packages/lint/package.json b/packages/lint/package.json
index 47bbccfdb8..b0f1cbe8ff 100644
--- a/packages/lint/package.json
+++ b/packages/lint/package.json
@@ -54,6 +54,8 @@
},
"dependencies": {
"@hyperframes/parsers": "workspace:*",
+ "acorn": "^8.17.0",
+ "acorn-walk": "^8.3.5",
"htmlparser2": "^10.1.0",
"linkedom": "^0.18.12",
"postcss": "^8.5.8",
diff --git a/packages/lint/src/context.ts b/packages/lint/src/context.ts
index 85149c5532..a8a4e559d3 100644
--- a/packages/lint/src/context.ts
+++ b/packages/lint/src/context.ts
@@ -1,16 +1,12 @@
+import { mappedHtmlSource, sourcePosition, type SourceLocation } from "./sourceCoordinates";
import type { HyperframeLintFinding, HyperframeLinterOptions } from "./types";
-import {
- parseHtmlStructure,
- findRootTag,
- collectCompositionIds,
- readDecodedAttr,
- stripHtmlComments,
-} from "./utils";
+import { parseHtmlStructure, findRootTag, collectCompositionIds, readDecodedAttr } from "./utils";
import type { OpenTag, ExtractedBlock } from "./utils";
export type { OpenTag, ExtractedBlock };
export type LintContext = {
+ locate: (block: ExtractedBlock, offset: number | undefined) => SourceLocation;
source: string;
rawSource: string;
tags: OpenTag[];
@@ -30,7 +26,9 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
// Strip HTML comments before scanning so a commented-out <template> or tag can't
// hijack the boundary match below. Linear + fixpoint (see stripHtmlComments) to
// stay ReDoS-free and catch markers that re-form when a comment is removed.
- let source = stripHtmlComments(rawSource);
+ const mapped = mappedHtmlSource(rawSource);
+ let source = mapped.source;
+ let sourceStart = 0;
const initialStructure = parseHtmlStructure(source);
const templateTags = initialStructure.tags.filter(
(tag) => tag.name === "template" && tag.closeIndex != null,
@@ -49,7 +47,8 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
const template = templateTags[0];
let structure = initialStructure;
if (template && !findRootTag(sourceWithoutTemplates)) {
- source = source.slice(template.index + template.raw.length, template.closeIndex);
+ sourceStart = template.index + template.raw.length;
+ source = source.slice(sourceStart, template.closeIndex);
structure = parseHtmlStructure(source);
}
@@ -61,6 +60,7 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
content: style.content,
raw: style.content,
index: -1,
+ file: style.file ?? style.href,
})),
];
const scripts = structure.scripts;
@@ -68,7 +68,17 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
const rootTag = findRootTag(source, tags);
const rootCompositionId = readDecodedAttr(rootTag?.raw || "", "data-composition-id");
+ const locate = (block: ExtractedBlock, offset: number | undefined): SourceLocation => {
+ if (offset === undefined || offset < 0 || offset > block.content.length) return {};
+ if (block.index === -1) return sourcePosition(block.content, offset, block.file);
+ if (block.contentStart === undefined) return {};
+ const originalOffset = mapped.originalOffset(sourceStart + block.contentStart + offset);
+ return originalOffset === undefined
+ ? {}
+ : sourcePosition(rawSource, originalOffset, options.filePath);
+ };
return {
+ locate,
source,
rawSource,
tags,
diff --git a/packages/lint/src/hyperframeLinter.ts b/packages/lint/src/hyperframeLinter.ts
index f6293b5199..4f95a37402 100644
--- a/packages/lint/src/hyperframeLinter.ts
+++ b/packages/lint/src/hyperframeLinter.ts
@@ -121,7 +121,7 @@ function collectFindings(
const dedupeKey = dedupeKeyFor(finding);
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
- into.push(filePath ? { ...finding, file: filePath } : finding);
+ into.push(filePath ? { ...finding, file: finding.file ?? filePath } : finding);
}
}
@@ -134,6 +134,17 @@ export async function lintHyperframeHtml(
const { findings: rawFindings, timings } = await runRules(ctx, options.filePath);
const locate = createSourceLocator(html);
const findings = rawFindings.map((finding) => {
+ if (
+ finding.line !== undefined ||
+ finding.code === "invalid_inline_script_syntax" ||
+ finding.code === "non_deterministic_code" ||
+ [
+ "gsap_infinite_repeat",
+ "gsap_repeat_ceil_overshoot",
+ "gsap_repeat_floor_unclamped",
+ ].includes(finding.code)
+ )
+ return finding;
// External CSS has its own source coordinates; never attribute it to the HTML document.
if (
finding.snippet &&
diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.ts
index c7659217c1..d4d996e575 100644
--- a/packages/lint/src/project.ts
+++ b/packages/lint/src/project.ts
@@ -111,11 +111,15 @@ function collectExternalStyles(
projectDir: string,
html: string,
compSrcPath?: string,
-): Array<{ href: string; content: string }> {
- const styles: Array<{ href: string; content: string }> = [];
+): Array<{ href: string; content: string; file?: string }> {
+ const styles: Array<{ href: string; content: string; file?: string }> = [];
const { document } = parseHTML(html);
- for (const { href, content } of collectLocalStylesheets(projectDir, document, compSrcPath)) {
- styles.push({ href, content });
+ for (const { href, content, rootRelativePath } of collectLocalStylesheets(
+ projectDir,
+ document,
+ compSrcPath,
+ )) {
+ styles.push({ href, content, file: join(projectDir, rootRelativePath) });
}
return styles;
}
diff --git a/packages/lint/src/rules/core.ts b/packages/lint/src/rules/core.ts
index 8c3e3ed90d..e634afe968 100644
--- a/packages/lint/src/rules/core.ts
+++ b/packages/lint/src/rules/core.ts
@@ -5,7 +5,7 @@ import {
HTML_BODY_CSS_WIDTH_FIRST_RE,
HTML_BODY_CSS_HEIGHT_FIRST_RE,
VIEWPORT_META_SIZE_RE,
-} from "@hyperframes/parsers";
+} from "@hyperframes/parsers/composition";
import {
readAttr,
readDecodedAttr,
@@ -497,7 +497,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
},
// CSS selector safety
- ({ styles }) => {
+ ({ styles, locate }) => {
const findings: HyperframeLintFinding[] = [];
const reportedRepeatedIds = new Set<string>();
const reportedHiddenStyleSelectors = new Set<string>();
@@ -507,6 +507,12 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
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"}`,
@@ -581,7 +587,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
},
// invalid_inline_script_syntax (JS parse error)
- ({ scripts }) => {
+ ({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
for (const script of scripts) {
const attrs = script.attrs || "";
@@ -595,9 +601,10 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
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: `Inline script has invalid syntax: ${syntaxError.message}`,
fixHint: "Fix the inline script syntax before render verification.",
snippet: truncateSnippet(script.content),
});
@@ -672,7 +679,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
},
// non_deterministic_code
- ({ scripts }) => {
+ ({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
const patterns: Array<{
pattern: RegExp;
@@ -734,8 +741,10 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// way to clear the error while still rendering the snippet.
const executable = stripStringLiterals(withoutComments);
for (const { pattern, label, hint, scansStrings } of patterns) {
- if (pattern.test(scansStrings ? withoutComments : executable)) {
+ 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.`,
@@ -748,3 +757,20 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
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;
+}
diff --git a/packages/lint/src/rules/fonts.ts b/packages/lint/src/rules/fonts.ts
index bede023cf8..cb9bb7df59 100644
--- a/packages/lint/src/rules/fonts.ts
+++ b/packages/lint/src/rules/fonts.ts
@@ -1,3 +1,5 @@
+import postcss from "postcss";
+import type { SourceLocation } from "../sourceCoordinates";
import { FONT_ALIAS_KEYS, resolveAliasDisplayName } from "@hyperframes/parsers/composition";
import type { LintContext, HyperframeLintFinding } from "../context";
import { isRegistrySourceFile, isRegistryInstalledFile } from "./composition";
@@ -187,7 +189,7 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
},
// font_family_without_font_face
- ({ styles, source, rawSource, options }) => {
+ ({ styles, source, rawSource, options, locate }) => {
if (isRegistrySourceFile(options.filePath) || isRegistryInstalledFile(rawSource)) return [];
const findings: HyperframeLintFinding[] = [];
const declared = extractFontFaceFamilies(styles);
@@ -203,6 +205,7 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
if (undeclared.length === 0) return findings;
findings.push({
+ ...uniqueFontLocation(styles, undeclared, locate),
code: "font_family_without_font_face",
severity: "error",
message:
@@ -219,3 +222,34 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
return findings;
},
];
+
+/** Aggregate diagnostics get a location only when exactly one declaration supplies their evidence. */
+function uniqueFontLocation(
+ styles: LintContext["styles"],
+ families: string[],
+ locate: LintContext["locate"],
+): SourceLocation {
+ const locations: SourceLocation[] = [];
+ for (const style of styles) {
+ try {
+ postcss.parse(style.content).walkDecls(/^font-family$/i, (decl) => {
+ let parent: postcss.AnyNode | undefined = decl.parent;
+ while (parent) {
+ if (parent.type === "atrule" && parent.name.toLowerCase() === "font-face") return;
+ parent = parent.parent;
+ }
+ if (
+ !decl.value
+ .split(",")
+ .some((part) => families.includes(normalizeUsedFontName(part) ?? ""))
+ )
+ return;
+ locations.push(locate(style, decl.source?.start?.offset));
+ });
+ } catch {
+ // The CSS syntax rule reports malformed styles; a guessed declaration is not useful.
+ return {};
+ }
+ }
+ return locations.length === 1 ? locations[0]! : {};
+}
diff --git a/packages/lint/src/rules/gsap.ts b/packages/lint/src/rules/gsap.ts
index 3549d79042..215669de77 100644
--- a/packages/lint/src/rules/gsap.ts
+++ b/packages/lint/src/rules/gsap.ts
@@ -1,3 +1,4 @@
+import { gsapCallOffset, containingCallOffset } from "../scriptPositions";
interface LintParsedGsap {
animations: Array<{
targetSelector: string;
@@ -530,8 +531,12 @@ function scanScriptsForRegexMatches(
scripts: LintContext["scripts"],
pattern: RegExp,
options: { stripComments: boolean; contextBefore: number; contextAfter: number },
-): Array<{ match: RegExpExecArray; snippet: string }> {
- const hits: Array<{ match: RegExpExecArray; snippet: string }> = [];
+): Array<{ match: RegExpExecArray; snippet: string; script: LintContext["scripts"][number] }> {
+ const hits: Array<{
+ match: RegExpExecArray;
+ snippet: string;
+ script: LintContext["scripts"][number];
+ }> = [];
for (const script of scripts) {
const content = options.stripComments ? stripJsComments(script.content) : script.content;
const regex = new RegExp(pattern.source, pattern.flags);
@@ -542,7 +547,7 @@ function scanScriptsForRegexMatches(
content.length,
match.index + match[0].length + options.contextAfter,
);
- hits.push({ match, snippet: content.slice(contextStart, contextEnd) });
+ hits.push({ match, snippet: content.slice(contextStart, contextEnd), script });
}
}
return hits;
@@ -1534,7 +1539,7 @@ export const gsapRules: LintRule<LintContext>[] = [
},
// gsap_infinite_repeat
- ({ scripts, rootTag }) => {
+ ({ scripts, rootTag, locate }) => {
const findings: HyperframeLintFinding[] = [];
const declaredDuration = Number.parseFloat(
rootTag ? (readAttr(rootTag.raw, "data-duration") ?? "") : "",
@@ -1542,12 +1547,13 @@ export const gsapRules: LintRule<LintContext>[] = [
const hasFiniteCompositionWindow = Number.isFinite(declaredDuration) && declaredDuration > 0;
// Match repeat: -1 in GSAP tweens or timeline configs
const pattern = /repeat\s*:\s*-1(?!\d)/g;
- for (const { snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ for (const { snippet, match, script } of scanScriptsForRegexMatches(scripts, pattern, {
stripComments: true,
contextBefore: 60,
contextAfter: 60,
})) {
findings.push({
+ ...locate(script, containingCallOffset(script, match.index)),
code: "gsap_infinite_repeat",
severity: hasFiniteCompositionWindow ? "warning" : "error",
message: hasFiniteCompositionWindow
@@ -1566,17 +1572,18 @@ export const gsapRules: LintRule<LintContext>[] = [
},
// gsap_repeat_ceil_overshoot
- ({ scripts }) => {
+ ({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
// Match patterns like: repeat: Math.ceil(duration / X) - 1
// or repeat: Math.ceil(totalDuration / cycleDuration) - 1
const pattern = /repeat\s*:\s*Math\.ceil\s*\([^)]+\)\s*-\s*1/g;
- for (const { snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ for (const { snippet, match, script } of scanScriptsForRegexMatches(scripts, pattern, {
stripComments: false,
contextBefore: 40,
contextAfter: 40,
})) {
findings.push({
+ ...locate(script, containingCallOffset(script, match.index)),
code: "gsap_repeat_ceil_overshoot",
severity: "warning",
message:
@@ -1593,18 +1600,19 @@ export const gsapRules: LintRule<LintContext>[] = [
},
// gsap_repeat_floor_unclamped
- ({ scripts }) => {
+ ({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
// A direct floor-minus-one expression becomes GSAP's infinite -1 sentinel when
// the visible duration is shorter than one full cycle. Math.max-wrapped forms
// intentionally do not match because `repeat:` is followed by Math.max, not Math.floor.
const pattern = /repeat\s*:\s*Math\.floor\s*\([^)]+\)\s*-\s*1/g;
- for (const { snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ for (const { snippet, match, script } of scanScriptsForRegexMatches(scripts, pattern, {
stripComments: false,
contextBefore: 40,
contextAfter: 40,
})) {
findings.push({
+ ...locate(script, containingCallOffset(script, match.index)),
code: "gsap_repeat_floor_unclamped",
severity: "warning",
message:
@@ -1620,7 +1628,7 @@ export const gsapRules: LintRule<LintContext>[] = [
},
// gsap_timeline_not_registered
- ({ scripts, rawSource, options }) => {
+ ({ scripts, rawSource, options, locate }) => {
const findings: HyperframeLintFinding[] = [];
const canInheritFromHost =
options.isSubComposition || rawSource.trimStart().toLowerCase().startsWith("<template");
@@ -1633,6 +1641,7 @@ export const gsapRules: LintRule<LintContext>[] = [
TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(content);
if (hasRegistration || canInheritFromHost) continue;
findings.push({
+ ...locate(script, gsapCallOffset(script, "timeline")),
code: "gsap_timeline_not_registered",
severity: "error",
message:
diff --git a/packages/lint/src/rules/media.ts b/packages/lint/src/rules/media.ts
index 3e4bebd4b2..abfd1a6419 100644
--- a/packages/lint/src/rules/media.ts
+++ b/packages/lint/src/rules/media.ts
@@ -1,7 +1,7 @@
import type { LintContext, HyperframeLintFinding, OpenTag } from "../context";
import { readAttr, readDecodedAttr, stripJsComments, truncateSnippet, isMediaTag } from "../utils";
import { validateColorGradingContract } from "@hyperframes/parsers/color-grading-contract";
-import { extractMediaSrcMutations } from "@hyperframes/parsers";
+import { extractMediaSrcMutations } from "@hyperframes/parsers/composition";
import { parseHTML } from "linkedom";
/**
diff --git a/packages/lint/src/scriptPositions.ts b/packages/lint/src/scriptPositions.ts
new file mode 100644
index 0000000000..ecfd3230df
--- /dev/null
+++ b/packages/lint/src/scriptPositions.ts
@@ -0,0 +1,55 @@
+import { parse, type CallExpression } from "acorn";
+import { simple } from "acorn-walk";
+import type { ExtractedBlock } from "./utils";
+
+// Blocks belong to a single lint context. Weak keys release AST evidence after the pass.
+const callIndexes = new WeakMap<ExtractedBlock, CallExpression[]>();
+
+function callsFor(script: ExtractedBlock): CallExpression[] {
+ const cached = callIndexes.get(script);
+ if (cached) return cached;
+ const calls: CallExpression[] = [];
+ try {
+ const ast = parse(script.content, {
+ ecmaVersion: "latest",
+ sourceType: "script",
+ allowReturnOutsideFunction: true,
+ });
+ simple(ast, {
+ CallExpression: (node) => {
+ calls.push(node);
+ },
+ });
+ } catch {
+ // Syntax findings own malformed programs; never guess a call from comment text.
+ }
+ calls.sort((a, b) => a.start - b.start);
+ callIndexes.set(script, calls);
+ return calls;
+}
+
+/** AST offsets follow the same Acorn representation used by Studio's GSAP editor. */
+export function gsapCallOffset(script: ExtractedBlock, method: string): number | undefined {
+ return callsFor(script).find(
+ ({ callee }) =>
+ callee.type === "MemberExpression" &&
+ !callee.computed &&
+ callee.object.type === "Identifier" &&
+ callee.object.name === "gsap" &&
+ callee.property.type === "Identifier" &&
+ callee.property.name === method,
+ )?.start;
+}
+
+/** The innermost call containing an already-detected token (for example repeat: -1). */
+export function containingCallOffset(
+ script: ExtractedBlock,
+ tokenOffset: number,
+): number | undefined {
+ let start: number | undefined;
+ for (const call of callsFor(script)) {
+ if (call.start > tokenOffset) break;
+ if (call.end > tokenOffset) start = call.start;
+ }
+ return start;
+}
diff --git a/packages/lint/src/sourceCoordinates.ts b/packages/lint/src/sourceCoordinates.ts
new file mode 100644
index 0000000000..181e7fe088
--- /dev/null
+++ b/packages/lint/src/sourceCoordinates.ts
@@ -0,0 +1,37 @@
+import type { HyperframeLintFinding } from "./types";
+import { stripHtmlComments } from "./utils";
+
+export type SourceLocation = Pick<HyperframeLintFinding, "file" | "line" | "column">;
+
+/** Keep the existing fixpoint deletion semantics and map only retained UTF-16 units. */
+export function mappedHtmlSource(original: string) {
+ let offsets: Uint32Array | undefined;
+ const source = stripHtmlComments(original, (ranges) => {
+ const previous = offsets;
+ const length =
+ (previous?.length ?? original.length + 1) - ranges.reduce((n, [a, b]) => n + b - a, 0);
+ offsets = new Uint32Array(length);
+ let target = 0;
+ let start = 0;
+ const spans: Array<[number, number]> = [
+ ...ranges,
+ [previous ? previous.length : original.length + 1, 0],
+ ];
+ for (const [a, b] of spans) {
+ for (let i = start; i < a; i++) offsets[target++] = previous ? previous[i]! : i;
+ start = b;
+ }
+ });
+ return { source, originalOffset: (index: number) => (offsets ? offsets[index] : index) };
+}
+
+/** UTF-16 offsets, one-based lines/columns; CRLF counts as one newline. */
+export function sourcePosition(source: string, offset: number, file?: string): SourceLocation {
+ if (!Number.isInteger(offset) || offset < 0 || offset > source.length) return {};
+ const before = source.slice(0, offset);
+ return {
+ ...(file ? { file } : {}),
+ line: before.split(/\r\n|\r|\n/).length,
+ column: offset - Math.max(before.lastIndexOf("\n"), before.lastIndexOf("\r")),
+ };
+}
diff --git a/packages/lint/src/sourceLocations.test.ts b/packages/lint/src/sourceLocations.test.ts
index 179db38817..0cfe7603ca 100644
--- a/packages/lint/src/sourceLocations.test.ts
+++ b/packages/lint/src/sourceLocations.test.ts
@@ -59,3 +59,145 @@ it("does not point synthesized code snippets at commented examples", () => {
),
).toEqual({});
});
+
+describe("rule-owned source positions", () => {
+ const shell = (content: string) =>
+ `<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="3">\n${content}\n</div>`;
+ const at = (html: string, token: string) => {
+ const offset = html.indexOf(token);
+ const before = html.slice(0, offset);
+ return {
+ line: before.split(/\r\n|\r|\n/).length,
+ column: offset - Math.max(before.lastIndexOf("\n"), before.lastIndexOf("\r")),
+ };
+ };
+ it.each(["\n", "\r\n"])(
+ "locates the offending JS expression through comments and templates (%j)",
+ async (nl) => {
+ const html = (
+ `<!--\n😀 header\n-->\n<template>\n` +
+ shell(
+ "<script>\nconst before = 1;\n// Math.random()\n\nconst x = Math.random();\n</script>",
+ ) +
+ "\n</template>"
+ ).replaceAll("\n", nl);
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "non_deterministic_code")).toMatchObject(
+ at(html, "Math.random();"),
+ );
+ },
+ );
+ it("locates an Acorn syntax error rather than the script prefix", async () => {
+ const html = shell("<script>\nconst before = 1;\n\nconst broken = ;\n</script>");
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "invalid_inline_script_syntax")).toMatchObject(
+ at(html, ";\n</script>"),
+ );
+ });
+ it("maps CSS parser positions to original HTML", async () => {
+ const html =
+ "<!-- header -->\n<template>\n" +
+ shell("<style>\n.x {\n color red;\n}\n</style>") +
+ "\n</template>";
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "css_parse_error")).toMatchObject(
+ at(html, "color red"),
+ );
+ });
+ it("keeps an external stylesheet's identity", async () => {
+ const result = await lintHyperframeHtml(shell(""), {
+ filePath: "scenes/a.html",
+ externalStyles: [{ href: "theme.css", content: ".x {\n color red;\n}" }],
+ });
+ expect(result.findings.find((f) => f.code === "css_parse_error")).toMatchObject({
+ file: "theme.css",
+ line: 2,
+ column: 2,
+ });
+ });
+ it("locates a unique font declaration and GSAP timeline call", async () => {
+ const html = shell(
+ '<style>\n.x { font-family: "NoSuchFont"; }\n</style>\n<script>\nconst a = 1;\nconst tl = gsap.timeline();\n</script>',
+ );
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "font_family_without_font_face")).toMatchObject(
+ at(html, "font-family"),
+ );
+ expect(result.findings.find((f) => f.code === "gsap_timeline_not_registered")).toMatchObject(
+ at(html, "gsap.timeline"),
+ );
+ });
+ it("does not arbitrarily locate a multi-declaration font finding", async () => {
+ const result = await lintHyperframeHtml(
+ shell('<style>.a {font-family:"FooUnknown"} .b {font-family:"BarUnknown"}</style>'),
+ );
+ expect(
+ result.findings.find((f) => f.code === "font_family_without_font_face")?.line,
+ ).toBeUndefined();
+ });
+});
+
+it("locates repeated GSAP config errors at the triggering Acorn call", async () => {
+ const html = '<script>\nconst unrelated = 1;\n\ngsap.to(".x", {repeat: -1});\n</script>';
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "gsap_infinite_repeat")).toMatchObject({
+ line: 4,
+ column: 1,
+ });
+});
+
+it("uses Acorn without executing source and preserves classic/module handling", async () => {
+ const classic = await lintHyperframeHtml(
+ "<script>return; globalThis.__lintMustNotRun = true;</script>",
+ );
+ expect(classic.findings.some((f) => f.code === "invalid_inline_script_syntax")).toBe(false);
+ expect("__lintMustNotRun" in globalThis).toBe(false);
+ const module = await lintHyperframeHtml(
+ '<script type="module">import x from "x"; await x;</script>',
+ );
+ expect(module.findings.some((f) => f.code === "invalid_inline_script_syntax")).toBe(false);
+});
+
+it("maps fixpoint comment deletion and repeated script text without guessing", async () => {
+ const html =
+ "<<!-- -->!-- removed -->\n<template>\n<script>const safe = 1;</script>\n<script>const safe = 1; Math.random();</script>\n</template>";
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "non_deterministic_code")).toMatchObject({
+ line: 4,
+ column: 25,
+ });
+});
+
+it("counts same-line Unicode columns as UTF-16 units", async () => {
+ const html = '<script>const text = "😀"; Math.random();</script>';
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "non_deterministic_code")).toMatchObject({
+ line: 1,
+ column: html.indexOf("Math.random") + 1,
+ });
+});
+
+it("leaves the mapped EOF error at the end of its own script", async () => {
+ const html = "<!-- header -->\n<script>const foo = (</script>\n<script>const ok = 1;</script>";
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "invalid_inline_script_syntax")).toMatchObject({
+ line: 2,
+ column: 22,
+ });
+});
+
+it("maps PostCSS offsets when bare CR and LF are mixed", async () => {
+ const html = "<style>.x {\r}\r.y {\n color red;\n}</style>";
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "css_parse_error")).toMatchObject({
+ line: 4,
+ column: 2,
+ });
+});
+
+it("uses classic-script Acorn semantics for new.target and hashbang", async () => {
+ const target = await lintHyperframeHtml("<script>new.target;</script>");
+ expect(target.findings.some((f) => f.code === "invalid_inline_script_syntax")).toBe(true);
+ const hashbang = await lintHyperframeHtml("<script>#!/usr/bin/env node\nconst a=1;</script>");
+ expect(hashbang.findings.some((f) => f.code === "invalid_inline_script_syntax")).toBe(false);
+});
diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.ts
index 86ffb8e964..b5dcaee16a 100644
--- a/packages/lint/src/types.ts
+++ b/packages/lint/src/types.ts
@@ -40,7 +40,7 @@ export type HyperframeLintResult = {
export type HyperframeLinterOptions = {
filePath?: string;
isSubComposition?: boolean;
- externalStyles?: Array<{ href: string; content: string }>;
+ externalStyles?: Array<{ href: string; content: string; file?: string }>;
/**
* Set to `true` when linting compositions destined for distributed / Lambda
* rendering, where system-font capture (`allowSystemFontCapture`) is
diff --git a/packages/lint/src/utils.ts b/packages/lint/src/utils.ts
index 97fd85581c..cf4712a7e2 100644
--- a/packages/lint/src/utils.ts
+++ b/packages/lint/src/utils.ts
@@ -2,6 +2,7 @@
// Nothing in this file should emit findings — it only parses and extracts.
import { Parser } from "htmlparser2";
+import { parse } from "acorn";
export type OpenTag = {
raw: string;
@@ -13,6 +14,8 @@ export type OpenTag = {
};
export type ExtractedBlock = {
+ contentStart?: number;
+ file?: string;
attrs: string;
content: string;
raw: string;
@@ -121,6 +124,7 @@ export function parseHtmlStructure(source: string): {
blocks[name].push({
attrs: block.attrs,
content: source.slice(block.contentStart, parser.startIndex),
+ contentStart: block.contentStart,
raw: source.slice(block.index, parser.endIndex + 1),
index: block.index,
});
@@ -353,15 +357,26 @@ function readTimelineRegistryTopLevelKeys(source: string): string[] {
return keys;
}
-export function getInlineScriptSyntaxError(source: string): string | null {
+export function getInlineScriptSyntaxError(
+ source: string,
+): { message: string; offset?: number } | null {
if (!source.trim()) return null;
try {
- // eslint-disable-next-line no-new-func
- new Function(source);
+ // Match the former Function-body grammar (including top-level return), without eval.
+ parse(source, {
+ ecmaVersion: "latest",
+ sourceType: "script",
+ allowReturnOutsideFunction: true,
+ });
return null;
} catch (error) {
- if (error instanceof Error) return error.message;
- return String(error);
+ return {
+ message: error instanceof Error ? error.message : String(error),
+ offset:
+ error instanceof SyntaxError && "pos" in error && typeof error.pos === "number"
+ ? error.pos
+ : undefined,
+ };
}
}
@@ -753,7 +768,10 @@ export function stripCssComments(source: string): string {
// `/<!--[\s\S]*?-->/` regex: that pattern backtracks O(n²) on inputs with many
// unterminated "<!--" (CodeQL js/polynomial-redos). An unterminated "<!--" with
// no closing "-->" is kept verbatim, matching the prior regex's no-match behavior.
-function stripHtmlCommentsOnce(source: string): string {
+function stripHtmlCommentsOnce(
+ source: string,
+ removed?: (start: number, end: number) => void,
+): string {
let out = "";
let i = 0;
for (;;) {
@@ -762,6 +780,7 @@ function stripHtmlCommentsOnce(source: string): string {
const end = source.indexOf("-->", start + 4);
if (end < 0) return out + source.slice(i);
out += source.slice(i, start);
+ removed?.(start, end + 3);
i = end + 3;
}
}
@@ -770,11 +789,16 @@ function stripHtmlCommentsOnce(source: string): string {
// comment can splice adjacent markers into a fresh, complete <!-- … --> (e.g.
// "<<!-- -->!-- … -->" → "<!-- … -->"), which would otherwise survive and let a
// commented-out <template>/tag hijack the linter's tag scan.
-export function stripHtmlComments(source: string): string {
+export function stripHtmlComments(
+ source: string,
+ pass?: (ranges: Array<[number, number]>) => void,
+): string {
let out = source;
for (let prev = ""; prev !== out; ) {
prev = out;
- out = stripHtmlCommentsOnce(out);
+ const ranges: Array<[number, number]> = [];
+ out = stripHtmlCommentsOnce(out, pass ? (start, end) => ranges.push([start, end]) : undefined);
+ if (ranges.length) pass?.(ranges);
}
return out;
}
diff --git a/packages/parsers/src/composition.ts b/packages/parsers/src/composition.ts
index d0c08d9cab..0078f15fe2 100644
--- a/packages/parsers/src/composition.ts
+++ b/packages/parsers/src/composition.ts
@@ -18,3 +18,6 @@ export {
} from "./compositionVariables.js";
export { scanVariableUsage, type VariableUsageScan } from "./variableUsage.js";
export * from "./compositionContract.js";
+
+export * from "./canvasScaffoldPatterns.js";
+export { extractMediaSrcMutations, type MediaSrcMutation } from "./mediaSrcMutation.js";