@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 CHANGED
@@ -5,6 +5,34 @@ All notable changes to `@raintree-technology/hig-doctor-core` are documented her
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.2] - 2026-09-02
9
+
10
+ ### Fixed
11
+
12
+ - Match `onMouseOver` and `onMouseOut` accessibility concerns within one JSX
13
+ element so handlers on separate elements cannot satisfy each other.
14
+ - Preserve valid `onFocus` and `onBlur` counterparts regardless of their
15
+ attribute order or line position inside the element.
16
+
17
+ ## [0.1.1] - 2026-07-26
18
+
19
+ ### Fixed
20
+
21
+ - Report the opening element's line for JSX findings and honor inline
22
+ suppressions in the AST tier.
23
+ - Fall back to regex analysis when Bun resolves a missing TypeScript compiler
24
+ to an unusable stub module.
25
+ - Include analysis-tier availability in cache identity so caches cannot replay
26
+ AST findings in environments without the AST tier.
27
+ - Scan native platform directories unless the project is Flutter or React
28
+ Native, and normalize Windows paths before applying config overrides.
29
+ - Keep safe CSS fixes out of comments and strings, including multi-line forms.
30
+
31
+ ### Added
32
+
33
+ - `suggestFixInContent`, which uses surrounding file context when producing
34
+ machine-readable edits.
35
+
8
36
  ## [0.1.0] - 2026-07-21
9
37
 
10
38
  Initial release of the extracted rule engine.
@@ -17,7 +45,7 @@ Initial release of the extracted rule engine.
17
45
  Swift structural + TypeScript-compiler JSX refinement, each finding tagged
18
46
  with its engine).
19
47
  - Rule catalog with stable IDs, severities, engines, HIG citations, and fix
20
- guidance (`ruleCatalog`, `getRuleById`); 431 rules across 15 frameworks.
48
+ guidance (`ruleCatalog`, `getRuleById`); 431 rules across 14 frameworks.
21
49
  - SARIF 2.1.0 output (`toSarif`) with suggested fixes.
22
50
  - Baseline (`createBaseline` / `applyBaseline`), config (`loadConfig` /
23
51
  `applyConfig`), fixes (`suggestFix` / `applyFixes`), and cache (`ScanCache`) APIs.
package/README.md CHANGED
@@ -4,8 +4,19 @@
4
4
 
5
5
  # @raintree-technology/hig-doctor-core
6
6
 
