ploop/scripts/check_frontend_architecture.py
2026-08-31 20:19:05 +08:00

217 lines
7.7 KiB
Python

"""对 PLoop 浏览器端源码执行离线静态架构检查。"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
RULES = {
"FEND001": "shared code must not import pages",
"FEND002": "a route page must not import another route page internals",
"FEND003": "page components must not call fetch or import generated transport types",
"FEND004": "browser source and fixtures must not contain restricted persistence fields",
}
FORBIDDEN_BROWSER_FIELDS = (
"private_gold",
"gold_answer",
"storage_key",
"operator_staging",
"source_path",
"artifact_bytes",
)
FETCH_RE = re.compile(r"\bfetch\s*\(")
STATIC_MODULE_PARSER = Path(__file__).with_name("parse_static_module_specifiers.mjs")
FRONTEND_INSTALL = "pnpm --dir frontend install --frozen-lockfile"
class StaticModuleParserError(RuntimeError):
"""本地 AST 解析器无法生成可信的导入记录。"""
@dataclass(frozen=True)
class Violation:
path: Path
line: int
rule_id: str
message: str
def render(self) -> str:
return f"{self.rule_id} {self.path.as_posix()}:{self.line}: {self.message}"
def main() -> int:
arguments = _parser().parse_args()
try:
violations = check_trees(tuple(arguments.roots))
except StaticModuleParserError as error:
print(f"frontend architecture check failed: {error}", file=sys.stderr)
return 2
print(f"violations={len(violations)}")
for violation in violations:
print(violation.render())
return 1 if violations else 0
def check_trees(roots: tuple[Path, ...]) -> tuple[Violation, ...]:
violations: list[Violation] = []
for root in roots:
if root.is_dir():
violations.extend(_check_tree(root))
return tuple(violations)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Check PLoop frontend architecture boundaries.")
parser.add_argument("roots", type=Path, nargs="+")
return parser
def _check_tree(root: Path) -> tuple[Violation, ...]:
resolved_root = root.resolve()
paths = tuple(
sorted(
candidate
for candidate in resolved_root.rglob("*")
if candidate.is_file() and candidate.suffix in {".ts", ".tsx"}
)
)
imports = _module_specifiers(paths)
violations: list[Violation] = []
for path in paths:
relative_path = path.relative_to(resolved_root)
source = path.read_text(encoding="utf-8")
violations.extend(_check_file(resolved_root, relative_path, source, imports[path]))
return tuple(violations)
def _check_file(
root: Path, path: Path, source: str, imports: tuple[tuple[int, str], ...]
) -> tuple[Violation, ...]:
violations: list[Violation] = []
for line_number, specifier in imports:
target = _resolve_import(root, path, specifier)
violations.extend(_import_violations(path, line_number, target, specifier))
for line_number, line in enumerate(source.splitlines(), start=1):
violations.extend(_content_violations(path, line_number, line))
return tuple(sorted(violations, key=lambda violation: violation.line))
def _module_specifiers(paths: tuple[Path, ...]) -> dict[Path, tuple[tuple[int, str], ...]]:
"""对一个根目录调用一次已锁定版本的 TypeScript AST 解析器,绝不执行待解析源码。"""
imports: dict[Path, list[tuple[int, str]]] = {path: [] for path in paths}
if not paths:
return {}
try:
result = subprocess.run(
["node", str(STATIC_MODULE_PARSER)],
input=json.dumps([str(path) for path in paths]),
text=True,
capture_output=True,
check=False,
timeout=30,
)
except OSError as error:
raise StaticModuleParserError(
"Node.js is required for the TypeScript AST parser; "
f"install Node.js and run {FRONTEND_INSTALL}"
) from error
except subprocess.TimeoutExpired as error:
raise StaticModuleParserError("TypeScript AST parser timed out") from error
if result.returncode:
raise StaticModuleParserError(result.stderr.strip() or "TypeScript AST parser failed")
try:
for output_line in result.stdout.splitlines():
record = json.loads(output_line)
if not isinstance(record, dict) or not isinstance(record.get("path"), str):
raise ValueError("invalid record path")
path = Path(record["path"])
line = record.get("line")
specifier = record.get("specifier")
if (
path not in imports
or type(line) is not int
or line < 1
or not isinstance(specifier, str)
):
raise ValueError("invalid module specifier record")
imports[path].append((line, specifier))
except (ValueError, TypeError) as error:
raise StaticModuleParserError("Invalid response from the TypeScript AST parser") from error
return {path: tuple(records) for path, records in imports.items()}
def _resolve_import(root: Path, path: Path, specifier: str) -> Path | None:
if not specifier.startswith("."):
return None
target = (root / path.parent / specifier).resolve()
for candidate in (target, *(target.with_suffix(extension) for extension in (".ts", ".tsx"))):
if candidate.is_file():
return candidate.relative_to(root)
return None
def _import_violations(
path: Path, line: int, target: Path | None, specifier: str
) -> tuple[Violation, ...]:
violations: list[Violation] = []
if _is_shared(path) and _is_page(target, specifier):
violations.append(_violation(path, line, "FEND001"))
if _is_route_module(path) and _is_other_page(path, target, specifier):
violations.append(_violation(path, line, "FEND002"))
if _is_page_component(path) and _is_generated_transport(target, specifier):
violations.append(_violation(path, line, "FEND003"))
return tuple(violations)
def _content_violations(path: Path, line: int, content: str) -> tuple[Violation, ...]:
violations: list[Violation] = []
if _is_page_component(path) and FETCH_RE.search(content):
violations.append(_violation(path, line, "FEND003"))
if any(re.search(rf"\b{re.escape(field)}\b", content) for field in FORBIDDEN_BROWSER_FIELDS):
violations.append(_violation(path, line, "FEND004"))
return tuple(violations)
def _violation(path: Path, line: int, rule_id: str) -> Violation:
return Violation(path, line, rule_id, RULES[rule_id])
def _is_shared(path: Path) -> bool:
return path.parts[:1] == ("shared",)
def _is_page(path: Path | None, specifier: str) -> bool:
return (path is not None and path.parts[:1] == ("pages",)) or "/pages/" in specifier
def _is_route_module(path: Path) -> bool:
return path.parts[:1] == ("pages",) and len(path.parts) >= 4 and path.parts[2] != "_shared"
def _is_other_page(source: Path, target: Path | None, specifier: str) -> bool:
if target is not None:
if target.parts[:1] != ("pages",):
return False
if target.parts[2:3] == ("_shared",):
return target.parts[1:2] != source.parts[1:2]
return target.parts[:3] != source.parts[:3]
return "/pages/" in specifier and not specifier.endswith("/page")
def _is_page_component(path: Path) -> bool:
return path.parts[:1] == ("pages",) and "components" in path.parts
def _is_generated_transport(target: Path | None, specifier: str) -> bool:
parts = target.parts if target is not None else Path(specifier).parts
return "generated" in parts or "transport" in parts
if __name__ == "__main__":
raise SystemExit(main())