Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(lint): report original source line and column locations (#4353)
Miguel Ángeld27435c070ed
diff --git a/packages/cli/src/utils/lintFormat.test.ts b/packages/cli/src/utils/lintFormat.test.tsindex c66f5b0d56..cb625ba4cc 100644--- a/packages/cli/src/utils/lintFormat.test.ts+++ b/packages/cli/src/utils/lintFormat.test.ts@@ -239,3 +239,10 @@ describe("formatLintStartupMessage", () => {expect(lines.length).toBeGreaterThan(1);});});++it("prints source coordinates for a single-file finding", () => {+ const result = project([+ { file: "index.html", findings: [finding("error", { line: 5, column: 3 })] },+ ]);+ expect(formatLintFindings(result)[0]).toContain("index.html:5:3");+});diff --git a/packages/cli/src/utils/lintFormat.ts b/packages/cli/src/utils/lintFormat.tsindex 8da13a8ae8..74d7eb83d7 100644--- a/packages/cli/src/utils/lintFormat.ts+++ b/packages/cli/src/utils/lintFormat.ts@@ -39,7 +39,7 @@ export function formatLintFindings(: finding.severity === "warning"? c.warn("⚠"): c.dim("ℹ");- const fileLabel = multiFile ? c.dim(`[${file}] `) : "";+ const fileLabel = findingFileLabel(file, finding, multiFile);const loc =showElementId && finding.elementId ? ` ${c.accent(`[${finding.elementId}]`)}` : "";lines.push(` ${prefix} ${fileLabel}${c.bold(finding.code)}${loc}: ${finding.message}`);@@ -94,3 +94,13 @@ export function formatLintStartupMessage(: "run with --lint-verbose for full output";return [` Lint: ${counts} — ${hint}.`];}++function findingFileLabel(+ file: string,+ finding: import("@hyperframes/lint").HyperframeLintFinding,+ multiFile: boolean,+): string {+ if (finding.line === undefined) return multiFile ? c.dim(`[${file}] `) : "";+ const column = finding.column === undefined ? "" : `:${finding.column}`;+ return c.dim(`[${finding.file ?? file}:${finding.line}${column}] `);+}diff --git a/packages/lint/src/hyperframeLinter.ts b/packages/lint/src/hyperframeLinter.tsindex 68e9028a1d..f6293b5199 100644--- a/packages/lint/src/hyperframeLinter.ts+++ b/packages/lint/src/hyperframeLinter.ts@@ -5,6 +5,7 @@ import type {LintRule,LintTimings,} from "./types";+import { createSourceLocator } from "./sourceLocations";import type { LintContext } from "./context";import { buildLintContext } from "./context";import { parseHtmlStructure, readAttr, truncateSnippet } from "./utils";@@ -130,7 +131,19 @@ export async function lintHyperframeHtml(): Promise<HyperframeLintResult> {const startedAt = performance.now();const ctx = buildLintContext(html, options);- const { findings, timings } = await runRules(ctx, options.filePath);+ const { findings: rawFindings, timings } = await runRules(ctx, options.filePath);+ const locate = createSourceLocator(html);+ const findings = rawFindings.map((finding) => {+ // External CSS has its own source coordinates; never attribute it to the HTML document.+ if (+ finding.snippet &&+ options.externalStyles?.some((style) =>+ style.content.replace(/\s+/g, " ").includes(finding.snippet!.replace(/\.\.\.$/, "")),+ )+ )+ return finding;+ return { ...finding, ...locate(finding) };+ });const errorCount = findings.filter((f) => f.severity === "error").length;const warningCount = findings.filter((f) => f.severity === "warning").length;diff --git a/packages/lint/src/sourceLocations.test.ts b/packages/lint/src/sourceLocations.test.tsnew file mode 100644index 0000000000..179db38817--- /dev/null+++ b/packages/lint/src/sourceLocations.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";+import { sourceLocationFor } from "./sourceLocations";+import { lintHyperframeHtml } from "./hyperframeLinter";+import type { HyperframeLintFinding } from "./types";+const finding = (fields: Partial<HyperframeLintFinding>): HyperframeLintFinding => ({+ code: "probe",+ severity: "error",+ message: "bad",+ ...fields,+});+describe("original source locations", () => {+ it("locates a tag after comments and a template wrapper", () => {+ const html = '<!--\n comment\n-->\n<template>\n <div id="bad">x</div>\n</template>';+ expect(sourceLocationFor(html, finding({ elementId: "bad" }))).toEqual({ line: 5, column: 3 });+ });+ it("locates normalized CSS snippets across CRLF", () => {+ const html = "<style>\r\n .bad {\r\n position: fixed;\r\n }\r\n</style>";+ expect(sourceLocationFor(html, finding({ snippet: ".bad { position: fixed; }" }))).toEqual({+ line: 2,+ column: 3,+ });+ });+ it("locates a script snippet", () => {+ expect(+ sourceLocationFor(+ '<script>\n gsap.to("#x", { x: 1 });\n</script>',+ finding({ snippet: 'gsap.to("#x", { x: 1 });' }),+ ),+ ).toEqual({ line: 2, column: 3 });+ });+ it("does not invent a location for repeated snippets or global findings", () => {+ expect(+ sourceLocationFor("<div>x</div>\n<div>x</div>", finding({ snippet: "<div>x</div>" })),+ ).toEqual({});+ expect(sourceLocationFor("<html></html>", finding({}))).toEqual({});+ });+ it("does not use a commented-out id", () => {+ expect(+ sourceLocationFor('<!-- <div id="x"> -->\n<div id="x">', finding({ elementId: "x" })),+ ).toEqual({ line: 2, column: 1 });+ });+ it("attaches locations to real lint findings", async () => {+ const html =+ '<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="3">\n <div id="bad" class="clip" data-start="0">x</div>\n</div>';+ const r = await lintHyperframeHtml(html, { filePath: "index.html" });+ expect(r.findings.find((f) => f.code === "timeline_element_missing_timing")).toMatchObject({+ file: "index.html",+ line: 2,+ column: 3,+ });+ });+});++it("does not point synthesized code snippets at commented examples", () => {+ expect(+ sourceLocationFor(+ "<!-- p.getTotalLength() -->\n<script>p.getTotalLength( /* measure */ );</script>",+ finding({ snippet: "p.getTotalLength()" }),+ ),+ ).toEqual({});+});diff --git a/packages/lint/src/sourceLocations.ts b/packages/lint/src/sourceLocations.tsnew file mode 100644index 0000000000..914d988f8c--- /dev/null+++ b/packages/lint/src/sourceLocations.ts@@ -0,0 +1,67 @@+import { Parser } from "htmlparser2";+import type { HyperframeLintFinding } from "./types";+import { parseHtmlStructure, readDecodedAttr } from "./utils";++type Location = Pick<HyperframeLintFinding, "line" | "column">;++function normalized(source: string): { text: string; offsets: number[] } {+ let text = "";+ const offsets: number[] = [];+ for (let i = 0; i < source.length; i++) {+ const char = source[i]!;+ if (/\s/.test(char)) {+ if (text.endsWith(" ")) continue;+ text += " ";+ } else text += char;+ offsets.push(i);+ }+ return { text, offsets };+}++/** Resolve against original bytes, not the comment-stripped/template-unwrapped rule input.+ * Ambiguous snippets/IDs deliberately have no coordinates rather than pointing at the wrong copy. */+export function createSourceLocator(source: string): (finding: HyperframeLintFinding) => Location {+ const tags = parseHtmlStructure(source).tags;+ const searchable = source.split("");+ const parser = new Parser({+ oncomment() {+ searchable.fill("\0", parser.startIndex, parser.endIndex + 1);+ },+ });+ parser.write(source);+ parser.end();+ const normalizedSource = normalized(searchable.join(""));+ const at = (offset: number): Location => {+ const before = source.slice(0, offset);+ return {+ line: before.split(/\r\n|\r|\n/).length,+ column: offset - Math.max(before.lastIndexOf("\n"), before.lastIndexOf("\r")),+ };+ };+ return (finding) => {+ if (finding.line !== undefined) return { line: finding.line, column: finding.column };+ if (finding.snippet) {+ const offset = snippetOffset(normalizedSource, finding.snippet);+ return offset === undefined ? {} : at(offset);+ }+ const id = finding.elementId ?? /^#([\w-]+)$/.exec(finding.selector ?? "")?.[1];+ if (!id) return {};+ const matches = tags.filter((tag) => readDecodedAttr(tag.raw, "id") === id);+ return matches.length === 1 ? at(matches[0]!.index) : {};+ };+}++export function sourceLocationFor(source: string, finding: HyperframeLintFinding): Location {+ return createSourceLocator(source)(finding);+}++function snippetOffset(source: ReturnType<typeof normalized>, snippet: string): number | undefined {+ const needle = snippet+ .replace(/\s+/g, " ")+ .trim()+ .replace(/\.\.\.$/, "");+ if (!needle) return undefined;+ const index = source.text.indexOf(needle);+ if (index < 0 || source.text.indexOf(needle, index + 1) >= 0) return undefined;+ return source.offsets[index];+}diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.tsindex bb9d988fe9..86ffb8e964 100644--- a/packages/lint/src/types.ts+++ b/packages/lint/src/types.ts@@ -5,6 +5,9 @@ export type HyperframeLintFinding = {severity: HyperframeLintSeverity;message: string;file?: string;+ /** One-based coordinates in the original source; absent when no unique location exists. */+ line?: number;+ column?: number;selector?: string;elementId?: string;fixHint?: string;