7
+ **Active library for tool authors embedding HIG Doctor audits.** It provides
8
+ framework detection, rule metadata, tiered analysis, and report generation.
9
+
7
10
  The rule engine behind [HIG Doctor](https://github.com/raintree-technology/hig-doctor): framework detection, the Apple HIG rule catalog, tiered analysis (regex → Swift structural → TypeScript-compiler JSX), and the audit pipeline. The [`hig-doctor`](../cli) CLI and [`hig-mcp`](../mcp) server are thin wrappers over this package; embed it directly to run audits from your own tooling.
8
11
 
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @raintree-technology/hig-doctor-core
16
+ ```
17
+
18
+ ## Run an audit
19
+
9
20
  ```ts
10
21
  import { audit, analyzeFile, ruleCatalog, toSarif } from "@raintree-technology/hig-doctor-core";
11
22
 
@@ -22,6 +33,9 @@ for (const rule of ruleCatalog()) {
22
33
  }
23
34
  ```
24
35
 
36
+ Expected result: `audit` returns categorized, engine-tagged findings without
37
+ sending source code over the network.
38
+
25
39
  ## Exports
26
40
 
27
41
  - `audit(dir, skillsDir?, options?)` — full scan → detect → categorize → report, with config, baseline, and cache support.
@@ -33,6 +47,14 @@ for (const rule of ruleCatalog()) {
33
47
 
34
48
  The `ast-tsx` tier uses the TypeScript compiler when the optional `typescript` dependency is present, and falls back to the regex tier otherwise.
35
49
 
50
+ ## Compatibility and limits
51
+
52
+ The package runs on Node 20+ and Bun. It is a static review aid, not proof of
53
+ HIG conformance, accessibility, or design quality. Apple-platform checks cite
54
+ the HIG directly; other surfaces use aligned interface-quality rules. See the
55
+ [project guide](../../README.md), [benchmark](../../docs/benchmark.md), and
56
+ [security policy](../../SECURITY.md).
57
+
36
58
  ## License
37
59
 
38
- MIT. Apple HIG reference content the engine cites is © Apple Inc. — see the repository [LICENSE](../../LICENSE).
60
+ MIT. Apple HIG reference content the engine cites is © Apple Inc. — see the repository [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,2 @@
1
+ import { type PatternMatch } from "./patterns";
2
+ export declare function analyzeFile(code: string, file: string): PatternMatch[];
@@ -0,0 +1,28 @@
1
+ import type { PatternMatch } from "./patterns";
2
+ export declare const BASELINE_FILENAME = ".hig-baseline.json";
3
+ export interface Baseline {
4
+ version: 1;
5
+ /** ISO date the baseline was written. Informational only. */
6
+ generated: string;
7
+ /** fingerprint → number of tolerated occurrences */
8
+ findings: Record<string, number>;
9
+ }
10
+ export declare function baselineKey(match: PatternMatch): string;
11
+ /** Build a baseline from current findings (concerns only). */
12
+ export declare function createBaseline(matches: PatternMatch[], generated: string): Baseline;
13
+ export interface BaselineApplication {
14
+ kept: PatternMatch[];
15
+ /** Concerns absorbed by the baseline. */
16
+ baselined: number;
17
+ /** Baseline entries (by occurrence) that no longer match anything — fixed or moved. */
18
+ stale: number;
19
+ }
20
+ /** Filter matches against a baseline. Non-concern matches always pass through. */
21
+ export declare function applyBaseline(matches: PatternMatch[], baseline: Baseline): BaselineApplication;
22
+ export declare function parseBaseline(raw: string, sourcePath: string): Baseline;
23
+ /** Load a baseline; returns null when the default file doesn't exist. */
24
+ export declare function loadBaseline(directory: string, explicitPath?: string): Promise<{
25
+ path: string;
26
+ baseline: Baseline;
27
+ } | null>;
28
+ export declare function writeBaseline(path: string, baseline: Baseline): Promise<void>;
@@ -0,0 +1,38 @@
1
+ export interface BenchmarkCase {
2
+ id: string;
3
+ framework: string;
4
+ file: string;
5
+ kind: "good" | "bad";
6
+ code: string;
7
+ /** Concern rule IDs this fixture must produce (empty for good fixtures). */
8
+ expect: string[];
9
+ }
10
+ export declare const BENCHMARK_CASES: BenchmarkCase[];
11
+ export interface RuleScore {
12
+ ruleId: string;
13
+ tp: number;
14
+ fp: number;
15
+ fn: number;
16
+ precision: number;
17
+ recall: number;
18
+ }
19
+ export interface BenchmarkReport {
20
+ perRule: RuleScore[];
21
+ overall: {
22
+ tp: number;
23
+ fp: number;
24
+ fn: number;
25
+ precision: number;
26
+ recall: number;
27
+ };
28
+ falsePositives: Array<{
29
+ case: string;
30
+ ruleId: string;
31
+ line: number;
32
+ }>;
33
+ falseNegatives: Array<{
34
+ case: string;
35
+ ruleId: string;
36
+ }>;
37
+ }
38
+ export declare function runBenchmark(cases?: BenchmarkCase[]): BenchmarkReport;
@@ -0,0 +1,19 @@
1
+ import { type PatternMatch } from "./patterns";
2
+ export declare const CACHE_FILENAME = ".hig-cache.json";
3
+ export declare class ScanCache {
4
+ private entries;
5
+ private hits;
6
+ private misses;
7
+ private constructor();
8
+ static load(path: string): Promise<ScanCache>;
9
+ /** Return cached findings for this file, or null on a miss. */
10
+ get(path: string, content: string): PatternMatch[] | null;
11
+ set(path: string, content: string, matches: PatternMatch[]): void;
12
+ get stats(): {
13
+ hits: number;
14
+ misses: number;
15
+ };
16
+ /** Persist only the keys touched this run, so deleted files don't accumulate. */
17
+ save(path: string, touched: Set<string>): Promise<void>;
18
+ keyOf(path: string, content: string): string;
19
+ }
@@ -0,0 +1,26 @@
1
+ import type { PatternMatch, Severity } from "./patterns";
2
+ export type RuleSetting = "off" | "on" | Severity;
3
+ export interface ConfigOverride {
4
+ files: string[];
5
+ rules: Record<string, RuleSetting>;
6
+ }
7
+ export interface HigDoctorConfig {
8
+ rules?: Record<string, RuleSetting>;
9
+ ignore?: string[];
10
+ overrides?: ConfigOverride[];
11
+ }
12
+ export interface LoadedConfig {
13
+ /** Absolute path of the loaded file, or null when no config exists. */
14
+ path: string | null;
15
+ config: HigDoctorConfig;
16
+ /** Non-fatal problems (e.g. unknown rule IDs) surfaced to the caller. */
17
+ warnings: string[];
18
+ }
19
+ export declare const CONFIG_FILENAME = "hig-doctor.config.json";
20
+ export declare function parseConfig(raw: string, sourcePath: string): {
21
+ config: HigDoctorConfig;
22
+ warnings: string[];
23
+ };
24
+ export declare function loadConfig(directory: string, explicitPath?: string): Promise<LoadedConfig>;
25
+ /** Apply rule settings (global + per-path overrides) to detected matches. */
26
+ export declare function applyConfig(matches: PatternMatch[], config: HigDoctorConfig): PatternMatch[];
@@ -0,0 +1,12 @@
1
+ import type { PatternMatch } from "../patterns";
2
+ export declare const AST_TSX_RULES: Set<string>;
3
+ type TS = any;
4
+ /** Exported for tests: proves a resolved module is the real compiler, not a stub. */
5
+ export declare function isUsableTs(mod: TS): boolean;
6
+ export declare function astTsxAvailable(): boolean;
7
+ /**
8
+ * Analyze a JSX/TSX file. Returns null when typescript is unavailable or the
9
+ * file isn't JSX — the caller then keeps the regex findings unchanged.
10
+ */
11
+ export declare function analyzeTsx(code: string, file: string): PatternMatch[] | null;
12
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { PatternMatch } from "../patterns";
2
+ /**
3
+ * Refine Swift matches: drop `Image without a11y` and `onTapGesture without
4
+ * traits` findings that structural analysis proves are handled, and re-tag the
5
+ * survivors engine "swift-structural". Other matches pass through untouched.
6
+ */
7
+ export declare function refineSwift(matches: PatternMatch[], code: string): PatternMatch[];
@@ -0,0 +1,26 @@
1
+ import type { PatternMatch } from "./patterns";
2
+ export interface SuggestedFix {
3
+ ruleId: string;
4
+ line: number;
5
+ before: string;
6
+ after: string;
7
+ safe: boolean;
8
+ description: string;
9
+ }
10
+ export declare function isFixable(ruleId: string): boolean;
11
+ /** Compute the suggested fix for a match given the raw (untrimmed) source line. */
12
+ export declare function suggestFix(match: Pick<PatternMatch, "ruleId" | "line">, rawLine: string): SuggestedFix | null;
13
+ /** Compute a suggested fix with the surrounding file context needed for safe CSS edits. */
14
+ export declare function suggestFixInContent(match: Pick<PatternMatch, "ruleId" | "line">, content: string): SuggestedFix | null;
15
+ export interface FixApplication {
16
+ content: string;
17
+ applied: SuggestedFix[];
18
+ /** Unsafe fixes that were surfaced but not written. */
19
+ suggestions: SuggestedFix[];
20
+ }
21
+ /**
22
+ * Apply every SAFE fix for the given matches to a file's content and collect
23
+ * the unsafe ones as suggestions. Matches must belong to this file. At most one
24
+ * fixer runs per (line, rule); multiple rules on one line apply in sequence.
25
+ */
26
+ export declare function applyFixes(content: string, matches: PatternMatch[]): FixApplication;
package/dist/index.d.ts CHANGED
@@ -10,5 +10,5 @@ export { generateAuditMarkdown, loadSkillContent, } from "./audit-generator";
10
10
  export { createBaseline, applyBaseline, loadBaseline, parseBaseline, writeBaseline, baselineKey, BASELINE_FILENAME, type Baseline, type BaselineApplication, } from "./baseline";
11
11
  export { ScanCache, CACHE_FILENAME } from "./cache";
12
12
  export { toSarif, type SarifOptions, } from "./sarif";
13
- export { suggestFix, applyFixes, isFixable, type SuggestedFix, type FixApplication, } from "./fixes";
13
+ export { suggestFix, suggestFixInContent, applyFixes, isFixable, type SuggestedFix, type FixApplication, } from "./fixes";
14
14
  export { runBenchmark, BENCHMARK_CASES, type BenchmarkCase, type BenchmarkReport, type RuleScore, } from "./benchmark";
package/dist/index.js CHANGED
@@ -20,13 +20,9 @@ var IGNORED_DIRS = /* @__PURE__ */ new Set([
20
20
  "coverage",
21
21
  "__pycache__",
22
22
  ".dart_tool",
23
- ".pub-cache",
24
- "android",
25
- "ios",
26
- "macos",
27
- "linux",
28
- "windows"
23
+ ".pub-cache"
29
24
  ]);
25
+ var PLATFORM_HOST_DIRS = /* @__PURE__ */ new Set(["android", "ios", "macos", "linux", "windows"]);
30
26
  var MAX_FILE_BYTES = 15e5;
31
27
  var MAX_DEPTH = 25;
32
28
  var GENERATED_FILE = /\.(min|bundle|chunk)\.(js|css|mjs|cjs)$/i;
@@ -134,7 +130,26 @@ async function readText(path) {
134
130
  return null;
135
131
  }
136
132
  }
137
- async function walkDir(dir, rootDir, result, isIgnored, depth = 0) {
133
+ async function hasCrossPlatformHost(directory) {
134
+ const exists = async (name) => {
135
+ try {
136
+ await stat(join(directory, name));
137
+ return true;
138
+ } catch {
139
+ return false;
140
+ }
141
+ };
142
+ if (await exists("pubspec.yaml")) return true;
143
+ if (await exists("app.json") || await exists("expo.json") || await exists("eas.json")) return true;
144
+ try {
145
+ const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf-8"));
146
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
147
+ if (deps["react-native"] || deps["expo"]) return true;
148
+ } catch {
149
+ }
150
+ return false;
151
+ }
152
+ async function walkDir(dir, rootDir, result, isIgnored, skipPlatformHosts, depth = 0) {
138
153
  if (depth > MAX_DEPTH) return;
139
154
  let entries;
140
155
  try {
@@ -148,6 +163,7 @@ async function walkDir(dir, rootDir, result, isIgnored, depth = 0) {
148
163
  if (entry.isSymbolicLink()) continue;
149
164
  if (entry.isDirectory()) {
150
165
  if (IGNORED_DIRS.has(entry.name)) continue;
166
+ if (skipPlatformHosts && PLATFORM_HOST_DIRS.has(entry.name)) continue;
151
167
  if (isIgnored(relPath)) continue;
152
168
  if (entry.name.endsWith(".xcassets")) {
153
169
  result.assetCatalogs.push(relPath);
@@ -157,7 +173,7 @@ async function walkDir(dir, rootDir, result, isIgnored, depth = 0) {
157
173
  result.xcodeProjects.push(relPath);
158
174
  continue;
159
175
  }
160
- await walkDir(fullPath, rootDir, result, isIgnored, depth + 1);
176
+ await walkDir(fullPath, rootDir, result, isIgnored, skipPlatformHosts, depth + 1);
161
177
  } else if (entry.isFile()) {
162
178
  const ext = extname(entry.name);
163
179
  if (/\.(test|spec)\.[^.]+$/.test(entry.name)) continue;
@@ -268,7 +284,7 @@ async function scanProject(directory, options = {}) {
268
284
  };
269
285
  const patterns = [...await loadIgnorePatterns(directory), ...options.exclude ?? []];
270
286
  const isIgnored = buildIgnoreMatcher(patterns);
271
- await walkDir(directory, directory, result, isIgnored);
287
+ await walkDir(directory, directory, result, isIgnored, await hasCrossPlatformHost(directory));
272
288
  result.frameworks = detectFrameworks(result);
273
289
  return result;
274
290
  }
@@ -449,8 +465,8 @@ var webCodeRules = [
449
465
  { 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 },
450
466
  { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "positive tabindex", regex: /tabIndex=\{[1-9]|tabindex="[1-9]/, fileFilter: WEB_ALL },
451
467
  { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "aria-hidden on focusable", regex: /aria-hidden=["']true["'][^>]*(?:<button|<a\s|<input|tabIndex)/, fileFilter: WEB_ALL },
452
- { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOver without onFocus", regex: /onMouseOver=(?![^>]*onFocus)/, fileFilter: TSX_JSX },
453
- { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOut without onBlur", regex: /onMouseOut=(?![^>]*onBlur)/, fileFilter: TSX_JSX },
468
+ { 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" },
469
+ { 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" },
454
470
  { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "autoFocus", regex: /autoFocus\b|autofocus\b/, fileFilter: WEB_ALL },
455
471
  // ── Heading & Structure ─────────────────────────────────────
456
472
  { category: "foundations", subcategory: "structure", type: "concern", pattern: "empty heading", regex: /<h[1-6][^>]*>\s*<\/h[1-6]>/, fileFilter: WEB_ALL, scope: "document" },
@@ -1168,8 +1184,7 @@ function suppressionCovers(ids, ruleId) {
1168
1184
  (id) => id.endsWith("*") ? ruleId.startsWith(id.slice(0, -1)) : ruleId === id
1169
1185
  );
1170
1186
  }
1171
- function detectPatterns(code, file) {
1172
- const matches = [];
1187
+ function buildSuppressionFilter(code) {
1173
1188
  const rawLines = code.split("\n");
1174
1189
  let fileSuppression = null;
1175
1190
  const lineSuppressions = /* @__PURE__ */ new Map();
@@ -1187,11 +1202,16 @@ function detectPatterns(code, file) {
1187
1202
  );
1188
1203
  }
1189
1204
  }
1190
- const isSuppressed = (ruleId, line) => {
1205
+ return (ruleId, line) => {
1191
1206
  if (fileSuppression && suppressionCovers(fileSuppression, ruleId)) return true;
1192
1207
  const forLine = lineSuppressions.get(line);
1193
1208
  return forLine !== void 0 && suppressionCovers(forLine, ruleId);
1194
1209
  };
1210
+ }
1211
+ function detectPatterns(code, file) {
1212
+ const matches = [];
1213
+ const rawLines = code.split("\n");
1214
+ const isSuppressed = buildSuppressionFilter(code);
1195
1215
  const isStyleFile = /\.(css|scss|sass|less)$/.test(file);
1196
1216
  const allowLineComments = !/\.(css|html?|xml|storyboard|xib)$/i.test(file);
1197
1217
  const commentState = { inBlock: false, inHtml: false };
@@ -1470,10 +1490,29 @@ var AST_TSX_RULES = /* @__PURE__ */ new Set([
1470
1490
  "web/positive-tabindex"
1471
1491
  ]);
1472
1492
  var tsModule;
1493
+ var REQUIRED_TS_MEMBERS = [
1494
+ "createSourceFile",
1495
+ "ScriptTarget",
1496
+ "ScriptKind",
1497
+ "SyntaxKind",
1498
+ "forEachChild",
1499
+ "isJsxSpreadAttribute",
1500
+ "isJsxAttribute",
1501
+ "isJsxExpression",
1502
+ "isStringLiteral",
1503
+ "isNumericLiteral",
1504
+ "isJsxOpeningElement",
1505
+ "isJsxSelfClosingElement"
1506
+ ];
1507
+ function isUsableTs(mod) {
1508
+ if (mod == null || typeof mod !== "object") return false;
1509
+ return REQUIRED_TS_MEMBERS.every((key) => mod[key] != null);
1510
+ }
1473
1511
  function loadTs() {
1474
1512
  if (tsModule !== void 0) return tsModule;
1475
1513
  try {
1476
- tsModule = createRequire(import.meta.url)("typescript");
1514
+ const mod = createRequire(import.meta.url)("typescript");
1515
+ tsModule = isUsableTs(mod) ? mod : null;
1477
1516
  } catch {
1478
1517
  tsModule = null;
1479
1518
  }
@@ -1539,18 +1578,18 @@ function analyzeTsx(code, file) {
1539
1578
  const tag = tagNameOf(opening);
1540
1579
  const { names, hasSpread, byName } = attrs(opening);
1541
1580
  if ((tag === "img" || tag === "Image") && !hasSpread && !names.has("alt")) {
1542
- push(findings, "web/missing-alt", ts, opening.parent ?? opening, source);
1581
+ push(findings, "web/missing-alt", ts, opening, source);
1543
1582
  }
1544
1583
  if ((tag === "div" || tag === "span") && names.has("onClick") && !hasSpread) {
1545
1584
  const interactive = names.has("role") || names.has("tabIndex") || names.has("onKeyDown") || names.has("onKeyPress") || names.has("onKeyUp");
1546
1585
  if (!interactive) {
1547
1586
  const ruleId = tag === "div" ? "web/div-with-on-click-no-role" : "web/span-with-on-click-no-role";
1548
- push(findings, ruleId, ts, opening.parent ?? opening, source);
1587
+ push(findings, ruleId, ts, opening, source);
1549
1588
  }
1550
1589
  }
1551
1590
  const tabIndexAttr = byName.get("tabIndex");
1552
1591
  if (tabIndexAttr && positiveTabIndex(tabIndexAttr)) {
1553
- push(findings, "web/positive-tabindex", ts, opening.parent ?? opening, source);
1592
+ push(findings, "web/positive-tabindex", ts, opening, source);
1554
1593
  }
1555
1594
  void attrIsTruthy;
1556
1595
  };
@@ -1586,8 +1625,9 @@ function analyzeFile(code, file) {
1586
1625
  }
1587
1626
  const ast = analyzeTsx(code, file);
1588
1627
  if (ast !== null) {
1628
+ const isSuppressed = buildSuppressionFilter(code);
1589
1629
  matches = matches.filter((m) => !AST_TSX_RULES.has(m.ruleId));
1590
- matches.push(...ast);
1630
+ matches.push(...ast.filter((m) => !isSuppressed(m.ruleId, m.line)));
1591
1631
  matches.sort((a, b) => a.line - b.line);
1592
1632
  }
1593
1633
  return matches;
@@ -2021,8 +2061,9 @@ function applyConfig(matches, config) {
2021
2061
  const out = [];
2022
2062
  for (const match of matches) {
2023
2063
  let setting = settingFor(match.ruleId, config.rules);
2064
+ const posixFile = match.file.replace(/\\/g, "/");
2024
2065
  for (const override of overrides) {
2025
- if (override.files.some((re) => re.test(match.file))) {
2066
+ if (override.files.some((re) => re.test(posixFile))) {
2026
2067
  const s = settingFor(match.ruleId, override.rules);
2027
2068
  if (s !== null) setting = s;
2028
2069
  }
@@ -2110,10 +2151,10 @@ async function writeBaseline(path, baseline) {
2110
2151
  // src/cache.ts
2111
2152
  import { createHash } from "node:crypto";
2112
2153
  import { readFile as readFile5, writeFile as writeFile2 } from "node:fs/promises";
2113
- var CACHE_VERSION = 2;
2154
+ var CACHE_VERSION = 3;
2114
2155
  var CACHE_FILENAME = ".hig-cache.json";
2115
2156
  function namespace() {
2116
- return `v${CACHE_VERSION}.rules${RULE_COUNT}`;
2157
+ return `v${CACHE_VERSION}.rules${RULE_COUNT}.ast${astTsxAvailable() ? 1 : 0}`;
2117
2158
  }
2118
2159
  function keyFor(path, content) {
2119
2160
  return createHash("sha256").update(path).update("\0").update(content).digest("hex").slice(0, 24);
@@ -2352,12 +2393,110 @@ function stripViewportToken(line, token) {
2352
2393
  out = out.replace(/,\s*,/g, ", ").replace(/,\s*(["'])/g, "$1").replace(/=\s*,/g, "=");
2353
2394
  return out === line ? null : out;
2354
2395
  }
2396
+ function replaceInCssCode(line, transform, startsInBlockComment = false, startsInQuote = null) {
2397
+ let out = "";
2398
+ let segment = "";
2399
+ let i = 0;
2400
+ let quote = startsInQuote;
2401
+ let inBlockComment = startsInBlockComment;
2402
+ while (i < line.length) {
2403
+ if (inBlockComment) {
2404
+ const end = line.indexOf("*/", i);
2405
+ if (end === -1) return out + line.slice(i);
2406
+ out += line.slice(i, end + 2);
2407
+ i = end + 2;
2408
+ inBlockComment = false;
2409
+ continue;
2410
+ }
2411
+ const ch = line[i];
2412
+ if (quote) {
2413
+ out += ch;
2414
+ if (ch === "\\" && i + 1 < line.length) {
2415
+ out += line[i + 1];
2416
+ i += 2;
2417
+ continue;
2418
+ }
2419
+ if (ch === quote) quote = null;
2420
+ i++;
2421
+ continue;
2422
+ }
2423
+ if (ch === '"' || ch === "'") {
2424
+ out += transform(segment);
2425
+ segment = "";
2426
+ quote = ch;
2427
+ out += ch;
2428
+ i++;
2429
+ continue;
2430
+ }
2431
+ if (ch === "/" && line[i + 1] === "*") {
2432
+ out += transform(segment);
2433
+ segment = "";
2434
+ const end = line.indexOf("*/", i + 2);
2435
+ if (end === -1) {
2436
+ out += line.slice(i);
2437
+ return out;
2438
+ }
2439
+ out += line.slice(i, end + 2);
2440
+ i = end + 2;
2441
+ continue;
2442
+ }
2443
+ segment += ch;
2444
+ i++;
2445
+ }
2446
+ return out + transform(segment);
2447
+ }
2448
+ function lineStartContexts(content) {
2449
+ const lines = content.split("\n");
2450
+ const contexts = [];
2451
+ let inBlockComment = false;
2452
+ let quote = null;
2453
+ for (const line of lines) {
2454
+ contexts.push({ startsInBlockComment: inBlockComment, startsInQuote: quote });
2455
+ for (let i = 0; i < line.length; i++) {
2456
+ const ch = line[i];
2457
+ if (inBlockComment) {
2458
+ if (ch === "*" && line[i + 1] === "/") {
2459
+ inBlockComment = false;
2460
+ i++;
2461
+ }
2462
+ continue;
2463
+ }
2464
+ if (quote) {
2465
+ if (ch === "\\") {
2466
+ i++;
2467
+ } else if (ch === quote) {
2468
+ quote = null;
2469
+ }
2470
+ continue;
2471
+ }
2472
+ if (ch === '"' || ch === "'") {
2473
+ quote = ch;
2474
+ } else if (ch === "/" && line[i + 1] === "*") {
2475
+ inBlockComment = true;
2476
+ i++;
2477
+ }
2478
+ }
2479
+ if (quote) {
2480
+ let trailingBackslashes = 0;
2481
+ for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i--) {
2482
+ trailingBackslashes++;
2483
+ }
2484
+ if (trailingBackslashes % 2 === 0) quote = null;
2485
+ }
2486
+ }
2487
+ return contexts;
2488
+ }
2355
2489
  var FIXERS = {
2356
2490
  "css/physical-text-align": {
2357
2491
  safe: true,
2358
2492
  description: "Use logical text-align (start/end) so text follows writing direction.",
2359
- apply: (line) => {
2360
- const fixed = line.replace(/text-align:\s*left\b/g, "text-align: start").replace(/text-align:\s*right\b/g, "text-align: end");
2493
+ apply: (line, context) => {
2494
+ const fixed = replaceInCssCode(
2495
+ line,
2496
+ (seg) => seg.replace(/text-align:\s*left\b/g, "text-align: start").replace(/text-align:\s*right\b/g, "text-align: end"),
2497
+ context?.startsInBlockComment,
2498
+ context?.startsInQuote
2499
+ );
2361
2500
  return fixed === line ? null : fixed;
2362
2501
  }
2363
2502
  },
@@ -2401,8 +2540,26 @@ function suggestFix(match, rawLine) {
2401
2540
  if (after === null || after === rawLine) return null;
2402
2541
  return { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
2403
2542
  }
2543
+ function suggestFixInContent(match, content) {
2544
+ const idx = match.line - 1;
2545
+ const rawLine = content.split("\n")[idx];
2546
+ if (rawLine === void 0) return null;
2547
+ const fixer = FIXERS[match.ruleId];
2548
+ if (!fixer) return null;
2549
+ const after = fixer.apply(rawLine, lineStartContexts(content)[idx]);
2550
+ if (after === null || after === rawLine) return null;
2551
+ return {
2552
+ ruleId: match.ruleId,
2553
+ line: match.line,
2554
+ before: rawLine,
2555
+ after,
2556
+ safe: fixer.safe,
2557
+ description: fixer.description
2558
+ };
2559
+ }
2404
2560
  function applyFixes(content, matches) {
2405
2561
  const lines = content.split("\n");
2562
+ const contexts = lineStartContexts(content);
2406
2563
  const applied = [];
2407
2564
  const suggestions = [];
2408
2565
  const seen = /* @__PURE__ */ new Set();
@@ -2415,7 +2572,7 @@ function applyFixes(content, matches) {
2415
2572
  if (seen.has(key)) continue;
2416
2573
  seen.add(key);
2417
2574
  const rawLine = lines[idx];
2418
- const after = fixer.apply(rawLine);
2575
+ const after = fixer.apply(rawLine, contexts[idx]);
2419
2576
  if (after === null || after === rawLine) continue;
2420
2577
  const fix = { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
2421
2578
  if (fixer.safe) {
@@ -2775,6 +2932,7 @@ export {
2775
2932
  scanProject,
2776
2933
  severityFor,
2777
2934
  suggestFix,
2935
+ suggestFixInContent,
2778
2936
  toSarif,
2779
2937
  writeBaseline
2780
2938
  };
@@ -48,6 +48,12 @@ export interface RuleMeta {
48
48
  }
49
49
  export declare function ruleCatalog(): RuleMeta[];
50
50
  export declare function getRuleById(id: string): RuleMeta | undefined;
51
+ /**
52
+ * Build the inline-suppression predicate for a file. Exported so the refinement
53
+ * tiers (which produce findings outside detectPatterns) honour the same
54
+ * `hig-disable-*` comments the regex tier does.
55
+ */
56
+ export declare function buildSuppressionFilter(code: string): (ruleId: string, line: number) => boolean;
51
57
  export declare function detectPatterns(code: string, file: string): PatternMatch[];
52
58
  export declare const RULE_COUNT: number;
53
59
  export {};
@@ -0,0 +1,11 @@
1
+ import type { PatternMatch } from "./patterns";
2
+ import type { SuggestedFix } from "./fixes";
3
+ export interface SarifOptions {
4
+ /** Tool version reported in the SARIF driver. */
5
+ toolVersion: string;
6
+ /** HIG snapshot date the ruleset was authored against. */
7
+ snapshotDate?: string;
8
+ /** Optional resolver returning a suggested fix for a match (safe or unsafe). */
9
+ getFix?: (match: PatternMatch) => SuggestedFix | null;
10
+ }
11
+ export declare function toSarif(matches: PatternMatch[], options: SarifOptions): object;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raintree-technology/hig-doctor-core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Rule engine powering HIG Doctor: framework detection, Apple HIG pattern rules, and the audit pipeline.",
5
5
  "type": "module",
6
6
  "license": "MIT",