"""Deterministic structural linter for composing-html output. No LLM, no network, stdlib only. Catches the ways body content breaks *out* of the composer's fixed design system or miswires its interactive hooks — the inverse of a freehand design linter. The composer supplies a vetted token palette and type stacks; this checker flags content that bypasses them or wires `base.js` behaviours (tabs / binds / sortables) to nothing. Each rule carries a stable `id` that is anchored in SKILL.md (``) so the teaching and the enforcement stay linked. Public API: check_html(html, *, fragment=None) -> list[Finding] format_findings(findings) -> str Exit-code contract (CLI): 1 if any error-severity finding, else 0. Deliberately NOT checked in v1: colour-contrast ratios. The token pairs are pre-vetted, and contrast on author-introduced custom pairs needs colour math + rendering that a regex pass can't do without false positives. Deferred. """ from __future__ import annotations import html.parser as _hp import re from dataclasses import dataclass, field # --------------------------------------------------------------------------- # # canonical design tokens (mirror of assets/base.css :root) # # --------------------------------------------------------------------------- # BASE_TOKENS = { "ivory", "paper", "slate", "clay", "clay-d", "oat", "olive", "rust", "moss", "g100", "g150", "g200", "g300", "g500", "g700", "border", "border-soft", "radius", "radius-sm", "radius-lg", "shadow-card", "shadow-pop", "serif", "sans", "mono", "ok", "warn", "err", "info", } # colours that are fine as literals (not palette drift) _COLOR_KEYWORD_OK = {"transparent", "currentcolor", "inherit", "none", "initial", "unset"} _HEX_RE = re.compile(r"#[0-9a-fA-F]{3,8}\b") _FUNC_COLOR_RE = re.compile(r"\b(?:rgb|rgba|hsl|hsla)\s*\(", re.IGNORECASE) _VAR_RE = re.compile(r"var\(\s*--([a-z0-9-]+)", re.IGNORECASE) _FONT_FAMILY_RE = re.compile(r"font-family\s*:", re.IGNORECASE) _FONT_SIZE_RE = re.compile(r"font-size\s*:", re.IGNORECASE) # --------------------------------------------------------------------------- # # findings # # --------------------------------------------------------------------------- # @dataclass class Finding: rule: str severity: str # "error" | "warn" message: str detail: str = "" def __str__(self) -> str: tail = f" — {self.detail}" if self.detail else "" return f"[{self.severity}] {self.rule}: {self.message}{tail}" # --------------------------------------------------------------------------- # # minimal DOM (parent pointers; enough for structural rules) # # --------------------------------------------------------------------------- # _VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"} @dataclass class Node: tag: str attrs: dict parent: Node | None = None children: list = field(default_factory=list) @property def classes(self) -> set: return set((self.attrs.get("class") or "").split()) class _DOM(_hp.HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.root = Node("#root", {}) self._stack = [self.root] self.nodes: list[Node] = [] def handle_starttag(self, tag, attrs): node = Node(tag, {k: (v or "") for k, v in attrs}, parent=self._stack[-1]) self._stack[-1].children.append(node) self.nodes.append(node) if tag not in _VOID: self._stack.append(node) def handle_startendtag(self, tag, attrs): node = Node(tag, {k: (v or "") for k, v in attrs}, parent=self._stack[-1]) self._stack[-1].children.append(node) self.nodes.append(node) def handle_endtag(self, tag): for i in range(len(self._stack) - 1, 0, -1): if self._stack[i].tag == tag: del self._stack[i:] break def _parse(html: str) -> _DOM: dom = _DOM() dom.feed(html) return dom def _ancestors(node: Node): p = node.parent while p is not None: yield p p = p.parent # --------------------------------------------------------------------------- # # rules # # --------------------------------------------------------------------------- # def _is_fragment(html: str) -> bool: head = html.lstrip()[:200].lower() return not (head.startswith(" in body content", "the composer supplies page chrome; body_html must not")) elif node.tag in ("style", "script"): out.append(Finding("chrome-leak", "warn", f"top-level <{node.tag}> in body content", "prefer extra_css / extra_js spec fields")) def _defined_tokens(html: str, dom: _DOM) -> set: """Tokens legitimately available: base palette + --bind-* (created by data-bind hooks) + any custom --x declared in an author