@raintree-technology/hig-doctor-core 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -1
- package/README.md +23 -1
- package/dist/analyze.d.ts +2 -0
- package/dist/baseline.d.ts +28 -0
- package/dist/benchmark.d.ts +38 -0
- package/dist/cache.d.ts +19 -0
- package/dist/config.d.ts +26 -0
- package/dist/engines/ast-tsx.d.ts +12 -0
- package/dist/engines/swift-structural.d.ts +7 -0
- package/dist/fixes.d.ts +26 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +183 -25
- package/dist/patterns.d.ts +6 -0
- package/dist/sarif.d.ts +11 -0
- package/package.json +1 -1
- package/src/analyze.ts +5 -3
- package/src/cache.test.ts +26 -0
- package/src/cache.ts +8 -2
- package/src/config.test.ts +25 -0
- package/src/config.ts +6 -1
- package/src/engines/ast-tsx.test.ts +68 -1
- package/src/engines/ast-tsx.ts +32 -4
- package/src/fixes.test.ts +66 -1
- package/src/fixes.ts +135 -6
- package/src/index.ts +1 -0
- package/src/patterns.test.ts +29 -1
- package/src/patterns.ts +20 -9
- package/src/scanner.test.ts +43 -0
- package/src/scanner.ts +29 -4
package/src/analyze.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// optional `typescript` dependency is absent.
|
|
10
10
|
//
|
|
11
11
|
// Every returned match's `engine` reflects the tier that actually produced it.
|
|
12
|
-
import { detectPatterns, type PatternMatch } from "./patterns";
|
|
12
|
+
import { buildSuppressionFilter, detectPatterns, type PatternMatch } from "./patterns";
|
|
13
13
|
import { refineSwift } from "./engines/swift-structural";
|
|
14
14
|
import { analyzeTsx, AST_TSX_RULES } from "./engines/ast-tsx";
|
|
15
15
|
|
|
@@ -25,9 +25,11 @@ export function analyzeFile(code: string, file: string): PatternMatch[] {
|
|
|
25
25
|
const ast = analyzeTsx(code, file);
|
|
26
26
|
if (ast !== null) {
|
|
27
27
|
// Drop regex findings for the rules the AST engine owns, keep the rest,
|
|
28
|
-
// and splice in the AST verdicts in source order.
|
|
28
|
+
// and splice in the AST verdicts in source order. The AST tier is built
|
|
29
|
+
// outside detectPatterns, so inline suppressions are applied here instead.
|
|
30
|
+
const isSuppressed = buildSuppressionFilter(code);
|
|
29
31
|
matches = matches.filter(m => !AST_TSX_RULES.has(m.ruleId));
|
|
30
|
-
matches.push(...ast);
|
|
32
|
+
matches.push(...ast.filter(m => !isSuppressed(m.ruleId, m.line)));
|
|
31
33
|
matches.sort((a, b) => a.line - b.line);
|
|
32
34
|
}
|
|
33
35
|
|
package/src/cache.test.ts
CHANGED
|
@@ -46,6 +46,32 @@ describe("ScanCache", () => {
|
|
|
46
46
|
}
|
|
47
47
|
});
|
|
48
48
|
|
|
49
|
+
// The available tiers change the findings for identical content, so they must
|
|
50
|
+
// be part of the cache identity — otherwise a cache written where the AST tier
|
|
51
|
+
// ran replays ast-tsx verdicts in an environment that cannot produce them.
|
|
52
|
+
test("namespace is scoped to the available analysis tiers", async () => {
|
|
53
|
+
const dir = await mkdtemp(join(tmpdir(), "hig-cache-ns-"));
|
|
54
|
+
const path = join(dir, CACHE_FILENAME);
|
|
55
|
+
try {
|
|
56
|
+
const cache = await ScanCache.load(path);
|
|
57
|
+
cache.set("a.tsx", "x", []);
|
|
58
|
+
await cache.save(path, new Set([cache.keyOf("a.tsx", "x")]));
|
|
59
|
+
|
|
60
|
+
const raw = JSON.parse(await readFile(path, "utf-8"));
|
|
61
|
+
expect(raw.namespace).toMatch(/\.ast[01]$/);
|
|
62
|
+
|
|
63
|
+
// Flipping only the tier marker must invalidate the whole cache.
|
|
64
|
+
const flipped = raw.namespace.endsWith(".ast1")
|
|
65
|
+
? raw.namespace.replace(/\.ast1$/, ".ast0")
|
|
66
|
+
: raw.namespace.replace(/\.ast0$/, ".ast1");
|
|
67
|
+
await writeFile(path, JSON.stringify({ ...raw, namespace: flipped }));
|
|
68
|
+
const reloaded = await ScanCache.load(path);
|
|
69
|
+
expect(reloaded.get("a.tsx", "x")).toBeNull();
|
|
70
|
+
} finally {
|
|
71
|
+
await rm(dir, { recursive: true });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
49
75
|
test("audit --cache produces identical findings and reports hits on re-run", async () => {
|
|
50
76
|
const dir = await mkdtemp(join(tmpdir(), "hig-cache-audit-"));
|
|
51
77
|
try {
|
package/src/cache.ts
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
9
|
import { readFile, writeFile } from "node:fs/promises";
|
|
10
10
|
import { RULE_COUNT, type PatternMatch } from "./patterns";
|
|
11
|
+
import { astTsxAvailable } from "./engines/ast-tsx";
|
|
11
12
|
|
|
12
|
-
const CACHE_VERSION =
|
|
13
|
+
const CACHE_VERSION = 3; // bump when analysis semantics change independent of rule count
|
|
13
14
|
export const CACHE_FILENAME = ".hig-cache.json";
|
|
14
15
|
|
|
15
16
|
interface CacheFile {
|
|
@@ -17,8 +18,13 @@ interface CacheFile {
|
|
|
17
18
|
entries: Record<string, PatternMatch[]>;
|
|
18
19
|
}
|
|
19
20
|
|
|
21
|
+
// The available tiers are part of the analysis identity, not just the ruleset:
|
|
22
|
+
// the same file yields different findings with and without the optional
|
|
23
|
+
// `typescript` dependency. Without this, a cache written where the AST tier ran
|
|
24
|
+
// would replay ast-tsx verdicts in an environment that cannot produce them —
|
|
25
|
+
// e.g. a committed cache shared between a dev machine and CI.
|
|
20
26
|
function namespace(): string {
|
|
21
|
-
return `v${CACHE_VERSION}.rules${RULE_COUNT}`;
|
|
27
|
+
return `v${CACHE_VERSION}.rules${RULE_COUNT}.ast${astTsxAvailable() ? 1 : 0}`;
|
|
22
28
|
}
|
|
23
29
|
|
|
24
30
|
function keyFor(path: string, content: string): string {
|
package/src/config.test.ts
CHANGED
|
@@ -53,6 +53,31 @@ describe("parseConfig", () => {
|
|
|
53
53
|
});
|
|
54
54
|
});
|
|
55
55
|
|
|
56
|
+
describe("applyConfig — path separators", () => {
|
|
57
|
+
// match.file carries the platform separator; the globs are POSIX. Without
|
|
58
|
+
// normalizing, every per-path override silently no-ops on Windows.
|
|
59
|
+
test("per-path overrides match regardless of separator", () => {
|
|
60
|
+
const config = {
|
|
61
|
+
overrides: [{ files: ["marketing/**"], rules: { "css/outline-none": "off" as const } }],
|
|
62
|
+
};
|
|
63
|
+
for (const file of ["marketing/promo.css", "marketing\\promo.css"]) {
|
|
64
|
+
const match = {
|
|
65
|
+
ruleId: "css/outline-none",
|
|
66
|
+
engine: "regex" as const,
|
|
67
|
+
category: "foundations",
|
|
68
|
+
subcategory: "accessibility",
|
|
69
|
+
type: "concern" as const,
|
|
70
|
+
pattern: "outline none",
|
|
71
|
+
line: 1,
|
|
72
|
+
lineContent: "outline: none;",
|
|
73
|
+
file,
|
|
74
|
+
severity: "serious" as const,
|
|
75
|
+
};
|
|
76
|
+
expect(applyConfig([match], config)).toEqual([]);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
56
81
|
describe("applyConfig", () => {
|
|
57
82
|
test("off drops matches; severities remap concerns only", () => {
|
|
58
83
|
const matches = [
|
package/src/config.ts
CHANGED
|
@@ -157,8 +157,13 @@ export function applyConfig(matches: PatternMatch[], config: HigDoctorConfig): P
|
|
|
157
157
|
const out: PatternMatch[] = [];
|
|
158
158
|
for (const match of matches) {
|
|
159
159
|
let setting = settingFor(match.ruleId, config.rules);
|
|
160
|
+
// Globs are POSIX-style, but match.file carries the platform separator —
|
|
161
|
+
// without this, per-path overrides silently never fire on Windows. The
|
|
162
|
+
// scanner never emits a backslash as anything but a separator, so this is
|
|
163
|
+
// unconditional rather than platform-gated (and therefore testable here).
|
|
164
|
+
const posixFile = match.file.replace(/\\/g, "/");
|
|
160
165
|
for (const override of overrides) {
|
|
161
|
-
if (override.files.some(re => re.test(
|
|
166
|
+
if (override.files.some(re => re.test(posixFile))) {
|
|
162
167
|
const s = settingFor(match.ruleId, override.rules);
|
|
163
168
|
if (s !== null) setting = s;
|
|
164
169
|
}
|
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
import { describe, test, expect } from "bun:test";
|
|
2
|
-
import { analyzeTsx, astTsxAvailable, AST_TSX_RULES } from "./ast-tsx";
|
|
2
|
+
import { analyzeTsx, astTsxAvailable, isUsableTs, AST_TSX_RULES } from "./ast-tsx";
|
|
3
3
|
import { analyzeFile } from "../analyze";
|
|
4
4
|
|
|
5
|
+
// Under Bun a missing optional `typescript` resolves to a stub object rather
|
|
6
|
+
// than throwing, so a bare null check let the engine run and crash on the first
|
|
7
|
+
// property access instead of falling back to regex.
|
|
8
|
+
describe("typescript capability probe", () => {
|
|
9
|
+
test("rejects stubs and non-modules, accepts the real compiler", () => {
|
|
10
|
+
expect(isUsableTs(null)).toBe(false);
|
|
11
|
+
expect(isUsableTs(undefined)).toBe(false);
|
|
12
|
+
expect(isUsableTs({})).toBe(false);
|
|
13
|
+
expect(isUsableTs({ default: {}, __esModule: true })).toBe(false);
|
|
14
|
+
// Present but missing the JSX predicates the engine calls.
|
|
15
|
+
expect(isUsableTs({ createSourceFile: () => {}, ScriptTarget: {}, ScriptKind: {} })).toBe(false);
|
|
16
|
+
expect(isUsableTs(require("typescript"))).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
5
20
|
// These tests assume the optional `typescript` dependency is installed (it is in
|
|
6
21
|
// this repo's toolchain). They assert the AST tier's precision over regex.
|
|
7
22
|
describe.if(astTsxAvailable())("ast-tsx engine", () => {
|
|
@@ -45,6 +60,58 @@ describe.if(astTsxAvailable())("ast-tsx engine", () => {
|
|
|
45
60
|
expect(analyzeFile("const A = () => <div tabIndex={-1} />;", "H.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(false);
|
|
46
61
|
});
|
|
47
62
|
|
|
63
|
+
// Self-closing elements have no JsxElement wrapper, so reporting the node's
|
|
64
|
+
// parent pointed at the enclosing element instead — which also silently broke
|
|
65
|
+
// line-keyed `hig-disable-next-line` suppression for these rules.
|
|
66
|
+
test("reports the element's own line, not the enclosing element's", () => {
|
|
67
|
+
const code = [
|
|
68
|
+
"export const A = () => (",
|
|
69
|
+
" <section>",
|
|
70
|
+
" <p>one</p>",
|
|
71
|
+
' <img src="/x.png" />',
|
|
72
|
+
" <span tabIndex={4} />",
|
|
73
|
+
" <div onClick={go}>hi</div>",
|
|
74
|
+
" </section>",
|
|
75
|
+
");",
|
|
76
|
+
].join("\n");
|
|
77
|
+
const out = analyzeTsx(code, "L.tsx") ?? [];
|
|
78
|
+
const lineOf = (ruleId: string) => out.find(m => m.ruleId === ruleId)?.line;
|
|
79
|
+
expect(lineOf("web/missing-alt")).toBe(4);
|
|
80
|
+
expect(lineOf("web/positive-tabindex")).toBe(5);
|
|
81
|
+
expect(lineOf("web/div-with-on-click-no-role")).toBe(6);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// The AST tier builds findings outside detectPatterns, so it has to apply
|
|
85
|
+
// inline suppressions itself or `hig-disable-*` silently does nothing here.
|
|
86
|
+
test("honours inline suppressions for AST-owned rules", () => {
|
|
87
|
+
const nextLine = [
|
|
88
|
+
"export const S = () => (",
|
|
89
|
+
" <section>",
|
|
90
|
+
" {/* hig-disable-next-line web/missing-alt -- decorative */}",
|
|
91
|
+
' <img src="/spacer.png" />',
|
|
92
|
+
" </section>",
|
|
93
|
+
");",
|
|
94
|
+
].join("\n");
|
|
95
|
+
expect(analyzeFile(nextLine, "S.tsx").filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
|
|
96
|
+
|
|
97
|
+
const fileWide = [
|
|
98
|
+
"// hig-disable-file web/missing-alt",
|
|
99
|
+
'export const T = () => <img src="/a.png" />;',
|
|
100
|
+
].join("\n");
|
|
101
|
+
expect(analyzeFile(fileWide, "T.tsx").filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
|
|
102
|
+
|
|
103
|
+
// A suppression for a different rule must not swallow the finding.
|
|
104
|
+
const otherRule = [
|
|
105
|
+
"export const U = () => (",
|
|
106
|
+
" <section>",
|
|
107
|
+
" {/* hig-disable-next-line web/positive-tabindex */}",
|
|
108
|
+
' <img src="/b.png" />',
|
|
109
|
+
" </section>",
|
|
110
|
+
");",
|
|
111
|
+
].join("\n");
|
|
112
|
+
expect(analyzeFile(otherRule, "U.tsx").some(m => m.ruleId === "web/missing-alt")).toBe(true);
|
|
113
|
+
});
|
|
114
|
+
|
|
48
115
|
test("replaces regex verdicts for AST-owned rules (no duplicate findings)", () => {
|
|
49
116
|
const out = analyzeFile('const I = () => <img src="/x.png" />;', "I.tsx");
|
|
50
117
|
const alts = out.filter(m => m.ruleId === "web/missing-alt");
|
package/src/engines/ast-tsx.ts
CHANGED
|
@@ -28,12 +28,40 @@ export const AST_TSX_RULES = new Set([
|
|
|
28
28
|
type TS = any;
|
|
29
29
|
let tsModule: TS | null | undefined;
|
|
30
30
|
|
|
31
|
+
// The members this engine actually calls. Resolution alone isn't proof the real
|
|
32
|
+
// compiler is present: under Bun a missing `typescript` resolves to a stub
|
|
33
|
+
// object instead of throwing, which passed the null check and then crashed on
|
|
34
|
+
// the first property access (`ts.ScriptTarget.Latest`) — turning the documented
|
|
35
|
+
// regex fallback into a hard failure wherever the optional dependency wasn't
|
|
36
|
+
// installed, the GitHub Action included.
|
|
37
|
+
const REQUIRED_TS_MEMBERS = [
|
|
38
|
+
"createSourceFile",
|
|
39
|
+
"ScriptTarget",
|
|
40
|
+
"ScriptKind",
|
|
41
|
+
"SyntaxKind",
|
|
42
|
+
"forEachChild",
|
|
43
|
+
"isJsxSpreadAttribute",
|
|
44
|
+
"isJsxAttribute",
|
|
45
|
+
"isJsxExpression",
|
|
46
|
+
"isStringLiteral",
|
|
47
|
+
"isNumericLiteral",
|
|
48
|
+
"isJsxOpeningElement",
|
|
49
|
+
"isJsxSelfClosingElement",
|
|
50
|
+
] as const;
|
|
51
|
+
|
|
52
|
+
/** Exported for tests: proves a resolved module is the real compiler, not a stub. */
|
|
53
|
+
export function isUsableTs(mod: TS): boolean {
|
|
54
|
+
if (mod == null || typeof mod !== "object") return false;
|
|
55
|
+
return REQUIRED_TS_MEMBERS.every(key => mod[key] != null);
|
|
56
|
+
}
|
|
57
|
+
|
|
31
58
|
function loadTs(): TS | null {
|
|
32
59
|
if (tsModule !== undefined) return tsModule;
|
|
33
60
|
try {
|
|
34
61
|
// createRequire keeps this a runtime resolution (not bundled by esbuild,
|
|
35
62
|
// which marks typescript external) so a missing optional dep is survivable.
|
|
36
|
-
|
|
63
|
+
const mod = createRequire(import.meta.url)("typescript");
|
|
64
|
+
tsModule = isUsableTs(mod) ? mod : null;
|
|
37
65
|
} catch {
|
|
38
66
|
tsModule = null;
|
|
39
67
|
}
|
|
@@ -119,7 +147,7 @@ export function analyzeTsx(code: string, file: string): PatternMatch[] | null {
|
|
|
119
147
|
|
|
120
148
|
// <img> / <Image> without alt. Spread props may carry alt → abstain.
|
|
121
149
|
if ((tag === "img" || tag === "Image") && !hasSpread && !names.has("alt")) {
|
|
122
|
-
push(findings, "web/missing-alt", ts, opening
|
|
150
|
+
push(findings, "web/missing-alt", ts, opening, source);
|
|
123
151
|
}
|
|
124
152
|
|
|
125
153
|
// Lowercase host <div>/<span> with onClick and no role/interactive semantics.
|
|
@@ -128,14 +156,14 @@ export function analyzeTsx(code: string, file: string): PatternMatch[] | null {
|
|
|
128
156
|
names.has("onKeyDown") || names.has("onKeyPress") || names.has("onKeyUp");
|
|
129
157
|
if (!interactive) {
|
|
130
158
|
const ruleId = tag === "div" ? "web/div-with-on-click-no-role" : "web/span-with-on-click-no-role";
|
|
131
|
-
push(findings, ruleId, ts, opening
|
|
159
|
+
push(findings, ruleId, ts, opening, source);
|
|
132
160
|
}
|
|
133
161
|
}
|
|
134
162
|
|
|
135
163
|
// Positive tabIndex on any element.
|
|
136
164
|
const tabIndexAttr = byName.get("tabIndex");
|
|
137
165
|
if (tabIndexAttr && positiveTabIndex(tabIndexAttr)) {
|
|
138
|
-
push(findings, "web/positive-tabindex", ts, opening
|
|
166
|
+
push(findings, "web/positive-tabindex", ts, opening, source);
|
|
139
167
|
}
|
|
140
168
|
|
|
141
169
|
void attrIsTruthy; // reserved for future aria-hidden-on-focusable AST rule
|
package/src/fixes.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, test, expect } from "bun:test";
|
|
2
|
-
import { suggestFix, applyFixes, isFixable } from "./fixes";
|
|
2
|
+
import { suggestFix, suggestFixInContent, applyFixes, isFixable } from "./fixes";
|
|
3
3
|
import type { PatternMatch } from "./patterns";
|
|
4
4
|
|
|
5
5
|
const m = (over: Partial<PatternMatch>): PatternMatch => ({
|
|
@@ -16,6 +16,52 @@ const m = (over: Partial<PatternMatch>): PatternMatch => ({
|
|
|
16
16
|
...over,
|
|
17
17
|
});
|
|
18
18
|
|
|
19
|
+
// A "safe" fix must be behavior-preserving. Rewriting a quoted value changes
|
|
20
|
+
// what the page renders, and rewriting a comment silently rewords the author's
|
|
21
|
+
// note about the very declaration being changed.
|
|
22
|
+
describe("suggestFix — leaves strings and comments alone", () => {
|
|
23
|
+
test("fixes the declaration but not an identical string value", () => {
|
|
24
|
+
const line = '.a::before { content: "text-align: left"; text-align: left; }';
|
|
25
|
+
const fix = suggestFix(m({}), line);
|
|
26
|
+
expect(fix?.after).toBe('.a::before { content: "text-align: left"; text-align: start; }');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("fixes the declaration but not a trailing comment", () => {
|
|
30
|
+
const line = ".b { text-align: left; } /* keep text-align: left for legacy */";
|
|
31
|
+
const fix = suggestFix(m({}), line);
|
|
32
|
+
expect(fix?.after).toBe(".b { text-align: start; } /* keep text-align: left for legacy */");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("handles single quotes and an interior comment", () => {
|
|
36
|
+
expect(suggestFix(m({}), ".g::after { content: 'text-align: right'; }")).toBeNull();
|
|
37
|
+
const line = ".f { text-align: left; /* was right */ text-align: right; }";
|
|
38
|
+
expect(suggestFix(m({}), line)?.after).toBe(
|
|
39
|
+
".f { text-align: start; /* was right */ text-align: end; }",
|
|
40
|
+
);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("preserves a CRLF line ending", () => {
|
|
44
|
+
expect(suggestFix(m({}), ".c { text-align: left; }\r")?.after).toBe(".c { text-align: start; }\r");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("uses file context to preserve a multi-line comment before a declaration", () => {
|
|
48
|
+
const content = `.d { /* Keep this note:
|
|
49
|
+
text-align: left is required for the legacy view. */ text-align: left;
|
|
50
|
+
}`;
|
|
51
|
+
const fix = suggestFixInContent(m({ line: 2 }), content);
|
|
52
|
+
expect(fix?.after).toBe(
|
|
53
|
+
" text-align: left is required for the legacy view. */ text-align: start;",
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("uses file context to preserve an escaped multi-line string", () => {
|
|
58
|
+
const content = `.f::before { content: "Keep \\
|
|
59
|
+
text-align: left"; text-align: left; }`;
|
|
60
|
+
const fix = suggestFixInContent(m({ line: 2 }), content);
|
|
61
|
+
expect(fix?.after).toBe('text-align: left"; text-align: start; }');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
19
65
|
describe("suggestFix", () => {
|
|
20
66
|
test("safe: physical → logical text-align", () => {
|
|
21
67
|
const fix = suggestFix(m({}), " text-align: left;");
|
|
@@ -84,4 +130,23 @@ describe("applyFixes", () => {
|
|
|
84
130
|
expect(out.applied.length).toBe(1);
|
|
85
131
|
expect(out.content).toBe("text-align: start;");
|
|
86
132
|
});
|
|
133
|
+
|
|
134
|
+
test("does not rewrite text inside a multi-line comment on a matched line", () => {
|
|
135
|
+
const content = `.e { /* Keep this note:
|
|
136
|
+
text-align: right is intentional. */ text-align: right;
|
|
137
|
+
}`;
|
|
138
|
+
const out = applyFixes(content, [m({ line: 2 })]);
|
|
139
|
+
expect(out.content).toBe(`.e { /* Keep this note:
|
|
140
|
+
text-align: right is intentional. */ text-align: end;
|
|
141
|
+
}`);
|
|
142
|
+
expect(out.applied).toHaveLength(1);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("does not rewrite text inside an escaped multi-line string on a matched line", () => {
|
|
146
|
+
const content = `.g::before { content: "Keep \\
|
|
147
|
+
text-align: right"; text-align: right; }`;
|
|
148
|
+
const out = applyFixes(content, [m({ line: 2 })]);
|
|
149
|
+
expect(out.content).toBe(`.g::before { content: "Keep \\
|
|
150
|
+
text-align: right"; text-align: end; }`);
|
|
151
|
+
});
|
|
87
152
|
});
|
package/src/fixes.ts
CHANGED
|
@@ -20,7 +20,12 @@ export interface SuggestedFix {
|
|
|
20
20
|
interface Fixer {
|
|
21
21
|
safe: boolean;
|
|
22
22
|
description: string;
|
|
23
|
-
apply: (line: string) => string | null;
|
|
23
|
+
apply: (line: string, context?: FixContext) => string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface FixContext {
|
|
27
|
+
startsInBlockComment: boolean;
|
|
28
|
+
startsInQuote: string | null;
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
// Remove a comma-separated token (and a dangling separator) from a viewport
|
|
@@ -36,14 +41,115 @@ function stripViewportToken(line: string, token: RegExp): string | null {
|
|
|
36
41
|
return out === line ? null : out;
|
|
37
42
|
}
|
|
38
43
|
|
|
44
|
+
// Rewrite only the parts of a stylesheet line that are actual declarations,
|
|
45
|
+
// leaving quoted values and comments untouched. A blanket line-level replace
|
|
46
|
+
// would edit `content: "text-align: left"` — changing what the page renders,
|
|
47
|
+
// which a "safe" fix must never do — and would silently reword an author's
|
|
48
|
+
// comment about the very property being changed.
|
|
49
|
+
function replaceInCssCode(
|
|
50
|
+
line: string,
|
|
51
|
+
transform: (segment: string) => string,
|
|
52
|
+
startsInBlockComment = false,
|
|
53
|
+
startsInQuote: string | null = null,
|
|
54
|
+
): string {
|
|
55
|
+
let out = "";
|
|
56
|
+
let segment = "";
|
|
57
|
+
let i = 0;
|
|
58
|
+
let quote = startsInQuote;
|
|
59
|
+
let inBlockComment = startsInBlockComment;
|
|
60
|
+
while (i < line.length) {
|
|
61
|
+
if (inBlockComment) {
|
|
62
|
+
const end = line.indexOf("*/", i);
|
|
63
|
+
if (end === -1) return out + line.slice(i);
|
|
64
|
+
out += line.slice(i, end + 2);
|
|
65
|
+
i = end + 2;
|
|
66
|
+
inBlockComment = false;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const ch = line[i];
|
|
70
|
+
if (quote) {
|
|
71
|
+
out += ch;
|
|
72
|
+
if (ch === "\\" && i + 1 < line.length) { out += line[i + 1]; i += 2; continue; }
|
|
73
|
+
if (ch === quote) quote = null;
|
|
74
|
+
i++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (ch === '"' || ch === "'") {
|
|
78
|
+
out += transform(segment); segment = "";
|
|
79
|
+
quote = ch; out += ch; i++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (ch === "/" && line[i + 1] === "*") {
|
|
83
|
+
out += transform(segment); segment = "";
|
|
84
|
+
const end = line.indexOf("*/", i + 2);
|
|
85
|
+
if (end === -1) { out += line.slice(i); return out; }
|
|
86
|
+
out += line.slice(i, end + 2);
|
|
87
|
+
i = end + 2;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
segment += ch;
|
|
91
|
+
i++;
|
|
92
|
+
}
|
|
93
|
+
return out + transform(segment);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function lineStartContexts(content: string): FixContext[] {
|
|
97
|
+
const lines = content.split("\n");
|
|
98
|
+
const contexts: FixContext[] = [];
|
|
99
|
+
let inBlockComment = false;
|
|
100
|
+
let quote: string | null = null;
|
|
101
|
+
|
|
102
|
+
for (const line of lines) {
|
|
103
|
+
contexts.push({ startsInBlockComment: inBlockComment, startsInQuote: quote });
|
|
104
|
+
for (let i = 0; i < line.length; i++) {
|
|
105
|
+
const ch = line[i];
|
|
106
|
+
if (inBlockComment) {
|
|
107
|
+
if (ch === "*" && line[i + 1] === "/") {
|
|
108
|
+
inBlockComment = false;
|
|
109
|
+
i++;
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (quote) {
|
|
114
|
+
if (ch === "\\") {
|
|
115
|
+
i++;
|
|
116
|
+
} else if (ch === quote) {
|
|
117
|
+
quote = null;
|
|
118
|
+
}
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (ch === '"' || ch === "'") {
|
|
122
|
+
quote = ch;
|
|
123
|
+
} else if (ch === "/" && line[i + 1] === "*") {
|
|
124
|
+
inBlockComment = true;
|
|
125
|
+
i++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (quote) {
|
|
129
|
+
let trailingBackslashes = 0;
|
|
130
|
+
for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i--) {
|
|
131
|
+
trailingBackslashes++;
|
|
132
|
+
}
|
|
133
|
+
// An escaped newline continues a CSS string. An unescaped newline ends
|
|
134
|
+
// malformed string input so it cannot hide comments in every later line.
|
|
135
|
+
if (trailingBackslashes % 2 === 0) quote = null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return contexts;
|
|
139
|
+
}
|
|
140
|
+
|
|
39
141
|
const FIXERS: Record<string, Fixer> = {
|
|
40
142
|
"css/physical-text-align": {
|
|
41
143
|
safe: true,
|
|
42
144
|
description: "Use logical text-align (start/end) so text follows writing direction.",
|
|
43
|
-
apply: (line) => {
|
|
44
|
-
const fixed = line
|
|
45
|
-
|
|
46
|
-
|
|
145
|
+
apply: (line, context) => {
|
|
146
|
+
const fixed = replaceInCssCode(line, seg =>
|
|
147
|
+
seg
|
|
148
|
+
.replace(/text-align:\s*left\b/g, "text-align: start")
|
|
149
|
+
.replace(/text-align:\s*right\b/g, "text-align: end"),
|
|
150
|
+
context?.startsInBlockComment,
|
|
151
|
+
context?.startsInQuote,
|
|
152
|
+
);
|
|
47
153
|
return fixed === line ? null : fixed;
|
|
48
154
|
},
|
|
49
155
|
},
|
|
@@ -93,6 +199,28 @@ export function suggestFix(match: Pick<PatternMatch, "ruleId" | "line">, rawLine
|
|
|
93
199
|
return { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
|
|
94
200
|
}
|
|
95
201
|
|
|
202
|
+
/** Compute a suggested fix with the surrounding file context needed for safe CSS edits. */
|
|
203
|
+
export function suggestFixInContent(
|
|
204
|
+
match: Pick<PatternMatch, "ruleId" | "line">,
|
|
205
|
+
content: string,
|
|
206
|
+
): SuggestedFix | null {
|
|
207
|
+
const idx = match.line - 1;
|
|
208
|
+
const rawLine = content.split("\n")[idx];
|
|
209
|
+
if (rawLine === undefined) return null;
|
|
210
|
+
const fixer = FIXERS[match.ruleId];
|
|
211
|
+
if (!fixer) return null;
|
|
212
|
+
const after = fixer.apply(rawLine, lineStartContexts(content)[idx]);
|
|
213
|
+
if (after === null || after === rawLine) return null;
|
|
214
|
+
return {
|
|
215
|
+
ruleId: match.ruleId,
|
|
216
|
+
line: match.line,
|
|
217
|
+
before: rawLine,
|
|
218
|
+
after,
|
|
219
|
+
safe: fixer.safe,
|
|
220
|
+
description: fixer.description,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
96
224
|
export interface FixApplication {
|
|
97
225
|
content: string;
|
|
98
226
|
applied: SuggestedFix[];
|
|
@@ -107,6 +235,7 @@ export interface FixApplication {
|
|
|
107
235
|
*/
|
|
108
236
|
export function applyFixes(content: string, matches: PatternMatch[]): FixApplication {
|
|
109
237
|
const lines = content.split("\n");
|
|
238
|
+
const contexts = lineStartContexts(content);
|
|
110
239
|
const applied: SuggestedFix[] = [];
|
|
111
240
|
const suggestions: SuggestedFix[] = [];
|
|
112
241
|
const seen = new Set<string>();
|
|
@@ -121,7 +250,7 @@ export function applyFixes(content: string, matches: PatternMatch[]): FixApplica
|
|
|
121
250
|
seen.add(key);
|
|
122
251
|
|
|
123
252
|
const rawLine = lines[idx];
|
|
124
|
-
const after = fixer.apply(rawLine);
|
|
253
|
+
const after = fixer.apply(rawLine, contexts[idx]);
|
|
125
254
|
if (after === null || after === rawLine) continue;
|
|
126
255
|
const fix: SuggestedFix = { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
|
|
127
256
|
if (fixer.safe) {
|
package/src/index.ts
CHANGED
package/src/patterns.test.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { join } from "node:path";
|
|
|
10
10
|
// - AGENTS.md (root)
|
|
11
11
|
// - .claude-plugin/marketplace.json (plugin description)
|
|
12
12
|
// - website/components/AuditDemo.tsx (the "same N rules" copy)
|
|
13
|
-
// -
|
|
13
|
+
// - docs/remotion-showcase.md
|
|
14
14
|
// - demos/remotion-hig-doctor/src/data/report-data.json ("totalRules")
|
|
15
15
|
const EXPECTED_RULE_COUNT = 431;
|
|
16
16
|
test(`rule count is exactly ${EXPECTED_RULE_COUNT}`, () => {
|
|
@@ -668,6 +668,34 @@ describe("no false positives — negative-attribute rules", () => {
|
|
|
668
668
|
const matches = detectPatterns(`<svg viewBox="0 0 24 24"></svg>`, "Icon.tsx");
|
|
669
669
|
expect(matches.some(m => m.pattern === "svg without a11y" && m.type === "concern")).toBe(true);
|
|
670
670
|
});
|
|
671
|
+
test("does NOT flag onMouseOver when onFocus appears earlier in a multi-line tag", () => {
|
|
672
|
+
const code = `<button
|
|
673
|
+
onFocus={preview}
|
|
674
|
+
onMouseOver={preview}
|
|
675
|
+
aria-label="Preview"
|
|
676
|
+
>`;
|
|
677
|
+
expect(detectPatterns(code, "Hero.tsx").some(m => m.pattern === "onMouseOver without onFocus")).toBe(false);
|
|
678
|
+
});
|
|
679
|
+
test("does NOT flag onMouseOver when onFocus appears later in the tag", () => {
|
|
680
|
+
const code = `<button onMouseOver={preview} onFocus={preview}>Preview</button>`;
|
|
681
|
+
expect(detectPatterns(code, "Hero.tsx").some(m => m.pattern === "onMouseOver without onFocus")).toBe(false);
|
|
682
|
+
});
|
|
683
|
+
test("flags onMouseOver when the same tag has no onFocus", () => {
|
|
684
|
+
const code = `<button
|
|
685
|
+
onMouseOver={preview}
|
|
686
|
+
aria-label="Preview"
|
|
687
|
+
>`;
|
|
688
|
+
const matches = detectPatterns(code, "Hero.tsx").filter(m => m.pattern === "onMouseOver without onFocus");
|
|
689
|
+
expect(matches).toHaveLength(1);
|
|
690
|
+
expect(matches[0]?.line).toBe(1);
|
|
691
|
+
});
|
|
692
|
+
test("does NOT flag onMouseOut when onBlur appears in the same multi-line tag", () => {
|
|
693
|
+
const code = `<button
|
|
694
|
+
onMouseOut={hidePreview}
|
|
695
|
+
onBlur={hidePreview}
|
|
696
|
+
>`;
|
|
697
|
+
expect(detectPatterns(code, "Hero.tsx").some(m => m.pattern === "onMouseOut without onBlur")).toBe(false);
|
|
698
|
+
});
|
|
671
699
|
});
|
|
672
700
|
|
|
673
701
|
// ════════════════════════════════════════════════════════════════
|
package/src/patterns.ts
CHANGED
|
@@ -248,8 +248,8 @@ const webCodeRules: PatternRule[] = [
|
|
|
248
248
|
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "ambiguous link text", regex: />\s*(click here|read more|learn more|here|more)\s*</i, fileFilter: WEB_ALL },
|
|
249
249
|
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "positive tabindex", regex: /tabIndex=\{[1-9]|tabindex="[1-9]/, fileFilter: WEB_ALL },
|
|
250
250
|
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "aria-hidden on focusable", regex: /aria-hidden=["']true["'][^>]*(?:<button|<a\s|<input|tabIndex)/, fileFilter: WEB_ALL },
|
|
251
|
-
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOver without onFocus", regex:
|
|
252
|
-
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOut without onBlur", regex:
|
|
251
|
+
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOver without onFocus", regex: /<[A-Za-z][\w.:-]*\b(?:(?!\bonFocus\s*=)[^>])*\bonMouseOver\s*=(?:(?!\bonFocus\s*=)[^>])*>/, fileFilter: TSX_JSX, scope: "document" },
|
|
252
|
+
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOut without onBlur", regex: /<[A-Za-z][\w.:-]*\b(?:(?!\bonBlur\s*=)[^>])*\bonMouseOut\s*=(?:(?!\bonBlur\s*=)[^>])*>/, fileFilter: TSX_JSX, scope: "document" },
|
|
253
253
|
{ category: "foundations", subcategory: "accessibility", type: "concern", pattern: "autoFocus", regex: /autoFocus\b|autofocus\b/, fileFilter: WEB_ALL },
|
|
254
254
|
|
|
255
255
|
// ── Heading & Structure ─────────────────────────────────────
|
|
@@ -1125,12 +1125,12 @@ function suppressionCovers(ids: string[] | "all", ruleId: string): boolean {
|
|
|
1125
1125
|
);
|
|
1126
1126
|
}
|
|
1127
1127
|
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1128
|
+
/**
|
|
1129
|
+
* Build the inline-suppression predicate for a file. Exported so the refinement
|
|
1130
|
+
* tiers (which produce findings outside detectPatterns) honour the same
|
|
1131
|
+
* `hig-disable-*` comments the regex tier does.
|
|
1132
|
+
*/
|
|
1133
|
+
export function buildSuppressionFilter(code: string): (ruleId: string, line: number) => boolean {
|
|
1134
1134
|
const rawLines = code.split("\n");
|
|
1135
1135
|
|
|
1136
1136
|
// Collect suppressions before any stripping. next-line targets are 1-based.
|
|
@@ -1152,11 +1152,22 @@ export function detectPatterns(code: string, file: string): PatternMatch[] {
|
|
|
1152
1152
|
);
|
|
1153
1153
|
}
|
|
1154
1154
|
}
|
|
1155
|
-
|
|
1155
|
+
return (ruleId: string, line: number): boolean => {
|
|
1156
1156
|
if (fileSuppression && suppressionCovers(fileSuppression, ruleId)) return true;
|
|
1157
1157
|
const forLine = lineSuppressions.get(line);
|
|
1158
1158
|
return forLine !== undefined && suppressionCovers(forLine, ruleId);
|
|
1159
1159
|
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// The base regex tier. Every match it produces is tagged engine "regex" even
|
|
1163
|
+
// for rules whose declared (max) engine is stronger — those findings are only
|
|
1164
|
+
// upgraded to "swift-structural"/"ast-tsx" when analyzeFile runs the refinement
|
|
1165
|
+
// tiers on top. Callers wanting the strongest available analysis use analyzeFile.
|
|
1166
|
+
export function detectPatterns(code: string, file: string): PatternMatch[] {
|
|
1167
|
+
const matches: PatternMatch[] = [];
|
|
1168
|
+
const rawLines = code.split("\n");
|
|
1169
|
+
|
|
1170
|
+
const isSuppressed = buildSuppressionFilter(code);
|
|
1160
1171
|
const isStyleFile = /\.(css|scss|sass|less)$/.test(file);
|
|
1161
1172
|
// `//` is a line comment in code and in SCSS/Sass/Less, but NOT in plain CSS,
|
|
1162
1173
|
// HTML, or XML — where it legitimately appears in protocol-relative URLs like
|