@raintree-technology/hig-doctor-core 0.1.0 → 0.1.1
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 +20 -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 +181 -23
- 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.ts +18 -7
- package/src/scanner.test.ts +43 -0
- package/src/scanner.ts +29 -4
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.ts
CHANGED
|
@@ -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
|
package/src/scanner.test.ts
CHANGED
|
@@ -83,6 +83,49 @@ describe("scanProject", () => {
|
|
|
83
83
|
expect(result.codeFiles.length).toBe(1);
|
|
84
84
|
} finally { await rm(dir, { recursive: true }); }
|
|
85
85
|
});
|
|
86
|
+
|
|
87
|
+
// `ios/` is generated boilerplate in Flutter/RN but real source in a native
|
|
88
|
+
// app; skipping it unconditionally reported such projects clean.
|
|
89
|
+
test("scans ios/ sources in a native project", async () => {
|
|
90
|
+
const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
|
|
91
|
+
try {
|
|
92
|
+
await mkdir(join(dir, "ios", "MyApp"), { recursive: true });
|
|
93
|
+
await writeFile(join(dir, "ios", "MyApp", "ContentView.swift"), "import SwiftUI\nstruct ContentView: View {}");
|
|
94
|
+
const result = await scanProject(dir);
|
|
95
|
+
expect(result.swiftFiles.length).toBe(1);
|
|
96
|
+
expect(result.frameworks).toContain("swiftui");
|
|
97
|
+
} finally { await rm(dir, { recursive: true }); }
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("still skips generated platform hosts in a Flutter project", async () => {
|
|
101
|
+
const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
|
|
102
|
+
try {
|
|
103
|
+
await writeFile(join(dir, "pubspec.yaml"), "name: demo\n");
|
|
104
|
+
await mkdir(join(dir, "ios", "Runner"), { recursive: true });
|
|
105
|
+
await writeFile(join(dir, "ios", "Runner", "AppDelegate.swift"), "import UIKit");
|
|
106
|
+
await mkdir(join(dir, "android", "app"), { recursive: true });
|
|
107
|
+
await writeFile(join(dir, "android", "app", "Main.kt"), "class Main");
|
|
108
|
+
await mkdir(join(dir, "lib"), { recursive: true });
|
|
109
|
+
await writeFile(join(dir, "lib", "main.dart"), "void main() {}");
|
|
110
|
+
const result = await scanProject(dir);
|
|
111
|
+
expect(result.swiftFiles.length).toBe(0);
|
|
112
|
+
expect(result.codeFiles.map(f => f.relativePath)).toEqual([join("lib", "main.dart")]);
|
|
113
|
+
} finally { await rm(dir, { recursive: true }); }
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("still skips generated platform hosts in a React Native project", async () => {
|
|
117
|
+
const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
|
|
118
|
+
try {
|
|
119
|
+
await writeFile(join(dir, "package.json"), JSON.stringify({ dependencies: { "react-native": "0.76.0" } }));
|
|
120
|
+
await mkdir(join(dir, "ios"), { recursive: true });
|
|
121
|
+
await writeFile(join(dir, "ios", "AppDelegate.swift"), "import UIKit");
|
|
122
|
+
await mkdir(join(dir, "src"), { recursive: true });
|
|
123
|
+
await writeFile(join(dir, "src", "App.tsx"), "export const App = () => null;");
|
|
124
|
+
const result = await scanProject(dir);
|
|
125
|
+
expect(result.swiftFiles.length).toBe(0);
|
|
126
|
+
expect(result.codeFiles.some(f => f.relativePath.endsWith("App.tsx"))).toBe(true);
|
|
127
|
+
} finally { await rm(dir, { recursive: true }); }
|
|
128
|
+
});
|
|
86
129
|
});
|
|
87
130
|
|
|
88
131
|
describe("scanProject — ignore patterns", () => {
|
package/src/scanner.ts
CHANGED
|
@@ -31,9 +31,15 @@ const IGNORED_DIRS = new Set([
|
|
|
31
31
|
".build", ".git", "node_modules", "Pods", "DerivedData",
|
|
32
32
|
".swiftpm", "Carthage", "Build", ".next", ".nuxt", ".output",
|
|
33
33
|
"dist", "build", ".cache", ".turbo", "coverage", "__pycache__",
|
|
34
|
-
".dart_tool", ".pub-cache",
|
|
34
|
+
".dart_tool", ".pub-cache",
|
|
35
35
|
]);
|
|
36
36
|
|
|
37
|
+
// Flutter and React Native generate these as platform host directories full of
|
|
38
|
+
// boilerplate, so they're noise there. Everywhere else they hold real source —
|
|
39
|
+
// a native iOS app under `ios/` is the common layout — and skipping them
|
|
40
|
+
// unconditionally made the Swift tiers silently report such projects clean.
|
|
41
|
+
const PLATFORM_HOST_DIRS = new Set(["android", "ios", "macos", "linux", "windows"]);
|
|
42
|
+
|
|
37
43
|
// Skip files larger than this — generated bundles, minified assets, and data
|
|
38
44
|
// blobs cost memory and regex time without yielding real findings. The auditor
|
|
39
45
|
// runs on arbitrary paths (including via the MCP server), so this is also a DoS
|
|
@@ -139,7 +145,25 @@ async function readText(path: string): Promise<string | null> {
|
|
|
139
145
|
}
|
|
140
146
|
}
|
|
141
147
|
|
|
142
|
-
|
|
148
|
+
// Flutter/React Native roots own generated platform host directories; detected
|
|
149
|
+
// once at the scan root so the walker can skip them only for those projects.
|
|
150
|
+
async function hasCrossPlatformHost(directory: string): Promise<boolean> {
|
|
151
|
+
const exists = async (name: string) => {
|
|
152
|
+
try { await stat(join(directory, name)); return true; } catch { return false; }
|
|
153
|
+
};
|
|
154
|
+
if (await exists("pubspec.yaml")) return true;
|
|
155
|
+
if (await exists("app.json") || await exists("expo.json") || await exists("eas.json")) return true;
|
|
156
|
+
try {
|
|
157
|
+
const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf-8"));
|
|
158
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
159
|
+
if (deps["react-native"] || deps["expo"]) return true;
|
|
160
|
+
} catch {
|
|
161
|
+
// no/unreadable package.json — not a JS cross-platform root
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function walkDir(dir: string, rootDir: string, result: ScanResult, isIgnored: (relPath: string) => boolean, skipPlatformHosts: boolean, depth = 0): Promise<void> {
|
|
143
167
|
if (depth > MAX_DEPTH) return;
|
|
144
168
|
let entries;
|
|
145
169
|
try {
|
|
@@ -155,10 +179,11 @@ async function walkDir(dir: string, rootDir: string, result: ScanResult, isIgnor
|
|
|
155
179
|
if (entry.isSymbolicLink()) continue;
|
|
156
180
|
if (entry.isDirectory()) {
|
|
157
181
|
if (IGNORED_DIRS.has(entry.name)) continue;
|
|
182
|
+
if (skipPlatformHosts && PLATFORM_HOST_DIRS.has(entry.name)) continue;
|
|
158
183
|
if (isIgnored(relPath)) continue;
|
|
159
184
|
if (entry.name.endsWith(".xcassets")) { result.assetCatalogs.push(relPath); continue; }
|
|
160
185
|
if (entry.name.endsWith(".xcodeproj") || entry.name.endsWith(".xcworkspace")) { result.xcodeProjects.push(relPath); continue; }
|
|
161
|
-
await walkDir(fullPath, rootDir, result, isIgnored, depth + 1);
|
|
186
|
+
await walkDir(fullPath, rootDir, result, isIgnored, skipPlatformHosts, depth + 1);
|
|
162
187
|
} else if (entry.isFile()) {
|
|
163
188
|
const ext = extname(entry.name);
|
|
164
189
|
// Skip test/spec files — they contain example code that triggers false positives
|
|
@@ -298,7 +323,7 @@ export async function scanProject(directory: string, options: ScanOptions = {}):
|
|
|
298
323
|
};
|
|
299
324
|
const patterns = [...(await loadIgnorePatterns(directory)), ...(options.exclude ?? [])];
|
|
300
325
|
const isIgnored = buildIgnoreMatcher(patterns);
|
|
301
|
-
await walkDir(directory, directory, result, isIgnored);
|
|
326
|
+
await walkDir(directory, directory, result, isIgnored, await hasCrossPlatformHost(directory));
|
|
302
327
|
result.frameworks = detectFrameworks(result);
|
|
303
328
|
return result;
|
|
304
329
|
}
|