All files / src/test sourceScan.ts

86.15% Statements 56/65
67.64% Branches 23/34
70% Functions 7/10
87.27% Lines 48/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137                        1x                   1x 1x 36x 114x 36x 36x   78x 76x 64x 63x 63x 60x 60x             1x 1x         240x                                 4x 4x 240x     33812x     240x 34448x 34448x           4x     1x                                   60x 60x 60x     60x 598x 598x 598x   598x 20x 20x 3312x 3276x 36x 36x 20x 20x       578x 578x         598x 598x 598x   60x    
import path from "node:path";
 
import { readdirSyncRetry, readFileSyncRetry } from "../../../vitest.fsRetry";
 
/** One source file, read once, for the static-analysis suites. */
export interface SourceFile {
  /** Path relative to the package root, e.g. `src/pages/Error.tsx`. */
  path: string;
  text: string;
  lines: string[];
}
 
const SKIP_DIRS = new Set(["node_modules", "dist", "coverage", "assets"]);
 
/**
 * Every `.ts`/`.tsx` file under `src`, excluding tests and test helpers.
 *
 * These suites assert things the type system and the runtime tests cannot:
 * that we are not shipping debug logging, and that we are not building
 * Tailwind class names in ways the compiler cannot see.
 */
export function readSourceFiles(root: string): SourceFile[] {
  const out: SourceFile[] = [];
  const walk = (dir: string) => {
    for (const entry of readdirSyncRetry(dir)) {
      if (entry.isDirectory()) {
        if (!SKIP_DIRS.has(entry.name)) walk(path.join(dir, entry.name));
        continue;
      }
      if (!/\.tsx?$/.test(entry.name)) continue;
      if (/\.test\.tsx?$/.test(entry.name)) continue;
      if (entry.name.endsWith(".d.ts")) continue;
      const full = path.join(dir, entry.name);
      if (full.includes(`${path.sep}test${path.sep}`)) continue;
      const text = readFileSyncRetry(full);
      out.push({
        path: path.relative(root, full).split(path.sep).join("/"),
        text,
        lines: text.split("\n"),
      });
    }
  };
  walk(path.join(root, "src"));
  return out;
}
 
/** Strip `//` and `/* *\/` comments so a scan does not fire on commented code. */
export function stripComments(text: string): string {
  return text
    .replace(/\/\*[\s\S]*?\*\//g, "")
    .replace(/(^|[^:])\/\/.*$/gm, "$1");
}
 
export interface Finding {
  file: string;
  line: number;
  text: string;
}
 
/** Report every line matching `pattern`, ignoring commented-out code. */
export function scan(
  files: SourceFile[],
  pattern: RegExp,
  isExempt: (f: SourceFile, line: string) => boolean = () => false,
): Finding[] {
  const findings: Finding[] = [];
  for (const file of files) {
    const live = new Set(
      stripComments(file.text)
        .split("\n")
        .map((l) => l.trim())
        .filter(Boolean),
    );
    file.lines.forEach((line, i) => {
      const trimmed = line.trim();
      Eif (!pattern.test(line)) return;
      if (!live.has(trimmed)) return; // commented out
      if (isExempt(file, line)) return;
      findings.push({ file: file.path, line: i + 1, text: trimmed });
    });
  }
  return findings;
}
 
export const formatFindings = (findings: Finding[], limit = 25): string =>
  findings
    .slice(0, limit)
    .map((f) => `  ${f.file}:${f.line}  ${f.text}`)
    .join("\n") +
  (findings.length > limit ? `\n  …and ${findings.length - limit} more` : "");
 
/**
 * Every `className={...}` / `class="..."` expression in a file, flattened to
 * one line each so a multi-line template literal can be matched in one go.
 *
 * Scanning whole files for `bg-${` produces false positives — SVG gradient
 * ids look identical (`id={\`fill-${widget.id}\`}`) and are perfectly fine.
 * Only what actually reaches a `class` attribute matters.
 */
export function classNameExpressions(
  file: SourceFile,
): { value: string; line: number }[] {
  const out: { value: string; line: number }[] = [];
  const text = file.text;
  const re = /className\s*=\s*/g;
  let m: RegExpExecArray | null;
 
  while ((m = re.exec(text))) {
    const start = m.index + m[0].length;
    const open = text[start];
    let end = start;
 
    if (open === "{") {
      let depth = 0;
      for (let i = start; i < text.length; i++) {
        if (text[i] === "{") depth++;
        else if (text[i] === "}") {
          depth--;
          if (depth === 0) {
            end = i + 1;
            break;
          }
        }
      }
    } else if (open === '"' || open === "'") {
      end = text.indexOf(open, start + 1) + 1;
    } else E{
      continue;
    }
 
    const value = text.slice(start, end);
    const line = text.slice(0, start).split("\n").length;
    out.push({ value: value.replace(/\s+/g, " "), line });
  }
  return out;
}