Skip to content

Commit d27435c

Browse files
fix(lint): report original source line and column locations (#4353)
1 parent fb0d33c commit d27435c

6 files changed

Lines changed: 163 additions & 2 deletions

File tree

‎packages/cli/src/utils/lintFormat.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,3 +239,10 @@ describe("formatLintStartupMessage", () => {
239239
expect(lines.length).toBeGreaterThan(1);
240240
});
241241
});
242+
243+
it("prints source coordinates for a single-file finding", () => {
244+
const result = project([
245+
{ file: "index.html", findings: [finding("error", { line: 5, column: 3 })] },
246+
]);
247+
expect(formatLintFindings(result)[0]).toContain("index.html:5:3");
248+
});

‎packages/cli/src/utils/lintFormat.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export function formatLintFindings(
3939
: finding.severity === "warning"
4040
? c.warn("⚠")
4141
: c.dim("ℹ");
42-
const fileLabel = multiFile ? c.dim(`[${file}] `) : "";
42+
const fileLabel = findingFileLabel(file, finding, multiFile);
4343
const loc =
4444
showElementId && finding.elementId ? ` ${c.accent(`[${finding.elementId}]`)}` : "";
4545
lines.push(` ${prefix} ${fileLabel}${c.bold(finding.code)}${loc}: ${finding.message}`);
@@ -94,3 +94,13 @@ export function formatLintStartupMessage(
9494
: "run with --lint-verbose for full output";
9595
return [` Lint: ${counts} — ${hint}.`];
9696
}
97+
98+
function findingFileLabel(
99+
file: string,
100+
finding: import("@hyperframes/lint").HyperframeLintFinding,
101+
multiFile: boolean,
102+
): string {
103+
if (finding.line === undefined) return multiFile ? c.dim(`[${file}] `) : "";
104+
const column = finding.column === undefined ? "" : `:${finding.column}`;
105+
return c.dim(`[${finding.file ?? file}:${finding.line}${column}] `);
106+
}

‎packages/lint/src/hyperframeLinter.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {
55
LintRule,
66
LintTimings,
77
} from "./types";
8+
import { createSourceLocator } from "./sourceLocations";
89
import type { LintContext } from "./context";
910
import { buildLintContext } from "./context";
1011
import { parseHtmlStructure, readAttr, truncateSnippet } from "./utils";
@@ -130,7 +131,19 @@ export async function lintHyperframeHtml(
130131
): Promise<HyperframeLintResult> {
131132
const startedAt = performance.now();
132133
const ctx = buildLintContext(html, options);
133-
const { findings, timings } = await runRules(ctx, options.filePath);
134+
const { findings: rawFindings, timings } = await runRules(ctx, options.filePath);
135+
const locate = createSourceLocator(html);
136+
const findings = rawFindings.map((finding) => {
137+
// External CSS has its own source coordinates; never attribute it to the HTML document.
138+
if (
139+
finding.snippet &&
140+
options.externalStyles?.some((style) =>
141+
style.content.replace(/\s+/g, " ").includes(finding.snippet!.replace(/\.\.\.$/, "")),
142+
)
143+
)
144+
return finding;
145+
return { ...finding, ...locate(finding) };
146+
});
134147

135148
const errorCount = findings.filter((f) => f.severity === "error").length;
136149
const warningCount = findings.filter((f) => f.severity === "warning").length;
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { describe, expect, it } from "vitest";
2+
import { sourceLocationFor } from "./sourceLocations";
3+
import { lintHyperframeHtml } from "./hyperframeLinter";
4+
import type { HyperframeLintFinding } from "./types";
5+
const finding = (fields: Partial<HyperframeLintFinding>): HyperframeLintFinding => ({
6+
code: "probe",
7+
severity: "error",
8+
message: "bad",
9+
...fields,
10+
});
11+
describe("original source locations", () => {
12+
it("locates a tag after comments and a template wrapper", () => {
13+
const html = '<!--\n comment\n-->\n<template>\n <div id="bad">x</div>\n</template>';
14+
expect(sourceLocationFor(html, finding({ elementId: "bad" }))).toEqual({ line: 5, column: 3 });
15+
});
16+
it("locates normalized CSS snippets across CRLF", () => {
17+
const html = "<style>\r\n .bad {\r\n position: fixed;\r\n }\r\n</style>";
18+
expect(sourceLocationFor(html, finding({ snippet: ".bad { position: fixed; }" }))).toEqual({
19+
line: 2,
20+
column: 3,
21+
});
22+
});
23+
it("locates a script snippet", () => {
24+
expect(
25+
sourceLocationFor(
26+
'<script>\n gsap.to("#x", { x: 1 });\n</script>',
27+
finding({ snippet: 'gsap.to("#x", { x: 1 });' }),
28+
),
29+
).toEqual({ line: 2, column: 3 });
30+
});
31+
it("does not invent a location for repeated snippets or global findings", () => {
32+
expect(
33+
sourceLocationFor("<div>x</div>\n<div>x</div>", finding({ snippet: "<div>x</div>" })),
34+
).toEqual({});
35+
expect(sourceLocationFor("<html></html>", finding({}))).toEqual({});
36+
});
37+
it("does not use a commented-out id", () => {
38+
expect(
39+
sourceLocationFor('<!-- <div id="x"> -->\n<div id="x">', finding({ elementId: "x" })),
40+
).toEqual({ line: 2, column: 1 });
41+
});
42+
it("attaches locations to real lint findings", async () => {
43+
const html =
44+
'<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>';
45+
const r = await lintHyperframeHtml(html, { filePath: "index.html" });
46+
expect(r.findings.find((f) => f.code === "timeline_element_missing_timing")).toMatchObject({
47+
file: "index.html",
48+
line: 2,
49+
column: 3,
50+
});
51+
});
52+
});
53+
54+
it("does not point synthesized code snippets at commented examples", () => {
55+
expect(
56+
sourceLocationFor(
57+
"<!-- p.getTotalLength() -->\n<script>p.getTotalLength( /* measure */ );</script>",
58+
finding({ snippet: "p.getTotalLength()" }),
59+
),
60+
).toEqual({});
61+
});
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { Parser } from "htmlparser2";
2+
import type { HyperframeLintFinding } from "./types";
3+
import { parseHtmlStructure, readDecodedAttr } from "./utils";
4+
5+
type Location = Pick<HyperframeLintFinding, "line" | "column">;
6+
7+
function normalized(source: string): { text: string; offsets: number[] } {
8+
let text = "";
9+
const offsets: number[] = [];
10+
for (let i = 0; i < source.length; i++) {
11+
const char = source[i]!;
12+
if (/\s/.test(char)) {
13+
if (text.endsWith(" ")) continue;
14+
text += " ";
15+
} else text += char;
16+
offsets.push(i);
17+
}
18+
return { text, offsets };
19+
}
20+
21+
/** Resolve against original bytes, not the comment-stripped/template-unwrapped rule input.
22+
* Ambiguous snippets/IDs deliberately have no coordinates rather than pointing at the wrong copy. */
23+
export function createSourceLocator(source: string): (finding: HyperframeLintFinding) => Location {
24+
const tags = parseHtmlStructure(source).tags;
25+
const searchable = source.split("");
26+
const parser = new Parser({
27+
oncomment() {
28+
searchable.fill("\0", parser.startIndex, parser.endIndex + 1);
29+
},
30+
});
31+
parser.write(source);
32+
parser.end();
33+
const normalizedSource = normalized(searchable.join(""));
34+
const at = (offset: number): Location => {
35+
const before = source.slice(0, offset);
36+
return {
37+
line: before.split(/\r\n|\r|\n/).length,
38+
column: offset - Math.max(before.lastIndexOf("\n"), before.lastIndexOf("\r")),
39+
};
40+
};
41+
return (finding) => {
42+
if (finding.line !== undefined) return { line: finding.line, column: finding.column };
43+
if (finding.snippet) {
44+
const offset = snippetOffset(normalizedSource, finding.snippet);
45+
return offset === undefined ? {} : at(offset);
46+
}
47+
const id = finding.elementId ?? /^#([\w-]+)$/.exec(finding.selector ?? "")?.[1];
48+
if (!id) return {};
49+
const matches = tags.filter((tag) => readDecodedAttr(tag.raw, "id") === id);
50+
return matches.length === 1 ? at(matches[0]!.index) : {};
51+
};
52+
}
53+
54+
export function sourceLocationFor(source: string, finding: HyperframeLintFinding): Location {
55+
return createSourceLocator(source)(finding);
56+
}
57+
58+
function snippetOffset(source: ReturnType<typeof normalized>, snippet: string): number | undefined {
59+
const needle = snippet
60+
.replace(/\s+/g, " ")
61+
.trim()
62+
.replace(/\.\.\.$/, "");
63+
if (!needle) return undefined;
64+
const index = source.text.indexOf(needle);
65+
if (index < 0 || source.text.indexOf(needle, index + 1) >= 0) return undefined;
66+
return source.offsets[index];
67+
}

‎packages/lint/src/types.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ export type HyperframeLintFinding = {
55
severity: HyperframeLintSeverity;
66
message: string;
77
file?: string;
8+
/** One-based coordinates in the original source; absent when no unique location exists. */
9+
line?: number;
10+
column?: number;
811
selector?: string;
912
elementId?: string;
1013
fixHint?: string;

0 commit comments

Comments
 (0)