Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

v1.91.251.0 feat(design-lint): bundled free design lint (bin/gstack-design-lint + lib/design-lint/), hallmark sloplint port (#3459)

Garry Tanfa3a2400b5a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9070248f6..a65d6250e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,24 @@
# Changelog
+## [1.91.251.0] - 2026-10-26
+
+**A free, deterministic design lint ships with gstack: `bin/gstack-design-lint` checks a page's HTML, CSS and components for the tells that make it read as machine-made, in under a second, and with `--render` measures what only a browser can.** Until now gstack's only mechanical design check was the opt-in impeccable engine most users never install, plus `gstack-design-craft`'s seventeen copy and ship-floor regexes; everything else in the Slop Gate was prose the model judged itself. The lint ports the roughly fifty-five machine-checkable gates of [Nutlope/hallmark](https://github.com/Nutlope/hallmark)'s `sloplint` (MIT; see NOTICE.md) into TypeScript under `lib/design-lint/`, rewritten in gstack's voice and mapped onto gstack's severity words. This release is the tool alone (Phase 1 of the hallmark absorption plan, approved by Garry on 2026-10-26); /design-html and /design-review start calling it in Phase 2, so no skill prose changes here.
+
+### Added
+- **`bin/gstack-design-lint <file-or-dir ...> [--render] [--url] [--scope page|component] [--job <job>] [--json] [--rules]`**: reads `.html`, `.css`, `.jsx`, `.tsx`, `.vue`, `.svelte` and `.astro` (Tailwind class strings included, `cn()`/`clsx()`/`cva()` calls too), links each page to the stylesheets it reaches through `<link>` and `@import`, resolves CSS variables, converts colours to OKLCH and computes contrast, and prints one line per finding: `LINT: <blocks|ask|polish|waived> <rule-id> <file>:<line> <evidence> | fix: <fix>`, then `LINT_SUMMARY: blocks=N ask=N waived=N polish=N render=<ran|skipped: reason>`. Exit 2 on blocks, 1 on an unanswered ask, 0 otherwise. `docs/design-lint.md` is the contract and lists every rule.
+- **Three tiers in gstack's words, no fourth scale.** `blocks` (hallmark's Floor: contrast, focus rings, reduced motion, a card in a card, a purple-blue gradient, content hidden until JavaScript runs; never waivable), `ask` (hallmark's Reflex: three equal cards, Inter as the display, the centred-stack hero; waivable on the record) and `polish` (hallmark's Finish: straight quotes, a lonely last grid item; never blocks). Blocking and waived counts are never summed, so `blocks=0` is always a true sentence about the Floor. Three house rules hallmark holds at Floor stay at ask here: the eyebrow above a heading, the 80-word screen and the dash.
+- **Waivers on the record.** `<!-- gstack-lint-disable <rule-id>: <reason> -->` (or the `/* */` and `//` comment forms; `impeccable-disable <rule>: <reason>` is an alias) answers an ask or polish finding when the reason is about this page: 24 characters or more, not boilerplate, not reused on another waiver, sharing a word with the page's own text. A waiver of a blocking rule is refused and the rule still fires; more than three waivers on one page is reported as a house style that belongs in DESIGN.md.
+- **The render tier** (`--render`, or `--url` for a dev server) runs on the same engine `gstack-render` picks, Aside first and gstack's own headless browser otherwise, with nothing to install: the hero fits at 1280x800 (the headline's bottom and the first action; the lede and the visual are not measured), about 80 words per 900px window, contrast against the painted pixels, focus rings found by focusing every control, headings crowded against the section above, text painted under another element, horizontal scroll between 320 and 1920, wrapping button labels, a hero offering more than two actions, section gaps under 120px or all alike and more than nine sections, thin sections, dead bands, drawn illustrations, empty picture slots, counting marks and photographs covering more than a third of the page. Without a browser the summary says `render=skipped: <reason>` and the static tier still runs.
+- `lib/aside-render.ts`: an eval step takes an optional viewport (`width`, `height`, `deviceScaleFactor`, `mobile`), set before the eval and cleared after it the way the screenshot step already does, and a spec's `file` may be an http(s) URL, opened as it is with no loopback server. Both engines take the size; `deviceScaleFactor` and `mobile` on an eval step reach Aside only (the browse daemon's `viewport` takes a size alone). Nothing else in the file changes.
+- **The copy tier**: `gstack-design-craft`'s content-realism and ship-floor tells (placeholder names, lorem, buzzwords, round numbers, `[Needs proof]`, dead links, images without alt, the missing title, description, skip link and `aria-current`) report under the same contract and ids, so one command prints one list. `bin/gstack-design-craft` itself is unchanged until Phase 2 swaps the call.
+- Fixtures under `test/fixtures/design-lint/` (hallmark's `slopped.html`, eyebrow and Tailwind pass/fail pairs and the waiver page, MIT-attributed, plus a clean page every rule family must leave alone); `licenses/MIT-hallmark.txt`; a NOTICE.md entry.
+
+### Tests
+- `test/design-lint.test.ts`: the parsers (nested CSS, tokens, var() fallbacks, colour spaces, JSX pseudo-HTML), the rule table against `docs/design-lint.md`, the output lines and exit codes, waiver acceptance and every refusal reason, the waiver fixture. One test per rule family (`test/design-lint-<family>.test.ts`) holds a negative control and a planted positive for every rule id. `test/design-lint-render.test.ts` drives the browse daemon when it is built and skips with a named reason otherwise. `test/design-lint-recorded.test.ts` lints the repository's recorded design slop page (the review eval's ground truth) and pins which rule answers each annotated issue, the same gate set hallmark's sloplint reports on the same files.
+
+### Gate integrity
+- No threshold, budget, timeout, trial count or assertion was weakened. No template, catalog or eval changed. Gate edits in the diff: `test/fixtures/module-size-ratchet.json` registers the 27 new `lib/design-lint` modules under the existing 800-line cap, and `test/helpers/free-fixtures-data.ts` maps `test/fixtures/design-lint/**` to the design-lint test files; `lib/aside-render.ts` gains the viewport on eval steps and http(s) `file`, described above.
+
## [1.91.250.0] - 2026-10-26
**Three free-tier fixtures stop racing themselves (GSTA-107 daily flaky pass).** Two tests polled for a result file's existence while its writer created it with a plain `writeFileSync`, so a poll between create and write read an empty file; a third copied a shared template repository with `fs.cpSync` and threw once inside the directory walk.
diff --git a/NOTICE.md b/NOTICE.md
index 831e0162a..2c9acedc8 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -50,6 +50,24 @@ signature components are not carried over):
ship-floor tells, turned into a free check.
- `design-shotgun/SKILL.md.tmpl`: page archetypes as a variant axis.
+## hallmark — Copyright (c) 2026 Hallmark contributors — MIT License
+
+https://github.com/Nutlope/hallmark (`skills/hallmark/scripts/sloplint.mjs`,
+`sloplint-render.mjs`, `references/gates.md`, `scripts/fixtures/`, at 7ec8682).
+License text: `licenses/MIT-hallmark.txt`.
+
+Derived, modified (every gate rewritten in TypeScript and in gstack's voice,
+mapped onto gstack's severity words; hallmark's theme stamp, genres, posture
+guards, photo index and judged gates are not carried over):
+
+- `lib/design-lint/` and `bin/gstack-design-lint`: the static tier's parsers
+ (CSS rules and tokens, HTML and component pseudo-HTML, Tailwind class
+ strings), the colour maths, the waiver record, and the rule families under
+ `lib/design-lint/rules/`; the render tier in `lib/design-lint/render*.ts`,
+ driving gstack's own browser instead of puppeteer.
+- `test/fixtures/design-lint/{slopped.html,eyebrow-pass,eyebrow-fail,tailwind-pass,tailwind-fail,waiver}`:
+ the fixtures, with their waiver comments rewritten to the lint's form.
+
## DESIGN.md specification — Copyright Google LLC — Apache License 2.0
https://github.com/google-labs-code/design.md
diff --git a/VERSION b/VERSION
index e5e5d840f..b57ae0ba4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.91.250.0
+1.91.251.0
diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.md
index 9c7adff2e..8d783de42 100644
--- a/agents-digest/gstack-AGENTS.md
+++ b/agents-digest/gstack-AGENTS.md
@@ -1,4 +1,4 @@
-# gstack digest v1.91.250.0 — regenerate/re-copy after upgrading gstack
+# gstack digest v1.91.251.0 — regenerate/re-copy after upgrading gstack
Behavioral rules from gstack (https://github.com/garrytan/gstack), compressed
for agent hosts without a full skill install. The full skills add workflows,
diff --git a/bin/gstack-design-lint b/bin/gstack-design-lint
new file mode 100755
index 000000000..3ff9d5624
--- /dev/null
+++ b/bin/gstack-design-lint
@@ -0,0 +1,55 @@
+#!/usr/bin/env -S bun --no-env-file --config=/dev/null
+// gstack-design-lint — the free, deterministic design lint behind /design-html
+// and /design-review. Static tier over .html .css .jsx .tsx .vue .svelte .astro
+// (Tailwind class strings included); --render measures the page in gstack's own
+// browser (Aside first, the browse daemon otherwise).
+//
+// Usage: gstack-design-lint <file-or-dir ...> [--render] [--url <http://…>]
+// [--scope page|component] [--job <job>] [--json] [--rules]
+//
+// Prints one "LINT: <blocks|ask|polish|waived> <rule-id> <file>:<line> <evidence> | fix: <fix>"
+// line per finding, then "LINT_SUMMARY: blocks=N ask=N waived=N polish=N render=<ran|skipped: reason>".
+// Exit 2 on blocks, 1 on unanswered asks, 0 otherwise; 3 on a usage error.
+// docs/design-lint.md is the contract.
+
+import { formatResult, lint, type LintOptions } from '../lib/design-lint/index';
+import { ruleTable } from '../lib/design-lint/report';
+
+const USAGE = 'usage: gstack-design-lint <file-or-dir ...> [--render] [--url <http://…>] [--scope page|component] [--job <job>] [--json] [--rules]';
+
+const args = process.argv.slice(2);
+const opts: LintOptions & { json: boolean; rules: boolean } = { render: false, urls: [], scope: 'page', job: null, json: false, rules: false };
+const paths: string[] = [];
+const take = (flag: string): string => {
+ const v = args[++i];
+ if (v === undefined) { console.error(`${flag} needs a value`); console.error(USAGE); process.exit(3); }
+ return v;
+};
+let i = 0;
+for (; i < args.length; i++) {
+ const a = args[i];
+ if (a === '--render') opts.render = true;
+ else if (a === '--url') { opts.urls!.push(take(a)); opts.render = true; }
+ else if (a === '--scope') { const s = take(a); if (s !== 'page' && s !== 'component') { console.error('--scope must be page or component'); process.exit(3); } opts.scope = s; }
+ else if (a === '--job') opts.job = take(a).trim().toLowerCase();
+ else if (a === '--json') opts.json = true;
+ else if (a === '--rules') opts.rules = true;
+ else if (a === '--help' || a === '-h') { console.log(USAGE); process.exit(0); }
+ else if (a.startsWith('--')) { console.error(`unknown flag ${a}`); console.error(USAGE); process.exit(3); }
+ else paths.push(a);
+}
+if (opts.rules) {
+ for (const r of ruleTable()) console.log(`${r.tier.padEnd(6)} ${r.id.padEnd(26)} ${r.gate.padEnd(7)} ${r.title}`);
+ process.exit(0);
+}
+if (!paths.length && !opts.urls!.length) { console.error(USAGE); process.exit(3); }
+if (opts.urls!.some((u) => !/^https?:\/\//.test(u))) { console.error('--url takes an http or https address'); process.exit(3); }
+
+const result = await lint(paths, opts).catch((e: Error) => { console.error(`gstack-design-lint: ${e.message}`); process.exit(3); });
+if (!result.files.length && !opts.urls!.length) {
+ console.error('gstack-design-lint: no .html, .css, .jsx, .tsx, .vue, .svelte or .astro files found');
+ process.exit(3);
+}
+if (opts.json) console.log(JSON.stringify({ summary: result.summary, files: result.files.length, findings: result.findings }, null, 2));
+else console.log(formatResult(result));
+process.exit(result.exitCode);
diff --git a/docs/PROJECT_STRUCTURE.md b/docs/PROJECT_STRUCTURE.md
index e84f7cd36..90298fe34 100644
--- a/docs/PROJECT_STRUCTURE.md
+++ b/docs/PROJECT_STRUCTURE.md
@@ -70,7 +70,7 @@ gstack/
├── freeze/ # /freeze skill; bin/check-freeze.sh (PreToolUse edit-boundary hook; sources careful/bin/hook-extract.sh, fails closed)
├── guard/, unfreeze/ # /guard (careful + freeze in one), /unfreeze
├── gstack-upgrade/ # /gstack-upgrade skill + migrations/ (run after ./setup during an upgrade)
-├── bin/ # CLI utilities (gstack-render.ts = render a local HTML file through Aside or the engine, gstack-design-detect.ts = probe/scan through a user-installed impeccable engine; gstack-design-md.ts = open DESIGN.md check/convert/tokens/mark; gstack-repo-mode, gstack-slug, gstack-config, gstack-wtree, gstack-evidence, gstack-issue-guard, gstack-relink, gstack-memorable, etc.)
+├── bin/ # CLI utilities (gstack-render.ts = render a local HTML file through Aside or the engine, gstack-design-detect.ts = probe/scan through a user-installed impeccable engine; gstack-design-md.ts = open DESIGN.md check/convert/tokens/mark; gstack-design-lint = the free deterministic design lint over HTML/CSS/components, --render measures in the browser (docs/design-lint.md); gstack-repo-mode, gstack-slug, gstack-config, gstack-wtree, gstack-evidence, gstack-issue-guard, gstack-relink, gstack-memorable, etc.)
├── document-release/ # /document-release skill (every-ship pre-verification audit; standalone doc updates + Diataxis coverage map)
├── document-generate/ # /document-generate skill (Diataxis doc generator: tutorial/how-to/reference/explanation)
├── cso/ # /cso skill (OWASP Top 10 + STRIDE security audit)
@@ -88,7 +88,7 @@ gstack/
│ └── dist/ # Compiled binary
├── agents-digest/ # Committed 2KB instruction-tier rules digest (gstack-AGENTS.md) for rules-reading hosts
├── extension/ # Chrome extension (side panel + activity feed + CSS inspector)
-├── lib/ # Shared libraries (aside-render.ts = local-HTML rendering, Aside first, engine fallback; design-catalog.ts = the typed design anti-pattern catalog every design skill renders from; design-detect-contract.ts = detector sentinel vocabulary; design-md.ts = open DESIGN.md reader/writer; dom-dump-script.ts + generated dom-dump.js = rendered-DOM dump for the detector; review-evidence.ts = review-start receipt binding, computed freshness and shared-code snapshot eligibility; frontend-scope.ts; claude-bin.ts, error-handling.ts, worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts, tracker-guard.ts, version-source.ts, code-intelligence/)
+├── lib/ # Shared libraries (aside-render.ts = local-HTML rendering, Aside first, engine fallback; design-catalog.ts = the typed design anti-pattern catalog every design skill renders from; design-lint/ = the static and render tiers behind bin/gstack-design-lint, ported from hallmark's sloplint; design-detect-contract.ts = detector sentinel vocabulary; design-md.ts = open DESIGN.md reader/writer; dom-dump-script.ts + generated dom-dump.js = rendered-DOM dump for the detector; review-evidence.ts = review-start receipt binding, computed freshness and shared-code snapshot eligibility; frontend-scope.ts; claude-bin.ts, error-handling.ts, worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts, tracker-guard.ts, version-source.ts, code-intelligence/)
│ └── diagram-render/ # Vendored mermaid + excalidraw runtimes, built into one offline bundle the renderer loads
├── patches/ # bun `patchedDependencies` patches (playwright-core windowsHide)
├── docs/designs/ # Design documents (incl. IMPECCABLE_INTEROP.md = the design detector / catalog / open DESIGN.md record, and fork-port-residual-2026-09/ evaluation evidence)
@@ -102,7 +102,7 @@ gstack/
├── SKILL.md # Generated from SKILL.md.tmpl (don't edit directly)
├── SKILL.md.tmpl # Template: edit this, run gen:skill-docs
├── ETHOS.md # Builder philosophy (Boil the Ocean, Search Before Building)
-├── NOTICE.md # Third-party notices: material derived from impeccable and the DESIGN.md spec (both Apache-2.0)
-├── licenses/ # Verbatim license texts for the notices above (Apache-2.0.txt)
+├── NOTICE.md # Third-party notices: material derived from impeccable and the DESIGN.md spec (Apache-2.0), Elaya's design skills and hallmark's sloplint (MIT)
+├── licenses/ # Verbatim license texts for the notices above (Apache-2.0.txt, MIT-elaya.txt, MIT-hallmark.txt)
└── package.json # Build scripts for browse
```
diff --git a/docs/design-lint.md b/docs/design-lint.md
new file mode 100644
index 000000000..12a30b758
--- /dev/null
+++ b/docs/design-lint.md
@@ -0,0 +1,391 @@
+# design-lint: the free, deterministic design check
+
+`bin/gstack-design-lint` reads a page (or a directory of pages, stylesheets
+and components) and prints every machine-checkable design tell it finds, with
+a file and line, in under a second. With `--render` it also measures the page
+in gstack's own browser: the fold, the word budget per screen, contrast
+against the painted pixels, focus rings by tabbing, crowded headings, text
+painted under other elements, the share of the page that is photographs.
+Nothing is installed and nothing is paid for: the static tier is TypeScript
+over the files, and the render tier drives the same engine `gstack-render`
+picks (Aside when it is running, otherwise the browse daemon `./setup` built).
+
+The rules are ported from [Nutlope/hallmark](https://github.com/Nutlope/hallmark)'s
+`sloplint` (MIT; see NOTICE.md and licenses/MIT-hallmark.txt), rewritten in
+gstack's voice and mapped onto gstack's severity words. The copy tier is
+`gstack-design-craft`'s content-realism and ship-floor check under the same
+contract. Phase 1 (this document) is the tool alone; /design-html and
+/design-review call it in Phase 2.
+
+## Usage
+
+```
+gstack-design-lint <file-or-dir ...> [--render] [--url <http://…>] [--scope page|component] [--job <job>] [--json] [--rules]
+```
+
+- Reads `.html`, `.css`, `.jsx`, `.tsx`, `.vue`, `.svelte` and `.astro`.
+ Tailwind class strings in components are read too, including `cn()`,
+ `clsx()`, `cva()` and their kin. `node_modules`, dot folders and build
+ output below the top level are skipped; a symlink is followed once and lint
+ roots and the working directory are read through their real paths; a file
+ over 2 MB is a bundle, not a page, and is skipped with a warning on stderr.
+ A page or stylesheet the lint skipped (over the cap, unreadable,
+ unparseable; a linked sheet or an inline `<style>` block included) is also
+ one `internal-error` finding at ask, so a page whose CSS the lint could not
+ read is not a pass; only a linked stylesheet that does not exist is warned
+ about and otherwise ignored (its tokens are simply absent). A
+ relative stylesheet href may not climb out of the project (the nearest
+ directory holding a `package.json` or `.git`), by its path and by its real
+ path, so a symlink inside the project that points outside it is not read
+ either; outside any project it is bounded by the working directory the
+ lint runs in, and only `.css`
+ files are read.
+- Markup inside an HTML comment is dead for every rule, a commented-out
+ `<style>` or `<script>` included; a comment that never closes runs to the
+ end of the file, as it does in the browser. A tag start with no `>` (a stray
+ `<img `) and any `<` that starts no tag (`<1`, `a < b`) are read as text
+ and dropped from the markup, so a page whose tail is ten thousand of them
+ costs its length; a `<!doctype>` or `<?xml?>` declaration stays. A tree nests at most 512 elements deep
+ (the browser's own cap); a start tag deeper than that is read as empty. An
+ open heading is closed by the next heading start tag, an open `<p>` by the
+ next block start, and a repeated `<li>`, `<button>`, `<a>`, `<label>`,
+ `<select>`, `<form>` or table cell by its next start tag, as the browser
+ does, so a page of unclosed elements costs its length to lint. A nested
+ CSS selector is expanded against its parent (`&` replaced, a bare selector
+ descendant-joined) up to 8192 characters, and a sheet may store at most
+ four times its length plus 64 KB of expanded selectors; past either bound
+ the nested selector stands as written, so a sheet costs its length too.
+ Nesting is read 64 levels deep; a rule nested below that is dropped, not
+ parsed.
+- A page is linted with the stylesheets it links (`<link rel=stylesheet>`,
+ `@import`, and anything they reach); a directory of components shares the
+ project's tokens and global state styles, so a focus ring declared once in
+ `globals.css` is not reported missing on every component.
+- `--render` measures every HTML page found; `--url` measures a running dev
+ server (and implies `--render`). When no browser is available the render
+ tier is skipped and the summary says why.
+- `--scope component` skips the page-only rules (the nav, the footer, the
+ eyebrow, section gaps, the wireframe count) when linting a component alone.
+- `--job <job>` names what the visitor came to do (`book`, `buy`,
+ `subscribe`, `attend`, `visit`, `hire`, `listen`, `join`, `try`,
+ `sign up`): an email sign-up as the page's close is only a finding when the
+ job is not one where a mailing list is native.
+- `--json` prints `{ summary, files, findings }`; `--rules` prints the table below.
+
+## Output
+
+One line per finding, then one summary line:
+
+```
+LINT: <blocks|ask|polish|waived> <rule-id> <file>:<line> <evidence> | fix: <fix>
+LINT_SUMMARY: blocks=N ask=N waived=N polish=N render=<ran|skipped: reason>
+```
+
+Page-supplied text in a finding never holds the line's own ` | fix: `
+separator (it is printed as ` / fix: `), so splitting a line on its first
+` | fix: ` always reads the fix; a program reading many fields should take
+`--json`.
+
+Exit **2** when anything blocks, **1** when an ask is unanswered, **0**
+otherwise (**3** on a usage error). Findings sort blocks, ask, waived, polish,
+then by rule, file and line.
+
+## Tiers
+
+The lint uses gstack's severity words, not a fourth scale:
+
+| Tier | Meaning | hallmark's word |
+|---|---|---|
+| **blocks** | Never waivable. Correctness, access, honesty and the bans: a card in a card, a purple-blue gradient, a missing focus ring, contrast under threshold, a reveal that hides content until JavaScript runs. | Floor |
+| **ask** | A default a model falls into. Fix it, or waive it on the record with a reason about this page. | Reflex |
+| **polish** | Craft detail invisible at arm's length. Printed, never blocks. | Finish |
+
+`waived` marks an ask or polish finding a waiver answered. **Blocking and
+waived are never summed**: `blocks=0` is always a true sentence about the
+Floor. Three house rules hallmark holds at Floor stay at ask here on purpose:
+the eyebrow (`kicker-above-heading`; a figure caption or a plan name above a
+heading is often right), the 80-word screen (`screen-word-budget`; a Read-mode
+page legitimately exceeds it) and the dash (`em-dash-overuse`; gstack's rule is
+overuse, not a ban). A blocking rule the lint can only *suspect* (an invented
+metric it cannot prove invented) reports at ask so a person confirms it.
+
+## Waivers
+
+A finding is answered in a comment that names the rule and gives a reason
+about this page:
+
+```html
+<!-- gstack-lint-disable kicker-above-heading: the chapter number is the reader's bookmark through a forty-page spec -->
+```
+```css
+/* gstack-lint-disable section-gap: the ledger separates its rows with rules, not air */
+```
+```tsx
+// gstack-lint-disable template-nav: the three links are the product's three modes
+```
+
+`impeccable-disable <rule>: <reason>` is accepted as an alias, so a comment
+that already silences the impeccable engine answers the same tell here. The
+lint refuses, each as its own `waiver` finding at ask: a rule it does not
+know; the lint's own rules (`render`, `waiver`, `house-style`,
+`internal-error`: a fallback face or a failed measurement is never signed off);
+a **blocking** rule (the Floor is never waivable; the one exception is a
+blocking rule the lint could only *suspect* on this page, which it reports at
+ask and which a waiver answers like any ask); a reason under 24 characters,
+boilerplate ("by design", "intentional", "looks better"), reused word for
+word on another waiver, or sharing no word of four letters or more with the
+page's own text; a second waiver of one rule. More than three waivers
+on one page is a house style and belongs in DESIGN.md: reported once at polish
+as `house-style`.
+
+A claim written in a stylesheet answers for that stylesheet on every page
+that links it, and only for findings located in it: the shared-word check does
+not apply (a stylesheet has no prose), so the claim cannot reach a finding in
+the page's own markup. A claim written in the page answers for that page,
+including a finding in a stylesheet it links; a second page linking the same
+sheet without answering still reports it, so the sheet's finding may print
+once waived and once at ask, each from its own page. Which of these a context
+gets follows its shape, not the `--scope` flag: one html page keeps page
+semantics under either scope. In a directory of components, or a lone
+component file beside a stylesheet (under either scope), each file's claim answers for that file alone,
+weighed against that file's own text and its own suspected rules, so a sibling
+component is never covered and a sibling that measures a blocking rule does
+not turn this file's suspected finding into the Floor; a stylesheet beside the
+components answers for itself as on a page. Two claims on one line are both read. A blocking copy
+tell (`generic-hero-copy`) is the Floor inside the hero, the section or header
+that holds the h1; the same line, or a "Meet <Name>" or three-word triad
+heading, in body copy further down is suspected and reported at ask, so a
+waiver can answer it.
+
+## Rules
+
+| Rule | Tier | Source gate | The tell | The fix |
+|---|---|---|---|---|
+| `purple-blue-gradient` | blocks | 2a | purple-to-blue, purple-to-pink or cyan-on-dark gradient | one anchor hue and solid ink |
+| `gradient-text` | ask | 2b | gradient text | solid ink; carry emphasis with weight or a display face |
+| `pure-black-white` | blocks | 7a | #000 or #fff as a colour outside the token block | tint toward the anchor hue: chroma 0.005 or more |
+| `absolute-surface-token` | ask | 7b | a surface token that resolves to pure black or white | tint the paper |
+| `zero-chroma-neutrals` | ask | 22 | zero-chroma oklch() neutrals | give the neutrals chroma 0.005 or more |
+| `accent-footprint` | ask | 23 | accent colour past about 5% of a viewport | retreat the accent to actions and one signal |
+| `glow-wash` | ask | 29 | glow and wash: blurred orbs, a radial halo or a zero-offset coloured glow | a solid or grained surface; elevation by lightness, shadows with offset and blur |
+| `cream-palette` | ask | 65 | the cream paper, serif display and terracotta accent look | move one axis: the accent first, the paper second, the display last |
+| `framework-palette` | ask | 74 | a framework default palette (Tailwind indigo-500, slate-900 and kin) as a token or utility | a colour mixed for the page in OKLCH |
+| `overused-font` | ask | 1 | a training-data display face (Inter, Roboto, Fraunces, Playfair Display, Space Grotesk and the rest of gstack's catalog) or a system stack as the display | a display face chosen for the page |
+| `banned-font` | ask | catalog | a face gstack bans in any role (Papyrus, Comic Sans, Impact, Lobster, Raleway, Courier New and the rest of lib/design-catalog.ts BANNED_FONTS) | a face chosen for the page; the body face for body and labels |
+| `line-length` | ask | 25 | running prose outside 45 to 75 characters a line | max-width: 65ch |
+| `font-family-count` | ask | 37 | more than three font families | display, body and one outlier |
+| `italic-word-in-heading` | blocks | 38i | one italic word inside an otherwise roman heading | a line break, or the whole head set one way |
+| `italic-serif-display` | ask | 38ii | an italic display system | roman display, or declare it on --font-display with font-synthesis: none |
+| `accented-word` | ask | 38iii | one word in a heading set apart by colour, weight, a highlight or an underline | the whole head one way; a line break; a second line at a second size |
+| `caps-leading` | blocks | 55a | an uppercase display head that can wrap with line-height under 1.0 | line-height 1.0 at least (1.02 to 1.08 recommended) |
+| `caps-lockup-leading` | ask | 55b | a single-line caps lockup under 1.02 | line-height 1.02, or make sure it cannot wrap at 320px |
+| `monospace-costume` | ask | 64 | monospace on labels, captions or small type when the content is not code | labels in the body face, a step smaller, normal case |
+| `tiny-text` | ask | 75 | running text under 12px, functional text under 11px, or prose leaded under 1.3 (render) | body 16px at 1.5 to 1.65; labels one step smaller |
+| `wide-tracking` | blocks | 67 | the tracked-caps label: small text set uppercase or letter-spaced past 0.03em | the body face, a step smaller, sentence case, untracked |
+| `template-cards` | ask | 3 | three equal icon-above-heading tiles, an icon in a rounded tile, or a thick coloured side stripe | vary widths and heights, inline icons, hairline or no border |
+| `nested-cards` | blocks | 4 | a card inside a card | one containment layer |
+| `vh-height` | blocks | 6a | a hero sized in vh | dvh or svh |
+| `raw-spacing` | blocks | 24a | a raw padding, margin or gap length where a --space-* token exists | the token |
+| `off-scale-spacing` | ask | 24b | spacing off the page's scale | the scale; three optical nudges at most |
+| `overflow-x-unclipped` | ask | 34 | overflow-x missing on html and body, or a 100vw width | overflow-x: clip on both; width: 100% |
+| `horizontal-scroll` | blocks | 34 | horizontal scroll at a width between 320 and 1920 (render) | find the element wider than its viewport and cap it |
+| `hero-balance` | ask | 44a/44c | the hero's content sits off centre for its screen, or its visual stands apart from the text (render) | centre the content in its screen; put the visual beside the text |
+| `hero-fold` | blocks | 44b | the headline's bottom or the hero's first action below the 800px fold at 1280 wide; the lede and the visual are not measured (render) | pull the display clamp down, tighten leading, a two-line lede, trim padding |
+| `wide-container` | blocks | 44d | at 1920x1080 the container has no max-width, gutters under 120px, or a grid gains columns | cap 1360 to 1520px and centre; hold column counts; cap vw visuals |
+| `bare-fr-track` | blocks | 50 | an image-bearing grid track on bare 1fr | minmax(0, 1fr) |
+| `display-head-unwrapped` | blocks | 50 | a display head without overflow-wrap: break-word and min-width: 0 | overflow-wrap: break-word; min-width: 0 (never anywhere) |
+| `radio-tab-jump` | blocks | 53 | CSS-only radio tabs at position: absolute; top: 0 with no JS guard | radios in flow at zero size, or a handler with preventScroll |
+| `double-sticky` | blocks | 56 | two position: sticky; top: 0 elements | top: var(--banner-height) on the second |
+| `screen-word-budget` | ask | 58 | more than about 80 words in one 900px window, or a hero with more than two text blocks before its actions | headline, one sentence, actions; a section is a head block, then its composition |
+| `section-gap` | ask | 59 | a gap under 120px between sections at 1440, every gap the same, or more than nine sections (render) | 120px at least, varied; six to nine sections a page |
+| `heading-rhythm` | ask | 71 | a heading nearer what precedes it than what it heads (render) | at least twice the space above a head as below it |
+| `cramped-padding` | ask | 72 | text closer than 8px (or half an em) to the side of its filled box (render) | pad the box; a 16px gutter |
+| `thin-section` | ask | 77 | a section below the hero with no mass: a narrow body on a wide canvas (render) | widen the body, add a visual, set a statement, or merge the section |
+| `small-section-heads` | ask | 78 | the median h2 below the hero renders under 40px at 1440 (render) | h2 at the section size, item titles at the title size |
+| `dead-band` | ask | 79 | more than 160px of nothing between the hero's lowest content and the fold (render) | centre the content and grow the visual or the head; never fill with copy |
+| `hand-drawn-svg` | ask | 80 | an inline SVG of 120px or more with three curves or fills and no text: a drawn illustration (render) | a photograph, the product built, or type at scale |
+| `empty-picture` | ask | 81 | a slot or gradient block of 300x200px or more showing nothing but its wash (render) | the user's image, a credited photograph, or the product at full fidelity |
+| `counting-marks` | ask | 82 | 24 or more identical marks standing for a quantity (render) | set the number in type |
+| `photo-wall` | ask | 83 | photographs cover more than a third of the page below the hero (render) | keep the strongest pictures, set big; carry the rest in type, figures, the product, a table |
+| `email-band-close` | ask | 85 | the page ends on an email sign-up form (one or two fields, one of them the email; never a form with a password or a sign-in button) on a page whose job is not subscribe, join, attend, listen or visit | end on what the visitor came to do, or on the last strong section |
+| `aphoristic-cadence` | blocks | 19 | the rebuttal cadence three or more times ("Not a feature. A platform.") | say what the product does, in its own nouns |
+| `generic-hero-copy` | blocks | 19 | a filler opener ("Built for the modern team", "In today's landscape"), "quietly trusted by", or the catalog's "Welcome to" and "all-in-one solution" | say what the product does, in its own nouns |
+| `generic-cta-copy` | ask | 19/42 | a stock second action beside the primary (Learn more, Get started, Book a demo) | one action, or a second that names where it goes |
+| `em-dash-overuse` | ask | 19 | em or en dashes carrying the prose | a comma, a colon, a full stop or a line break |
+| `template-footer-line` | ask | 19 | a stock footer line (All rights reserved) | the page's own line, or nothing |
+| `template-nav` | ask | 42 | the reflex nav: wordmark left, inline links, a button right, hairline under | decide the nav and build another shape, or keep it on the record |
+| `template-footer` | ask | 42 | the reflex footer: four link columns, a social row, a copyright | decide the footer and build another shape, or keep it on the record |
+| `invented-proof` | blocks | 46a | an invented metric, testimonial, logo wall or case-study count | the user's number, a text slot, or nothing |
+| `drawn-browser-chrome` | blocks | 47a | a hand-drawn browser bar (traffic lights, URL pill) or OS window title bar | a real screenshot in a <figure>, or no chrome |
+| `device-frame` | ask | 47b | a phone, laptop, terminal or editor frame | one frame with real content inside, or none |
+| `imitation-material` | ask | 47c | styled divs standing in for a product, a photo edge or a physical object | the product built inside a slot, a real asset, or nothing |
+| `kicker-above-heading` | ask | 54 | the eyebrow: short inert type before a heading that only announces it | open the section another way; where the heading is figurative, the label becomes the heading |
+| `template-punctuation` | blocks | 63 | template punctuation: middle-dot meta strings, an arrow glued to link text, decorative status dots | line breaks, columns, hairlines; a verb as the label |
+| `wireframe-slots` | ask | 68 | more than five empty slots on one page, or four or more in one row | set the set in type; a slot that stays holds a real photo or the product |
+| `repeated-fact` | ask | 69 | one fact (a price, a time, a count) printed in four or more sections | say each fact once, where it does work |
+| `fake-send` | blocks | 70 | a form that prints success with no request behind it | validate, post nowhere and say so plainly until the endpoint exists |
+| `layout-transition` | blocks | 10a | transition: all, or animating width, height, top or left | list the properties; transform and opacity |
+| `spacing-transition` | ask | 10b | transitioning margin or padding | transform |
+| `hover-tells` | ask | 11 | the same lift on every card, two effects on one element, an image scaling on hover, or a hover on something inert | one signal per element, on the container, not the image |
+| `bounce-easing` | ask | 12 | bounce or overshoot easing on UI state | an exponential ease-out |
+| `focus-ring-fade` | blocks | 15 | a focus ring that fades in | instant: exclude outline and box-shadow from the transition |
+| `tooltip-focus-delay` | blocks | 17 | a tooltip whose focus delay equals its hover delay | hover 800 to 1000ms, focus 0 |
+| `autorotate-no-pause` | blocks | 18 | auto-rotating content with no pause on hover and focus | pause on hover and focus; a visible pause control past 5 seconds |
+| `missing-focus-visible` | blocks | 26a | an interactive element with no :focus-visible ring, or an outline removed with nothing in its place | a ring at 3:1 or better, instant |
+| `missing-states` | ask | 26b | no :active or :disabled state | all the states a control can be in |
+| `missing-reduced-motion` | blocks | 27 | a keyframe or transform transition without a prefers-reduced-motion fallback | add @media (prefers-reduced-motion: reduce) |
+| `autoplay-unmuted` | blocks | 28a | a video autoplaying without muted | autoplay muted loop playsinline |
+| `lazy-lcp` | blocks | 28a | loading="lazy" on the first image or the hero video | fetchpriority="high" on the LCP image |
+| `video-without-poster` | ask | 28b | a video without poster or a priority hint | add them |
+| `input-state-shift` | blocks | 39a | input states that break: a border that changes width, a focus ring built from border, disabled by opacity alone | constant border, outline, shared height, three disabled channels |
+| `control-height` | ask | 39b | control height outside 44 to 52px on a marketing page | the number |
+| `content-hidden-at-rest` | blocks | 62 | a reveal class hiding content until JavaScript runs | visible by default; hide only under a .js class, or animate from visible with @starting-style |
+| `emoji-decoration` | blocks | 30a | an emoji standing in for an icon | one icon library, custom SVG, or typography |
+| `two-icon-libraries` | ask | 30b | two icon libraries on one page | one library |
+| `unlabeled-decoration` | blocks | 33 | a decorative <svg>, <canvas> or CSS-art element with neither aria-hidden="true" nor a label | hide it or name it |
+| `broken-image` | blocks | 76 | an <img> with no source or one that does not load | the real file |
+| `stock-photo-hotlink` | blocks | 76 | a stock-site photo hotlink | the user's image, or a library photograph credited on the page |
+| `text-occlusion` | blocks | 73 | text painted under another element (render) | give the text its own space, or its own surface above the cover |
+| `low-contrast` | blocks | 40 | text, an icon, a focus ring or a field edge under its contrast threshold | fix the pair; body 4.5:1, large text and edges 3:1 |
+| `gray-on-color` | blocks | 41 | button text within a step of its fill, or grey text on a coloured surface | the paired ink token |
+| `literal-outside-tokens` | blocks | 48 | a colour or font-family literal outside the token block | lift it into the tokens |
+| `button-label-wraps` | blocks | 49a | a button label or primary nav link that wraps | shorten it; white-space: nowrap |
+| `link-wraps` | ask | 49b | a footer link, tab or breadcrumb that wraps | shorten it |
+| `straight-quotes` | polish | F1 | straight quotes in prose | curly quotes |
+| `three-dot-ellipsis` | polish | F2 | three dots for an ellipsis | the ellipsis character |
+| `balanced-display-head` | polish | F3 | a display head without text-wrap: balance | text-wrap: balance |
+| `two-primary-buttons` | polish | F4 | two filled primary buttons on one page, or side by side | one filled primary; the second as a text or outline action |
+| `icon-coin` | polish | F5 | an icon in a coloured coin | the icon inline, bare |
+| `display-figures-tabular` | polish | F6 | display-size figures without tabular numerals | font-variant-numeric: tabular-nums |
+| `stamped-recipe` | polish | F7 | one container recipe stamped on six or more selectors, or the pill radius on five or more non-controls | vary the recipe; pills on controls, tags and badges only |
+| `scroll-choreography-mix` | polish | F8 | more than one scroll-choreography pattern | one pattern a page |
+| `fake-avatar` | blocks | F9 | a fake-human avatar hotlink | the user's people, initials, or no portrait |
+| `stock-person-photo` | polish | F9 | a person-keyword stock photo URL | the user's photograph |
+| `page-invariants` | polish | F15 | page invariants broken: primary button style, container width, column gap or radius drifting | one recipe for each |
+| `unthemed-browser-surfaces` | polish | F16 | no ::selection, caret-color or scrollbar-color on a page with a committed palette | theme the browser surfaces |
+| `text-sliver` | polish | F17 | a text block squeezed into a sliver at 1440 (render) | give the block room or merge the columns |
+| `tiny-slot` | polish | F18 | a slot rendering under 40px in either dimension (render) | size the slot for what it will hold |
+| `font-weight-count` | polish | F19 | more than three font weights in running use (render) | three weights |
+| `lonely-grid-item` | polish | F20 | a grid or wrapping row leaving one item alone on its last row (render) | change the count or the columns |
+| `skipped-heading` | polish | F21 | a heading level skipped | step the levels one at a time |
+| `justified-text` | polish | F22 | justified text without hyphens: auto | hyphens: auto, or left-aligned |
+| `missing-lang` | polish | F23 | a document without lang | lang on <html> |
+| `hairline-under-shadow` | polish | F24 | a hairline border under a wide soft shadow on one surface | the shadow or the border, not both |
+| `placeholder-name` | blocks | craft | a placeholder name (John Doe) | use a supplied name, or one that fits the product in sample data |
+| `placeholder-brand` | blocks | craft | a placeholder brand (Acme, Nexus) | use a supplied customer, or a fitting name in sample data |
+| `lorem` | blocks | craft | lorem ipsum placeholder text | write real copy |
+| `marketing-buzzword` | ask | craft | a marketing buzzword | say the specific thing |
+| `round-number` | blocks | craft | a round invented number | use the supplied figure, or drop the claim |
+| `needs-proof` | blocks | craft | a [Needs proof] marker left in the page | supply the proof or remove the claim before publishing |
+| `oops` | ask | craft | "oops" as an error message | say what happened and what to do |
+| `scroll-listener` | ask | craft | a scroll event listener | use IntersectionObserver; read scroll inside requestAnimationFrame for a scroll-linked effect |
+| `dead-link` | ask | craft | a dead link (href="#") | link it, or render the control disabled |
+| `alert` | ask | craft | alert() for a message | show the message inline |
+| `img-no-alt` | blocks | craft | an <img> without alt | add alt text (alt="" when decorative) |
+| `missing-title` | blocks | craft | a document without a <title> | add a <title> |
+| `missing-meta-description` | ask | craft | no meta description | add <meta name="description"> |
+| `missing-favicon` | polish | craft | a document without a favicon | add a favicon <link rel="icon"> |
+| `missing-skip-link` | ask | craft | no skip link reaching <main> | add a "Skip to content" link first in <body> whose #id exists on <main> |
+| `missing-aria-current` | ask | craft | route navigation without aria-current | mark the current nav link aria-current="page" |
+
+Source gates are Nutlope/hallmark `references/gates.md` at 7ec8682; `craft`
+marks a rule carried over from `gstack-design-craft` (Elaya-derived). Four
+ids are the lint's own: `waiver` (a refused waiver, ask), `house-style` (more
+than three waivers, polish), `render` (a page that did not render, blocks:
+an unrendered page is never a pass) and `internal-error` (a page or stylesheet the lint could not read, or a rule family that
+threw on a page, ask: the page is not a pass until the lint has read it).
+
+## Token names the rules read
+
+Several rules key on hallmark's token names, which are also the names
+`/design-html` writes: `--color-paper` (the ground; `cream-palette`,
+`cyan-on-dark` and the dark-paper checks read it), `--color-accent`
+(`accent-footprint`, `cream-palette`), `--font-display` / `--font-heading` /
+`--font-title` / `--font-hero` (`overused-font`), `--space-*` (`raw-spacing`,
+`off-scale-spacing`) and any `--color-*` or `--font-*` token
+(`literal-outside-tokens` fires only on a page that declares one, since a
+literal on a page with no tokens bypasses nothing; its Tailwind half, an
+arbitrary value like `bg-[#0b0b12]` or `font-['Inter']`, fires on any page,
+since Tailwind's theme is the token block it bypasses). A project that names its
+tokens `--bg` or `--brand` gets none of those checks and no signal that they
+did not run; Phase 2 reads the roles from DESIGN.md.
+
+The token block is `:root`, `html`, a `[data-theme|mode|scheme]` scope, `@theme`,
+`@font-face` and anything in a `tokens.css`. Its values are read in one mode:
+the base block's last declaration wins, and a mode override (a token rule under
+`@media (prefers-color-scheme: …)` or a `[data-theme=…]` scope) only supplies
+tokens the base block never declares, so a page that carries both a light and
+a dark palette is measured in the mode it declares first, never a mix of the
+two. A custom property declared in any other scope (`.dark { --color-paper: … }`,
+a component-local `--accent`) is a token definition, not a literal, so
+`literal-outside-tokens` does not report it; the dark values of a class-scoped
+theme are not read either.
+
+## What the lint does not cover
+
+A clean `LINT_SUMMARY` is not the whole design checklist. These checklist and
+catalog items stay with the LLM pass in `/design-review` and are not rules
+here: `!important` in new CSS (the parser drops the flag), an h1 past 6rem
+(`oversized-h1`), tracking below -0.04em (`extreme-negative-tracking`), body
+text under 16px in a static stylesheet (`tiny-text` here is hallmark's 12px
+running-text floor, measured by the render tier), the `theater-slop-phrase`
+list beyond "built for the modern", the pulsing dot, a text container with
+no `max-width` (`line-length` reads a declared `ch` value), an uppercase
+paragraph at body size (`wide-tracking` reads caps at label size or tracked;
+a 16px untracked uppercase `<p>` passes), and a fixed px `width` on a
+container with no responsive handling (`wide-container` reads the opposite
+case). The copy tier
+reports at the document's first line with a count, because
+`gstack-design-craft` counts matches without positions; Phase 2 folds those
+patterns into the lint with lines. It reads the page with every open
+`<script>`, `<style>`, `<template>` or `<nav>` that nothing closes after it
+dropped, so a page of unclosed openers costs its length there too.
+`tooltip-focus-delay` reads the delay slot of a tooltip's `transition`
+(the second time in each comma part) or its `transition-delay`, 100ms and
+over; a `0.2s` or `200ms` fade is a duration, not a delay. Where a rule id is shared with
+`lib/design-catalog.ts`, the tier here follows hallmark's gate (several
+catalog `ask` rows are `blocks` here); Phase 2 reconciles the two before a
+catalog row is marked `detect: lint`. Also outside the lint: `system-ui` or
+`-apple-system` as the body's first face (`system-font-primary`; the
+`overused-font` rule reads display tokens and heading selectors, as hallmark's
+gate does), a gradient fill on the primary button (`gradient-cta`;
+`purple-blue-gradient` reports the banned hue pairs only, and an
+indigo-to-violet ramp needs stops 12° or more apart), `text-align: center`
+density, one large radius on everything, and backdrop blur on more than one
+container (`glow-wash` reports a blur over a translucent near-white or
+near-black fill; the zero-offset coloured glow is read from 8px in a Tailwind
+class and past 20px in a stylesheet, hallmark's two thresholds). The render
+tier's probes run in the page's own JavaScript, so a page that redefines them
+is caught only when it hands back a rule, grade or shape the lint does not
+know (each such answer is one `render` finding naming the probe and width,
+and every well-formed finding beside it is kept); a page that answers every
+probe with nothing passes the render tier, which is why the static tier stands
+on its own and a URL target is measured, never trusted. A stylesheet shared by
+many pages is parsed once but its stylesheet-only rules run per page and are
+deduplicated at the end, so forty pages on one bundle cost forty passes over
+it. `overused-font` and `banned-font` match a catalog stem to the whole
+family name or its first words (`Cormorant Garamond`, `DM Serif Display`,
+`Comic Sans MS`), never to a longer word (`Interstate` is not `Inter`).
+Four checklist items are read more narrowly here than the LLM pass reads
+them: `zero-chroma-neutrals` reports every opaque `oklch(L 0 H)` literal
+whether or not the page has an anchor hue (hallmark's stamp carried the hue;
+a deliberately monochrome page waives it on the record); `missing-focus-visible` reports a removed outline only when no
+`:focus` rule anywhere on the page draws a ring (the per-element check is the
+render tier's focus walk); `off-scale-spacing` holds every px length to the
+4px scale whether or not DESIGN.md declares one (`raw-spacing` is the rule
+gated on `--space-*` tokens); and `double-sticky` pairs any two `top: 0`
+sticky selectors without reading their scroll containers, so a sticky table
+header inside an `overflow: auto` wrapper under a sticky nav reports and
+wants a waiver on the record. As in hallmark, a selector the heading pattern
+matches (`__title`, `__headline`, `display`) is read as display type unless
+its name is also a label's or a control's, so a 12px uppercase tracked
+`.card__title` is caught by the markup half only when its text is typed in
+capitals. `em-dash-overuse` does not count an en dash between two digits (a
+range).
+
+## What is deliberately not ported
+
+hallmark's theme stamp (the CSS comment that declares a theme, a posture and a
+hero shape) and every guard that reads it; the genre flag; the judged gates
+(the AI template shape, section rhythm, hover by judgement, toasts, the
+reviews); the `--before` / `--kept` redesign record (Phase 2); the photo index.
diff --git a/lib/aside-render.ts b/lib/aside-render.ts
index 148890226..3ffde814a 100644
--- a/lib/aside-render.ts
+++ b/lib/aside-render.ts
@@ -13,6 +13,7 @@
* 1. Aside refuses `file://` URLs ("Cannot navigate to a file URL without
* local file access"), so the HTML's directory is served over loopback
* with Bun.serve on an ephemeral port for the duration of ONE render.
+ * An http(s) `file` is opened as it is and nothing is served.
* 2. One `aside repl` process runs ONE generated script: open the page,
* wait, run the steps in order, close the tab. Nothing persists between
* `aside repl` calls and tabs die with the script, so a render is always
@@ -37,7 +38,8 @@
* bookkeeping is best-effort: after a `cookie-import` the daemon refuses `js`
* on other origins, and a pdf/screenshot-only spec must still print. Not
* mirrored on this path: pageRanges/scale, screenshot quality, the 2x default
- * device scale.
+ * device scale, and an eval step's deviceScaleFactor and mobile (the browse
+ * daemon's `viewport` takes a size alone).
*
* Node builtins + Bun only (bun build --compile embeds this into make-pdf).
*/
@@ -133,11 +135,13 @@ export type RenderStep =
* the result is written to that file: strings verbatim; `data:` URLs are
* decoded to bytes; other values as JSON. Without `out`, the result comes
* back in `RenderResult.evals` (strings are truncated to `maxInline` chars).
+ * With `width`, the viewport is set before the eval the way a sized
+ * screenshot sets it, and cleared after.
*/
- | { kind: 'eval'; expression: string; out?: string; maxInline?: number };
+ | { kind: 'eval'; expression: string; out?: string; maxInline?: number; width?: number; height?: number; deviceScaleFactor?: number; mobile?: boolean };
export interface RenderSpec {
- /** Absolute path of the HTML file to open. */
+ /** Absolute path of the HTML file to open, or an http(s) URL (opened as it is, nothing served). */
file: string;
/** Directory served over loopback (default: the file's directory). Must contain `file`. */
serveRoot?: string;
@@ -217,8 +221,18 @@ export function buildRenderScript(url: string, spec: RenderSpec): string {
if (wait?.expression) {
L.push(`{ const deadline = Date.now() + ${wait.timeoutMs ?? DEFAULT_WAIT_MS}; let ok = false; while (Date.now() < deadline) { try { ok = !!(await pg.evaluate((src) => (0, eval)(src), ${JSON.stringify(wait.expression)})); } catch (e) {} if (ok) break; await sleep(150); } if (!ok) throw new Error("waitFor expression never became truthy: " + ${JSON.stringify(wait.expression)}); }`);
}
+ // The device override is set when a sized step's size differs from the one in force and cleared before an un-sized step, so consecutive evals at one width pay one override, not one per step.
+ let override: string | null = null;
+ const sized = (step: Exclude<RenderStep, { kind: 'pdf' }>): string | null => (step.width ? JSON.stringify({ width: step.width, height: step.height ?? Math.round(step.width * DEFAULT_ASPECT), deviceScaleFactor: step.deviceScaleFactor ?? DEFAULT_DEVICE_SCALE, mobile: step.mobile ?? step.width <= MOBILE_MAX_WIDTH }) : null);
+ const setOverride = (want: string | null) => {
+ if (want === override) return;
+ if (want) L.push(`await pg._sendToTarget("Emulation.setDeviceMetricsOverride", ${want}); await sleep(250);`);
+ else L.push(`await pg._sendToTarget("Emulation.clearDeviceMetricsOverride", {});`);
+ override = want;
+ };
spec.steps.forEach((step, i) => {
if (step.kind === 'pdf') {
+ setOverride(null);
const o = step.options ?? {};
if (o.waitForPagedJs) {
L.push(`{ const deadline = Date.now() + 3000; let ready = false; while (Date.now() < deadline) { try { ready = await pg.evaluate(() => !!window.__pagedjsAfterFired); } catch (e) {} if (ready) break; await sleep(150); } }`);
@@ -233,9 +247,7 @@ export function buildRenderScript(url: string, spec: RenderSpec): string {
const shot: Record<string, unknown> = { path: name, fullPage: step.fullPage !== false };
if (step.type) shot.type = step.type;
if (step.quality !== undefined) shot.quality = step.quality;
- if (step.width) {
- L.push(`await pg._sendToTarget("Emulation.setDeviceMetricsOverride", ${JSON.stringify({ width: step.width, height: step.height ?? Math.round(step.width * DEFAULT_ASPECT), deviceScaleFactor: step.deviceScaleFactor ?? DEFAULT_DEVICE_SCALE, mobile: step.mobile ?? step.width <= MOBILE_MAX_WIDTH })}); await sleep(250);`);
- }
+ setOverride(sized(step));
if (step.selector) {
const sel: Record<string, unknown> = { path: name };
if (step.type) sel.type = step.type;
@@ -243,10 +255,11 @@ export function buildRenderScript(url: string, spec: RenderSpec): string {
} else {
L.push(`await pg.screenshot(${JSON.stringify(shot)});`);
}
- if (step.width) L.push(`await pg._sendToTarget("Emulation.clearDeviceMetricsOverride", {});`);
+ setOverride(null);
L.push(`console.log("STEP_OK ${i}");`);
} else {
// eval: promises are awaited by evaluate; write or inline the result
+ setOverride(sized(step));
L.push(`{ const v = await pg.evaluate((src) => (0, eval)(src), ${JSON.stringify(step.expression)});`);
if (step.out) {
L.push(` const name = ${JSON.stringify(artifactName(i, step.out))};`);
@@ -262,6 +275,7 @@ export function buildRenderScript(url: string, spec: RenderSpec): string {
}
}
});
+ setOverride(null);
L.push(`console.log("PAGE_ERRORS=" + JSON.stringify(await pg.evaluate(() => window.__gstackErrs || [])));`);
L.push(`console.log("ASIDE_DIR=" + pwd);`);
L.push(`await closeTab(pg);`);
@@ -340,17 +354,33 @@ export async function renderWithAside(spec: RenderSpec): Promise<RenderResult> {
return { ...(await asideRender(spec)), engine: 'aside' };
}
-async function asideRender(spec: RenderSpec): Promise<RenderResult> {
+/** What the engine opens: an http(s) `file` as it is, else the file served from its root over loopback. */
+type PageTarget = { kind: 'url'; url: string } | { kind: 'file'; root: string; rel: string } | { kind: 'error'; error: string };
+
+function pageTarget(spec: RenderSpec): PageTarget {
+ if (/^https?:\/\//.test(spec.file)) return { kind: 'url', url: spec.file };
const file = path.resolve(spec.file);
- if (!fs.existsSync(file)) return { ok: false, outputs: [], evals: {}, stdout: '', error: `HTML file not found: ${file}` };
+ if (!fs.existsSync(file)) return { kind: 'error', error: `HTML file not found: ${file}` };
const root = path.resolve(spec.serveRoot ?? path.dirname(file));
const rel = path.relative(root, file);
- if (rel.startsWith('..')) return { ok: false, outputs: [], evals: {}, stdout: '', error: `file ${file} is outside serveRoot ${root}` };
+ if (rel.startsWith('..')) return { kind: 'error', error: `file ${file} is outside serveRoot ${root}` };
+ return { kind: 'file', root, rel };
+}
+
+/** Serve a file target for one render; an http(s) target needs no server. */
+function openTarget(target: Exclude<PageTarget, { kind: 'error' }>): { url: string; stop: () => void } {
+ if (target.kind === 'url') return { url: target.url, stop: () => {} };
+ const srv = serveDir(target.root);
+ return { url: `${srv.url}/${target.rel.split(path.sep).map(encodeURIComponent).join('/')}`, stop: srv.stop };
+}
+
+async function asideRender(spec: RenderSpec): Promise<RenderResult> {
+ const target = pageTarget(spec);
+ if (target.kind === 'error') return { ok: false, outputs: [], evals: {}, stdout: '', error: target.error };
- const srv = serveDir(root);
+ const srv = openTarget(target);
try {
- const url = `${srv.url}/${rel.split(path.sep).map(encodeURIComponent).join('/')}`;
- const script = buildRenderScript(url, spec);
+ const script = buildRenderScript(srv.url, spec);
// Async spawn: a synchronous wait would block this event loop, and the
// loopback server above runs on it — Page.navigate would then time out.
const proc = await runProc('aside', ['repl', script], (spec.timeoutMs ?? DEFAULT_TIMEOUT_MS) + processSlackMs());
@@ -492,11 +522,8 @@ export async function renderWithBrowse(spec: RenderSpec, bin: string | null = re
const log: string[] = [];
const fail = (error: string): RenderResult => ({ ok: false, engine: 'browse', outputs, evals, stdout: log.join('\n'), error });
if (!bin) return fail(`${NO_BROWSER}: ${NO_BROWSER_HELP}`);
- const file = path.resolve(spec.file);
- if (!fs.existsSync(file)) return fail(`HTML file not found: ${file}`);
- const root = path.resolve(spec.serveRoot ?? path.dirname(file));
- const rel = path.relative(root, file);
- if (rel.startsWith('..')) return fail(`file ${file} is outside serveRoot ${root}`);
+ const target = pageTarget(spec);
+ if (target.kind === 'error') return fail(target.error);
const deadline = Date.now() + (spec.timeoutMs ?? DEFAULT_TIMEOUT_MS);
const run = async (args: string[]): Promise<string> => {
@@ -525,7 +552,7 @@ export async function renderWithBrowse(spec: RenderSpec, bin: string | null = re
let tab: number | undefined;
try {
work = fs.mkdtempSync(path.join(SAFE_TMP_DIR, 'gstack-render-browse-'));
- srv = serveDir(root);
+ srv = openTarget(target);
// The first CLI call auto-starts the daemon; on a cold start it can answer
// "Unable to connect" once while the server is still coming up. One retry
// after a short pause turns that into the wait it really is.
@@ -555,7 +582,7 @@ export async function renderWithBrowse(spec: RenderSpec, bin: string | null = re
throw new Error(`${what} (waited ${timeoutMs}ms)`);
};
- await run(['goto', `${srv.url}/${rel.split(path.sep).map(encodeURIComponent).join('/')}`, ...T]);
+ await run(['goto', srv.url, ...T]);
// Best-effort: once `$B cookie-import` has run, the daemon blocks `js` on
// every other origin (127.0.0.1 included). pdf/screenshot/`js --out` steps
// must still run; a waitFor or eval step that is genuinely blocked fails
@@ -568,8 +595,16 @@ export async function renderWithBrowse(spec: RenderSpec, bin: string | null = re
if (wait?.selector) await until(`document.querySelector(${JSON.stringify(wait.selector)})`, `waitFor selector never attached: ${wait.selector}`, wait.timeoutMs ?? DEFAULT_WAIT_MS);
if (wait?.expression) await until(wait.expression, `waitFor expression never became truthy: ${wait.expression}`, wait.timeoutMs ?? DEFAULT_WAIT_MS);
+ // The viewport is set when a sized step's size differs from the one in force and reset to the daemon's default before an un-sized step, so consecutive evals at one width pay one `viewport` spawn, not two per step.
+ let vp: string | null = null;
+ const viewport = async (want: string | null) => {
+ if (want === vp) return;
+ await run(['viewport', want ?? '1280x720', ...T]);
+ vp = want;
+ };
for (const [i, step] of spec.steps.entries()) {
if (step.kind === 'pdf') {
+ await viewport(null);
const tmp = path.join(work, artifactName(i, step.out));
const payload = path.join(work, `pdf-${i}.json`);
fs.writeFileSync(payload, JSON.stringify(browsePdfPayload(step.options ?? {}, tmp)));
@@ -578,26 +613,31 @@ export async function renderWithBrowse(spec: RenderSpec, bin: string | null = re
} else if (step.kind === 'screenshot') {
const tmp = path.join(work, screenshotName(i, step));
if (step.width) {
- const vp = [`${step.width}x${step.height ?? Math.round(step.width * DEFAULT_ASPECT)}`];
+ const args = [`${step.width}x${step.height ?? Math.round(step.width * DEFAULT_ASPECT)}`];
// `--scale` recreates the daemon's browser context (and is refused in
// headed mode), so it is passed only when the caller asked for it; the
// 2x default stays Aside-only (see the header's "not mirrored" list).
- if (step.deviceScaleFactor) vp.push('--scale', String(step.deviceScaleFactor));
- await run(['viewport', ...vp, ...T]);
- }
+ if (step.deviceScaleFactor) args.push('--scale', String(step.deviceScaleFactor));
+ await run(['viewport', ...args, ...T]);
+ vp = args[0];
+ } else await viewport(null);
await run([...browseScreenshotArgs(step, tmp), ...T]);
copyOut(tmp, step.out, i);
// Aside clears its device override after each shot; restore the daemon's
// default so a later un-sized screenshot is not taken at this width.
- if (step.width) await run(['viewport', '1280x720', ...T]);
- } else if (step.out) {
- const tmp = path.join(work, artifactName(i, step.out));
- await js(step.expression, ['--out', tmp]); // the daemon decodes data: URLs to bytes itself
- copyOut(tmp, step.out, i);
+ if (step.width) await viewport(null);
} else {
- evals[i] = (await js(step.expression)).slice(0, step.maxInline ?? DEFAULT_MAX_INLINE);
+ await viewport(step.width ? `${step.width}x${step.height ?? Math.round(step.width * DEFAULT_ASPECT)}` : null);
+ if (step.out) {
+ const tmp = path.join(work, artifactName(i, step.out));
+ await js(step.expression, ['--out', tmp]); // the daemon decodes data: URLs to bytes itself
+ copyOut(tmp, step.out, i);
+ } else {
+ evals[i] = (await js(step.expression)).slice(0, step.maxInline ?? DEFAULT_MAX_INLINE);
+ }
}
}
+ await viewport(null);
const errs = await bestEffortJs('JSON.stringify(window.__gstackErrs || [])', 'PAGE_ERRORS');
if (errs !== null) log.push(`PAGE_ERRORS=${errs}`);
return { ok: true, engine: 'browse', outputs, evals, stdout: log.join('\n') };
diff --git a/lib/design-lint/color.ts b/lib/design-lint/color.ts
new file mode 100644
index 000000000..e17041238
--- /dev/null
+++ b/lib/design-lint/color.ts
@@ -0,0 +1,167 @@
+/**
+ * Colour parsing and contrast for the design lint: hex, rgb(), hsl() and
+ * oklch() to linear sRGB, sRGB to OKLCH for hue and chroma questions, WCAG
+ * relative luminance and contrast ratio.
+ *
+ * Ported from Nutlope/hallmark's sloplint.mjs (parseColor, oklchToSrgb,
+ * srgbToOklch, contrastRatio; MIT, see NOTICE.md).
+ */
+
+import { resolveVars, type Tokens } from './css';
+
+export interface Rgb { r: number; g: number; b: number }
+export interface Oklch { L: number; C: number; H: number }
+export interface Color extends Rgb { alpha: number; okl?: Oklch }
+
+const parseNum = (s: string): number | null => { const v = parseFloat(s); return Number.isNaN(v) ? null : v; };
+
+function alphaOf(parts: string[], nums: string[]): number {
+ if (parts[1] != null) return parts[1].trim().endsWith('%') ? (parseNum(parts[1]) ?? 100) / 100 : parseNum(parts[1]) ?? 1;
+ if (nums.length === 4) return nums[3].endsWith('%') ? (parseNum(nums[3]) ?? 100) / 100 : parseNum(nums[3]) ?? 1;
+ return 1;
+}
+
+function parseHex(h: string): Color | null {
+ if (h.length === 3 || h.length === 4) {
+ const r = parseInt(h[0] + h[0], 16) / 255, g = parseInt(h[1] + h[1], 16) / 255, b = parseInt(h[2] + h[2], 16) / 255;
+ return { r, g, b, alpha: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1 };
+ }
+ if (h.length === 6 || h.length === 8) {
+ const r = parseInt(h.slice(0, 2), 16) / 255, g = parseInt(h.slice(2, 4), 16) / 255, b = parseInt(h.slice(4, 6), 16) / 255;
+ return { r, g, b, alpha: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 };
+ }
+ return null;
+}
+
+function parseHsl(body: string): Color | null {
+ const parts = body.split('/');
+ const nums = parts[0].split(/[\s,]+/).filter(Boolean);
+ if (nums.length < 3) return null;
+ const h = parseNum(nums[0]);
+ const s = (parseNum(nums[1]) ?? NaN) / 100, l = (parseNum(nums[2]) ?? NaN) / 100;
+ if (h == null || Number.isNaN(s) || Number.isNaN(l)) return null;
+ const c = (1 - Math.abs(2 * l - 1)) * s;
+ const hp = ((h % 360) + 360) % 360 / 60;
+ const x = c * (1 - Math.abs((hp % 2) - 1));
+ let rgb: [number, number, number] = [0, 0, 0];
+ if (hp < 1) rgb = [c, x, 0]; else if (hp < 2) rgb = [x, c, 0];
+ else if (hp < 3) rgb = [0, c, x]; else if (hp < 4) rgb = [0, x, c];
+ else if (hp < 5) rgb = [x, 0, c]; else rgb = [c, 0, x];
+ const m = l - c / 2;
+ return { r: rgb[0] + m, g: rgb[1] + m, b: rgb[2] + m, alpha: alphaOf(parts, nums) };
+}
+
+/** Parse one CSS colour literal (hex, rgb[a], hsl[a], oklch, white/black/transparent); null for anything else. */
+export function parseColor(raw: string | null | undefined): Color | null {
+ if (!raw) return null;
+ const v = raw.trim().toLowerCase();
+ if (v === 'white') return { r: 1, g: 1, b: 1, alpha: 1 };
+ if (v === 'black') return { r: 0, g: 0, b: 0, alpha: 1 };
+ if (v === 'transparent') return { r: 0, g: 0, b: 0, alpha: 0 };
+ let m: RegExpExecArray | null;
+ if ((m = /^#([0-9a-f]{3,8})$/.exec(v))) return parseHex(m[1]);
+ if ((m = /^rgba?\(([^)]+)\)$/.exec(v))) {
+ const parts = m[1].split('/');
+ const nums = parts[0].split(/[\s,]+/).filter(Boolean);
+ if (nums.length < 3) return null;
+ const chan = (s: string) => s.endsWith('%') ? (parseNum(s) ?? NaN) / 100 : (parseNum(s) ?? NaN) / 255;
+ const [r, g, b] = nums.slice(0, 3).map(chan);
+ if ([r, g, b].some((x) => Number.isNaN(x))) return null;
+ return { r, g, b, alpha: alphaOf(parts, nums) };
+ }
+ if ((m = /^hsla?\(([^)]+)\)$/.exec(v))) return parseHsl(m[1]);
+ if ((m = /^oklch\(([^)]+)\)$/.exec(v))) {
+ const parts = m[1].split('/');
+ const nums = parts[0].split(/\s+/).filter(Boolean);
+ if (nums.length < 3) return null;
+ let L = parseNum(nums[0]);
+ if (L != null && nums[0].endsWith('%')) L = L / 100;
+ const C = parseNum(nums[1]);
+ const H = nums[2] === 'none' ? 0 : parseNum(nums[2]);
+ if (L == null || C == null || H == null) return null;
+ return { ...oklchToSrgb(L, C, H), alpha: alphaOf(parts, []), okl: { L, C, H } };
+ }
+ return null;
+}
+
+export function oklchToSrgb(L: number, C: number, H: number): Rgb {
+ const hr = (H * Math.PI) / 180;
+ const a = C * Math.cos(hr), b = C * Math.sin(hr);
+ const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
+ const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
+ const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
+ const l = l_ ** 3, mm = m_ ** 3, s = s_ ** 3;
+ const lin = [
+ 4.0767416621 * l - 3.3077115913 * mm + 0.2309699292 * s,
+ -1.2684380046 * l + 2.6097574011 * mm - 0.3413193965 * s,
+ -0.0041960863 * l - 0.7034186147 * mm + 1.7076147010 * s,
+ ].map((c) => Math.min(1, Math.max(0, c)));
+ const enc = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
+ return { r: enc(lin[0]), g: enc(lin[1]), b: enc(lin[2]) };
+}
+
+export function srgbToOklch(col: Rgb): Oklch {
+ const dec = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+ const r = dec(col.r), g = dec(col.g), b = dec(col.b);
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
+ const L = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
+ const a = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
+ const b2 = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
+ const C = Math.sqrt(a * a + b2 * b2);
+ let H = (Math.atan2(b2, a) * 180) / Math.PI;
+ if (H < 0) H += 360;
+ return { L, C, H };
+}
+
+/** OKLCH of a colour, from its own oklch() literal when it had one. */
+export function oklchOf(col: Color): Oklch {
+ return col.okl ?? srgbToOklch(col);
+}
+
+export function luminance(col: Rgb): number {
+ const dec = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+ return 0.2126 * dec(col.r) + 0.7152 * dec(col.g) + 0.0722 * dec(col.b);
+}
+
+/** WCAG 2 contrast ratio, 1 to 21. */
+export function contrastRatio(a: Rgb, b: Rgb): number {
+ const la = luminance(a), lb = luminance(b);
+ const hi = Math.max(la, lb), lo = Math.min(la, lb);
+ return (hi + 0.05) / (lo + 0.05);
+}
+
+/** Whether hue h (degrees) lies in [lo, hi], wrapping through 360 when lo > hi. */
+export const hueIn = (h: number, lo: number, hi: number): boolean => (lo <= hi ? h >= lo && h <= hi : h >= lo || h <= hi);
+
+export const COLOR_LITERAL = /#[0-9a-fA-F]{3,8}\b|oklch\([^)]*\)|rgba?\([^)]*\)|hsla?\([^)]*\)|color-mix\((?:[^()]|\([^()]*\))*\)|\b(white|black|transparent)\b/i;
+
+/** Whether the page's paper token resolves to a dark colour (OKLCH lightness under 0.4). */
+// sloplint paperIsDark (gate 2)
+export function paperIsDark(tokens: Tokens): boolean {
+ const p = parseColor(resolveVars(tokens['--color-paper'] || '', tokens));
+ return !!p && oklchOf(p).L < 0.4;
+}
+
+/** Two indigo-to-violet stops this many degrees apart read as a ramp; closer is one hue shaded. */
+const INDIGO_VIOLET_SPAN = 12;
+
+/**
+ * The banned ramp among a gradient's stop hues: purple to blue, purple to
+ * pink, indigo to violet, or cyan on a dark paper. One classifier for a
+ * stylesheet gradient and for Tailwind stops, so both tiers give one answer.
+ */
+// sloplint bannedGradient (gate 2a)
+export function bannedGradient(hues: number[], tokens: Tokens): string | null {
+ const purple = hues.some((h) => hueIn(h, 265, 330));
+ const blue = hues.some((h) => hueIn(h, 200, 264));
+ const pink = hues.some((h) => hueIn(h, 331, 25));
+ const cyan = hues.some((h) => hueIn(h, 170, 230));
+ if (purple && blue) return 'purple-to-blue';
+ if (purple && pink) return 'purple-to-pink';
+ const band = hues.filter((h) => hueIn(h, 250, 330));
+ if (band.length >= 2 && Math.max(...band) - Math.min(...band) >= INDIGO_VIOLET_SPAN) return 'indigo-to-violet';
+ if (cyan && paperIsDark(tokens)) return 'cyan-on-dark';
+ return null;
+}
diff --git a/lib/design-lint/context.ts b/lib/design-lint/context.ts
new file mode 100644
index 000000000..89765cde0
--- /dev/null
+++ b/lib/design-lint/context.ts
@@ -0,0 +1,60 @@
+/**
+ * The lint context: one page with the stylesheets it links (and anything
+ * they @import), or one directory of component files. Rules read it, the
+ * caches on it memoise the shared indexes.
+ */
+import { buildStyleIndex, declValue, fontPxOf, mergeBySelector, stylesFor, trackingEmOf, type CssDecl, type CssRule, type MergedRule, type StyleIndex, type Tokens } from './css';
+import type { Doc } from './html';
+
+export interface CssFile {
+ file: string;
+ raw: string;
+}
+
+/** Project-wide facts shared across a directory of components, so a focus ring in globals.css counts for Hero.tsx. */
+export interface SharedStyles {
+ focus: boolean;
+ active: boolean;
+ disabled: boolean;
+ reducedMotion: boolean;
+}
+
+export interface LintContext {
+ /** The page file, or the directory for a group of components. */
+ key: string;
+ rules: CssRule[];
+ tokens: Tokens;
+ docs: Doc[];
+ cssFiles: CssFile[];
+ /** Every stylesheet's text joined, for regex questions. */
+ allCss: string;
+ scope: 'page' | 'component';
+ /** The visitor's job (book, buy, subscribe, …) when the caller named one. */
+ job: string | null;
+ /** A stylesheet-only context whose rules are all tokens: nothing to lint but the tokens. */
+ tokensOnly: boolean;
+ shared: SharedStyles | null;
+ /** Tokens visible to Tailwind utilities in components: the project's merged tokens. */
+ twTokens: Tokens | null;
+ cache: Record<string, unknown>;
+}
+
+export function memo<T>(ctx: LintContext, key: string, make: () => T): T {
+ if (!(key in ctx.cache)) ctx.cache[key] = make();
+ return ctx.cache[key] as T;
+}
+
+export const mergedRules = (ctx: LintContext): MergedRule[] => memo(ctx, 'merged', () => mergeBySelector(ctx.rules));
+
+export const styleIndex = (ctx: LintContext): StyleIndex => memo(ctx, 'styleIndex', () => buildStyleIndex(ctx.rules));
+
+/** Declarations applying to an element by its class attribute and tag; restingOnly drops state and pseudo-element rules. */
+export const styleFor = (ctx: LintContext, classAttr: string | null | undefined, tag: string, restingOnly = false): CssDecl[] =>
+ stylesFor(styleIndex(ctx), classAttr, tag, restingOnly);
+
+export const valueOf = (ctx: LintContext, decls: CssDecl[], prop: string): string | null => declValue(decls, prop, ctx.tokens);
+
+export const fontPx = (ctx: LintContext, decls: CssDecl[]): number | null => fontPxOf(decls, ctx.tokens);
+
+export const trackingEm = (ctx: LintContext, decls: CssDecl[], px: number | null): number | null => trackingEmOf(decls, ctx.tokens, px);
+
diff --git a/lib/design-lint/css.ts b/lib/design-lint/css.ts
new file mode 100644
index 000000000..5f0618749
--- /dev/null
+++ b/lib/design-lint/css.ts
@@ -0,0 +1,400 @@
+/**
+ * CSS reading for the design lint: a comment-stripping, nesting-aware rule
+ * walker (no parser dependency), the token block (custom properties declared
+ * on :root, html or a data-theme scope, or in tokens.css / @theme), var()
+ * resolution with fallbacks, and the small unit helpers the rules share.
+ *
+ * Ported from Nutlope/hallmark's sloplint.mjs (parseCss, buildTokens,
+ * resolveVars, styleIndex and kin; MIT, see NOTICE.md), rewritten in TypeScript.
+ */
+import * as path from 'node:path';
+
+export interface CssDecl {
+ prop: string;
+ value: string;
+ line: number;
+}
+
+export interface CssRule {
+ selector: string;
+ decls: CssDecl[];
+ /** The @media query text this rule sits under, or null. */
+ media: string | null;
+ /** The @keyframes name this rule belongs to, or null for ordinary rules. */
+ keyframes: string | null;
+ file: string;
+ line: number;
+}
+
+/** Blank out comments and keep string literals, preserving every newline so line numbers hold. */
+export function stripComments(src: string): string {
+ let out = '';
+ let i = 0;
+ while (i < src.length) {
+ if (src[i] === '/' && src[i + 1] === '*') {
+ const end = src.indexOf('*/', i + 2);
+ const stop = end === -1 ? src.length : end + 2;
+ out += src.slice(i, stop).replace(/[^\n]/g, ' ');
+ i = stop;
+ } else if (src[i] === '"' || src[i] === "'") {
+ const q = src[i];
+ let j = i + 1;
+ while (j < src.length && src[j] !== q) { if (src[j] === '\\') j++; j++; }
+ out += src.slice(i, Math.min(j + 1, src.length));
+ i = j + 1;
+ } else { out += src[i]; i++; }
+ }
+ return out;
+}
+
+/** A binary search from newline offsets to a 1-based line number. */
+export function lineIndex(src: string, lineOffset = 0): (pos: number) => number {
+ const nl: number[] = [];
+ for (let i = 0; i < src.length; i++) if (src[i] === '\n') nl.push(i);
+ return (pos: number) => {
+ let lo = 0, hi = nl.length;
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (nl[mid] < pos) lo = mid + 1; else hi = mid; }
+ return lo + 1 + lineOffset;
+ };
+}
+
+/** The index just past the string literal opening at i, escape-aware (`"\""` is one string); end when it never closes. One skipper for the block scanner, the body flattener and the declaration split, so an escaped quote cannot rewrite the rest of a sheet. */
+function skipString(src: string, i: number, end: number): number {
+ const q = src[i];
+ let k = i + 1;
+ while (k < end && src[k] !== q) { if (src[k] === '\\') k++; k++; }
+ return k >= end ? end : k + 1;
+}
+
+/** A body split on the `;` outside string literals. */
+function splitDecls(body: string): string[] {
+ const parts: string[] = [];
+ let at = 0;
+ for (let i = 0; i < body.length; i++) {
+ if (body[i] === '"' || body[i] === "'") i = skipString(body, i, body.length) - 1;
+ else if (body[i] === ';') { parts.push(body.slice(at, i)); at = i + 1; }
+ }
+ parts.push(body.slice(at));
+ return parts;
+}
+
+/** Replace nested blocks inside [s, e) with spaces so the remaining text holds only this rule's own declarations. */
+function flatBody(src: string, s: number, e: number): string {
+ const body = src.slice(s, e), out = body.split('');
+ let depth = 0, edge = -1;
+ for (let i = 0; i < out.length; i++) {
+ const c = out[i];
+ if (c === '"' || c === "'") {
+ const j = skipString(body, i, body.length);
+ if (depth > 0) for (let k = i; k < j; k++) if (out[k] !== '\n') out[k] = ' ';
+ i = j - 1;
+ } else if (c === '{') {
+ if (depth === 0) for (let k = edge + 1; k < i; k++) if (out[k] !== '\n') out[k] = ' ';
+ depth++; out[i] = ' ';
+ } else if (c === '}') {
+ depth = Math.max(0, depth - 1); out[i] = ' ';
+ if (depth === 0) edge = i;
+ } else if (depth > 0) { if (c !== '\n') out[i] = ' '; }
+ else if (c === ';') edge = i;
+ }
+ return out.join('');
+}
+
+/** The tag names (a token at the start of a selector or after a combinator) and class names a list of selectors mentions, read once so a rule can ask "does any selector name this element" in constant time. */
+export function selectorNames(selectors: string[]): { tags: Set<string>; classes: Set<string> } {
+ const tags = new Set<string>(), classes = new Set<string>();
+ for (const sel of selectors) {
+ for (const m of sel.matchAll(/(?:^|[\s,>+~(])([a-zA-Z]\w*)/g)) tags.add(m[1]);
+ for (const m of sel.matchAll(/\.([\w-]+)/g)) classes.add(m[1]);
+ }
+ return { tags, classes };
+}
+
+/** A selector longer than this is a nesting blow-up (comma lists nested in comma lists, a parent repeated per '&'), not a stylesheet selector; a nested selector that would pass it stands without its parent, and every stored selector is cut there. The sheet as a whole may store at most expansionBudget() selector characters: once that is spent, nested selectors stand unexpanded (their own text, `&` kept), so thousands of children under one long parent cost the sheet its length and not children × MAX_SELECTOR. */
+const MAX_SELECTOR = 8192;
+const expansionBudget = (src: string): number => src.length * 4 + 65536;
+
+/** Expand a nested selector against its parent: `&` is replaced, a bare selector is descendant-joined; with expand off (the sheet's budget is spent) the selector stands as written. */
+function nestSelector(sel: string, parent: string, expand = true): string {
+ const parts = splitTop(sel).map((part) => part.trim());
+ if (!expand) return parts.filter(Boolean).join(', ') || '&';
+ const substitutions = parts.reduce((n, part) => n + Math.max(1, part.split('&').length - 1), 0);
+ const wrapped = parent.includes(',') ? parent.length + 5 : parent.length;
+ if (sel.length + wrapped * substitutions > MAX_SELECTOR) return parts.map((part) => part.replace(/&/g, '').trim()).filter(Boolean).join(', ') || splitTop(parent.slice(0, 256))[0].trim();
+ const p = parent.includes(',') ? `:is(${parent})` : parent;
+ return parts.map((part) => part.includes('&') ? part.replace(/&/g, p) : `${p} ${part}`).join(', ');
+}
+
+/** Faces that read as monospace, whether they arrive as a token, a utility or a declaration; one list so every check classifies a face the same way. */
+export const MONO_FACE = /(?:^|[\s"'-])mono(?:space)?\b|\bcode\b|courier|silkscreen|jetbrains|plex mono|geist mono|\bcommit\b|fira code|space mono|dm mono|roboto mono|source code|ibm plex mono|press start|vt323|share tech/i;
+
+/** The tracked-caps label: tracking past this (em) on text at or under LABEL_PX reads as the reflex, in CSS and in Tailwind alike. */
+export const TRACKED_EM = 0.03;
+export const LABEL_PX = 15;
+
+/** Real stylesheets nest a handful of levels; past this the rest reads as the parent's body instead of recursing. */
+const MAX_NESTING = 64;
+
+/**
+ * Parse a stylesheet into flat rules. Nested rules, @media / @supports /
+ * @layer / @container / @scope blocks, @keyframes, @font-face and Tailwind's
+ * @theme are all walked; every other at-rule is skipped whole.
+ */
+export function parseCss(source: string, file: string, lineOffset = 0): CssRule[] {
+ const src = stripComments(source);
+ const lineOf = lineIndex(src, lineOffset);
+ const rules: CssRule[] = [];
+ const budget = expansionBudget(src);
+ let stored = 0;
+ const makeRule = (selector: string, s: number, e: number, media: string | null, keyframes: string | null): CssRule => {
+ const body = flatBody(src, s, e);
+ const decls: CssDecl[] = [];
+ let off = 0;
+ for (const part of splitDecls(body)) {
+ const idx = part.indexOf(':');
+ if (idx > 0) {
+ const prop = part.slice(0, idx).trim().toLowerCase();
+ const value = part.slice(idx + 1).trim().replace(/!important\s*$/i, '').trim();
+ if (prop && value && /^-{0,2}[a-z]/.test(prop) && !/[{}]/.test(prop)) decls.push({ prop, value, line: lineOf(s + off + idx) });
+ }
+ off += part.length + 1;
+ }
+ return { selector, decls, media, keyframes, file, line: lineOf(s) };
+ };
+ const walk = (start: number, end: number, media: string | null, keyframes: string | null, parent: string | null = null, depthLeft = MAX_NESTING): void => {
+ let i = start;
+ while (i < end) {
+ while (i < end && /[\s;]/.test(src[i])) i++;
+ if (i >= end) break;
+ let j = i;
+ while (j < end && src[j] !== '{' && src[j] !== '}' && src[j] !== ';') j++;
+ if (j >= end) break;
+ if (src[j] === '}' || src[j] === ';') { i = j + 1; continue; }
+ const selector = src.slice(i, j).trim().replace(/\s+/g, ' ');
+ const blockStart = j + 1;
+ let depth = 1, k = blockStart;
+ while (k < end && depth > 0) {
+ const ch = src[k];
+ if (ch === '"' || ch === "'") { k = skipString(src, k, end); continue; }
+ if (ch === '{') depth++;
+ else if (ch === '}') depth--;
+ k++;
+ }
+ const blockEnd = Math.max(blockStart, k - 1);
+ if (selector.startsWith('@')) {
+ if (/^@(media|supports|layer|container|scope)/i.test(selector)) {
+ const q = /^@media/i.test(selector) ? selector.replace(/^@media/i, '').trim() : media;
+ if (parent) rules.push(makeRule(parent, blockStart, blockEnd, q, keyframes));
+ if (depthLeft > 0) walk(blockStart, blockEnd, q, keyframes, parent, depthLeft - 1);
+ } else if (/^@(-webkit-)?keyframes/i.test(selector)) {
+ const name = selector.replace(/^@(-webkit-)?keyframes/i, '').trim();
+ if (depthLeft > 0) walk(blockStart, blockEnd, media, name || 'anon', null, depthLeft - 1);
+ } else if (/^@font-face/i.test(selector)) {
+ rules.push(makeRule('@font-face', blockStart, blockEnd, media, null));
+ } else if (/^@theme\b/i.test(selector)) {
+ rules.push(makeRule('@theme', blockStart, blockEnd, media, null));
+ if (depthLeft > 0) walk(blockStart, blockEnd, media, keyframes, null, depthLeft - 1);
+ }
+ } else {
+ const nested = parent && !keyframes ? nestSelector(selector, parent, stored <= budget) : selector;
+ const sel = nested.length > MAX_SELECTOR ? nested.slice(0, MAX_SELECTOR) : nested;
+ stored += sel.length;
+ rules.push(makeRule(sel, blockStart, blockEnd, media, keyframes));
+ if (!keyframes && depthLeft > 0 && src.slice(blockStart, blockEnd).includes('{')) walk(blockStart, blockEnd, media, keyframes, sel, depthLeft - 1);
+ }
+ i = k;
+ }
+ };
+ walk(0, src.length, null, null);
+ return rules;
+}
+
+export type Tokens = Record<string, string>;
+
+const TOKEN_SEL = /^(?:html|:root)?(?:\[data-(?:theme|mode|scheme)[^\]]*\]|:root|:not\([^)]*\))*$/i;
+
+/** Whether a rule belongs to the token block: :root / html / a data-theme scope, @font-face, @theme, or anything in tokens.css. */
+export function isTokenRule(rule: Pick<CssRule, 'selector' | 'file'>): boolean {
+ if (rule.selector === '@font-face' || rule.selector === '@theme' || path.basename(rule.file).toLowerCase() === 'tokens.css') return true;
+ return rule.selector.split(',').every((p) => { const t = p.trim(); return t && TOKEN_SEL.test(t); });
+}
+
+/** A token rule that only answers for one colour mode: under a prefers-color-scheme query, or scoped to a data-theme/mode/scheme attribute. */
+const isModeOverride = (r: Pick<CssRule, 'selector' | 'media'>): boolean => /prefers-color-scheme/i.test(r.media ?? '') || /\[data-/i.test(r.selector);
+
+export interface TokenSite { value: string; file: string; line: number }
+
+/**
+ * Every custom property declared in the token block with the declaration it
+ * is read from: the last declaration of the base block wins, and a mode
+ * override (a dark-scheme query, a data-theme scope) only supplies tokens
+ * the base block never declares, so a page with both modes is read in the
+ * mode it declares first rather than a mix of the two.
+ */
+export function tokenSites(rules: CssRule[]): Map<string, TokenSite> {
+ const sites = new Map<string, TokenSite>();
+ const overrides = new Map<string, TokenSite>();
+ for (const r of rules) {
+ if (!isTokenRule(r)) continue;
+ const into = isModeOverride(r) ? overrides : sites;
+ for (const d of r.decls) if (d.prop.startsWith('--')) into.set(d.prop, { value: d.value, file: r.file, line: d.line });
+ }
+ for (const [prop, site] of overrides) if (!sites.has(prop)) sites.set(prop, site);
+ return sites;
+}
+
+export function buildTokens(rules: CssRule[]): Tokens {
+ const tokens: Tokens = {};
+ for (const [prop, site] of tokenSites(rules)) tokens[prop] = site.value;
+ return tokens;
+}
+
+/** The em of tracking an uppercase control may carry where the display itself is uppercase (hallmark's Tailwind half; its CSS half allowed 0.045). */
+export const CONTROL_TRACK_MAX_EM = 0.04;
+
+/** Contrast findings allow this much under the threshold, so a ratio of 4.46:1 is not reported against 4.5:1. */
+export const CONTRAST_SLACK = 0.05;
+
+/** A resolved value longer than this is a token that refers to itself, not a stylesheet value; expansion stops there. */
+const MAX_RESOLVED = 8192;
+
+/** value with every var() replaced by its token (or fallback), five levels deep; a token that re-enters its own chain, or a value past MAX_RESOLVED, is left as it stands, so a cyclic stylesheet costs its size and not its powers. */
+export function resolveVars(value: string, tokens: Tokens, local: Tokens | null = null, depth = 0, chain: ReadonlySet<string> = new Set()): string {
+ if (!value || depth > 5 || value.length > MAX_RESOLVED || !value.includes('var(')) return value;
+ const seen = new Set<string>();
+ let grown = 0;
+ const out = value.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*(?:\([^()]*\)[^()]*)*))?\)/g, (m0, name: string, fb: string | undefined) => {
+ if (chain.has(name) || grown > MAX_RESOLVED) return m0;
+ const v = local && local[name] != null ? local[name] : tokens[name];
+ if (v != null && v.length <= MAX_RESOLVED) { seen.add(name); grown += v.length; return v; }
+ if (v == null && fb != null) return fb.trim();
+ return m0;
+ });
+ if (out === value || out.length > MAX_RESOLVED) return out.length > MAX_RESOLVED ? value : out;
+ return resolveVars(out, tokens, local, depth + 1, new Set([...chain, ...seen]));
+}
+
+/** A family's identity ignores spaces, hyphens and underscores, so "GeistSans" and "Geist Sans" are one face. */
+export const famKey = (f: string | null | undefined): string => String(f || '').replace(/[\s_-]+/g, '');
+
+export function firstFamily(value: string): string {
+ return value.split(',')[0].trim().replace(/^['"]|['"]$/g, '').toLowerCase();
+}
+
+/** px, rem or em lengths to px at a 16px root; anything else is null. */
+export function pxOf(value: string): number | null {
+ const m = /^(-?\d*\.?\d+)(px|rem|em)$/.exec(value.trim());
+ if (!m) return null;
+ const n = parseFloat(m[1]);
+ return m[2] === 'px' ? n : n * 16;
+}
+
+export const GENERIC_FAMILIES = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-monospace', 'ui-serif', 'ui-sans-serif', 'ui-rounded', 'math', 'emoji', 'fangsong', 'inherit', 'initial', 'unset']);
+
+export const HEADING_SEL = /(^|[\s,>+~(])h[1-6]\b|__title|__display|__headline|hero__(title|display|headline|h\d)|wordmark|masthead|display/i;
+
+export function selectorIsInteractive(sel: string): boolean {
+ return /(^|[\s,>+~(])(a|button|input|select|textarea|summary)\b|\.(btn|button|cta|link|tab|chip|control)/i.test(sel);
+}
+
+/** Split a value at top-level commas (gradient stops, font lists), leaving parentheses intact. */
+export function splitTop(v: string): string[] {
+ const out: string[] = [];
+ let depth = 0, cur = '';
+ for (const c of v) {
+ if (c === '(') depth++;
+ else if (c === ')') depth--;
+ if (c === ',' && depth === 0) { out.push(cur.trim()); cur = ''; continue; }
+ cur += c;
+ }
+ if (cur.trim()) out.push(cur.trim());
+ return out;
+}
+
+export interface MergedRule { selector: string; media: string | null; decls: CssDecl[]; file: string; line: number }
+
+/** Rules folded by selector and media query, keyframes and @font-face excluded. */
+export function mergeBySelector(rules: CssRule[]): MergedRule[] {
+ const map = new Map<string, MergedRule>();
+ for (const r of rules) {
+ if (r.keyframes || r.selector === '@font-face') continue;
+ const key = r.selector + '@@' + (r.media || '');
+ if (!map.has(key)) map.set(key, { selector: r.selector, media: r.media, decls: [], file: r.file, line: r.line });
+ for (const d of r.decls) map.get(key)!.decls.push(d);
+ }
+ return [...map.values()];
+}
+
+export interface StyleEntry { classes: string[]; tag: string | null; decls: CssDecl[]; state: boolean; seq: number }
+
+/** Entries in source order, plus the same entries keyed by their first class or, for class-less compounds, by tag, so a lookup reads only the entries that can match. */
+export type StyleIndex = StyleEntry[] & { byClass?: Map<string, StyleEntry[]>; byTag?: Map<string, StyleEntry[]> };
+
+/** The last compound of every selector, indexed by class and tag, so an element's resting styles can be looked up. */
+export function buildStyleIndex(rules: CssRule[]): StyleIndex {
+ const entries: StyleIndex = [];
+ const byClass = new Map<string, StyleEntry[]>();
+ const byTag = new Map<string, StyleEntry[]>();
+ for (const r of rules) {
+ if (r.keyframes || r.selector === '@font-face') continue;
+ if (r.media && /max-width/i.test(r.media)) continue;
+ for (const part of r.selector.split(',')) {
+ const compound = part.trim().split(/[\s>+~]+/).filter(Boolean).pop();
+ if (!compound) continue;
+ const cleaned = compound.replace(/::?[a-z-]+(\([^)]*\))?/gi, '').replace(/\[[^\]]*\]/g, '');
+ const classes = (cleaned.match(/\.[a-zA-Z_][\w-]*/g) || []).map((c) => c.slice(1));
+ const tagM = /^([a-zA-Z][\w-]*)/.exec(cleaned);
+ const tag = tagM ? tagM[1].toLowerCase() : null;
+ if (!classes.length && !tag) continue;
+ const entry: StyleEntry = { classes, tag, decls: r.decls, state: /:(hover|active|focus|focus-visible|focus-within|disabled|checked|visited|target)\b|::?(before|after|marker|placeholder|selection|backdrop)\b/i.test(compound), seq: entries.length };
+ entries.push(entry);
+ const bucket = classes.length ? byClass : byTag;
+ const key = classes.length ? classes[0] : tag!;
+ if (!bucket.has(key)) bucket.set(key, []);
+ bucket.get(key)!.push(entry);
+ }
+ }
+ entries.byClass = byClass;
+ entries.byTag = byTag;
+ return entries;
+}
+
+/** The declarations that apply to an element with this class attribute and tag, in source order; restingOnly drops state and pseudo-element rules. */
+export function stylesFor(index: StyleIndex, classAttr: string | null | undefined, tagName: string, restingOnly = false): CssDecl[] {
+ const have = new Set(String(classAttr || '').split(/\s+/).filter(Boolean));
+ const candidates: StyleEntry[] = index.byClass
+ ? [...(index.byTag?.get(tagName) ?? []), ...[...have].flatMap((c) => index.byClass!.get(c) ?? [])].sort((a, b) => a.seq - b.seq)
+ : index;
+ const decls: CssDecl[] = [];
+ for (const e of candidates) {
+ if (restingOnly && e.state) continue;
+ if (e.tag && e.tag !== tagName) continue;
+ if (!e.classes.every((c) => have.has(c))) continue;
+ for (const d of e.decls) decls.push(d);
+ }
+ return decls;
+}
+
+/** The last value of a property in a declaration list, with tokens resolved. */
+export function declValue(decls: CssDecl[], prop: string, tokens: Tokens): string | null {
+ let v: string | null = null;
+ for (const d of decls) if (d.prop === prop) v = d.value;
+ return v == null ? null : resolveVars(v, tokens);
+}
+
+export function fontPxOf(decls: CssDecl[], tokens: Tokens): number | null {
+ const v = declValue(decls, 'font-size', tokens);
+ if (!v) return null;
+ const clamped = /clamp\(\s*([^,]+),/.exec(v);
+ return pxOf(clamped ? clamped[1].trim() : v);
+}
+
+export function trackingEmOf(decls: CssDecl[], tokens: Tokens, fontPx: number | null): number | null {
+ const v = declValue(decls, 'letter-spacing', tokens);
+ if (!v) return null;
+ const m = /^(-?\d*\.?\d+)em$/.exec(v.trim());
+ if (m) return parseFloat(m[1]);
+ const px = pxOf(v);
+ if (px == null || !fontPx) return null;
+ return px / fontPx;
+}
diff --git a/lib/design-lint/html.ts b/lib/design-lint/html.ts
new file mode 100644
index 000000000..874d862d0
--- /dev/null
+++ b/lib/design-lint/html.ts
@@ -0,0 +1,799 @@
+/**
+ * Markup reading for the design lint. A tag scanner over HTML (no DOM
+ * dependency) that keeps source positions, so every finding has a file:line;
+ * component files (.jsx .tsx .vue .svelte .astro) are first turned into
+ * pseudo-HTML: JSX by a small scanner that keeps elements and class
+ * attributes and blanks expressions, templates by masking frontmatter,
+ * braces and attribute expressions. Class-name helper calls (cn, clsx, cva …)
+ * are collected separately so Tailwind rules can read them.
+ *
+ * Ported from Nutlope/hallmark's sloplint.mjs (parseHtml, jsxPseudo,
+ * templateMask, clsLits, classCalls; MIT, see NOTICE.md).
+ */
+import * as path from 'node:path';
+import { lineIndex } from './css';
+
+export type DocKind = 'html' | 'jsx' | 'vue' | 'svelte' | 'astro';
+
+export interface Tag { close: boolean; name: string; attrs: string; pos: number; end: number; selfClosing: boolean; line: number }
+
+/** A string as a literal inside a RegExp source. */
+export const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+export interface StyleBlock { css: string; lineOffset: number }
+
+export interface ClassCall { pos: number; name: string; toks: string[] }
+
+export interface Doc {
+ file: string;
+ kind: DocKind;
+ /** The text the tags were scanned from: the HTML, or the pseudo-HTML of a component, with comments blanked and every `<` that starts no tag (a tag start with no `>`, `<1`, `a < b`; a `<!` or `<?` declaration with a `>` ahead stays) spaced out, positions kept, so no rule reads markup the browser never renders and no `[^>]*>` scan over it runs past its tag. */
+ src: string;
+ /** The original file text. */
+ raw: string;
+ /** src with comments, scripts and styles blanked (positions preserved). */
+ masked: string;
+ styles: StyleBlock[];
+ scripts: string;
+ tags: Tag[];
+ /** Non-HTML (component) tags in a component file. */
+ comps: Tag[];
+ /** Visible text with entities decoded and whitespace folded. */
+ text: string;
+ lineOf: (pos: number) => number;
+ /** JSX only: class tokens by element start position. */
+ classAt: Map<number, string[]>;
+ /** Class-name helper calls (cn, clsx, cva …) found in scripts. */
+ virtuals: ClassCall[];
+ /** Per-doc caches for the rules. */
+ cache: Record<string, unknown>;
+}
+
+export const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
+export const HTML_NAMES = new Set(('a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup svg table tbody td template textarea tfoot th thead time title tr track u ul var video wbr').split(' '));
+
+const pad = (t: string) => t.replace(/[^\n]/g, ' ');
+const VISIBLE = /\S/g;
+
+/** s lower-cased letter by letter (ASCII only, so every position still lines up with s). */
+const asciiLower = (s: string): string => s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
+
+/** A span found by spansOf: the whole match and, for an element, the body between its open and close tags. */
+interface Span { start: number; bodyStart: number; bodyEnd: number; end: number }
+
+/**
+ * Every `open … close` span of lower in one linear pass, so a file of
+ * unclosed openers costs its length and not its square. An unclosed comment
+ * runs to the end of the file, as a browser reads it; an element opener with
+ * no closer after it is left alone, as a tag. For an element, open is
+ * `<name`, which must end the name, and the span runs from that open tag
+ * through `</name>` (spaces before the `>` allowed).
+ */
+function spansOf(lower: string, open: string, close: string, element: boolean): Span[] {
+ const out: Span[] = [];
+ let i = 0;
+ for (;;) {
+ const start = lower.indexOf(open, i);
+ if (start < 0) break;
+ const after = start + open.length;
+ if (!element) {
+ const c = lower.indexOf(close, after);
+ if (c < 0) { out.push({ start, bodyStart: after, bodyEnd: lower.length, end: lower.length }); break; }
+ out.push({ start, bodyStart: after, bodyEnd: c, end: c + close.length });
+ i = c + close.length;
+ continue;
+ }
+ if (/[\w-]/.test(lower[after] || '')) { i = after; continue; }
+ const gt = lower.indexOf('>', after);
+ if (gt < 0) break;
+ let c = lower.indexOf(close, gt + 1), end = -1;
+ while (c >= 0) {
+ let k = c + close.length;
+ while (k < lower.length && /\s/.test(lower[k])) k++;
+ if (lower[k] === '>') { end = k + 1; break; }
+ c = lower.indexOf(close, c + 1);
+ }
+ if (end < 0) break;
+ out.push({ start, bodyStart: gt + 1, bodyEnd: c, end });
+ i = end;
+ }
+ return out;
+}
+
+/** s with each [a, b) range padded to spaces (positions kept) or, with cut set, replaced by one space. */
+function blankRanges(s: string, ranges: Array<[number, number]>, cut = false): string {
+ if (!ranges.length) return s;
+ let out = '', at = 0;
+ for (const [a, b] of ranges) if (a >= at) { out += s.slice(at, a) + (cut ? ' ' : pad(s.slice(a, b))); at = b; }
+ return out + s.slice(at);
+}
+
+/** s with every `<…>` run replaced by one space (or padded to spaces with keep set), in one linear pass; a `<` with no `>` after it is text. With a limit, the read stops once more than that many non-space characters are out, so a caller that only needs to know whether the text is short does not pay for an element that runs to the end of the file; a long whitespace run (a comment blanked to spaces) is skipped natively, so it costs its length once and the read still agrees with the unlimited one. */
+export function stripTags(s: string, keep = false, limit = Infinity): string {
+ let out = '', i = 0, seen = 0;
+ for (;;) {
+ if (limit < Infinity) for (let k = i, c = 0; k < s.length && s[k] !== '<'; k++) {
+ if ((c = s.charCodeAt(k)) > 32 && (c < 128 || !/\s/.test(s[k])) && ++seen > limit) return out + s.slice(i, k + (c >= 0xd800 && c < 0xdc00 ? 2 : 1));
+ if (k - i > 64 * limit + 4096) { VISIBLE.lastIndex = k + 1; const hit = VISIBLE.exec(s); if (!hit) return out + s.slice(i); k = hit.index - 1; }
+ }
+ const lt = s.indexOf('<', i);
+ if (lt < 0) break;
+ const gt = s.indexOf('>', lt + 1);
+ if (gt < 0) break;
+ out += s.slice(i, lt) + (keep ? pad(s.slice(lt, gt + 1)) : ' ');
+ i = gt + 1;
+ }
+ return out + s.slice(i);
+}
+
+/** Unquoted attribute text longer than this cannot be a tag; the scan gives the `<` up instead of reading on to the end of the file. */
+const MAX_UNQUOTED_ATTRS = 8192;
+
+/**
+ * Every tag in s, in document order and in one linear pass: `<name attrs>` and
+ * `</name>`, with quoted attribute values skipped whole. A `<` that never
+ * reaches a `>`, or a quote that never closes, is text; a `<` that opens a
+ * tag inside unquoted attribute text starts the next tag instead, as a
+ * browser reads `<a <b>`. Every `<` that starts no tag is a stray, except
+ * a `<!` or `<?` (a doctype, a declaration) with some `>` after it.
+ */
+function scanTags(s: string, onTag: (close: boolean, name: string, attrs: string, pos: number, end: number) => void, strays?: number[]): void {
+ const n = s.length;
+ const noQuoteFrom: Record<string, number> = { '"': n, "'": n };
+ let i = 0, nextGt = -1;
+ while (i < n) {
+ const lt = s.indexOf('<', i);
+ if (lt < 0) break;
+ let j = lt + 1;
+ const close = s[j] === '/';
+ if (close) j++;
+ if (!/[a-zA-Z]/.test(s[j] || '')) {
+ if (nextGt < lt) { const g = s.indexOf('>', lt); nextGt = g < 0 ? n : g; }
+ if (!/[!?]/.test(s[j] || '') || nextGt >= n) strays?.push(lt);
+ i = lt + 1;
+ continue;
+ }
+ let k = j + 1;
+ while (k < n && /[a-zA-Z0-9-]/.test(s[k])) k++;
+ let p = k, unquoted = 0, next = lt + 1, gt = -1;
+ while (p < n) {
+ const c = s[p];
+ if (c === '>') { gt = p; break; }
+ if (c === '"' || c === "'") {
+ if (p + 1 >= noQuoteFrom[c]) break;
+ const q = s.indexOf(c, p + 1);
+ if (q < 0) { noQuoteFrom[c] = p + 1; break; }
+ p = q + 1;
+ continue;
+ }
+ if (c === '<' && /[a-zA-Z/]/.test(s[p + 1] || '')) { next = p; break; }
+ if (++unquoted > MAX_UNQUOTED_ATTRS) break;
+ p++;
+ }
+ if (gt < 0) { strays?.push(lt); i = next; continue; }
+ onTag(close, s.slice(j, k), s.slice(k, gt), lt, gt + 1);
+ i = gt + 1;
+ }
+}
+
+/** The text with each stray `<` replaced by a space, so every `<` left starts a tag with its own `>`, a `<[^>]*>` regex over it costs its length, and a page whose tail is ten thousand unclosed `<img ` or `<1` costs its length. */
+function blankStrays(s: string, strays: number[]): string {
+ let out = '', from = 0;
+ for (const i of strays) { out += s.slice(from, i) + ' '; from = i + 1; }
+ return out + s.slice(from);
+}
+
+export function parseHtml(file: string, src: string, kind: DocKind = 'html'): Doc {
+ const lineOf = lineIndex(src);
+ const comments = spansOf(asciiLower(src), '<!--', '-->', false).map((s): [number, number] => [s.start, s.end]);
+ const live = blankRanges(src, comments);
+ const lower = asciiLower(live);
+ const scriptSpans = spansOf(lower, '<script', '</script', true);
+ const styleSpans = spansOf(lower, '<style', '</style', true);
+ const styles: StyleBlock[] = styleSpans.map((s) => ({ css: live.slice(s.bodyStart, s.bodyEnd), lineOffset: lineOf(s.start) - 1 }));
+ const scripts = scriptSpans.map((s) => live.slice(s.bodyStart, s.bodyEnd) + '\n').join('');
+ const bodies = [...scriptSpans, ...styleSpans].map((s): [number, number] => [s.bodyStart, s.bodyEnd]).sort((a, b) => a[0] - b[0]);
+ const strays: number[] = [];
+ const tags: Tag[] = [];
+ const comps: Tag[] = [];
+ scanTags(blankRanges(live, bodies), (close, rawName, attrs, pos, end) => {
+ if (kind !== 'html' && !HTML_NAMES.has(rawName)) {
+ comps.push({ close, name: rawName, attrs, pos, end, selfClosing: /\/\s*$/.test(attrs), line: lineOf(pos) });
+ return;
+ }
+ const name = rawName.toLowerCase();
+ tags.push({ close, name, attrs, pos, end, selfClosing: /\/\s*$/.test(attrs) || VOID_TAGS.has(name), line: lineOf(pos) });
+ }, strays);
+ const src2 = blankStrays(live, strays);
+ const masked = blankRanges(src2, bodies);
+ const whole = [...scriptSpans, ...styleSpans].map((s): [number, number] => [s.start, s.end]).sort((a, b) => a[0] - b[0]);
+ const text = stripTags(blankRanges(src2, whole, true))
+ .replace(/&quot;|&#0?34;/g, '"').replace(/&#0?39;|&apos;/g, "'")
+ .replace(/&hellip;|&#8230;/g, '\u2026').replace(/&mdash;|&#8212;|&#x2014;/gi, '\u2014').replace(/&ndash;|&#8211;|&#x2013;/gi, '\u2013')
+ .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
+ .replace(/&nbsp;/g, ' ').replace(/[ \t]+/g, ' ');
+ return { file, kind, src: src2, raw: src, masked, styles, scripts, tags, comps, text, lineOf, classAt: new Map(), virtuals: [], cache: {} };
+}
+
+/** The index of the brace that closes the one at j (strings skipped), or the string's length. */
+export function braceEnd(s: string, j: number): number {
+ let depth = 0;
+ for (let i = j; i < s.length; i++) {
+ const c = s[i];
+ if (c === '"' || c === "'" || c === '`') {
+ i++;
+ while (i < s.length && s[i] !== c) { if (s[i] === '\\') i++; i++; }
+ continue;
+ }
+ if (c === '{') depth++;
+ else if (c === '}' && --depth === 0) return i;
+ }
+ return s.length;
+}
+
+export const FRONTMATTER = /^\s*---[^\n]*\n[\s\S]*?\n---/;
+
+/** Blank Astro frontmatter, brace expressions in attributes (Svelte, Astro) and angle brackets inside attribute strings, keeping positions. */
+export function templateMask(src: string, kind: DocKind): string {
+ const n = src.length;
+ let out: string[] | null = null;
+ const put = (k: number, ch: string) => { if (!out) out = src.split(''); out[k] = ch; };
+ const blank = (a: number, b: number) => { for (let k = a; k < b; k++) if (src[k] !== '\n' && src[k] !== ' ') put(k, ' '); };
+ const lower = src.toLowerCase();
+ const braces = kind === 'svelte' || kind === 'astro';
+ let i = 0;
+ if (kind === 'astro') {
+ const fm = FRONTMATTER.exec(src);
+ if (fm) { blank(0, fm[0].length); i = fm[0].length; }
+ }
+ while (i < n) {
+ const lt = src.indexOf('<', i);
+ if (lt < 0) break;
+ if (src.startsWith('<!--', lt)) { const e = src.indexOf('-->', lt + 4); i = e < 0 ? n : e + 3; continue; }
+ if (!/[A-Za-z]/.test(src[lt + 1] || '')) { i = lt + 1; continue; }
+ let j = lt + 1;
+ while (j < n && /[\w:.-]/.test(src[j])) j++;
+ const name = lower.slice(lt + 1, j);
+ while (j < n && src[j] !== '>') {
+ const c = src[j];
+ if (c === '"' || c === "'") {
+ let e = src.indexOf(c, j + 1);
+ if (e < 0) e = n;
+ for (let k = j + 1; k < e; k++) if (src[k] === '<' || src[k] === '>') put(k, ' ');
+ j = e + 1;
+ continue;
+ }
+ if (c === '{' && braces) { const e = braceEnd(src, j); blank(j + 1, e); j = e + 1; continue; }
+ j++;
+ }
+ i = j + 1;
+ if (name === 'script' || name === 'style' || name === 'textarea') {
+ const e = lower.indexOf('</' + name, i);
+ i = e < 0 ? n : e;
+ }
+ }
+ return out ? (out as string[]).join('') : src;
+}
+
+const cutGlued = (seg: string, after: boolean, before: boolean): string => {
+ let s = seg;
+ if (after) s = s.replace(/^\S+/, '');
+ if (before) s = s.replace(/\S+$/, '');
+ return s;
+};
+
+/** Every string literal's class tokens inside a JS expression, template literals included (${} parts recursed, glued halves dropped). */
+export function clsLits(s: string, level = 0): string[] {
+ if (level > 20) return [];
+ const parts: string[] = [];
+ let i = 0;
+ while (i < s.length) {
+ const c = s[i];
+ if (c === '/' && s[i + 1] === '/') { const e = s.indexOf('\n', i); i = e < 0 ? s.length : e; continue; }
+ if (c === '/' && s[i + 1] === '*') { const e = s.indexOf('*/', i + 2); i = e < 0 ? s.length : e + 2; continue; }
+ if (c === '"' || c === "'") {
+ let j = i + 1;
+ while (j < s.length && s[j] !== c && s[j] !== '\n') { if (s[j] === '\\') j++; j++; }
+ parts.push(s.slice(i + 1, j));
+ i = j + 1;
+ continue;
+ }
+ if (c === '`') {
+ let j = i + 1, seg = '', after = false;
+ while (j < s.length && s[j] !== '`') {
+ if (s[j] === '\\') { seg += s[j + 1] || ''; j += 2; continue; }
+ if (s[j] === '$' && s[j + 1] === '{') {
+ parts.push(cutGlued(seg, after, true));
+ const e = braceEnd(s, j + 1);
+ parts.push(clsLits(s.slice(j + 2, e), level + 1).join(' '));
+ j = e + 1; seg = ''; after = true;
+ continue;
+ }
+ seg += s[j]; j++;
+ }
+ parts.push(cutGlued(seg, after, false));
+ i = j + 1;
+ continue;
+ }
+ i++;
+ }
+ return parts.join(' ').split(/\s+/).filter(Boolean);
+}
+
+const JS_EXPR_KW = new Set(['return', 'yield', 'await', 'case', 'default', 'else', 'do', 'throw', 'typeof', 'void', 'delete', 'in', 'of', 'new', 'instanceof']);
+export const CLASS_FNS = new Set(['cn', 'clsx', 'classNames', 'classnames', 'twMerge', 'twJoin', 'cva', 'cx', 'tv']);
+const CLASS_FN_CALL = new RegExp(`(?<![\\w$.])(?:${[...CLASS_FNS].join('|')})\\s*\\(`, 'g');
+
+/** Failed element starts a component file may spend before the scanner stops pairing; jsScan carries the same budget. */
+const MAX_FAILED_TAGS = 500;
+/** An element whose content ran to the end of the file without any closer: no ancestor can close either, so each fails at once instead of rescanning the same text. */
+const JSX_EOF = -2;
+
+/**
+ * Turn a JSX/TSX module into pseudo-HTML of the same length: elements and
+ * their class attributes survive (an expression-valued className becomes the
+ * literals it holds), everything else becomes spaces. Also records where
+ * class-helper calls start. A close tag naming an open ancestor closes every
+ * element under it, as a browser would; one naming nothing open is text.
+ */
+class JsxScanner {
+ private readonly n: number;
+ private readonly out: string[];
+ readonly classes: Array<[number, string[]]> = [];
+ readonly calls: number[] = [];
+ private hi = 0;
+ private fails = 0;
+ private inClass = 0;
+ private depth = 0;
+ private readonly open: string[] = [];
+
+ constructor(private readonly src: string) {
+ this.n = src.length;
+ this.out = new Array(this.n);
+ for (let k = 0; k < this.n; k++) this.out[k] = src[k] === '\n' ? '\n' : ' ';
+ }
+
+ pseudo(): string { this.js(0, false); return this.out.join(''); }
+
+ private blank(a: number, b: number): void { for (let k = a; k < b && k < this.n; k++) this.out[k] = this.src[k] === '\n' ? '\n' : ' '; }
+ private paint(a: number, b: number): void { for (let k = a; k < b && k < this.n; k++) this.out[k] = this.src[k]; if (b > this.hi) this.hi = b; }
+ private write(a: number, b: number, text: string): void {
+ this.blank(a, b);
+ let k = a;
+ for (const ch of text) { while (k < b && this.src[k] === '\n') k++; if (k >= b) break; this.out[k++] = ch; }
+ if (b > this.hi) this.hi = b;
+ }
+ private ws(i: number): number { while (i < this.n && /\s/.test(this.src[i])) i++; return i; }
+ private gap(i: number): number {
+ const { src, n } = this;
+ for (;;) {
+ i = this.ws(i);
+ if (src[i] === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); if (e < 0) return n; i = e + 2; continue; }
+ if (src[i] === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); if (e < 0) return n; i = e; continue; }
+ return i;
+ }
+ }
+ private strEnd(i: number): number {
+ const { src, n } = this;
+ const q = src[i];
+ let j = i + 1;
+ while (j < n && src[j] !== q && src[j] !== '\n') { if (src[j] === '\\') j++; j++; }
+ return Math.min(j + 1, n);
+ }
+ private tplEnd(i: number): number {
+ const { src, n } = this;
+ let j = i + 1;
+ while (j < n && src[j] !== '`') {
+ if (src[j] === '\\') { j += 2; continue; }
+ if (src[j] === '$' && src[j + 1] === '{') { j = this.js(j + 2, true) + 1; continue; }
+ j++;
+ }
+ return Math.min(j + 1, n);
+ }
+ private reEnd(i: number): number {
+ const { src, n } = this;
+ let j = i + 1, set = false;
+ while (j < n && src[j] !== '\n') {
+ const c = src[j];
+ if (c === '\\') { j += 2; continue; }
+ if (c === '[') set = true;
+ else if (c === ']') set = false;
+ else if (c === '/' && !set) { j++; while (j < n && /[a-z]/i.test(src[j])) j++; return j; }
+ j++;
+ }
+ return -1;
+ }
+ private js(i: number, stop: boolean): number {
+ if (this.depth > 200) return stop ? Math.min(braceEnd(this.src, i - 1), this.n) : this.n;
+ this.depth++;
+ const r = this.jsScan(i, stop);
+ this.depth--;
+ return r;
+ }
+ private jsScan(i: number, stop: boolean): number {
+ const { src, n } = this;
+ let level = 0, val = false;
+ while (i < n) {
+ const c = src[i];
+ if (c === ' ' || c === '\n' || c === '\t' || c === '\r') { i++; continue; }
+ if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); i = e < 0 ? n : e; continue; }
+ if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); i = e < 0 ? n : e + 2; continue; }
+ if (c === '"' || c === "'") { i = this.strEnd(i); val = true; continue; }
+ if (c === '`') { i = this.tplEnd(i); val = true; continue; }
+ if (c === '{') { level++; i++; val = false; continue; }
+ if (c === '}') { if (stop && level === 0) return i; level--; i++; val = true; continue; }
+ if (c === ')' || c === ']') { i++; val = true; continue; }
+ if (c === '<' && !val && this.fails < MAX_FAILED_TAGS && /[A-Za-z_$>]/.test(src[i + 1] || '')) {
+ const e = this.el(i);
+ if (e > 0) { i = e; val = true; continue; }
+ this.fails++;
+ }
+ if (c === '/' && !val) { const e = this.reEnd(i); if (e > 0) { i = e; val = true; continue; } }
+ if (/[A-Za-z_$]/.test(c)) {
+ let j = i + 1;
+ while (j < n && /[\w$]/.test(src[j])) j++;
+ const w = src.slice(i, j);
+ val = !JS_EXPR_KW.has(w);
+ if (!this.inClass && CLASS_FNS.has(w) && src[i - 1] !== '.' && src[this.ws(j)] === '(') this.calls.push(i);
+ i = j;
+ continue;
+ }
+ if (c >= '0' && c <= '9') { let j = i + 1; while (j < n && /[\w.]/.test(src[j])) j++; i = j; val = true; continue; }
+ i++;
+ val = false;
+ }
+ return n;
+ }
+ /** Starts that did not open an element: a retry from the same start fails the same way, so a run of unclosed elements costs its length, not two to its depth. */
+ private failed = new Set<number>();
+ /** Past MAX_FAILED_TAGS failed starts (jsScan and el together) every later start is text, so a run of unclosed elements under the depth cap costs its length. */
+ private el(start: number): number {
+ if (this.depth > 200 || this.fails >= MAX_FAILED_TAGS || this.failed.has(start)) return -1;
+ const mc = this.classes.length, mk = this.calls.length;
+ this.depth++;
+ const e = this.tag(start);
+ this.depth--;
+ if (e < 0) { this.failed.add(start); this.fails++; this.blank(start, Math.max(this.hi, start + 1)); this.hi = start; this.classes.length = mc; this.calls.length = mk; }
+ return e;
+ }
+ /** One attribute from i; returns the index after it, or -1 when the tag is not JSX after all. */
+ private attr(i: number, cls: { v: string[] | null }): number {
+ const { src, n } = this;
+ let k = i + 1;
+ while (k < n && /[\w$:.-]/.test(src[k])) k++;
+ const attr = src.slice(i, k);
+ let v = this.ws(k);
+ if (src[v] !== '=') { this.paint(i, k); return k; }
+ v = this.ws(v + 1);
+ const q = src[v];
+ const isCls = attr === 'className' || attr === 'class';
+ let e: number;
+ if (q === '"' || q === "'") {
+ e = src.indexOf(q, v + 1);
+ if (e < 0) return -1;
+ if (isCls) cls.v = (cls.v || []).concat(src.slice(v + 1, e).split(/\s+/).filter(Boolean));
+ else this.paint(i, e + 1);
+ } else if (q === '{') {
+ if (isCls) this.inClass++;
+ e = this.js(v + 1, true);
+ if (isCls) this.inClass--;
+ if (e >= n) return JSX_EOF;
+ if (isCls) cls.v = (cls.v || []).concat(clsLits(src.slice(v + 1, e)));
+ else { this.paint(i, v); this.write(v, e + 1, '"' + src.slice(v + 1, e).replace(/[^\w$.\-/:#@]+/g, ' ') + '"'); }
+ } else if (q === '<') {
+ e = this.el(v) - 1; if (e === JSX_EOF - 1) return JSX_EOF;
+ if (e < 0) return -1;
+ this.blank(i, e + 1);
+ } else return -1;
+ if (isCls && cls.v) this.write(i, e + 1, 'class="' + cls.v.join(' ').replace(/"/g, "'").replace(/[<>]/g, ' ') + '"');
+ return e + 1;
+ }
+ private tag(start: number): number {
+ const { src, n } = this;
+ let i = start + 1;
+ if (src[i] === '>') return this.kids(i + 1, '');
+ let j = i;
+ while (j < n && /[\w$.:-]/.test(src[j])) j++;
+ const name = src.slice(i, j);
+ this.paint(start, j);
+ i = j;
+ if (src[i] === '<') {
+ let d = 0, k = i;
+ do { if (src[k] === '<') d++; else if (src[k] === '>') d--; k++; } while (k < n && d > 0);
+ if (d) return -1;
+ this.blank(i, k); i = k;
+ }
+ const cls: { v: string[] | null } = { v: null };
+ for (;;) {
+ i = this.gap(i);
+ if (i >= n) return -1;
+ const c = src[i];
+ if (c === '/' && src[i + 1] === '>') { this.paint(i, i + 2); if (cls.v) this.classes.push([start, cls.v]); return i + 2; }
+ if (c === '>') { this.paint(i, i + 1); i++; break; }
+ if (c === '{') { const e = this.js(i + 1, true); if (e >= n) return JSX_EOF; this.blank(i, e + 1); i = e + 1; continue; }
+ if (!/[A-Za-z_$]/.test(c)) return -1;
+ i = this.attr(i, cls);
+ if (i < 0) return i;
+ }
+ if (cls.v) this.classes.push([start, cls.v]);
+ this.open.push(name);
+ const e = this.kids(i, name);
+ this.open.pop();
+ return e;
+ }
+ private kids(i: number, name: string): number {
+ const { src, n } = this;
+ while (i < n) {
+ const c = src[i];
+ if (c === '{') { const e = this.js(i + 1, true); if (e >= n) return JSX_EOF; i = e + 1; continue; }
+ if (c === '<') {
+ if (src[i + 1] === '/') {
+ const k = this.ws(i + 2);
+ let j = k;
+ while (j < n && /[\w$.:-]/.test(src[j])) j++;
+ const e = this.ws(j);
+ if (src[e] !== '>') { i = e; continue; }
+ const closer = src.slice(k, j);
+ if (closer === name) { if (name) this.paint(i, e + 1); return e + 1; }
+ if (this.open.lastIndexOf(closer) >= 0 && this.open.lastIndexOf(closer) < this.open.length - 1) return i;
+ i = e + 1;
+ continue;
+ }
+ if (/[A-Za-z_$>]/.test(src[i + 1] || '')) { const e = this.el(i); if (e > 0) { i = e; continue; } if (e === JSX_EOF) return JSX_EOF; }
+ i++;
+ continue;
+ }
+ this.out[i] = c;
+ if (i >= this.hi) this.hi = i + 1;
+ i++;
+ }
+ return JSX_EOF;
+ }
+}
+
+export function jsxPseudo(src: string): { pseudo: string; classAt: Map<number, string[]>; calls: number[] } {
+ const scanner = new JsxScanner(src);
+ const pseudo = scanner.pseudo();
+ return { pseudo, classAt: new Map(scanner.classes), calls: scanner.calls };
+}
+
+/** The class tokens inside each helper call (cn(...), clsx(...)) that starts at one of the sites. */
+export function classCalls(src: string, sites: number[]): ClassCall[] {
+ const out: ClassCall[] = [];
+ let last = -1;
+ for (const pos of [...sites].sort((a, b) => a - b)) {
+ if (pos < last) continue;
+ const open = src.indexOf('(', pos);
+ if (open < 0) continue;
+ let depth = 0, i = open;
+ for (; i < src.length; i++) {
+ const c = src[i];
+ if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); i = e < 0 ? src.length : e; continue; }
+ if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); i = e < 0 ? src.length : e + 1; continue; }
+ if (c === '"' || c === "'" || c === '`') { i++; while (i < src.length && src[i] !== c) { if (src[i] === '\\') i++; i++; } continue; }
+ if (c === '(') depth++;
+ else if (c === ')' && --depth === 0) break;
+ }
+ last = i;
+ const toks = clsLits(src.slice(open + 1, i));
+ if (toks.length) out.push({ pos, name: /^[\w$]+/.exec(src.slice(pos))![0], toks });
+ }
+ return out;
+}
+
+/** Positions of class-helper calls inside <script> blocks (and Astro frontmatter). */
+export function scriptSites(src: string, kind: DocKind): number[] {
+ const live = blankRanges(src, spansOf(asciiLower(src), '<!--', '-->', false).map((s): [number, number] => [s.start, s.end]));
+ const ranges = spansOf(asciiLower(live), '<script', '</script', true).map((s): [number, number] => [s.bodyStart, s.bodyEnd]);
+ const fm = kind === 'astro' ? FRONTMATTER.exec(live) : null;
+ if (fm) ranges.push([0, fm[0].length]);
+ const sites: number[] = [];
+ for (const [a, b] of ranges) {
+ for (const m of live.slice(a, b).matchAll(CLASS_FN_CALL)) sites.push(a + m.index!);
+ }
+ return sites;
+}
+
+export function docKindOf(file: string): DocKind | null {
+ const ext = path.extname(file).toLowerCase();
+ if (ext === '.html' || ext === '.htm') return 'html';
+ if (ext === '.jsx' || ext === '.tsx') return 'jsx';
+ if (ext === '.vue' || ext === '.svelte' || ext === '.astro') return ext.slice(1) as DocKind;
+ return null;
+}
+
+/** Parse a page or component file into a Doc; kind comes from the extension. */
+export function parseDoc(file: string, raw: string): Doc {
+ const kind = docKindOf(file) ?? 'html';
+ if (kind === 'jsx') {
+ const j = jsxPseudo(raw);
+ const doc = parseHtml(file, j.pseudo, 'jsx');
+ doc.styles = [];
+ doc.scripts = raw;
+ doc.classAt = j.classAt;
+ doc.virtuals = classCalls(raw, j.calls);
+ doc.raw = raw;
+ return doc;
+ }
+ const doc = parseHtml(file, kind === 'html' ? raw : templateMask(raw, kind), kind);
+ doc.raw = raw;
+ doc.virtuals = kind === 'html' ? [] : classCalls(raw, scriptSites(raw, kind));
+ return doc;
+}
+
+export function getAttr(attrStr: string, name: string): string | null {
+ const re = new RegExp(`(?:^|\\s)${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>/]+))`, 'i');
+ const m = re.exec(attrStr);
+ if (!m) return null;
+ return m[2] ?? m[3] ?? m[4] ?? '';
+}
+
+export function hasAttr(attrStr: string, name: string): boolean {
+ return new RegExp(`(?:^|\\s)${name}(?=[\\s=/]|$)`, 'i').test(attrStr);
+}
+
+/** Elements a browser closes when the same element opens again (optional end tags, and the elements that cannot nest in themselves), so a list of unclosed <li> or a run of unclosed <h2> does not read as nested. */
+const IMPLICIT_CLOSE = new Set(['li', 'p', 'dt', 'dd', 'option', 'tr', 'td', 'th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'button', 'a', 'form', 'label', 'select']);
+/** A heading start tag closes any open heading, and a block start tag closes an open <p>, as the browser does. */
+const HEADING = /^h[1-6]$/;
+const CLOSES_P = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'div', 'dl', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul']);
+/** Past this depth an open tag is read as empty: a real page nests tens deep, and a file that nests thousands deep must cost its length, not its square. */
+const MAX_DEPTH = 512;
+
+export interface Tree {
+ /** For an open tag, the index of the tag that ends it: its own close tag, the sibling that implicitly closed it, or the close tag of an ancestor; -1 when it runs to the end of the document. */
+ close: Int32Array;
+ /** For every tag, the index of the nearest open ancestor, or -1 at the top. */
+ parent: Int32Array;
+}
+
+/**
+ * Open and close tags paired once per document. A close tag pops to its own
+ * open tag, so a stray or missing end tag does not deepen everything after
+ * it, and an element with an optional end tag ends where its next sibling
+ * starts. Every tree reader (ancestors, innerOf, closeIndex, directChildren)
+ * answers from this one pairing, so they agree on every element's extent.
+ */
+export function treeOf(doc: Doc): Tree {
+ const cached = doc.cache.tree as Tree | undefined;
+ if (cached) return cached;
+ const n = doc.tags.length;
+ const close = new Int32Array(n).fill(-1);
+ const parent = new Int32Array(n).fill(-1);
+ const stack: number[] = [];
+ const openByName = new Map<string, Array<{ idx: number; depth: number }>>();
+ for (let i = 0; i < n; i++) {
+ const t = doc.tags[i];
+ if (t.close) {
+ const opens = openByName.get(t.name);
+ if (!opens) continue;
+ while (opens.length && stack[opens[opens.length - 1].depth] !== opens[opens.length - 1].idx) opens.pop();
+ if (!opens.length) continue;
+ const { depth } = opens.pop()!;
+ for (let k = stack.length - 1; k >= depth; k--) close[stack[k]] = i;
+ stack.length = depth;
+ parent[i] = stack.length ? stack[stack.length - 1] : -1;
+ continue;
+ }
+ if (stack.length) {
+ const top = doc.tags[stack[stack.length - 1]].name;
+ if ((IMPLICIT_CLOSE.has(t.name) && top === t.name) || (HEADING.test(t.name) && HEADING.test(top)) || (top === 'p' && CLOSES_P.has(t.name))) close[stack.pop()!] = i;
+ }
+ parent[i] = stack.length ? stack[stack.length - 1] : -1;
+ if (t.selfClosing) continue;
+ if (stack.length >= MAX_DEPTH) { close[i] = i; continue; }
+ let opens = openByName.get(t.name);
+ if (!opens) openByName.set(t.name, opens = []);
+ opens.push({ idx: i, depth: stack.length });
+ stack.push(i);
+ }
+ const tree = { close, parent };
+ doc.cache.tree = tree;
+ return tree;
+}
+
+/** The names of the open ancestors of the tag at idx, outermost first. */
+export function ancestorsOf(doc: Doc, idx: number): string[] {
+ const { parent } = treeOf(doc);
+ const out: string[] = [];
+ for (let p = parent[idx]; p >= 0; p = parent[p]) out.push(doc.tags[p].name);
+ return out.reverse();
+}
+
+export interface Child { name: string; open: string; html: string; idx: number }
+
+/** Where the element opened at idx ends in the source: after its own close tag, or where the tag that implicitly ended it starts. */
+function outerEnd(doc: Doc, idx: number, closeAt: number): number {
+ if (closeAt < 0) return doc.src.length;
+ const c = doc.tags[closeAt];
+ return c.close && c.name === doc.tags[idx].name ? c.end : c.pos;
+}
+
+/** The direct element children of the tag at idx, each with its open tag, outer HTML and tag index. */
+export function directChildren(doc: Doc, idx: number): Child[] {
+ const open = doc.tags[idx];
+ if (open.close || open.selfClosing) return [];
+ const { close, parent } = treeOf(doc);
+ const end = close[idx] < 0 ? doc.tags.length : close[idx];
+ const children: Child[] = [];
+ for (let i = idx + 1; i < end; i++) {
+ const t = doc.tags[i];
+ if (t.close || parent[i] !== idx) continue;
+ const openHtml = doc.src.slice(t.pos, t.end);
+ children.push({ name: t.name, open: openHtml, html: t.selfClosing ? openHtml : doc.src.slice(t.pos, outerEnd(doc, i, close[i])), idx: i });
+ }
+ return children;
+}
+
+/** Visible text of an HTML fragment with the common entities decoded and whitespace folded. */
+export function plainText(html: string): string {
+ return stripTags(html)
+ .replace(/&middot;|&#0?183;|&#x0?b7;/gi, '·').replace(/&bull;|&#8226;|&#x2022;/gi, '•').replace(/&mdash;|&#8212;|&#x2014;/gi, '\u2014').replace(/&ndash;|&#8211;|&#x2013;/gi, '\u2013')
+ .replace(/&rarr;|&#8594;|&#x2192;|&xrarr;|&#10230;/gi, '\u2192').replace(/&raquo;|&#187;|&#xbb;/gi, '\u00bb').replace(/&rsaquo;|&#8250;|&#x203a;/gi, '\u203a')
+ .replace(/&nbsp;|&#160;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
+ .replace(/&rsquo;|&lsquo;|&#8217;|&#8216;|&#x2019;|&#x2018;/gi, '\u2019').replace(/&rdquo;|&ldquo;|&#8220;|&#8221;/gi, '"')
+ .replace(/&#\d+;|&[a-z]+;/gi, ' ')
+ .replace(/\s+/g, ' ').trim();
+}
+
+/** The inner HTML of the element opened at idx and the position its close tag starts. */
+export function innerOf(doc: Doc, idx: number): { inner: string; endPos: number } | null {
+ const open = doc.tags[idx];
+ if (open.close || open.selfClosing) return null;
+ const c = treeOf(doc).close[idx];
+ const endPos = c < 0 ? doc.src.length : doc.tags[c].pos;
+ return { inner: doc.src.slice(open.end, endPos), endPos };
+}
+
+/** The visible text of the element opened at idx, computed once per element however many rules read it; '' for a close or void tag. */
+export function textOf(doc: Doc, idx: number): string {
+ const cache = (doc.cache.text ??= new Map<number, string>()) as Map<number, string>;
+ const hit = cache.get(idx);
+ if (hit != null) return hit;
+ const text = plainText(innerOf(doc, idx)?.inner || '');
+ cache.set(idx, text);
+ return text;
+}
+
+export interface Element { idx: number; tag: Tag; inner: string }
+
+/** The elements opened by a tag named by `name` between tag indices from and to, each with its inner HTML from the shared pairing; a tag walk, so an unclosed element costs its own extent and nothing scans to the end of the file for it. */
+export function openTags(doc: Doc, name: RegExp, from = 0, to = doc.tags.length, pick: (t: Tag) => boolean = () => true): Element[] {
+ const out: Element[] = [];
+ for (let i = from; i < to; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !name.test(t.name) || !pick(t)) continue;
+ const inner = innerOf(doc, i);
+ if (inner) out.push({ idx: i, tag: t, inner: inner.inner });
+ }
+ return out;
+}
+
+/** The index of the tag that ends the element opened at idx: its close tag, or the tag that implicitly closed it (or the last tag when nothing does). */
+export function closeIndex(doc: Doc, idx: number): number {
+ const c = treeOf(doc).close[idx];
+ return c < 0 ? doc.tags.length - 1 : c;
+}
+
+// sloplint proseRun
+const proseRun = (run: string): string => {
+ let r = run;
+ for (let k = 0; k < 3 && /\{[^{}]*\}/.test(r); k++) r = r.replace(/\{[^{}]*\}/g, pad);
+ return /[;=(){}]|\breturn\b/.test(r) ? pad(r) : r;
+};
+
+const CODE_ELEMENTS = ['script', 'style', 'pre', 'code', 'kbd', 'samp', 'textarea'];
+
+/** The document's prose: tags, comments, scripts, styles and code blanked with positions preserved; component text runs that read as code are blanked too. */
+// sloplint maskedProse
+export function maskedProse(doc: Doc): string {
+ const cached = doc.cache.prose as string | undefined;
+ if (cached != null) return cached;
+ let prose = doc.kind !== 'html' ? doc.src.replace(/(^|>)([^<>]*)(?=<|$)/g, (_m0, a: string, run: string) => a + proseRun(run)) : doc.src;
+ for (const name of CODE_ELEMENTS) prose = blankRanges(prose, spansOf(asciiLower(prose), '<' + name, '</' + name, true).map((s): [number, number] => [s.start, s.end]));
+ prose = stripTags(prose, true);
+ doc.cache.prose = prose;
+ return prose;
+}
+
+export const wordsOf = (t: string): string[] => plainText(t).split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w));
diff --git a/lib/design-lint/index.ts b/lib/design-lint/index.ts
new file mode 100644
index 000000000..e3a374cb1
--- /dev/null
+++ b/lib/design-lint/index.ts
@@ -0,0 +1,69 @@
+/**
+ * gstack's free design lint: the deterministic gates behind /design-html and
+ * /design-review. The static tier reads HTML, CSS and component files and runs
+ * in well under a second; the render tier (--render) measures the page in
+ * gstack's own browser. One contract for both:
+ *
+ * LINT: <blocks|ask|polish|waived> <rule-id> <file>:<line> <evidence> | fix: <fix>
+ * LINT_SUMMARY: blocks=N ask=N waived=N polish=N render=<ran|skipped: reason>
+ *
+ * Exit 2 when anything blocks, 1 when an ask is unanswered, 0 otherwise.
+ * docs/design-lint.md is the user-facing contract.
+ */
+import { docKindOf } from './html';
+import { lintRender, type RenderOptions } from './render';
+import { exitCodeOf, finalize, formatFinding, formatSummary, oneLine, relPath, summarize, type Finding, type Summary } from './report';
+import { lintStaticRaw, realDir, settleContext, type StaticOptions } from './static';
+
+export interface LintOptions extends StaticOptions {
+ render?: boolean;
+ urls?: string[];
+ /** Replaces the render engine choice (tests inject one). */
+ engine?: RenderOptions['engine'];
+ /** Replaces the render page runner (tests inject one). */
+ run?: RenderOptions['run'];
+}
+
+export interface LintResult {
+ files: string[];
+ findings: Finding[];
+ summary: Summary;
+ exitCode: 0 | 1 | 2;
+}
+
+/**
+ * Both tiers, then the page's waivers once over both: a waiver on a blocking
+ * rule that only the render tier suspects is honoured, and one the render tier
+ * measures for real is refused, because the page's findings are settled after
+ * every measurement is in.
+ */
+export async function lint(paths: string[], opts: LintOptions = {}): Promise<LintResult> {
+ const cwd = realDir(opts.cwd ?? process.cwd());
+ const stat = lintStaticRaw(paths, opts);
+ let render = 'skipped: not requested';
+ const byPage = new Map<string, Finding[]>();
+ if (opts.render || opts.urls?.length) {
+ const pages = stat.files.filter((f) => docKindOf(f) === 'html');
+ const r = await lintRender([...pages, ...(opts.urls ?? [])], { cwd, scope: opts.scope, engine: opts.engine, run: opts.run });
+ render = r.status;
+ for (const f of r.findings) byPage.set(f.file, [...(byPage.get(f.file) ?? []), f]);
+ }
+ const findings: Finding[] = [];
+ stat.contexts.forEach((ctx, i) => {
+ const page = ctx.docs.length === 1 && ctx.docs[0].kind === 'html' ? oneLine(relPath(ctx.key, cwd)) : null;
+ const measured = page ? byPage.get(page) ?? [] : [];
+ if (page) byPage.delete(page);
+ findings.push(...settleContext(ctx, [...stat.raw[i], ...measured], cwd));
+ });
+ for (const rest of byPage.values()) findings.push(...rest);
+ findings.push(...stat.skipped);
+ const final = finalize(findings);
+ const summary = summarize(final, render);
+ return { files: stat.files, findings: final, summary, exitCode: exitCodeOf(summary) };
+}
+
+export function formatResult(result: LintResult): string {
+ return [...result.findings.map(formatFinding), formatSummary(result.summary)].join('\n');
+}
+
+export { formatFinding, formatSummary, type Finding, type Summary } from './report';
diff --git a/lib/design-lint/render-png.ts b/lib/design-lint/render-png.ts
new file mode 100644
index 000000000..d1c507c23
--- /dev/null
+++ b/lib/design-lint/render-png.ts
@@ -0,0 +1,78 @@
+/**
+ * A small PNG reader for the render tier: 8-bit greyscale, RGB, palette and
+ * alpha variants, non-interlaced, inflated with node:zlib. Enough to sample
+ * the pixels behind a run of text or around a focus ring in a screenshot the
+ * browser took; anything else returns null and the caller keeps its computed
+ * estimate.
+ */
+import { inflateSync } from 'node:zlib';
+
+export interface Png { width: number; height: number; channels: number; data: Uint8Array }
+
+export interface SampleRect { x: number; y: number; w: number; h: number; inner?: { l: number; t: number; r: number; b: number } }
+
+const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+
+export function decodePng(buf: Uint8Array): Png | null {
+ if (buf.length < 8 || SIGNATURE.some((b, i) => buf[i] !== b)) return null;
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
+ let width = 0, height = 0, depth = 0, colorType = 0, interlace = 0;
+ let palette: Uint8Array | null = null;
+ const idat: Uint8Array[] = [];
+ for (let pos = 8; pos + 8 <= buf.length;) {
+ const len = view.getUint32(pos);
+ const type = String.fromCharCode(buf[pos + 4], buf[pos + 5], buf[pos + 6], buf[pos + 7]);
+ const body = buf.subarray(pos + 8, pos + 8 + len);
+ if (type === 'IHDR') { width = view.getUint32(pos + 8); height = view.getUint32(pos + 12); depth = buf[pos + 16]; colorType = buf[pos + 17]; interlace = buf[pos + 20]; }
+ else if (type === 'PLTE') palette = body;
+ else if (type === 'IDAT') idat.push(body);
+ else if (type === 'IEND') break;
+ pos += 12 + len;
+ }
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[colorType];
+ if (!width || !height || depth !== 8 || interlace !== 0 || !channels || (colorType === 3 && !palette)) return null;
+ let raw: Uint8Array;
+ try { raw = inflateSync(Buffer.concat(idat.map((c) => Buffer.from(c)))); } catch { return null; }
+ const stride = width * channels;
+ if (raw.length < (stride + 1) * height) return null;
+ const out = new Uint8Array(stride * height);
+ for (let y = 0; y < height; y++) {
+ const filter = raw[y * (stride + 1)];
+ const src = y * (stride + 1) + 1, dst = y * stride, prev = (y - 1) * stride;
+ for (let i = 0; i < stride; i++) {
+ const x = raw[src + i];
+ const a = i >= channels ? out[dst + i - channels] : 0;
+ const b = y > 0 ? out[prev + i] : 0;
+ const c = y > 0 && i >= channels ? out[prev + i - channels] : 0;
+ let v: number;
+ if (filter === 0) v = x;
+ else if (filter === 1) v = x + a;
+ else if (filter === 2) v = x + b;
+ else if (filter === 3) v = x + ((a + b) >> 1);
+ else if (filter === 4) { const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c); }
+ else return null;
+ out[dst + i] = v & 255;
+ }
+ }
+ if (colorType !== 3) return { width, height, channels, data: out };
+ const rgb = new Uint8Array(width * height * 3);
+ for (let i = 0; i < width * height; i++) { const p = out[i] * 3; rgb[i * 3] = palette![p]; rgb[i * 3 + 1] = palette![p + 1]; rgb[i * 3 + 2] = palette![p + 2]; }
+ return { width, height, channels: 3, data: rgb };
+}
+
+/** The median colour (0..1 per channel) of a rectangle, leaving out an inner rectangle when one is given; null when nothing is sampled. */
+export function medianRgb(png: Png, rect: SampleRect): number[] | null {
+ const x0 = Math.max(0, Math.floor(rect.x)), y0 = Math.max(0, Math.floor(rect.y));
+ const x1 = Math.min(png.width, Math.ceil(rect.x + rect.w)), y1 = Math.min(png.height, Math.ceil(rect.y + rect.h));
+ const hist = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
+ const grey = png.channels < 3;
+ let n = 0;
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
+ if (rect.inner) { const ix = x - rect.x, iy = y - rect.y; if (ix >= rect.inner.l && ix < rect.inner.r && iy >= rect.inner.t && iy < rect.inner.b) continue; }
+ const i = (y * png.width + x) * png.channels;
+ hist[0][png.data[i]]++; hist[1][png.data[grey ? i : i + 1]]++; hist[2][png.data[grey ? i : i + 2]]++;
+ n++;
+ }
+ if (!n) return null;
+ return hist.map((h) => { let seen = 0; for (let v = 0; v < 256; v++) { seen += h[v]; if (seen > n >> 1) return v / 255; } return 1; });
+}
diff --git a/lib/design-lint/render-probe-quality.ts b/lib/design-lint/render-probe-quality.ts
new file mode 100644
index 000000000..e44719aa0
--- /dev/null
+++ b/lib/design-lint/render-probe-quality.ts
@@ -0,0 +1,193 @@
+/**
+ * The render tier's in-page measurements of quality at 1440: heading rhythm,
+ * cramped boxes, over-long prose lines, weak field edges, text that strains,
+ * the weight count and the lonely grid item. Same rules as render-probe.ts:
+ * each function is serialised into the page and may touch nothing outside its
+ * arguments.
+ *
+ * Ported from Nutlope/hallmark's sloplint-render.mjs observeQuality (MIT, see
+ * NOTICE.md): gates 71, 72, 25, 40 (field edges), 75, F19, F20.
+ */
+import type { ProbeFinding, Probes } from './render-probe';
+
+// sloplint-render observeQuality: the quality checks in one eval
+export function glQuality(P: Probes): ProbeFinding[] {
+ const { vis } = P.H;
+ const quiet = (el: Element) => !!el.closest('script, style, noscript, [aria-hidden="true"], dialog:not([open])') || !!(el.parentElement && el.parentElement.closest('svg'));
+ const all = Array.from(document.body.querySelectorAll('*')).filter((el) => !quiet(el) && vis(el));
+ return [...P.rhythm(P, all), ...P.padding(P, all), ...P.prose(P, all), ...P.fields(P, all), ...P.strain(P), ...P.grid(P, all)];
+}
+
+// sloplint-render observeQuality, the crowded head (gate 71)
+export function glRhythm(P: Probes, all: Element[]): ProbeFinding[] {
+ const { vis, name, text, clear, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const quiet = (el: Element) => !!el.closest('script, style, noscript, [aria-hidden="true"], dialog:not([open])') || !!(el.parentElement && el.parentElement.closest('svg'));
+ const abs = (r: DOMRect) => ({ top: r.top + scrollY, bottom: r.bottom + scrollY, left: r.left, right: r.right });
+ const boxes: Array<{ el: Element; top: number; bottom: number; left: number; right: number }> = [];
+ for (const el of all) {
+ const media = /^(IMG|svg|CANVAS|VIDEO|PICTURE|IFRAME|INPUT|BUTTON|SELECT|TEXTAREA)$/.test(el.tagName) || el.hasAttribute('data-slot');
+ if (!media && !Array.from(el.childNodes).some((n) => n.nodeType === 3 && (n.textContent || '').trim())) continue;
+ boxes.push({ el, ...abs(el.getBoundingClientRect()) });
+ }
+ const overlapX = (a: { left: number; right: number }, b: { left: number; right: number }) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 8;
+ const crowded: Array<{ text: string; el: Element }> = [];
+ for (const h of document.querySelectorAll('h2, h3, h4')) {
+ if (!vis(h) || quiet(h) || h.closest('nav, footer, table, [data-slot]')) continue;
+ let small = false;
+ for (let p = h.parentElement; p && p !== document.body; p = p.parentElement) {
+ const cs = getComputedStyle(p);
+ if (!clear(cs.backgroundColor) || parseFloat(cs.borderTopWidth) > 0 || cs.boxShadow !== 'none') { small = p.getBoundingClientRect().height < 200; break; }
+ }
+ if (small) continue;
+ const hb = abs(h.getBoundingClientRect());
+ let above: typeof boxes[number] | null = null, below: typeof boxes[number] | null = null;
+ for (const b of boxes) {
+ if (h.contains(b.el) || b.el.contains(h) || !overlapX(b, hb)) continue;
+ if (b.bottom <= hb.top + 1 && (!above || b.bottom > above.bottom)) above = b;
+ if (b.top >= hb.bottom - 1 && (!below || b.top < below.top)) below = b;
+ }
+ if (!above || !below) continue;
+ const up = hb.top - above.bottom, down = below.top - hb.bottom;
+ if (down < 6 || down > 160) continue;
+ if (up < 0.75 * down && down - up >= 12) crowded.push({ text: name(h) + ' "' + text(h).slice(0, 18) + '" ' + Math.round(up) + 'px over, ' + Math.round(down) + 'px under', el: h });
+ }
+ if (crowded.length >= 2) out.push({ rule: 'heading-rhythm', grade: 'fail', evidence: 'heads nearer what precedes them than what they head: ' + crowded.slice(0, 2).map((c) => c.text).join('; '), at: at(crowded[0].el) });
+ return out;
+}
+
+// sloplint-render observeQuality, the cramped box (gate 72)
+export function glPadding(P: Probes, all: Element[]): ProbeFinding[] {
+ const { vis, name, clear, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const tight: Array<{ text: string; el: Element }> = [];
+ for (const el of all) {
+ if (tight.length >= 3) break;
+ if (/^(SECTION|MAIN|HEADER|FOOTER|NAV|ARTICLE|INPUT|TEXTAREA|SELECT|svg|IMG|TABLE|THEAD|TBODY|TR|TD|TH|PRE|CODE|IFRAME|VIDEO|CANVAS|DIALOG)$/.test(el.tagName) || el.closest('[data-slot], table')) continue;
+ const r = el.getBoundingClientRect();
+ if (r.width <= 100 || r.height <= 30 || r.width > innerWidth * 0.9) continue;
+ const cs = getComputedStyle(el);
+ if (cs.display === 'inline') continue;
+ if (/auto|scroll/.test(cs.overflowX + cs.overflowY)) continue;
+ const bw = [cs.borderTopWidth, cs.borderRightWidth, cs.borderBottomWidth, cs.borderLeftWidth].map((v) => parseFloat(v) || 0);
+ const bc = [cs.borderTopColor, cs.borderRightColor, cs.borderBottomColor, cs.borderLeftColor];
+ const inked = (k: number) => bw[k] >= 1 && !clear(bc[k]);
+ let under = 'rgb(255, 255, 255)';
+ for (let p = el.parentElement; p; p = p.parentElement) { const c = getComputedStyle(p).backgroundColor; if (!clear(c)) { under = c; break; } }
+ const filled = !clear(cs.backgroundColor) && cs.backgroundColor !== under;
+ if (!filled && !(inked(1) && inked(3))) continue;
+ let L = Infinity, T = Infinity, Rr = -Infinity, B = -Infinity, fs = parseFloat(cs.fontSize) || 16;
+ const walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ for (let t = walk.nextNode(); t; t = walk.nextNode()) {
+ const host = t.parentElement;
+ if (!(t.textContent || '').trim() || !host || host.closest('svg') || !vis(host)) continue;
+ let nested = false;
+ for (let p: Element | null = host; p && p !== el; p = p.parentElement) {
+ const ps = getComputedStyle(p);
+ if (/absolute|fixed/.test(ps.position) || (!clear(ps.backgroundColor) && ps.backgroundColor !== cs.backgroundColor) || (parseFloat(ps.borderTopWidth) >= 1 && parseFloat(ps.borderLeftWidth) >= 1)) { nested = true; break; }
+ }
+ if (nested) continue;
+ const rg = document.createRange(); rg.selectNodeContents(t);
+ const hf = parseFloat(getComputedStyle(host).fontSize) || 16; const trim = hf >= 40 ? 0.2 * hf : 0;
+ for (const q of rg.getClientRects()) { if (!q.width || !q.height) continue; L = Math.min(L, q.left); T = Math.min(T, q.top + trim); Rr = Math.max(Rr, q.right); B = Math.max(B, q.bottom - trim); fs = hf; }
+ }
+ if (L === Infinity) continue;
+ const side = Math.max(8, Math.min(0.5 * fs, 24)) - 0.5, end = Math.max(4, Math.min(0.3 * fs, 12)) - 0.5;
+ const inset: Array<[string, number, number]> = [['left', L - (r.left + bw[3]), side], ['right', r.right - bw[1] - Rr, side], ['top', T - (r.top + bw[0]), end], ['bottom', r.bottom - bw[2] - B, end]];
+ const short = inset.filter(([, v, min]) => v < min);
+ if (short.length) tight.push({ text: name(el) + ' ' + short.map(([k, v]) => k + ' ' + Math.round(v) + 'px').join(', '), el });
+ }
+ if (tight.length) out.push({ rule: 'cramped-padding', grade: 'fail', evidence: 'text crowds the edge of its box: ' + tight.map((t) => t.text).join('; '), fix: 'pad the box: max(8px, 0.5em) at the sides, max(4px, 0.3em) above and below', at: at(tight[0].el) });
+ return out;
+}
+
+// sloplint-render observeQuality, running prose set too wide (gate 25)
+export function glProse(P: Probes, all: Element[]): ProbeFinding[] {
+ const { name, text, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const long: Array<{ text: string; el: Element }> = [];
+ for (const el of all) {
+ if (long.length >= 2 || el.tagName !== 'P' || el.closest('nav, footer, table, figure, [data-slot]')) continue;
+ const t = text(el);
+ if (t.length < 240) continue;
+ const cs = getComputedStyle(el);
+ const lh = parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.4;
+ let cols = 1;
+ for (let q: Element | null = el; q && q !== document.body && cols === 1; q = q.parentElement) { const qc = getComputedStyle(q); if (qc.columnCount !== 'auto' || qc.columnWidth !== 'auto') cols = Math.max(1, Math.round(q.getBoundingClientRect().width / Math.max(1, (el.getClientRects()[0] && el.getClientRects()[0].width) || q.getBoundingClientRect().width))); }
+ const lines = Math.round(el.getBoundingClientRect().height / lh) * cols;
+ if (lines >= 3 && t.length / lines > 88) long.push({ text: name(el) + ' about ' + Math.round(t.length / lines) + ' characters a line', el });
+ }
+ if (long.length) out.push({ rule: 'line-length', grade: 'fail', evidence: 'running prose set too wide: ' + long.map((l) => l.text).join(', '), fix: 'cap the measure at 45 to 75ch', at: at(long[0].el) });
+ return out;
+}
+
+// sloplint-render observeQuality, a field's edge under 3:1 (gate 40)
+export function glFields(P: Probes, all: Element[]): ProbeFinding[] {
+ const { name, rgb, ratio, over, bgOf, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const weak: Array<{ text: string; el: Element }> = [];
+ const fields = all.filter((el) => /^(TEXTAREA|SELECT)$/.test(el.tagName) || (el.tagName === 'INPUT' && /^(text|email|search|tel|url|password|number|date|time)$/.test((el as HTMLInputElement).type)));
+ for (const f of fields) {
+ const fh = f.getBoundingClientRect().height;
+ const around = bgOf(f.parentElement);
+ let best = ratio(over(rgb(getComputedStyle(f).backgroundColor), around), around);
+ for (let n: Element | null = f, d = 0; n && d < 3 && n.getBoundingClientRect().height <= fh + 48; n = n.parentElement, d++) {
+ const cs = getComputedStyle(n); const back = d ? bgOf(n.parentElement) : around;
+ const sides: Array<[string, string, string]> = [[cs.borderTopWidth, cs.borderTopStyle, cs.borderTopColor], [cs.borderRightWidth, cs.borderRightStyle, cs.borderRightColor], [cs.borderBottomWidth, cs.borderBottomStyle, cs.borderBottomColor], [cs.borderLeftWidth, cs.borderLeftStyle, cs.borderLeftColor]];
+ for (const [w, s, c] of sides) if (parseFloat(w) >= 1 && s !== 'none') best = Math.max(best, ratio(over(rgb(c), back), back));
+ for (const m of (cs.boxShadow || '').matchAll(/((?:rgba?|oklch|oklab|color)\([^)]*\)|#[0-9a-f]{3,8})\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px\s+(-?[\d.]+)px/gi)) if (+m[4] === 0 && (+m[5] >= 1 || Math.abs(+m[3]) >= 1)) best = Math.max(best, ratio(over(rgb(m[1]), back), back));
+ }
+ if (best < 2.95) weak.push({ text: name(f) + ' ' + best.toFixed(2) + ':1', el: f });
+ }
+ if (weak.length) out.push({ rule: 'low-contrast', grade: 'fail', evidence: 'a field\'s edge is under 3:1 against what surrounds it: ' + weak.slice(0, 3).map((w) => w.text).join(', '), fix: 'draw the field in the muted token, or fill it a step off the surface it sits on', at: at(weak[0].el) });
+ return out;
+}
+
+// sloplint-render observeQuality, text that strains and the weight count (gates 75 and F19)
+export function glStrain(P: Probes): ProbeFinding[] {
+ const { vis, name, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const quiet = (el: Element) => !!el.closest('script, style, noscript, [aria-hidden="true"], dialog:not([open])') || !!(el.parentElement && el.parentElement.closest('svg'));
+ const weights = new Map<number, number>();
+ const strained: Array<{ el: Element; why: string }> = [];
+ const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ for (let t = tw.nextNode(); t; t = tw.nextNode()) {
+ const host = t.parentElement; const txt = (t.textContent || '').trim();
+ if (!txt || !host || quiet(host) || host.closest('svg') || !vis(host)) continue;
+ const hs = getComputedStyle(host);
+ const w = Math.round((parseFloat(hs.fontWeight) || 400) / 100) * 100;
+ weights.set(w, (weights.get(w) || 0) + txt.length);
+ if (strained.length >= 4 || txt.length < 3 || host.closest('sup, sub, [data-slot], figure svg') || strained.some((x) => x.el === host)) continue;
+ const size = parseFloat(hs.fontSize) || 16;
+ const prose = !!host.closest('p, li, dd, blockquote') && txt.length > 60 && size < 28;
+ const lh = parseFloat(hs.lineHeight);
+ if (size < 11 || (prose && size < 12)) strained.push({ el: host, why: name(host) + ' at ' + Math.round(size * 10) / 10 + 'px' });
+ else if (prose && lh && lh / size < 1.3 && host.getBoundingClientRect().height > lh * 2.2) strained.push({ el: host, why: name(host) + ' leaded ' + (lh / size).toFixed(2) });
+ }
+ if (strained.length) out.push({ rule: 'tiny-text', grade: 'fail', evidence: 'text that strains the eye: ' + strained.map((x) => x.why).join(', '), fix: 'running text 12px or more (16px for body), functional text 11px or more, multi-line prose leaded 1.3 or more', at: at(strained[0].el) });
+ const used = Array.from(weights).filter(([, n]) => n >= 30).map(([w]) => w).sort((a, b) => a - b);
+ if (used.length > 3) out.push({ rule: 'font-weight-count', grade: 'warn', evidence: used.length + ' font weights in running use (' + used.join(', ') + ')', fix: 'three weights at most, display and body together, picked as extremes' });
+ return out;
+}
+
+// sloplint-render observeQuality, the lonely grid item (gate F20)
+export function glGrid(P: Probes, all: Element[]): ProbeFinding[] {
+ const { vis, name, at } = P.H;
+ const out: ProbeFinding[] = [];
+ for (const g of all) {
+ const cs = getComputedStyle(g);
+ const grid = /grid/.test(cs.display);
+ const wrap = /flex/.test(cs.display) && cs.flexWrap === 'wrap' && cs.flexDirection.startsWith('row');
+ if ((!grid && !wrap) || g.closest('nav, footer, form')) continue;
+ const kids = Array.from(g.children).filter((c) => vis(c) && !/absolute|fixed/.test(getComputedStyle(c).position));
+ if (kids.length < 3) continue;
+ const rects = kids.map((c) => c.getBoundingClientRect());
+ if (grid && Math.max(...rects.map((r) => r.width)) > Math.min(...rects.map((r) => r.width)) * 1.15) continue;
+ if (wrap && !kids.every((c) => c.querySelector('img, svg') || /^(IMG|svg)$/.test(c.tagName) || c.getBoundingClientRect().width >= 120)) continue;
+ const rows: Array<{ top: number; n: number }> = [];
+ for (const r of rects) { const row = rows.find((x) => Math.abs(x.top - r.top) < 4); if (row) row.n++; else rows.push({ top: r.top, n: 1 }); }
+ rows.sort((a, b) => a.top - b.top);
+ if (rows.length >= 2 && rows[rows.length - 1].n === 1 && rows[rows.length - 2].n >= 2) { out.push({ rule: 'lonely-grid-item', grade: 'warn', evidence: name(g) + ' leaves one item alone on its last row (' + rows.map((x) => x.n).join(' + ') + ')', at: at(g) }); break; }
+ }
+ return out;
+}
diff --git a/lib/design-lint/render-probe-space.ts b/lib/design-lint/render-probe-space.ts
new file mode 100644
index 000000000..47fe5b989
--- /dev/null
+++ b/lib/design-lint/render-probe-space.ts
@@ -0,0 +1,451 @@
+/**
+ * The render tier's in-page measurements of space: the hero, the word budget,
+ * slots and slivers, drawn illustrations, empty pictures, counting marks, the
+ * photo wall, the dead band, thin sections and the 1920 checks. Same rules as
+ * render-probe.ts: each function is serialised into the page and may touch
+ * nothing outside its arguments.
+ *
+ * Ported from Nutlope/hallmark's sloplint-render.mjs observeSpace (MIT, see
+ * NOTICE.md): gates 44a, 44c, 44d, 58, 59, 77, 78, 79, 80, 81, 82, 83, F17, F18.
+ * The posture, hero-shape, photo-shape and job guards are gone: the strict
+ * form applies.
+ */
+import type { ProbeFinding, Probes } from './render-probe';
+
+export interface Box { top: number; bottom: number; left: number; right: number }
+export interface Fig extends Box { w: number; h: number; el: Element; side: 'left' | 'right'; colEdge: number }
+
+export interface HeroCtx {
+ secs: Element[];
+ hero: Element | null;
+ h1: HTMLElement | null;
+ heroEnd: number | null;
+ /** Text blocks in the hero before its first action. */
+ stack: number;
+ textBox: Box | null;
+ fig: Fig | null;
+ /** The painted extent of a section's content, in page coordinates. */
+ content: (s: Element) => { top: number; bottom: number };
+}
+
+// sloplint-render observeSpace, the hero: its sections, text block, visual and content extents
+export function glHero(P: Probes): HeroCtx {
+ const { vis, abs, text } = P.H;
+ const vw = innerWidth;
+ let secs = Array.from(document.querySelectorAll('section, main > div, footer')).filter((s) => vis(s) && s.getBoundingClientRect().height > 40);
+ secs = secs.filter((s) => !secs.some((o) => o !== s && o.contains(s)));
+ const h1 = document.querySelector('h1');
+ const heroish = (el: Element) => /^(SECTION|HEADER)$/.test(el.tagName) || Array.from(el.classList).some((c) => /^hero(-[\w-]+)?$/i.test(c) || /(^|-)hero$/i.test(c));
+ let hero: Element | null = null;
+ for (let n: Element | null = h1; n && n !== document.body; n = n.parentElement) if (heroish(n)) { hero = n; break; }
+ hero = hero || Array.from(document.querySelectorAll('section, header, [class]')).find(heroish) || secs[0] || null;
+ const heroEnd = hero ? abs(hero).bottom : null;
+ let stack = 0, textBox: Box | null = null;
+ const best: { fig: Fig | null; area: number } = { fig: null, area: 0 };
+ if (hero && h1) {
+ const cta = Array.from(hero.querySelectorAll('a, button')).filter((c) => vis(c) && (c.textContent || '').trim() && !c.closest('nav'))[0];
+ const ctaTop = cta ? abs(cta).top : Infinity;
+ const texts = Array.from(hero.querySelectorAll('h1, h2, p, small, [class*="sub"], [class*="lede"], [class*="eyebrow"], [class*="kicker"], [class*="label"]')).filter((e) => vis(e) && text(e) && !e.closest('nav, svg, table, figure, [data-slot], form, fieldset, label, output, [role="tabpanel"], [role="group"]') && abs(e).top < ctaTop);
+ const seen: Element[] = [];
+ for (const e of texts) { if (seen.some((o) => o.contains(e) || e.contains(o))) continue; seen.push(e); }
+ stack = seen.length;
+ const ink = (el: Element): Box => {
+ let L = Infinity, T = Infinity, R = -Infinity, B = -Infinity;
+ const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ for (let t = w.nextNode(); t; t = w.nextNode()) { if (!(t.textContent || '').trim() || t.parentElement!.closest('svg')) continue; const rg = document.createRange(); rg.selectNodeContents(t); for (const q of rg.getClientRects()) { if (!q.width || !q.height) continue; L = Math.min(L, q.left); T = Math.min(T, q.top); R = Math.max(R, q.right); B = Math.max(B, q.bottom); } }
+ return L === Infinity ? abs(el) : { top: T + scrollY, bottom: B + scrollY, left: L, right: R };
+ };
+ const boxes = [h1, ...seen.filter((e) => Math.abs(abs(e).left - abs(h1).left) < 40)].map(ink);
+ const tb: Box = { top: Math.min(...boxes.map((b) => b.top)), bottom: Math.max(...boxes.map((b) => b.bottom), cta ? abs(cta).bottom : 0), left: Math.min(...boxes.map((b) => b.left)), right: Math.max(...boxes.map((b) => b.right)) };
+ textBox = tb;
+ const clipped = (el: Element) => { const r = el.getBoundingClientRect(); let L = r.left, T = r.top, R = r.right, B = r.bottom; for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) { const cs = getComputedStyle(p); if (/hidden|clip/.test(cs.overflow + ' ' + cs.overflowX + ' ' + cs.overflowY)) { const q = p.getBoundingClientRect(); L = Math.max(L, q.left); T = Math.max(T, q.top); R = Math.min(R, q.right); B = Math.min(B, q.bottom); } } R = Math.min(R, vw); return { top: T + scrollY, bottom: B + scrollY, left: L, right: R, w: Math.max(0, R - L), h: Math.max(0, B - T) }; };
+ const beside = (b: Box) => b.left >= tb.right - 40 || b.right <= tb.left + 40;
+ const consider = (e: Element) => {
+ if (!vis(e) || e.closest('nav') || e.contains(h1) || seen.some((t) => e.contains(t))) return;
+ const b = clipped(e); const a = b.w * b.h;
+ if (b.w > 160 && b.h > 120 && a > best.area && b.w < vw * 0.95 && beside(b)) { best.fig = { ...b, el: e, side: 'right', colEdge: 0 }; best.area = a; }
+ };
+ for (const e of hero.querySelectorAll('svg, canvas, img, figure, video, picture, [data-slot], [class*="fig"], [class*="visual"], [class*="device"], [class*="demo"], [class*="shot"], [class*="illus"], [class*="panel"]')) consider(e);
+ if (!best.fig) {
+ const heroBg = getComputedStyle(hero).backgroundColor;
+ for (const e of hero.querySelectorAll('div, span, aside, i, b')) {
+ const cs = getComputedStyle(e);
+ if (cs.backgroundImage !== 'none' || (cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== heroBg) || parseFloat(cs.borderTopWidth) > 0) consider(e);
+ }
+ }
+ const f = best.fig;
+ if (f) {
+ f.side = f.left >= tb.right - 40 ? 'right' : 'left';
+ let lca = h1.parentElement;
+ while (lca && !lca.contains(f.el)) lca = lca.parentElement;
+ let col: Element = h1;
+ while (col.parentElement && col.parentElement !== lca) col = col.parentElement;
+ const cb = abs(col);
+ f.colEdge = f.side === 'right' ? Math.max(tb.right, cb.right) : Math.min(tb.left, cb.left);
+ }
+ }
+ const clipAbs = (el: Element, stop: Element) => { const r0 = el.getBoundingClientRect(); let T = r0.top, B = r0.bottom; for (let q = el.parentElement; q && q !== document.body; q = q.parentElement) { const cs = getComputedStyle(q); if (/hidden|clip/.test(cs.overflow + ' ' + cs.overflowY)) { const qr = q.getBoundingClientRect(); T = Math.max(T, qr.top); B = Math.min(B, qr.bottom); } if (q === stop) break; } return { top: T + scrollY, bottom: B + scrollY }; };
+ const content = (s: Element) => {
+ let top = Infinity, bottom = -Infinity;
+ for (const c of s.querySelectorAll('*')) {
+ if (!vis(c)) continue;
+ const painted = text(c) || /^(SVG|IMG|CANVAS|VIDEO)$/i.test(c.tagName) || getComputedStyle(c).backgroundColor !== 'rgba(0, 0, 0, 0)';
+ if (!painted) continue;
+ if (c.children.length && !Array.from(c.childNodes).some((n) => n.nodeType === 3 && (n.textContent || '').trim()) && !/^svg$/i.test(c.tagName) && getComputedStyle(c).backgroundColor === 'rgba(0, 0, 0, 0)') continue;
+ const b = clipAbs(c, s);
+ if (b.bottom <= b.top) continue;
+ top = Math.min(top, b.top); bottom = Math.max(bottom, b.bottom);
+ }
+ return top === Infinity ? abs(s) : { top, bottom };
+ };
+ return { secs, hero, h1, heroEnd, stack, textBox, fig: best.fig, content };
+}
+
+// sloplint-render observeSpace at 1440 and 1920: the space checks in one eval
+export function glSpace(P: Probes, atLaptop: boolean): ProbeFinding[] {
+ const ctx = P.hero(P);
+ if (!atLaptop) return P.wide(P, ctx);
+ return [...P.words(P, ctx), ...P.slots(P), ...P.pictures(P), ...P.marks(P), ...P.photos(P, ctx), ...P.heroSpace(P, ctx), ...P.thin(P, ctx), ...P.gaps(P, ctx)];
+}
+
+// sloplint-render observeSpace, the gaps between sections at 1440 and the section count (gate 59)
+export function glGaps(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { at } = P.H;
+ const out: ProbeFinding[] = [];
+ const { secs, content } = ctx;
+ const paperOf = (el: Element): string => {
+ for (let q: Element | null = el; q; q = q.parentElement) {
+ const cs = getComputedStyle(q);
+ if (/gradient|url\(/.test(cs.backgroundImage)) return cs.backgroundColor + '|' + cs.backgroundImage;
+ if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(cs.backgroundColor)) return cs.backgroundColor;
+ }
+ return 'none';
+ };
+ const gaps: number[] = [], shifts: boolean[] = [];
+ for (let i = 0; i < secs.length - 1; i++) {
+ gaps.push(Math.round(content(secs[i + 1]).top - content(secs[i]).bottom));
+ shifts.push(paperOf(secs[i]) !== paperOf(secs[i + 1]));
+ }
+ const real = gaps.filter((g) => g > -50);
+ const short = gaps.filter((g, i) => g > -50 && g < (shifts[i] ? 64 : 112));
+ if (real.length) {
+ if (short.length) {
+ const i = gaps.indexOf(Math.min(...short));
+ out.push({ rule: 'section-gap', grade: 'fail', evidence: 'the smallest gap between sections is ' + Math.min(...short) + 'px (gaps: ' + real.join(', ') + ')', fix: '120px or more between sections (64px where the paper changes)', at: at(secs[i + 1]) });
+ } else if (real.length > 2 && new Set(real).size === 1) {
+ out.push({ rule: 'section-gap', grade: 'fail', evidence: 'every section gap is ' + real[0] + 'px', fix: 'vary the rhythm: a small, a regular and a large section gap', at: at(secs[1]) });
+ }
+ }
+ if (secs.length > 9) out.push({ rule: 'section-gap', grade: 'warn', evidence: secs.length + ' sections on one page', fix: 'six to nine sections a page, hero and footer included; merge or cut', at: at(secs[9]) });
+ return out;
+}
+
+// sloplint-render observeSpace, the word budget (gate 58)
+export function glWords(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { vis } = P.H;
+ const out: ProbeFinding[] = [];
+ const words: Array<{ top: number; bottom: number; c: number }> = [];
+ const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ for (let n = tw.nextNode(); n; n = tw.nextNode()) {
+ const p = n.parentElement; if (!p || !vis(p) || p.closest('script, style, noscript, svg, [data-slot], [data-credits]')) continue;
+ const t = (n.textContent || '').trim(); if (!t) continue;
+ const pr = p.getBoundingClientRect(); const c = t.split(/\s+/).filter((w) => /[A-Za-z]{2,}/.test(w)).length;
+ if (c) words.push({ top: pr.top + scrollY, bottom: pr.bottom + scrollY, c });
+ }
+ const H = document.documentElement.scrollHeight;
+ let maxWords = 0, at = 0;
+ for (let y = 0; y < H; y += 50) {
+ const w = Math.round(words.reduce((a, x) => { const h = Math.max(1, x.bottom - x.top); const ov = Math.max(0, Math.min(x.bottom, y + innerHeight) - Math.max(x.top, y)); return a + x.c * Math.min(1, ov / h); }, 0));
+ if (w > maxWords) { maxWords = w; at = y; }
+ }
+ if (maxWords > 95) out.push({ rule: 'screen-word-budget', grade: 'fail', evidence: maxWords + ' words on one ' + innerHeight + 'px screen (from y=' + at + ')', fix: 'one idea per screen: cut to about 80 words and make the section an object' });
+ else if (maxWords > 80) out.push({ rule: 'screen-word-budget', grade: 'warn', evidence: maxWords + ' words on one ' + innerHeight + 'px screen (from y=' + at + '), close to the 80-word budget' });
+ if (ctx.stack > 2) out.push({ rule: 'screen-word-budget', grade: 'fail', evidence: 'the hero carries ' + ctx.stack + ' text blocks before its actions', fix: 'headline, one sentence, actions; delete the rest', at: ctx.h1 ? P.H.at(ctx.h1) : undefined });
+ if (ctx.hero && ctx.h1) {
+ const actions = Array.from(ctx.hero.querySelectorAll('a, button')).filter((c) => vis(c) && (c.textContent || '').trim() && !c.closest('nav, form, figure, footer'));
+ if (actions.length > 2) out.push({ rule: 'screen-word-budget', grade: 'fail', evidence: 'the hero offers ' + actions.length + ' actions', fix: 'one primary action and at most one quiet second; the rest belong to their sections', at: P.H.at(actions[2]) });
+ }
+ return out;
+}
+
+// sloplint-render observeSpace, slots and slivers at 1440 (gates F18 and F17)
+export function glSlots(P: Probes): ProbeFinding[] {
+ const { vis, at, text, name } = P.H;
+ const out: ProbeFinding[] = [];
+ for (const sl of document.querySelectorAll('[data-slot]')) {
+ const cs = getComputedStyle(sl);
+ if (cs.display === 'none' || cs.visibility === 'hidden' || !sl.getClientRects().length || sl.closest('[hidden]')) continue;
+ const r = sl.getBoundingClientRect();
+ if (r.width < 40 || r.height < 40) { out.push({ rule: 'tiny-slot', grade: 'warn', evidence: 'slot "' + sl.getAttribute('data-slot') + '" renders at ' + Math.round(r.width) + ' x ' + Math.round(r.height) + 'px', fix: 'the slot collapsed: give it a width from its track and a real aspect-ratio, never a percentage of a shrink-to-fit parent', at: at(sl) }); break; }
+ }
+ for (const e of document.querySelectorAll('p, li, dd, td, th, h2, h3, h4, figcaption, blockquote')) {
+ if (!vis(e) || e.closest('nav, svg, [aria-hidden="true"]')) continue;
+ const t = text(e);
+ if (t.length < 24) continue;
+ const cs = getComputedStyle(e);
+ const fs = parseFloat(cs.fontSize) || 16;
+ const lh = parseFloat(cs.lineHeight) || fs * 1.4;
+ const r = e.getBoundingClientRect();
+ if (r.width < fs * 8 && r.height / lh >= 3.6) { out.push({ rule: 'text-sliver', grade: 'warn', evidence: '"' + t.slice(0, 28) + '" squeezed to ' + Math.round(r.width) + 'px wide over ' + Math.round(r.height / lh) + ' lines (' + name(e) + ')', fix: 'a grid placement or a span ran wide; give the text its column back', at: at(e) }); break; }
+ }
+ return out;
+}
+
+// sloplint-render observeSpace, drawn illustrations and empty pictures (gates 80 and 81)
+export function glPictures(P: Probes): ProbeFinding[] {
+ const { vis, at, text } = P.H;
+ const out: ProbeFinding[] = [];
+ const vw = innerWidth;
+ const nameOf = (e: Element) => e.tagName.toLowerCase() + (e.getAttribute('data-slot') ? '[data-slot=' + e.getAttribute('data-slot') + ']' : e.classList[0] ? '.' + e.classList[0] : '');
+ const dataish = /chart|graph|plot|spark|map|diagram|logo|wordmark|brand|icon|flag|qr|avatar/i;
+ const drawn: Array<{ text: string; el: Element }> = [];
+ for (const svg of document.querySelectorAll('svg')) {
+ if (!vis(svg) || !svg.parentElement || svg.parentElement.closest('svg')) continue;
+ const r = svg.getBoundingClientRect();
+ if (r.width < 120 || r.height < 120) continue;
+ let named = false;
+ for (let q: Element | null = svg; q && q !== document.body && !named; q = q.parentElement) named = dataish.test((q.getAttribute('class') || '') + ' ' + (q.id || '') + ' ' + (q.getAttribute('aria-label') || '') + ' ' + (q.getAttribute('data-kind') || ''));
+ if (named || svg.querySelector('text')) continue;
+ const shapes = Array.from(svg.querySelectorAll('path, ellipse, circle, polygon'));
+ const curvy = shapes.filter((s) => s.tagName === 'ellipse' || (s.tagName === 'circle' && parseFloat(s.getAttribute('r') || '0') > 6) || /[CcQqSsAa]/.test(s.getAttribute('d') || '')).length;
+ const fills = new Set(shapes.map((s) => getComputedStyle(s).fill).filter((f) => f && f !== 'none'));
+ if (curvy >= 3 || (shapes.length >= 6 && fills.size >= 3)) drawn.push({ text: nameOf(svg.parentElement || svg) + ' (' + Math.round(r.width) + 'x' + Math.round(r.height) + ', ' + shapes.length + ' shapes)', el: svg });
+ }
+ if (drawn.length) out.push({ rule: 'hand-drawn-svg', grade: 'fail', evidence: 'drawn illustration: ' + drawn.slice(0, 3).map((d) => d.text).join('; '), fix: 'a photograph, the product built, or type at scale; SVG is for icons, logos and labelled charts or diagrams', at: at(drawn[0].el) });
+ const empty: Array<{ text: string; el: Element }> = [];
+ const shows = (box: Element) => {
+ const b = box.getBoundingClientRect();
+ let area = 0;
+ for (const m of box.querySelectorAll('img, video, picture, canvas, iframe, svg')) {
+ if (!vis(m) || (m.tagName.toLowerCase() === 'svg' && m.parentElement && m.parentElement.closest('svg'))) continue;
+ if (m.tagName === 'IMG' && !(m.getAttribute('src') || m.getAttribute('srcset') || '').trim()) continue;
+ const q = m.getBoundingClientRect(); area += q.width * q.height;
+ if (area >= b.width * b.height * 0.25) return true;
+ }
+ const bits = Array.from(box.querySelectorAll('*')).filter((e) => vis(e) && (text(e) || /^(INPUT|SELECT|TEXTAREA|BUTTON)$/.test(e.tagName)) && !e.children.length);
+ return bits.length >= 4 || text(box).length >= 80 || box.matches('[data-kind="product"]') || !!box.closest('[data-kind="product"]');
+ };
+ for (const sl of document.querySelectorAll('[data-slot]')) { if (!vis(sl) || sl.closest('[hidden]')) continue; const r = sl.getBoundingClientRect(); if (r.width < 160 || r.height < 120) continue; if (!shows(sl)) empty.push({ text: nameOf(sl) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height), el: sl }); }
+ for (const e of document.querySelectorAll('div, figure, span, i, aside')) {
+ if (e.hasAttribute('data-slot') || e.closest('[data-slot]') || !vis(e)) continue;
+ const r = e.getBoundingClientRect(); const cs = getComputedStyle(e);
+ if (r.width < 300 || r.height < 200 || r.width > vw * 0.9 || !/gradient/.test(cs.backgroundImage) || /url\(/.test(cs.backgroundImage)) continue;
+ if (text(e).length > 60 || e.querySelector('img, video, canvas, svg, picture, input, table')) continue;
+ if (!shows(e)) empty.push({ text: nameOf(e) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ', a gradient with nothing in it', el: e });
+ }
+ if (empty.length) out.push({ rule: 'empty-picture', grade: 'fail', evidence: empty.length + ' empty picture' + (empty.length > 1 ? 's' : '') + ': ' + empty.slice(0, 3).map((d) => d.text).join('; '), fix: 'put the picture in: the user\'s image, a credited photograph or the product at full fidelity; the wash is only a loading colour', at: at(empty[0].el) });
+ return out;
+}
+
+// sloplint-render observeSpace, the counting device (gate 82)
+export function glMarks(P: Probes): ProbeFinding[] {
+ const { vis, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const nameOf = (e: Element) => e.tagName.toLowerCase() + (e.getAttribute('data-slot') ? '[data-slot=' + e.getAttribute('data-slot') + ']' : e.classList[0] ? '.' + e.classList[0] : '');
+ const marks: Array<{ el: Element; text: string }> = [];
+ const colourOf = (e: Element) => { const cs = getComputedStyle(e); return e instanceof SVGElement ? cs.fill + '|' + cs.stroke : cs.backgroundColor + '|' + cs.borderTopColor + '|' + cs.color; };
+ for (const p of document.querySelectorAll('*')) {
+ if (p.children.length < 24 || !vis(p)) continue;
+ const kids = Array.from(p.children).filter((k) => !/^(defs|title|desc|style|script)$/i.test(k.tagName));
+ if (kids.length < 24) continue;
+ const small = kids.filter((k) => { const q = k.getBoundingClientRect(); return !(k.textContent || '').trim() && q.width > 0 && q.height > 0 && ((q.width <= 24 && q.height <= 48) || q.width <= 6 || q.height <= 6); });
+ if (small.length < 24 || small.length < kids.length * 0.8) continue;
+ const tally = new Map<string, number>(); for (const k of small) { const c = colourOf(k); tally.set(c, (tally.get(c) || 0) + 1); }
+ if (Math.max(...tally.values()) < small.length * 0.6 || tally.size > 4) continue;
+ const sizes = small.map((k) => { const q = k.getBoundingClientRect(); return Math.round(q.width) * 1000 + Math.round(q.height); });
+ const common = Math.max(...Array.from(new Set(sizes)).map((s) => sizes.filter((x) => x === s).length));
+ if (common < small.length * 0.7) continue;
+ if (marks.some((m) => m.el.contains(p) || p.contains(m.el))) continue;
+ marks.push({ el: p, text: nameOf(p) + ' holds ' + small.length + ' identical marks' });
+ }
+ const ONE_FOR_EACH = /\bone (?:mark|dot|stroke|tick|line|square|bar|cell|pin|block|circle|seed|bead|stripe|notch)s? (?:for|per) (?:each|every)\b/i;
+ const ONE_FOR_EACH_BARE = /\bone (?:for|per) (?:each|every)\b/i;
+ for (const e of document.querySelectorAll('[aria-label], figcaption, svg title, p, small, span')) {
+ if (marks.length >= 2) break;
+ const t = (e.getAttribute('aria-label') || '') + ' ' + ((e.textContent || '').length < 160 ? e.textContent : '');
+ const counting = ONE_FOR_EACH.test(t) || (ONE_FOR_EACH_BARE.test(t) && (e.matches('figcaption') || (e.getAttribute('aria-label') && e.closest('svg, figure, [role="img"]'))));
+ if (counting && !marks.some((m) => m.el.contains(e))) marks.push({ el: e, text: '"' + t.trim().slice(0, 60) + '"' });
+ }
+ if (marks.length) out.push({ rule: 'counting-marks', grade: 'fail', evidence: 'counting device: ' + marks.slice(0, 2).map((m) => m.text).join('; '), fix: 'set the number in type at the size it deserves; never one mark for each thing', at: at(marks[0].el) });
+ return out;
+}
+
+// sloplint-render observeSpace, the photo wall (gate 83): the strict third, no photographic shape
+export function glPhotos(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { vis, abs } = P.H;
+ const out: ProbeFinding[] = [];
+ if (ctx.heroEnd == null) return out;
+ const vw = innerWidth, vh = innerHeight;
+ const foot = Array.from(document.querySelectorAll('body footer, [role="contentinfo"]')).filter(vis).pop();
+ const docH = foot ? Math.min(document.documentElement.scrollHeight, abs(foot).top) : document.documentElement.scrollHeight, from = Math.max(ctx.heroEnd, vh);
+ const box = document.querySelector('.container') || document.body;
+ const cw = Math.min(box.getBoundingClientRect().width || vw, vw);
+ let area = 0, n = 0;
+ const seenA: Element[] = [];
+ let first: Element | null = null;
+ const add = (el: Element) => {
+ if (!vis(el) || el.closest('footer') || seenA.some((o) => o.contains(el))) return;
+ const b = abs(el); const top = Math.max(b.top, from), bot = Math.min(b.bottom, docH);
+ if (bot - top < 80 || b.w < 160) return;
+ seenA.push(el); area += (bot - top) * Math.min(b.w, cw); n++;
+ first = first || el;
+ };
+ for (const m of document.querySelectorAll('img, video')) {
+ if (m.closest('[data-kind="product"], [data-product]')) continue;
+ const nw = (m as HTMLImageElement).naturalWidth || (m as HTMLVideoElement).videoWidth || 0;
+ if (m.tagName === 'IMG' && /\.svg(\?|$)/i.test((m as HTMLImageElement).currentSrc || (m as HTMLImageElement).src || '')) continue;
+ if (m.tagName === 'IMG' && nw && nw < 200) continue;
+ add(m);
+ }
+ for (const e of document.querySelectorAll('section *, main *')) { const bi = getComputedStyle(e).backgroundImage; if (/url\(/.test(bi) && !/svg|data:image\/svg/i.test(bi)) add(e); }
+ const share = area / Math.max(1, (docH - from) * cw);
+ if (share > 0.36 && n >= 3) out.push({ rule: 'photo-wall', grade: 'fail', evidence: 'photographs cover ' + Math.round(share * 100) + '% of the page below the hero (' + n + ' pictures)', fix: 'cut or shrink pictures until they cover a quarter to a third of the page, and carry the freed sections in type, figures, the product or a list', at: first ? P.H.at(first) : undefined });
+ return out;
+}
+
+// sloplint-render observeSpace, the hero's balance and its dead band (gates 44a, 44c, 79)
+export function glHeroSpace(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { vis, abs, text, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const { hero, secs, heroEnd, textBox, fig } = ctx;
+ const vw = innerWidth, vh = innerHeight;
+ const heroAt = hero ? at(hero) : undefined;
+ let heroFoot: { cBottom: number; navBottom: number } | null = null;
+ if (hero) {
+ const hb = abs(hero);
+ let cTop = Infinity, cBottom = -Infinity;
+ for (const c of hero.querySelectorAll('*')) {
+ const nv = c.closest('nav');
+ if (!vis(c) || (nv && abs(nv).top <= hb.top + 220) || c === hero) continue;
+ const cs = getComputedStyle(c);
+ const painted = text(c) || /^(SVG|IMG|CANVAS|VIDEO|PICTURE)$/i.test(c.tagName) || cs.backgroundColor !== 'rgba(0, 0, 0, 0)' || cs.backgroundImage !== 'none' || parseFloat(cs.borderTopWidth) > 0;
+ if (!painted || /fixed|sticky/.test(cs.position)) continue;
+ const b = abs(c); cTop = Math.min(cTop, b.top); cBottom = Math.max(cBottom, Math.min(b.bottom, hb.bottom));
+ }
+ let navBottom = hb.top;
+ for (const n of document.querySelectorAll('header, nav, [class*="nav"], [class*="bar"]')) {
+ if (!vis(n) || (hero.contains(n) && !/fixed|sticky/.test(getComputedStyle(n).position))) continue;
+ const cs = getComputedStyle(n); const b = abs(n);
+ if ((/fixed|sticky/.test(cs.position) || hero.contains(n)) && b.top <= hb.top + 40 && b.bottom < hb.top + 220) navBottom = Math.max(navBottom, b.bottom);
+ }
+ const after = secs.find((x) => x !== hero && !hero.contains(x) && abs(x).top >= hb.bottom - 4);
+ const bottomEdge = after ? Math.min(ctx.content(after).top, hb.bottom + 240) : hb.bottom;
+ const topPad = cTop - navBottom, bottomPad = bottomEdge - cBottom;
+ if (isFinite(topPad) && isFinite(bottomPad) && topPad > 24 && bottomPad < topPad - 8) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero content sits low: ' + Math.round(topPad) + 'px above it, ' + Math.round(bottomPad) + 'px below', fix: 'centre the content in its screen: the space below 1.0 to 1.5 times the space above', at: heroAt });
+ heroFoot = { cBottom, navBottom };
+ }
+ if (heroEnd != null) {
+ if (heroEnd > vh + 8) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero runs past the ' + innerWidth + 'x' + innerHeight + ' fold (it ends at ' + Math.round(heroEnd) + 'px)', fix: 'size the display and the visual so the hero is one screen', at: heroAt });
+ else if (heroEnd < vh * 0.84 && secs.length > 1) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero ends at ' + Math.round(heroEnd) + 'px of a ' + innerHeight + 'px screen', fix: 'fill the first screen with the visual or the headline, not with copy', at: heroAt });
+ }
+ if (fig && textBox) {
+ const off = Math.round((fig.top + fig.bottom) / 2 - (textBox.top + textBox.bottom) / 2);
+ const gap = Math.round(fig.side === 'right' ? fig.left - fig.colEdge : fig.colEdge - fig.right);
+ const edge = Math.round(fig.side === 'right' ? vw - fig.right : fig.left);
+ const figAt = at(fig.el);
+ if (Math.abs(off) > 60) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero visual\'s centre is ' + off + 'px from the text block\'s centre', fix: 'align the visual beside the text', at: figAt });
+ const inkGap = Math.round(fig.side === 'right' ? fig.left - textBox.right : textBox.left - fig.right);
+ if (inkGap > 240 && gap <= 120) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero text ends ' + inkGap + 'px short of its visual', fix: 'widen the text column or bring the visual in: text and visual stand 48 to 120px apart', at: figAt });
+ if (gap > 120 || (edge < 8 && gap > 48)) out.push({ rule: 'hero-balance', grade: 'fail', evidence: 'the hero visual sits ' + gap + 'px from the text and ' + edge + 'px from the viewport edge', fix: 'bring the visual to within 48 to 120px of the text; never pin it to the corner', at: figAt });
+ }
+ if (heroFoot && hero && isFinite(heroFoot.cBottom)) {
+ const hb = abs(hero);
+ const after = secs.find((x) => x !== hero && !hero.contains(x) && abs(x).top >= hb.bottom - 4);
+ const nextTop = after ? ctx.content(after).top : Infinity;
+ const band = Math.round(Math.min(vh, nextTop) - heroFoot.cBottom);
+ if (heroFoot.cBottom < vh && band > 160) out.push({ rule: 'dead-band', grade: 'fail', evidence: band + 'px of nothing between the hero\'s last content (y ' + Math.round(heroFoot.cBottom) + ') and ' + (nextTop < vh ? 'the next section' : 'the fold'), at: heroAt });
+ }
+ return out;
+}
+
+// sloplint-render observeSpace, section heads and thin sections below the hero (gates 78 and 77)
+export function glThin(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { vis, abs, text, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const { hero, secs, h1 } = ctx;
+ const vw = innerWidth;
+ const below = secs.filter((x) => x !== hero && !(hero && (hero.contains(x) || x.contains(hero))) && x.tagName !== 'FOOTER' && !x.closest('footer, nav') && (!hero || abs(x).top >= abs(hero).bottom - 4));
+ const leavesOf = (root: Element): Box[] => {
+ const leaves: Box[] = [];
+ const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ for (let t = w.nextNode(); t; t = w.nextNode()) { if (!(t.textContent || '').trim()) continue; const p = t.parentElement; if (!p || !vis(p) || p.closest('script, style, noscript')) continue; const rg = document.createRange(); rg.selectNodeContents(t); for (const q of rg.getClientRects()) if (q.width > 1 && q.height > 1) leaves.push({ top: q.top + scrollY, bottom: q.bottom + scrollY, left: q.left, right: q.right }); }
+ for (const e of root.querySelectorAll('*')) {
+ if (!vis(e) || (e.closest('svg') && e.tagName.toLowerCase() !== 'svg')) continue;
+ const cs = getComputedStyle(e);
+ const border = (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0) + (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth) || 0);
+ const painted = /^(IMG|SVG|CANVAS|VIDEO|PICTURE|IFRAME|INPUT|TEXTAREA|SELECT|TABLE)$/i.test(e.tagName) || e.hasAttribute('data-slot') || cs.backgroundImage !== 'none' || cs.backgroundColor !== 'rgba(0, 0, 0, 0)' || border >= 2;
+ if (!painted) continue;
+ const b = e.getBoundingClientRect(); if (b.width * b.height < 64 || (b.width > vw * 0.97 && !/^(IMG|PICTURE|VIDEO|CANVAS|SVG)$/i.test(e.tagName) && !e.hasAttribute('data-slot'))) continue;
+ leaves.push({ top: b.top + scrollY, bottom: b.bottom + scrollY, left: b.left, right: b.right });
+ }
+ return leaves;
+ };
+ const span = (ls: Box[]) => ls.filter((b) => b.right > 0 && b.left < vw).reduce((a, b) => ({ left: Math.min(a.left, Math.max(0, b.left)), right: Math.max(a.right, Math.min(vw, b.right)) }), { left: Infinity, right: -Infinity });
+ const all = span([...(hero ? [hero] : []), ...below].flatMap(leavesOf));
+ const W = all.right - all.left;
+ const h1fs = h1 ? parseFloat(getComputedStyle(h1).fontSize) : 0;
+ const heads = below.flatMap((x) => Array.from(x.querySelectorAll('h2'))).filter((h) => vis(h) && !h.closest('nav, footer'));
+ if (heads.length) {
+ const sizes = heads.map((h) => parseFloat(getComputedStyle(h).fontSize)).sort((a, b) => a - b);
+ const med = sizes[Math.floor(sizes.length / 2)];
+ if (med < 40) out.push({ rule: 'small-section-heads', grade: 'fail', evidence: 'section heads render at ' + Math.round(med) + 'px' + (h1fs ? ' under a ' + Math.round(h1fs) + 'px hero head' : ''), fix: 'h2 at the section size (about 52px at 1440), item titles at the title size', at: at(heads[0]) });
+ }
+ const thin: Array<{ text: string; el: Element }> = [];
+ let bands = 0;
+ if (W > 400) for (const sec of below) {
+ const ls = leavesOf(sec);
+ if (!ls.length) continue;
+ const u = span(ls);
+ const wPct = (Math.min(u.right, all.right) - Math.max(u.left, all.left)) / W;
+ const words = text(sec).split(/\s+/).filter((x) => /[A-Za-z0-9]/.test(x)).length;
+ let mass = false, statement = false;
+ const secBg = getComputedStyle(sec).backgroundColor;
+ for (const e of sec.querySelectorAll('img, svg, canvas, video, picture, figure, iframe, [data-slot]')) { if (!vis(e) || (e.tagName.toLowerCase() === 'svg' && e.closest('[data-slot], figure') && e.closest('[data-slot], figure') !== e)) continue; if (e.getBoundingClientRect().height >= 300) { mass = true; break; } }
+ if (!mass) for (const e of sec.querySelectorAll('div, article, aside, ul, ol, dl, table, form, a')) {
+ if (!vis(e)) continue;
+ const cs = getComputedStyle(e); const r = e.getBoundingClientRect();
+ const border = (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0) + (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth) || 0);
+ const filled = (cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== secBg) || cs.backgroundImage !== 'none' || border >= 2;
+ if (filled && r.height >= 240 && r.width >= W * 0.35 && r.width < vw * 0.97) { mass = true; break; }
+ }
+ if (!mass) for (const t of sec.querySelectorAll('table, ul, ol, dl, div, [class]')) {
+ if (!vis(t)) continue;
+ if (t.tagName === 'TABLE') { const r = t.getBoundingClientRect(); if (t.querySelectorAll('tr').length >= 4 && r.width >= W * 0.6) { mass = true; break; } continue; }
+ const kids = Array.from(t.children).filter((k) => vis(k) && k.getBoundingClientRect().height > 20);
+ if (kids.length < 3) continue;
+ const rs = kids.map((k) => k.getBoundingClientRect());
+ const across = rs.every((r) => Math.abs(r.top - rs[0].top) < 12) && new Set(rs.map((r) => Math.round(r.left))).size === rs.length;
+ const spread = Math.max(...rs.map((r) => r.right)) - Math.min(...rs.map((r) => r.left));
+ const tall = Math.max(...rs.map((r) => r.bottom)) - Math.min(...rs.map((r) => r.top));
+ if ((across && spread >= W * 0.7) || (!across && spread >= W * 0.4 && tall >= 120)) { mass = true; break; }
+ }
+ if (!mass && Array.from(sec.querySelectorAll('input:not([type=hidden]), select, textarea')).filter(vis).length >= 2) mass = true;
+ for (const e of sec.querySelectorAll('h2, h3, p, blockquote, h2 span, p span, div, output, [contenteditable]')) {
+ if (!vis(e) || (/^(DIV|OUTPUT)$/.test(e.tagName) && !Array.from(e.childNodes).some((n) => n.nodeType === 3 && (n.textContent || '').trim()))) continue;
+ const cs = getComputedStyle(e); const fs = parseFloat(cs.fontSize); const lh = parseFloat(cs.lineHeight) || fs * 1.15; const r = e.getBoundingClientRect(); const n = text(e).split(/\s+/).filter(Boolean).length;
+ if ((fs >= 40 && n <= 40 && r.height >= lh * 1.8 && r.width >= W * 0.5) || fs >= 72) { statement = true; break; }
+ }
+ if (statement) mass = true;
+ const painted = getComputedStyle(sec).backgroundColor !== 'rgba(0, 0, 0, 0)' || getComputedStyle(sec).backgroundImage !== 'none';
+ if (!mass && painted && words <= 40 && sec.querySelector('a, button, form') && !bands) { bands++; continue; }
+ if ((wPct < 0.72 && !statement) || !mass) {
+ const head = sec.querySelector('h2, h3');
+ thin.push({ text: (head && text(head) ? '"' + text(head).slice(0, 28) + '"' : sec.tagName.toLowerCase() + (sec.classList[0] ? '.' + sec.classList[0] : '')) + ' (' + Math.round(wPct * 100) + '% wide' + (mass ? '' : ', no mass') + ')', el: sec });
+ }
+ }
+ if (thin.length) out.push({ rule: 'thin-section', grade: 'fail', evidence: thin.length + ' thin section' + (thin.length > 1 ? 's' : '') + ': ' + thin.slice(0, 3).map((t) => t.text).join('; '), fix: 'widen the body to ten of twelve columns and give it mass: a visual 300px tall or more, a set of three across, rows, or a statement', at: at(thin[0].el) });
+ return out;
+}
+
+// sloplint-render observeSpace at 1920 (gate 44d)
+export function glWide(P: Probes, ctx: HeroCtx): ProbeFinding[] {
+ const { vis, text, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const vh = innerHeight;
+ if (ctx.textBox && ctx.textBox.left < 120) out.push({ rule: 'wide-container', grade: 'fail', evidence: 'the hero text starts ' + Math.round(ctx.textBox.left) + 'px from the edge at ' + innerWidth, fix: 'cap the container at 1360 to 1520px and centre it', at: ctx.h1 ? at(ctx.h1) : undefined });
+ if (ctx.heroEnd != null && ctx.heroEnd > vh + 8) out.push({ rule: 'wide-container', grade: 'fail', evidence: 'the hero runs past the ' + innerWidth + 'x' + innerHeight + ' screen (it ends at ' + Math.round(ctx.heroEnd) + 'px)', fix: 'cap vw-sized visuals and display sizes', at: ctx.hero ? at(ctx.hero) : undefined });
+ const inkWidth = (e: Element) => { const range = document.createRange(); range.selectNodeContents(e); return range.getBoundingClientRect().width; };
+ const wide = Array.from(document.querySelectorAll('p, h1, h2, h3, li')).filter((e) => vis(e) && !e.querySelector('p, h1, h2, h3, h4, div, figure, ul, ol, table, section') && text(e).length > 40 && inkWidth(e) > 1600);
+ if (wide.length) out.push({ rule: 'wide-container', grade: 'fail', evidence: wide.length + ' text block' + (wide.length > 1 ? 's run' : ' runs') + ' wider than 1600px at ' + innerWidth + ' (first: ' + wide[0].tagName.toLowerCase() + ' "' + text(wide[0]).slice(0, 28) + '")', fix: 'cap the container; hold the measure', at: at(wide[0]) });
+ return out;
+}
diff --git a/lib/design-lint/render-probe.ts b/lib/design-lint/render-probe.ts
new file mode 100644
index 000000000..dd76e5b70
--- /dev/null
+++ b/lib/design-lint/render-probe.ts
@@ -0,0 +1,471 @@
+/**
+ * The render tier's in-page measurements. Each function here runs inside the
+ * page: it is serialised with Function.prototype.toString, installed once on
+ * window.__gstackLint by the first eval step, and called by later steps at
+ * the viewport they need. Nothing here may touch module scope: a function
+ * sees only its arguments, the helpers object and the DOM.
+ *
+ * Ported from Nutlope/hallmark's sloplint-render.mjs (MIT, see NOTICE.md):
+ * observe (gates 34, 44b, 49a, 49b, 40, 41, 23, F18 and 72 at 375),
+ * focusRing (26a), observeOcclusion (73) and pixelBehind's preparation. The
+ * space and quality measurements are in render-probe-space.ts and
+ * render-probe-quality.ts.
+ */
+import { glGaps, glHero, glHeroSpace, glMarks, glPhotos, glPictures, glSlots, glSpace, glThin, glWide, glWords } from './render-probe-space';
+import { glFields, glGrid, glPadding, glProse, glQuality, glRhythm, glStrain } from './render-probe-quality';
+import type { SampleRect } from './render-png';
+
+export interface ProbeAt { tag: string; cls: string; text: string; /** A distinguishing attribute in the open tag, like data-slot="hero" or id="main". */ attr?: string }
+
+export interface ProbeFinding {
+ rule: string;
+ /** fail: the tell is measured; warn: suspected (a blocking rule lands at ask). */
+ grade: 'fail' | 'warn';
+ evidence: string;
+ fix?: string;
+ at?: ProbeAt;
+ /** A contrast claim to confirm against painted pixels: the element's path, its ink and its threshold. */
+ probe?: { path: string; fg: number[]; threshold: number };
+}
+
+export interface RingProbe {
+ key: string;
+ path: string;
+ at: ProbeAt;
+ bare: boolean;
+ ratio: number | null;
+ ring?: number[];
+ pad?: number;
+}
+
+export interface SetupReport { lost: string[] }
+
+export interface PixelItem { path: string; kind: 'text' | 'ring'; pad?: number }
+
+/** Shared in-page helpers; built once by the install step. */
+export function glHelpers() {
+ const vis = (el: Element): boolean => {
+ const cs = getComputedStyle(el);
+ if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return false;
+ const r = el.getBoundingClientRect();
+ return r.width > 1 && r.height > 1;
+ };
+ const clsOf = (el: Element): string[] => (el.getAttribute('class') || '').trim().split(/\s+/).filter(Boolean);
+ const describe = (el: Element): string => el.tagName.toLowerCase() + (clsOf(el).length ? '.' + clsOf(el).slice(0, 2).join('.') : '');
+ const name = (el: Element): string => el.tagName.toLowerCase() + (clsOf(el)[0] ? '.' + clsOf(el)[0] : '');
+ const text = (el: Element): string => ((el as HTMLElement).innerText || el.textContent || '').replace(/\s+/g, ' ').trim();
+ const at = (el: Element): ProbeAt => {
+ const hint = el.getAttribute('data-slot') ? 'data-slot="' + el.getAttribute('data-slot') + '"' : el.id ? 'id="' + el.id + '"' : '';
+ return { tag: el.tagName.toLowerCase(), cls: clsOf(el)[0] || '', text: text(el).slice(0, 40), ...(hint ? { attr: hint } : {}) };
+ };
+ const pathOf = (el: Element): string => {
+ const parts: string[] = [];
+ for (let n: Element | null = el; n && n !== document.documentElement; n = n.parentElement) {
+ const p = n.parentElement;
+ parts.unshift(n.tagName.toLowerCase() + ':nth-child(' + (p ? Array.prototype.indexOf.call(p.children, n) + 1 : 1) + ')');
+ }
+ return 'html > ' + parts.join(' > ');
+ };
+ const abs = (el: Element) => { const r = el.getBoundingClientRect(); return { top: r.top + scrollY, bottom: r.bottom + scrollY, left: r.left, right: r.right, w: r.width, h: r.height }; };
+ const cv = document.createElement('canvas'); cv.width = cv.height = 1;
+ const cx = cv.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D;
+ const rgb = (s: string): number[] => { cx.clearRect(0, 0, 1, 1); cx.fillStyle = 'rgba(0, 0, 0, 0)'; cx.fillStyle = s; cx.fillRect(0, 0, 1, 1); const d = cx.getImageData(0, 0, 1, 1).data; return [d[0] / 255, d[1] / 255, d[2] / 255, d[3] / 255]; };
+ const lin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+ const lum = (c: number[]) => 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]);
+ const ratio = (a: number[], b: number[]) => (Math.max(lum(a), lum(b)) + 0.05) / (Math.min(lum(a), lum(b)) + 0.05);
+ const over = (c: number[], b: number[]) => [0, 1, 2].map((i) => c[i] * c[3] + b[i] * (1 - c[3]));
+ const clear = (c: string) => /^(transparent|rgba\(0, 0, 0, 0\))$/.test(c);
+ const bgOf = (n0: Element | null): number[] => {
+ for (let n = n0; n && n !== document.documentElement; n = n.parentElement) { const c = rgb(getComputedStyle(n).backgroundColor); if (c[3] >= 0.9) return c; }
+ const b = rgb(getComputedStyle(document.body).backgroundColor);
+ return b[3] > 0 ? b : [1, 1, 1, 1];
+ };
+ const settle = async () => {
+ if (document.fonts && document.fonts.status !== 'loaded') await Promise.race([document.fonts.ready, new Promise((r) => setTimeout(r, 3000))]);
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
+ };
+ return { vis, clsOf, describe, name, text, at, pathOf, abs, rgb, lum, ratio, over, clear, bgOf, settle };
+}
+
+export type Helpers = ReturnType<typeof glHelpers>;
+
+const PROBE_FNS = { setup: glSetup, layout: glLayout, contrast: glContrast, accent: glAccent, focus: glFocus, occlusion: glOcclusion, hide: glHide, restore: glRestore, hero: glHero, space: glSpace, words: glWords, slots: glSlots, pictures: glPictures, marks: glMarks, photos: glPhotos, heroSpace: glHeroSpace, thin: glThin, gaps: glGaps, wide: glWide, quality: glQuality, rhythm: glRhythm, padding: glPadding, prose: glProse, fields: glFields, strain: glStrain, grid: glGrid };
+
+/** Everything installed on window.__gstackLint: the helpers and every measurement, typed from PROBE_FNS so a probe is declared once. */
+export interface Probes extends ProbeFns { H: Helpers }
+type ProbeFns = typeof PROBE_FNS;
+
+export const PROBE_GLOBAL = 'window.__gstackLint';
+
+/** The JS that installs every probe on the page, as one expression. */
+export function installScript(): string {
+ const entries = Object.entries(PROBE_FNS).map(([k, fn]) => k + ': (' + fn.toString() + ')');
+ return '(' + PROBE_GLOBAL + ' = { H: (' + glHelpers.toString() + ')(), ' + entries.join(', ') + ' })';
+}
+
+/**
+ * An eval expression that runs one probe and returns its JSON, or {error} when
+ * it throws. Written without the word await: the browse daemon wraps an
+ * expression that mentions it, and a wrapper it cannot parse drops the value.
+ */
+export function probeScript(call: string): string {
+ return '(() => { const P = ' + PROBE_GLOBAL + '; return Promise.resolve().then(() => (' + call + ')).then((v) => JSON.stringify(v), (e) => JSON.stringify({ error: String((e && e.stack) || e).slice(0, 300) })); })()';
+}
+
+// sloplint-render renderCheck's page preparation: the quiet style, running animations finished through document.getAnimations(), lazy images eager-loaded and settled
+export async function glSetup(P: Probes): Promise<SetupReport> {
+ const quiet = document.createElement('style');
+ quiet.textContent = 'nextjs-portal, astro-dev-toolbar { display: none !important } * { transition: none !important } html, body { scroll-behavior: auto !important }';
+ document.head.appendChild(quiet);
+ for (const a of document.getAnimations()) { try { a.finish(); } catch { /* an infinite animation keeps running */ } }
+ for (const i of document.querySelectorAll('img[loading="lazy"]')) (i as HTMLImageElement).loading = 'eager';
+ for (let y = 0; y < document.documentElement.scrollHeight; y += 700) { window.scrollTo(0, y); await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); }
+ window.scrollTo(0, 0);
+ const waiting = Array.from(document.images).filter((i) => !i.complete);
+ await Promise.race([Promise.all(waiting.map((i) => new Promise((r) => { i.addEventListener('load', r, { once: true }); i.addEventListener('error', r, { once: true }); }))), new Promise((r) => setTimeout(r, 5000))]);
+ await Promise.all(Array.from(document.images).map((i) => (i.complete && i.naturalWidth && i.decode ? i.decode().catch(() => {}) : null)));
+ await P.H.settle();
+ const lost: string[] = [];
+ for (const l of document.querySelectorAll('link[rel~="stylesheet"][href]')) if (!(l as HTMLLinkElement).sheet) lost.push((l.getAttribute('href') || '').split('/').pop() || 'stylesheet');
+ for (const e of performance.getEntriesByType('resource') as PerformanceResourceTiming[]) if ((e.initiatorType === 'link' || e.initiatorType === 'css') && e.responseStatus >= 400) lost.push(e.name.split('?')[0].split('/').pop() || e.name);
+ if (document.fonts) for (const f of document.fonts) if (f.status === 'error') lost.push(f.family.replace(/^["']|["']$/g, ''));
+ return { lost: Array.from(new Set(lost)) };
+}
+
+// sloplint-render observe (gates 34, 49a, 49b, 44b; F18 and 72 at 375)
+export function glLayout(P: Probes, checkFold: boolean): ProbeFinding[] {
+ const { vis, describe, at, text } = P.H;
+ const out: ProbeFinding[] = [];
+ const vw = innerWidth, sw = document.documentElement.scrollWidth;
+ if (sw > vw + 1) out.push({ rule: 'horizontal-scroll', grade: 'fail', evidence: 'the page scrolls sideways: it is ' + sw + 'px wide in a ' + vw + 'px viewport', fix: 'overflow-x: clip on html and body, then find the block that overflows' });
+ if (vw === 375) {
+ const clipped = (el: Element) => { for (let q = el.parentElement; q && q !== document.body && q !== document.documentElement; q = q.parentElement) { const cs = getComputedStyle(q); if (/hidden|clip|auto|scroll/.test(cs.overflowX + ' ' + cs.overflow)) return true; } return false; };
+ const spill = Array.from(document.querySelectorAll('body *')).find((el) => { if (!vis(el) || getComputedStyle(el).position === 'fixed' || el.closest('svg') || clipped(el)) return false; const r = el.getBoundingClientRect(); return r.right > vw + 2 || r.left < -2; });
+ if (spill && sw <= vw + 1) { const r = spill.getBoundingClientRect(); out.push({ rule: 'horizontal-scroll', grade: 'fail', evidence: describe(spill) + ' runs ' + Math.round(Math.max(r.right - vw, -r.left)) + 'px past the 375px screen, hidden only by the page\'s clip', fix: 'stack it below 60rem: drop the desktop column gap, widths and offsets on the phone', at: at(spill) }); }
+ for (const sl of document.querySelectorAll('[data-slot]')) {
+ const cs = getComputedStyle(sl);
+ if (cs.display === 'none' || !sl.getClientRects().length || sl.closest('[hidden]')) continue;
+ const r = sl.getBoundingClientRect();
+ if (r.width < 40 || r.height < 40) { out.push({ rule: 'tiny-slot', grade: 'warn', evidence: 'slot "' + sl.getAttribute('data-slot') + '" renders at ' + Math.round(r.width) + ' x ' + Math.round(r.height) + 'px on a phone', fix: 'the slot collapsed: give it width: 100% and an aspect-ratio in the stacked layout', at: at(sl) }); break; }
+ }
+ const flush = Array.from(document.querySelectorAll('p, li, h1, h2, h3, blockquote, dd')).find((el) => {
+ if (!vis(el) || el.closest('nav, pre, table, [data-slot]')) return false;
+ const own = Array.from(el.childNodes).filter((n) => n.nodeType === 3 && (n.textContent || '').trim().length >= 20);
+ if (own.reduce((n, t) => n + (t.textContent || '').trim().length, 0) < 40) return false;
+ let left = Infinity, right = -Infinity;
+ for (const t of own) { const range = document.createRange(); range.selectNodeContents(t); for (const r of range.getClientRects()) { if (r.width < 2) continue; left = Math.min(left, r.left); right = Math.max(right, r.right); } }
+ return right - left > 120 && right <= vw + 1 && (left < 8 || right > vw - 8);
+ });
+ if (flush) out.push({ rule: 'cramped-padding', grade: 'fail', evidence: 'text runs to the edge of the phone screen (' + describe(flush) + ')', fix: 'give the page a gutter: 16px or more at each side on a phone', at: at(flush) });
+ }
+ for (const el of document.querySelectorAll('a, button, [role="button"], [role="tab"]')) {
+ if (!vis(el)) continue;
+ const label = (el.textContent || '').trim();
+ if (!label) continue;
+ const isButton = el.tagName === 'BUTTON' || el.getAttribute('role') === 'button' || /btn|button|cta/i.test(el.getAttribute('class') || '');
+ const block = el.closest('p, li, dd, td, blockquote, figcaption');
+ if (!isButton && block && text(block).length > label.length + 12) continue;
+ if (Array.from(el.querySelectorAll('*')).some((d) => !d.closest('svg') && /^(block|flex|grid|list-item|table)$/.test(getComputedStyle(d).display))) continue;
+ const cs = getComputedStyle(el);
+ const lh = parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.4;
+ const tops: number[] = [];
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
+ const host = n.parentElement;
+ if (!(n.textContent || '').trim() || !host || host.closest('svg')) continue;
+ const hr = host.getBoundingClientRect();
+ if (hr.width <= 2 || hr.height <= 2) continue;
+ const range = document.createRange();
+ range.selectNodeContents(n);
+ for (const r of range.getClientRects()) if (r.width > 0 && r.height > 0) tops.push(r.top);
+ }
+ tops.sort((a, b) => a - b);
+ let lines = tops.length ? 1 : 0;
+ for (let i = 1; i < tops.length; i++) if (tops[i] - tops[i - 1] > lh * 0.6) lines++;
+ if (lines <= 1) continue;
+ const primary = isButton || (!!el.closest('nav') && !el.closest('footer') && !el.closest('nav[aria-label*="bread" i]'));
+ out.push({ rule: primary ? 'button-label-wraps' : 'link-wraps', grade: 'fail', evidence: (primary ? 'control' : 'link') + ' "' + label.slice(0, 32) + '" wraps to ' + lines + ' lines (' + describe(el) + ')', fix: 'shorten the label, or white-space: nowrap', at: at(el) });
+ }
+ if (checkFold) {
+ const h1 = document.querySelector('h1');
+ if (h1 && vis(h1)) {
+ const hr = h1.getBoundingClientRect();
+ const scope = h1.closest('section, header, main, div') || document.body;
+ const cta = Array.from(scope.querySelectorAll('a, button')).find((c) => vis(c) && (c.textContent || '').trim());
+ const fold = innerHeight, view = innerWidth + 'x' + innerHeight;
+ if (hr.bottom > fold || hr.top < 0) out.push({ rule: 'hero-fold', grade: 'fail', evidence: 'the headline crosses the ' + view + ' fold (its bottom is at ' + Math.round(hr.bottom) + 'px)', fix: 'pull the display clamp down so the headline fits the fold', at: at(h1) });
+ else if (cta) {
+ const cr = cta.getBoundingClientRect();
+ if (cr.bottom > fold) out.push({ rule: 'hero-fold', grade: 'fail', evidence: 'the primary action sits below the ' + view + ' fold (its bottom is at ' + Math.round(cr.bottom) + 'px)', fix: 'trim the hero padding so the action fits the fold', at: at(cta) });
+ }
+ }
+ }
+ return out;
+}
+
+// sloplint-render observe, the contrast walk (gates 40 and 41); pixelBehind confirms the probes afterwards
+export function glContrast(P: Probes): ProbeFinding[] {
+ const { vis, describe, at, text, rgb, ratio, over, pathOf } = P.H;
+ const out: ProbeFinding[] = [];
+ const parse = (s: string): number[] | null => {
+ if (!s || s === 'transparent') return null;
+ const m = /^rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)$/.exec(s.trim());
+ if (m) return [+m[1] / 255, +m[2] / 255, +m[3] / 255, m[4] == null ? 1 : +m[4]];
+ const alpha = /\/\s*([\d.]+%?)\s*\)$/.exec(s);
+ const c = rgb(s);
+ if (alpha) c[3] = alpha[1].endsWith('%') ? parseFloat(alpha[1]) / 100 : parseFloat(alpha[1]);
+ return c;
+ };
+ const bgOf = (el: Element): number[] => {
+ for (let node: Element | null = el; node && node !== document.documentElement; node = node.parentElement) { const c = parse(getComputedStyle(node).backgroundColor); if (c && c[3] >= 0.9) return c; }
+ const root = parse(getComputedStyle(document.body).backgroundColor);
+ return root && root[3] > 0 ? root : [1, 1, 1, 1];
+ };
+ const gradStops = (el: Element, base: number[]): number[][] => {
+ const stops: number[][] = [];
+ for (let node: Element | null = el; node && node !== document.documentElement; node = node.parentElement) {
+ const cs2 = getComputedStyle(node);
+ if (/gradient/.test(cs2.backgroundImage)) {
+ const layers: string[] = []; let depth = 0, cur = '';
+ for (const ch of cs2.backgroundImage) { if (ch === '(') depth++; if (ch === ')') depth--; if (ch === ',' && depth === 0) { layers.push(cur); cur = ''; } else cur += ch; }
+ layers.push(cur);
+ const sizes = cs2.backgroundSize.split(',');
+ layers.forEach((layer, li) => {
+ const bh = /\s([\d.]+)px\s*$/.exec((sizes[li] || sizes[0] || '').trim()); if (bh && parseFloat(bh[1]) <= 6) return;
+ if (!/^\s*(linear|radial|conic)-gradient/.test(layer) || /[\s,(]\d(?:\.\d+)?px\b/.test(layer)) return;
+ for (const m of layer.matchAll(/(?:oklch|oklab|lab|lch|rgba?|hsla?|color)\([^()]*\)|#[0-9a-fA-F]{3,8}\b/g)) stops.push(over(rgb(m[0]), base));
+ });
+ }
+ const c = parse(cs2.backgroundColor);
+ if (c && c[3] >= 0.9) break;
+ }
+ return stops;
+ };
+ let reported = 0;
+ const seen = new Set<string>();
+ for (const el of document.querySelectorAll('body *')) {
+ if (reported >= 10) break;
+ if (!vis(el) || el.closest('svg')) continue;
+ if (!Array.from(el.childNodes).some((n) => n.nodeType === 3 && (n.textContent || '').trim().length > 2)) continue;
+ const cs = getComputedStyle(el);
+ const fg = parse(cs.color);
+ if (!fg || fg[3] < 0.9) continue;
+ const bg = bgOf(el);
+ const size = parseFloat(cs.fontSize), weight = parseInt(cs.fontWeight, 10) || 400;
+ const threshold = size >= 24 || (size >= 18 && weight >= 700) ? 3.0 : 4.5;
+ const key = describe(el);
+ const where = key + ' "' + text(el).slice(0, 24) + '"';
+ const stops = gradStops(el, bg);
+ if (stops.length && !seen.has(key)) {
+ const rs = stops.map((c) => ratio(fg, c));
+ const worst = Math.min(...rs), best = Math.max(...rs);
+ if (best < threshold - 0.05) { seen.add(key); reported++; out.push({ rule: 'low-contrast', grade: 'fail', evidence: 'contrast ' + best.toFixed(2) + ':1 at best over the gradient behind ' + where, fix: 'raise the contrast to threshold, or give the text its own ground', at: at(el) }); }
+ else if (worst < threshold - 0.05) { seen.add(key); reported++; out.push({ rule: 'low-contrast', grade: 'warn', evidence: 'contrast drops to ' + worst.toFixed(2) + ':1 over the gradient behind ' + where, fix: 'check the text where the gradient is darkest or lightest; give the label its own ground', at: at(el) }); }
+ continue;
+ }
+ const r = ratio(fg, bg);
+ if (r >= threshold - 0.05 || seen.has(key)) continue;
+ seen.add(key);
+ reported++;
+ const probe = { path: pathOf(el), fg: fg.slice(0, 3), threshold };
+ out.push({ rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast ' + r.toFixed(2) + ':1 under ' + threshold + ':1 on ' + where, at: at(el), probe });
+ if (el.closest('a, button, [class*="btn"], [class*="cta"]') && r < 1.6) out.push({ rule: 'gray-on-color', grade: 'fail', evidence: 'button text within a step of its fill on ' + key + ' (' + r.toFixed(2) + ':1)', fix: 'the paired ink token: the accent\'s ink or the paper for the label', at: at(el), probe });
+ }
+ return out;
+}
+
+// sloplint-render observe, the accent footprint (gate 23): the strict form, no posture and no genre
+export function glAccent(P: Probes): ProbeFinding[] {
+ const { vis } = P.H;
+ const out: ProbeFinding[] = [];
+ const cs0 = getComputedStyle(document.documentElement);
+ const cv = document.createElement('canvas'); cv.width = cv.height = 1;
+ const cx = cv.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D;
+ const toRgb = (raw: string): number[] | null => {
+ const s = (raw || '').trim();
+ if (!s || s === 'transparent') return null;
+ cx.clearRect(0, 0, 1, 1); cx.fillStyle = 'rgba(1, 2, 3, 0.5)'; cx.fillStyle = s;
+ if (cx.fillStyle === 'rgba(1, 2, 3, 0.5)') return null;
+ cx.fillRect(0, 0, 1, 1);
+ const d = cx.getImageData(0, 0, 1, 1).data;
+ return [d[0], d[1], d[2], d[3] / 255];
+ };
+ const targets = ['--color-accent', '--color-accent-2', '--accent', '--accent-2'].map((t) => toRgb(cs0.getPropertyValue(t))).filter((c): c is number[] => !!c);
+ if (!targets.length) return out;
+ const near = (str: string) => { const p = toRgb(str); return !!p && p[3] >= 0.5 && targets.some((t) => Math.abs(t[0] - p[0]) + Math.abs(t[1] - p[1]) + Math.abs(t[2] - p[2]) <= 30); };
+ const CW = 16, COLS = Math.ceil(innerWidth / CW), ROWS = Math.ceil(innerHeight / CW), view = innerWidth + 'x' + innerHeight;
+ const grid = new Uint8Array(COLS * ROWS);
+ let walked = 0;
+ for (const el of document.querySelectorAll('body, body *')) {
+ if (++walked > 4000) break;
+ if (el !== document.body && !vis(el)) continue;
+ const cs = getComputedStyle(el);
+ const isBg = near(cs.backgroundColor);
+ const isTxt = near(cs.color) && parseFloat(cs.fontSize) >= 32 && Array.from(el.childNodes).some((nd) => nd.nodeType === 3 && (nd.textContent || '').trim());
+ if (!isBg && !isTxt) continue;
+ const r = el.getBoundingClientRect();
+ const x0 = Math.max(0, Math.floor(r.left / CW)), x1 = Math.min(COLS - 1, Math.floor((Math.min(r.right, innerWidth) - 1) / CW));
+ const y0 = Math.max(0, Math.floor(r.top / CW)), y1 = Math.min(ROWS - 1, Math.floor((Math.min(r.bottom, innerHeight) - 1) / CW));
+ const turned = cs.transform !== 'none' && !/^matrix\(1, 0, 0, 1, /.test(cs.transform);
+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
+ if (turned) { const hit = document.elementFromPoint(x * CW + CW / 2, y * CW + CW / 2); if (!hit || !(hit === el || el.contains(hit))) continue; }
+ grid[y * COLS + x] = 1;
+ }
+ }
+ let filled = 0;
+ for (const c of grid) filled += c;
+ const pct = (100 * filled) / (COLS * ROWS);
+ if (pct > 8) out.push({ rule: 'accent-footprint', grade: 'fail', evidence: 'the accent paints about ' + pct.toFixed(1) + '% of the ' + view + ' viewport (over 8%)', fix: 'retreat the accent to 5% or less: large colour belongs to the paper and field tokens' });
+ else if (pct > 5) out.push({ rule: 'accent-footprint', grade: 'warn', evidence: 'the accent paints about ' + pct.toFixed(1) + '% of the ' + view + ' viewport', fix: 'retreat the accent to 5% or less, or keep the surface on the record' });
+ return out;
+}
+
+// sloplint-render focusRing (gate 26a): each focusable element is focused in turn instead of pressing Tab
+export function glFocus(P: Probes): RingProbe[] {
+ const { vis, rgb, lum, pathOf, at } = P.H;
+ const out: RingProbe[] = [];
+ const seen = new Set<string>();
+ const declared = (el: Element): boolean => {
+ for (const sheet of Array.from(document.styleSheets)) {
+ let rules: CSSRuleList;
+ try { rules = sheet.cssRules; } catch { continue; }
+ for (const r of Array.from(rules)) {
+ const sel = (r as CSSStyleRule).selectorText;
+ if (!sel || !/:focus-visible/.test(sel)) continue;
+ try { if (el.matches(sel.replace(/:focus-visible/g, '')) || el.matches(sel.replace(/:focus-visible/g, '*'))) return true; } catch { /* a selector the engine cannot test */ }
+ }
+ }
+ return false;
+ };
+ const candidates = Array.from(document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]')).filter((el) => vis(el) && el.getAttribute('tabindex') !== '-1' && !(el as HTMLButtonElement).disabled && !el.closest('[hidden], dialog:not([open])')).slice(0, 16);
+ for (const target of candidates) {
+ (target as HTMLElement).focus({ preventScroll: true });
+ if (document.activeElement !== target) continue;
+ let el: Element | null = target;
+ const box = el.getBoundingClientRect();
+ if (box.width < 4 || box.height < 4) el = ((target as HTMLInputElement).labels && (target as HTMLInputElement).labels![0]) || target.closest('label') || target.parentElement;
+ if (!el) continue;
+ (el as HTMLElement).style.setProperty('transition', 'none', 'important');
+ const cs = getComputedStyle(el);
+ const key = el.tagName.toLowerCase() + (el.classList[0] ? '.' + el.classList[0] : '') + ((el.textContent || '').trim() ? ' "' + (el.textContent || '').trim().slice(0, 18) + '"' : '');
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const base = { key, path: pathOf(target), at: at(target) };
+ if (cs.outlineStyle === 'none' || !(parseFloat(cs.outlineWidth) > 0)) {
+ if (!target.matches(':focus-visible')) { out.push({ ...base, bare: !declared(target), ratio: null }); continue; }
+ const chain: Element[] = []; for (let n: Element | null = el, i = 0; n && n !== document.body && i < 5; n = n.parentElement, i++) chain.push(n);
+ const look = () => chain.flatMap((n) => [null, '::before', '::after'].map((ps) => { const c = getComputedStyle(n, ps); return [c.outlineStyle, c.outlineWidth, c.boxShadow, c.borderTopColor, c.borderBottomColor, c.borderLeftColor, c.borderBottomWidth, c.backgroundColor, c.backgroundImage, c.color, c.textDecorationLine, c.opacity].join('|'); })).join('~');
+ const focused = look();
+ (target as HTMLElement).blur();
+ const rest = look();
+ (target as HTMLElement).focus({ preventScroll: true });
+ out.push({ ...base, bare: focused === rest, ratio: null });
+ continue;
+ }
+ let node: Element | null = parseFloat(cs.outlineOffset) < 0 ? el : el.parentElement;
+ let bg: number[] | null = null;
+ for (; node && node !== document.documentElement; node = node.parentElement) { const c = rgb(getComputedStyle(node).backgroundColor); if (c[3] >= 0.9) { bg = c; break; } }
+ if (!bg) { const b = rgb(getComputedStyle(document.body).backgroundColor); bg = b[3] > 0 ? b : [1, 1, 1, 1]; }
+ const ring = rgb(cs.outlineColor);
+ if (ring[3] < 0.5) { out.push({ ...base, bare: false, ratio: null }); continue; }
+ const a = lum(ring), b = lum(bg);
+ out.push({ ...base, bare: false, ring: ring.slice(0, 3), ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05), pad: Math.max(0, parseFloat(cs.outlineOffset)) + parseFloat(cs.outlineWidth) + 3 });
+ }
+ if (document.activeElement && document.activeElement !== document.body) (document.activeElement as HTMLElement).blur();
+ window.scrollTo(0, 0);
+ return out;
+}
+
+// sloplint-render observeOcclusion (gate 73)
+export async function glOcclusion(P: Probes): Promise<ProbeFinding[]> {
+ const { text, at } = P.H;
+ const out: ProbeFinding[] = [];
+ const vis = (el: Element) => { const cs = getComputedStyle(el); if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return false; const r = el.getBoundingClientRect(); return r.width > 3 && r.height > 3; };
+ const pinnedMemo = new Map<Element, boolean>();
+ const pinned = (el: Element): boolean => {
+ const hit = pinnedMemo.get(el);
+ if (hit !== undefined) return hit;
+ let out = false;
+ for (let p: Element | null = el; p && p !== document.body; p = p.parentElement) if (/fixed|sticky/.test(getComputedStyle(p).position)) { out = true; break; }
+ pinnedMemo.set(el, out);
+ return out;
+ };
+ const unseen = (el: Element) => { const cs = getComputedStyle(el); return parseFloat(cs.opacity) < 0.05 || (/^(transparent|rgba\(0, 0, 0, 0\))$/.test(cs.backgroundColor) && cs.backgroundImage === 'none' && !text(el) && !/^(IMG|svg|CANVAS|VIDEO|PICTURE)$/.test(el.tagName) && !el.querySelector('img, svg, canvas, video')); };
+ const runs: Array<{ t: Node; host: Element }> = [];
+ const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ for (let t = tw.nextNode(); t; t = tw.nextNode()) {
+ const host = t.parentElement; const txt = (t.textContent || '').trim();
+ if (!txt || !host || host.closest('script, style, noscript, svg, [aria-hidden="true"], nav, header, dialog, [popover], [role="menu"], details:not([open]), [hidden]')) continue;
+ let gone = false;
+ for (let p: Element | null = host; p && p !== document.body; p = p.parentElement) { const cs = getComputedStyle(p); if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) { gone = true; break; } }
+ if (!gone && !host.closest('[data-slot]') && vis(host)) runs.push({ t, host });
+ }
+ const bad: Array<{ text: string; el: Element }> = [];
+ const H = document.documentElement.scrollHeight;
+ for (let y = 0; y < H && bad.length < 3; y += Math.max(200, innerHeight - 100)) {
+ window.scrollTo(0, y);
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
+ for (const { t, host } of runs) {
+ if (bad.length >= 3) break;
+ if (pinned(host)) continue;
+ const rg = document.createRange(); rg.selectNodeContents(t);
+ for (const q of rg.getClientRects()) {
+ if (q.width < 6 || q.height < 6) continue;
+ const cx = q.left + q.width / 2, cy = q.top + q.height / 2;
+ if (cy < 0 || cy >= innerHeight || cx < 0 || cx >= innerWidth) continue;
+ const ghost = getComputedStyle(host).pointerEvents === 'none'; if (ghost) (host as HTMLElement).style.setProperty('pointer-events', 'auto', 'important');
+ const top = document.elementFromPoint(cx, cy);
+ if (ghost) (host as HTMLElement).style.removeProperty('pointer-events');
+ if (!top || top === host || host.contains(top) || top.contains(host) || pinned(top) || unseen(top)) continue;
+ const tr = top.getBoundingClientRect();
+ if (!(cx >= tr.left && cx <= tr.right && cy >= tr.top && cy <= tr.bottom)) {
+ const clearPseudo = (ps: CSSStyleDeclaration) => /^(none|normal)$/.test(ps.content) || (/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ps.backgroundColor) && ps.backgroundImage === 'none');
+ if (clearPseudo(getComputedStyle(top, '::after')) && clearPseudo(getComputedStyle(top, '::before'))) continue;
+ }
+ bad.push({ text: top.tagName.toLowerCase() + (top.classList[0] ? '.' + top.classList[0] : '') + ' over "' + (t.textContent || '').trim().slice(0, 16) + '"', el: host });
+ break;
+ }
+ }
+ }
+ window.scrollTo(0, 0);
+ if (bad.length) out.push({ rule: 'text-occlusion', grade: 'fail', evidence: 'text painted under another element: ' + bad.map((b) => b.text).join('; '), at: at(bad[0].el) });
+ return out;
+}
+
+// sloplint-render pixelBehind and pixelsAroundRing, the preparation half: hide the ink, report where to sample in page coordinates
+export function glHide(P: Probes, items: PixelItem[]): Array<SampleRect | null> {
+ window.scrollTo(0, 0);
+ const vw = innerWidth;
+ const els = items.map((item) => document.querySelector(item.path) as HTMLElement | null);
+ els.forEach((el, i) => {
+ if (!el) return;
+ if (items[i].kind === 'text') { for (const [k, v] of [['color', 'transparent'], ['text-shadow', 'none'], ['-webkit-text-stroke', '0'], ['text-decoration-color', 'transparent']]) el.style.setProperty(k, v, 'important'); return; }
+ el.style.setProperty('outline-style', 'none', 'important');
+ el.style.setProperty('box-shadow', 'none', 'important');
+ });
+ return items.map((item, i) => {
+ const el = els[i];
+ if (!el) return null;
+ if (item.kind === 'text') {
+ const r = el.getBoundingClientRect();
+ const x = Math.max(0, r.left), y = Math.max(0, r.top + scrollY);
+ return { x, y, w: Math.min(r.right, vw) - x, h: Math.min(r.bottom + scrollY, y + 400) - y };
+ }
+ const r = el.getBoundingClientRect(), pad = item.pad || 4;
+ const x = Math.max(0, r.left - pad), y = Math.max(0, r.top + scrollY - pad);
+ return { x, y, w: Math.min(vw, r.right + pad) - x, h: r.bottom + scrollY + pad - y, inner: { l: r.left - x, t: r.top + scrollY - y, r: r.right - x, b: r.bottom + scrollY - y } };
+ });
+}
+
+// sloplint-render pixelBehind's restore
+export function glRestore(P: Probes, items: PixelItem[]): number {
+ let n = 0;
+ for (const item of items) {
+ const el = document.querySelector(item.path) as HTMLElement | null;
+ if (!el) continue;
+ for (const k of ['color', 'text-shadow', '-webkit-text-stroke', 'text-decoration-color', 'outline-style', 'box-shadow']) el.style.removeProperty(k);
+ n++;
+ }
+ window.scrollTo(0, 0);
+ return n;
+}
diff --git a/lib/design-lint/render.ts b/lib/design-lint/render.ts
new file mode 100644
index 000000000..85e83538d
--- /dev/null
+++ b/lib/design-lint/render.ts
@@ -0,0 +1,271 @@
+/**
+ * The render tier: what only a browser can measure. Drives the same engine
+ * gstack-render picks (Aside when it is running, otherwise gstack's own
+ * headless browser) through lib/aside-render, so nothing is installed and no
+ * puppeteer is needed. Each page is opened once, the probes in
+ * render-probe*.ts are installed, and one eval runs per viewport; a second
+ * pass takes full-page screenshots only when a contrast claim needs the
+ * painted pixels behind it (hallmark's pixelBehind and pixelsAroundRing).
+ *
+ * Ported from Nutlope/hallmark's sloplint-render.mjs renderCheck (MIT, see
+ * NOTICE.md). Gates covered here and in the probe files: 23, 25, 26a, 34, 40,
+ * 41, 44a, 44b, 44c, 44d, 49a, 49b, 58, 71, 72, 73, 75, 77, 78, 79, 80, 81,
+ * 82, 83, F17, F18, F19, F20, plus the page that did not render.
+ */
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { pickEngine, render, renderWithBrowse, type EngineChoice, type RenderResult as EngineResult, type RenderSpec, type RenderStep } from '../aside-render';
+import { contrastRatio } from './color';
+import { CONTRAST_SLACK, lineIndex } from './css';
+import { escapeRe, parseHtml, plainText } from './html';
+import { decodePng, medianRgb, type SampleRect } from './render-png';
+import { installScript, probeScript, type PixelItem, type ProbeAt, type ProbeFinding, type RingProbe, type SetupReport } from './render-probe';
+import { Reporter, type Finding } from './report';
+import { ruleMeta } from './rules/ids';
+
+export interface RenderOptions {
+ cwd?: string;
+ scope?: 'page' | 'component';
+ /** Replaces the engine choice (tests inject one); defaults to lib/aside-render's pickEngine. */
+ engine?: () => EngineChoice;
+ /** Replaces the page runner itself, so every answer the browser could give (none, null, malformed, a probe error) can be settled without a browser. */
+ run?: Runner;
+}
+
+export interface RenderResult {
+ findings: Finding[];
+ /** 'ran', or 'skipped: <reason>' naming why no page was measured. */
+ status: string;
+}
+
+const WIDTHS = [320, 375, 414, 768, 1024, 1280, 1920];
+const LAPTOP = { width: 1440, height: 900 };
+/** The viewport of the contrast walk and of the pixel pass that confirms it. */
+const CONTRAST_VIEW = { width: 1280, height: 800 };
+const RING_FLOOR = 2.95;
+const RENDER_TIMEOUT_MS = 120_000;
+
+export type Runner = (spec: RenderSpec) => Promise<EngineResult>;
+
+export async function lintRender(targets: string[], opts: RenderOptions = {}): Promise<RenderResult> {
+ if (!targets.length) return { findings: [], status: 'skipped: no HTML page to render' };
+ let run = opts.run;
+ if (!run) {
+ const choice = (opts.engine ?? pickEngine)();
+ if (!choice.engine) return { findings: [], status: `skipped: ${choice.error}` };
+ run = (spec) => (choice.engine === 'browse' ? renderWithBrowse(spec, choice.bin) : render(spec));
+ }
+ const r = new Reporter(opts.scope ?? 'page', opts.cwd ?? process.cwd());
+ for (const target of targets) {
+ try { await lintPage(target, r, run); } catch (e) {
+ r.report('render', isUrl(target) ? target : path.resolve(target), 1, `the page could not be measured: ${(e as Error).message}`, { source: 'render' });
+ }
+ }
+ return { findings: r.findings, status: 'ran' };
+}
+
+const isUrl = (t: string): boolean => /^https?:\/\//.test(t);
+
+async function unreachable(url: string): Promise<string | null> {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(10_000), redirect: 'follow' });
+ return res.ok || res.status === 304 ? null : `HTTP ${res.status}`;
+ } catch (e) {
+ return (e as Error).message;
+ }
+}
+
+interface Measure { label: string; width: number; height: number; call: string }
+
+/** The first pass: one eval per viewport, the 1280 one carrying the fold, contrast and accent walks. */
+function measures(): Measure[] {
+ const m: Measure[] = WIDTHS.map((w) => ({ label: `${w}px`, width: w, height: CONTRAST_VIEW.height, call: w === CONTRAST_VIEW.width ? 'P.layout(P, true).concat(P.contrast(P), P.accent(P))' : 'P.layout(P, false)' }));
+ m.push({ label: `${LAPTOP.width}px`, ...LAPTOP, call: 'P.space(P, true)' });
+ m.push({ label: '1920px', width: 1920, height: 1080, call: 'P.space(P, false)' });
+ for (const call of ['P.quality(P)', 'P.occlusion(P)', 'P.focus(P)']) m.push({ label: `${LAPTOP.width}px`, ...LAPTOP, call });
+ return m;
+}
+
+const evalStep = (call: string, width: number, height: number): RenderStep =>
+ ({ kind: 'eval', expression: probeScript(call), width, height, deviceScaleFactor: 1, mobile: false, maxInline: 200_000 });
+
+/** The probes are installed by a step of their own: its value is not read, so whatever wrapper the engine puts around 70KB of source does not matter. */
+const openingSteps = (): RenderStep[] => [{ kind: 'eval', expression: installScript(), width: LAPTOP.width, height: LAPTOP.height, deviceScaleFactor: 1, mobile: false, maxInline: 10 }, evalStep('P.setup(P)', LAPTOP.width, LAPTOP.height)];
+
+type Parsed<T> = { value: T } | { error: string };
+
+function parsed<T>(text: string | undefined): Parsed<T> {
+ if (text === undefined) return { error: 'no result came back' };
+ try {
+ const v = JSON.parse(text) as T | { error: string } | null;
+ if (v === null) return { error: 'empty result' };
+ if (typeof v === 'object' && 'error' in v && typeof v.error === 'string') return { error: v.error };
+ return { value: v as T };
+ } catch (e) {
+ return { error: (e as Error).message };
+ }
+}
+
+/** A probe's locator field: a string no longer than a class name or an opening line could be; anything else locates nothing. */
+const SHORT = (v: unknown): v is string => typeof v === 'string' && v.length <= 400;
+
+/** The source line of the element a finding names: its tag, first class, a distinguishing attribute and its opening text. Best effort; 1 when nothing matches, or when the locator is not shaped like one the probes emit. */
+export function lineOf(src: string | null, at?: ProbeAt, lineAt: (i: number) => number = src ? lineIndex(src) : () => 1): number {
+ if (!src || !at || !SHORT(at.tag) || !/^[a-z]/i.test(at.tag) || !SHORT(at.text)) return 1;
+ const cls = SHORT(at.cls) && at.cls ? at.cls : null;
+ const attr = SHORT(at.attr) && at.attr ? at.attr : null;
+ const want = at.text.toLowerCase();
+ let fallback = -1;
+ for (const m of src.matchAll(new RegExp(`<${escapeRe(at.tag)}\\b[^>]*>`, 'gi'))) {
+ const pos = m.index ?? 0;
+ if (cls && !(/(?:^|\s)class\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[0]) ?? ['', '']).slice(1).join(' ').split(/\s+/).includes(cls)) continue;
+ if (attr && !m[0].includes(attr)) continue;
+ if (!want) { fallback = pos; break; }
+ if (plainText(src.slice(pos + m[0].length, pos + m[0].length + 600)).toLowerCase().startsWith(want)) { fallback = pos; break; }
+ if (fallback < 0) fallback = pos;
+ }
+ return fallback < 0 ? 1 : lineAt(fallback);
+}
+
+const isRgb = (v: unknown): v is number[] => Array.isArray(v) && v.length >= 3 && v.slice(0, 3).every((n) => typeof n === 'number' && Number.isFinite(n));
+
+/** Whether a page's finding carries a pixel probe the lint can act on; a probe of another shape is dropped so the computed ratio stands. */
+const probeOk = (f: ProbeFinding): boolean => !f.probe || (typeof f.probe === 'object' && typeof f.probe.path === 'string' && isRgb(f.probe.fg) && typeof f.probe.threshold === 'number');
+
+/** Whether a focus-walk entry has the shape the ring confirmation reads. */
+const ringOk = (x: RingProbe): boolean => typeof x.key === 'string' && typeof x.path === 'string' && typeof x.bare === 'boolean'
+ && (x.ratio == null || (typeof x.ratio === 'number' && Number.isFinite(x.ratio) && (x.ratio >= RING_FLOOR || isRgb(x.ring))));
+
+interface Found extends ProbeFinding { label: string }
+
+async function lintPage(target: string, r: Reporter, run: Runner): Promise<void> {
+ const file = isUrl(target) ? target : path.resolve(target);
+ let lineAt: (i: number) => number = () => 1;
+ const report = (f: Found | ProbeFinding, src: string | null) => {
+ const meta = ruleMeta(f.rule);
+ if (!meta || (f.grade !== 'fail' && f.grade !== 'warn')) {
+ r.report('render', file, 1, `the page handed back a measurement the lint does not know (${String(f.rule).slice(0, 40)}); its scripts may be tampering with the probes`, { fix: 'a page must not touch the lint; remove whatever redefines window.__gstackLint or the layout APIs', source: 'render' });
+ return;
+ }
+ r.report(f.rule, file, lineOf(src, f.at, lineAt), ('label' in f ? `[${f.label}] ` : '') + f.evidence, { fix: f.fix, suspected: f.grade === 'warn', source: 'render' });
+ };
+ if (isUrl(target)) {
+ const err = await unreachable(target);
+ if (err) { report({ rule: 'render', grade: 'fail', evidence: `could not reach ${target}: ${err}` }, null); return; }
+ }
+ let src: string | null = null;
+ if (!isUrl(target)) { try { src = parseHtml(file, fs.readFileSync(file, 'utf8')).src; } catch { src = null; } }
+ if (src) lineAt = lineIndex(src);
+ const plan = measures();
+ const opening = openingSteps();
+ const steps: RenderStep[] = [...opening, ...plan.map((m) => evalStep(m.call, m.width, m.height))];
+ const res = await run({ file, steps, timeoutMs: RENDER_TIMEOUT_MS });
+ if (!res.ok) { report({ rule: 'render', grade: 'fail', evidence: `the page did not render: ${res.error ?? 'unknown error'}` }, null); return; }
+
+ const setup = parsed<SetupReport>(res.evals[opening.length - 1]);
+ if ('error' in setup || !Array.isArray(setup.value?.lost)) report({ rule: 'render', grade: 'fail', evidence: `the page could not be prepared for measurement: ${'error' in setup ? setup.error : 'the setup answer has no list of lost assets'}` }, null);
+ else if (setup.value.lost.length) report({ rule: 'render', grade: 'warn', evidence: `fonts or stylesheets did not load (${setup.value.lost.slice(0, 2).join(', ')}): the measurements show a fallback face`, fix: 'fix the path or wait for the host, then measure again; never sign off a fallback face' }, null);
+ const errs = parsed<string[]>(res.stdout.match(/^PAGE_ERRORS=(.+)$/m)?.[1]);
+ const uncaught = 'value' in errs && Array.isArray(errs.value) ? errs.value.find((e) => typeof e === 'string' && e.startsWith('uncaught: ')) : undefined;
+ if (uncaught) report({ rule: 'render', grade: 'fail', evidence: `a script threw on load: ${uncaught.slice(10, 100)}`, fix: 'fix the script; a page that throws ships half-working' }, null);
+
+ const found: Found[] = [];
+ let rings: RingProbe[] = [];
+ const seen = new Map<string, Found>();
+ plan.forEach((m, i) => {
+ const p = parsed<ProbeFinding[] | RingProbe[]>(res.evals[opening.length + i]);
+ const list = 'error' in p ? null : (p.value as unknown);
+ const bad = 'error' in p ? p.error : !Array.isArray(list) ? 'the answer is not a list' : (list as unknown[]).some((f) => !f || typeof f !== 'object') ? 'the list holds a non-object entry' : null;
+ if (bad != null) { report({ rule: 'render', grade: 'fail', evidence: `the ${m.call.replace(/^P\.(\w+).*/, '$1')} measurement at ${m.label} failed: ${bad}` }, null); return; }
+ if (m.call === 'P.focus(P)') {
+ rings = (list as RingProbe[]).filter(ringOk);
+ if (rings.length < (list as RingProbe[]).length) report({ rule: 'focus', grade: 'malformed' as ProbeFinding['grade'], evidence: '' }, null);
+ return;
+ }
+ for (const f of list as ProbeFinding[]) {
+ if (typeof f.rule !== 'string' || typeof f.evidence !== 'string' || (f.grade !== 'fail' && f.grade !== 'warn') || !ruleMeta(f.rule)) { report({ rule: String(f.rule ?? '?'), grade: 'malformed' as ProbeFinding['grade'], evidence: '' }, null); continue; }
+ const key = f.rule + '|' + f.evidence;
+ const earlier = seen.get(key);
+ if (earlier) { if (f.grade === 'fail' && earlier.grade === 'warn') { earlier.grade = 'fail'; earlier.label = m.label; } continue; }
+ const item: Found = { ...f, fix: typeof f.fix === 'string' ? f.fix : undefined, label: m.label, probe: probeOk(f) ? f.probe : undefined };
+ seen.set(key, item);
+ found.push(item);
+ }
+ });
+ const scrolls = found.filter((f) => f.rule === 'horizontal-scroll' && !f.at);
+ if (scrolls.length > 1) {
+ const keep = scrolls.find((f) => f.grade === 'fail') ?? scrolls[0];
+ const rest = scrolls.filter((f) => f !== keep);
+ const widths = [...new Set(rest.map((f) => f.label.replace(/px$/, '')))].filter((w) => w !== keep.label.replace(/px$/, ''));
+ if (widths.length) keep.evidence += ` (also at ${widths.join(', ')}px)`;
+ for (const f of rest) found.splice(found.indexOf(f), 1);
+ }
+ const bare = rings.filter((x) => x.bare);
+ if (bare.length) report({ rule: 'missing-focus-visible', grade: 'fail', evidence: `[${LAPTOP.width}px] nothing shows keyboard focus on ${bare.slice(0, 4).map((x) => x.key).join(', ')}`, fix: 'give every control a :focus-visible ring; never remove an outline without putting one back', at: bare[0].at }, src);
+
+ const textProbes = found.filter((f) => f.probe);
+ const weakRings = rings.filter((x) => x.ratio != null && x.ratio < RING_FLOOR);
+ const confirmed = textProbes.length || weakRings.length ? await confirmPixels(file, run, textProbes, weakRings).catch(() => null) : null;
+ const dropped = new Set<string>();
+ for (const f of textProbes) {
+ const real = confirmed?.text.get(f.probe!.path);
+ if (real == null) continue;
+ if (real >= f.probe!.threshold - CONTRAST_SLACK) { dropped.add(f.probe!.path); continue; }
+ f.evidence = f.evidence.replace(/computed contrast [\d.]+:1 under/, `contrast ${real.toFixed(2)}:1 against the pixels behind, under`).replace(/\([\d.]+:1\)$/, `(${real.toFixed(2)}:1)`);
+ }
+ for (const f of found) if (!(f.probe && dropped.has(f.probe.path))) report(f, src);
+ for (const ring of weakRings) {
+ const real = confirmed?.ring.get(ring.path) ?? ring.ratio!;
+ if (real < RING_FLOOR) report({ rule: 'missing-focus-visible', grade: 'fail', evidence: `[${LAPTOP.width}px] focus ring ${real.toFixed(2)}:1 against what is behind it on ${ring.key}`, fix: 'a ring at 3:1 or better against the surface it is drawn over', at: ring.at }, src);
+ }
+}
+
+interface Confirmed { text: Map<string, number>; ring: Map<string, number> }
+
+/** hallmark's pixelBehind and pixelsAroundRing: hide the ink, screenshot the whole page, sample the median colour behind each claim. */
+async function confirmPixels(file: string, run: Runner, textProbes: Found[], weakRings: RingProbe[]): Promise<Confirmed | null> {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-design-lint-'));
+ try {
+ const textItems: PixelItem[] = [...new Map(textProbes.map((f) => [f.probe!.path, { path: f.probe!.path, kind: 'text' as const }])).values()];
+ const ringItems: PixelItem[] = weakRings.map((x) => ({ path: x.path, kind: 'ring' as const, pad: x.pad }));
+ const groups: Array<{ items: PixelItem[]; width: number; height: number; shot: string; evalIdx: number }> = [];
+ if (textItems.length) groups.push({ items: textItems, ...CONTRAST_VIEW, shot: path.join(dir, 'text.png'), evalIdx: -1 });
+ if (ringItems.length) groups.push({ items: ringItems, width: LAPTOP.width, height: LAPTOP.height, shot: path.join(dir, 'ring.png'), evalIdx: -1 });
+ const steps: RenderStep[] = openingSteps();
+ for (const g of groups) {
+ g.evalIdx = steps.length;
+ steps.push(evalStep(`P.hide(P, ${JSON.stringify(g.items)})`, g.width, g.height));
+ steps.push({ kind: 'screenshot', out: g.shot, width: g.width, height: g.height, deviceScaleFactor: 1, fullPage: true, type: 'png', mobile: false });
+ steps.push(evalStep(`P.restore(P, ${JSON.stringify(g.items)})`, g.width, g.height));
+ }
+ const res = await run({ file, steps, timeoutMs: RENDER_TIMEOUT_MS });
+ if (!res.ok) return null;
+ const out: Confirmed = { text: new Map(), ring: new Map() };
+ groups.forEach((g) => {
+ const rects = parsed<Array<SampleRect | null>>(res.evals[g.evalIdx]);
+ if ('error' in rects || !fs.existsSync(g.shot)) return;
+ const png = decodePng(fs.readFileSync(g.shot));
+ if (!png) return;
+ const scale = png.width / g.width;
+ g.items.forEach((item, i) => {
+ const rect = rects.value[i];
+ if (!rect || rect.w < 2 || rect.h < 2) return;
+ const scaled: SampleRect = { x: rect.x * scale, y: rect.y * scale, w: rect.w * scale, h: rect.h * scale, inner: rect.inner && { l: rect.inner.l * scale, t: rect.inner.t * scale, r: rect.inner.r * scale, b: rect.inner.b * scale } };
+ const bg = medianRgb(png, scaled);
+ if (!bg) return;
+ const under = { r: bg[0], g: bg[1], b: bg[2] };
+ if (item.kind === 'text') {
+ const fg = textProbes.find((f) => f.probe!.path === item.path)!.probe!.fg;
+ out.text.set(item.path, contrastRatio({ r: fg[0], g: fg[1], b: fg[2] }, under));
+ } else {
+ const ring = weakRings.find((x) => x.path === item.path)!.ring!;
+ out.ring.set(item.path, contrastRatio({ r: ring[0], g: ring[1], b: ring[2] }, under));
+ }
+ });
+ });
+ return out;
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
diff --git a/lib/design-lint/report.ts b/lib/design-lint/report.ts
new file mode 100644
index 000000000..59c12ace3
--- /dev/null
+++ b/lib/design-lint/report.ts
@@ -0,0 +1,121 @@
+/**
+ * Findings and the output contract of the design lint.
+ *
+ * LINT: <blocks|ask|polish|waived> <rule-id> <file>:<line> <evidence> | fix: <fix>
+ * LINT_SUMMARY: blocks=N ask=N waived=N polish=N render=<ran|skipped: reason>
+ *
+ * Blocking and waived are never summed: a waived finding leaves the ask count
+ * and lands in waived, so blocks=0 is always a true sentence about the Floor.
+ * Exit 2 when anything blocks, 1 when an ask is unanswered, 0 otherwise.
+ */
+import * as path from 'node:path';
+import { RULES, ruleMeta, type Tier } from './rules/ids';
+
+export type Grade = Tier | 'waived';
+
+export type Source = 'static' | 'render' | 'copy';
+
+export interface Finding {
+ rule: string;
+ tier: Tier;
+ grade: Grade;
+ file: string;
+ line: number;
+ evidence: string;
+ fix: string;
+ source: Source;
+ /** Set when a waiver answered the finding: the reason it recorded. */
+ waiver?: string;
+}
+
+export interface ReportOptions {
+ fix?: string;
+ /** A tell the rule can only suspect: a blocking rule reports at ask so a person confirms it. */
+ suspected?: boolean;
+ source?: Source;
+}
+
+export const trunc = (s: string, n = 120): string => (s.length > n ? s.slice(0, n - 1) + '…' : s);
+
+/** One printable line: control characters, line separators and runs of whitespace become one space, so no value a page controls can forge a LINT line or drive the terminal. */
+export const oneLine = (s: string): string => s.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\s]+/g, ' ').trim();
+
+export const relPath = (file: string, cwd = process.cwd()): string =>
+ /^https?:\/\//.test(file) ? file : path.isAbsolute(file) && file.startsWith(cwd + path.sep) ? file.slice(cwd.length + 1) : file;
+
+/** Collects findings for one context (a page and its stylesheets, or a directory of components). */
+export class Reporter {
+ readonly findings: Finding[] = [];
+
+ constructor(readonly scope: 'page' | 'component' = 'page', readonly cwd = process.cwd()) {}
+
+ /** Records one finding and returns it; null when the rule is page-only and the scope is component. */
+ report(rule: string, file: string, line: number | null | undefined, evidence: string, opts: ReportOptions = {}): Finding | null {
+ const meta = ruleMeta(rule);
+ if (!meta) throw new Error(`design-lint: unknown rule id ${rule}`);
+ if (this.scope === 'component' && meta.pageOnly) return null;
+ const tier: Tier = opts.suspected && meta.tier === 'blocks' ? 'ask' : meta.tier;
+ const finding: Finding = {
+ rule, tier, grade: tier,
+ file: oneLine(relPath(file, this.cwd)), line: line || 1,
+ evidence: trunc(field(evidence)),
+ fix: trunc(field(opts.fix ?? meta.fix), 240),
+ source: opts.source ?? (meta.render ? 'render' : 'static'),
+ };
+ this.findings.push(finding);
+ return finding;
+ }
+}
+
+/** One line, with the LINT line's own separator kept out of page-supplied text, so a parser splitting on the first ` | fix: ` reads the fix. */
+const field = (s: unknown): string => oneLine(String(s)).replace(/ \| fix: /g, ' / fix: ');
+
+const GRADE_RANK: Record<Grade, number> = { blocks: 0, ask: 1, waived: 2, polish: 3 };
+
+/** Drop exact duplicates and order findings: blocks, ask, waived, polish; then rule, file, line. */
+export function finalize(findings: Finding[]): Finding[] {
+ const seen = new Set<string>();
+ const unique = findings.filter((f) => {
+ const k = `${f.rule}|${f.grade}|${f.file}|${f.line}|${f.evidence}`;
+ if (seen.has(k)) return false;
+ seen.add(k);
+ return true;
+ });
+ return unique.sort((a, b) =>
+ GRADE_RANK[a.grade] - GRADE_RANK[b.grade]
+ || (a.rule < b.rule ? -1 : a.rule > b.rule ? 1 : 0)
+ || (a.file < b.file ? -1 : a.file > b.file ? 1 : 0)
+ || a.line - b.line);
+}
+
+export interface Summary {
+ blocks: number;
+ ask: number;
+ waived: number;
+ polish: number;
+ render: string;
+}
+
+export function summarize(findings: Finding[], render: string): Summary {
+ const count = (g: Grade) => findings.filter((f) => f.grade === g).length;
+ return { blocks: count('blocks'), ask: count('ask'), waived: count('waived'), polish: count('polish'), render };
+}
+
+export function formatFinding(f: Finding): string {
+ const fix = f.grade === 'waived' ? `waived (${f.waiver ?? 'on the record'})` : f.fix;
+ return oneLine(`LINT: ${f.grade} ${f.rule} ${f.file}:${f.line} ${f.evidence} | fix: ${fix}`);
+}
+
+export function formatSummary(s: Summary): string {
+ return `LINT_SUMMARY: blocks=${s.blocks} ask=${s.ask} waived=${s.waived} polish=${s.polish} render=${s.render}`;
+}
+
+export function exitCodeOf(s: Summary): 0 | 1 | 2 {
+ if (s.blocks > 0) return 2;
+ if (s.ask > 0) return 1;
+ return 0;
+}
+
+/** Every rule id, so a caller can list the contract. */
+export const ruleTable = (): Array<{ id: string; tier: Tier; gate: string; title: string }> =>
+ Object.entries(RULES).map(([id, m]) => ({ id, tier: m.tier, gate: m.gate, title: m.title }));
diff --git a/lib/design-lint/rules/assets.ts b/lib/design-lint/rules/assets.ts
new file mode 100644
index 000000000..0fdb59223
--- /dev/null
+++ b/lib/design-lint/rules/assets.ts
@@ -0,0 +1,247 @@
+/**
+ * Assets rules of the design lint (sloplint gates 30a 30b 33 40 41 49a 49b 76; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: emoji-decoration, two-icon-libraries, unlabeled-decoration, low-contrast, gray-on-color, button-label-wraps, link-wraps, broken-image, stock-photo-hotlink.
+ * The static tier can only suspect contrast and wrapping (it has no painted pixels and no
+ * widths), so low-contrast, gray-on-color and button-label-wraps report at ask for a person to
+ * confirm; the render tier proves them. hallmark's photo library (a credited Commons photo) is
+ * not shipped, so the no-credit half of gate 76 is not ported.
+ */
+import { contrastRatio, oklchOf, parseColor, type Color } from '../color';
+import { mergedRules, type LintContext } from '../context';
+import { CONTRAST_SLACK, isTokenRule, resolveVars, pxOf, selectorNames, type MergedRule, type Tokens } from '../css';
+import { ancestorsOf, getAttr, hasAttr, innerOf, stripTags, textOf, treeOf } from '../html';
+import { trunc, type Finding, type Reporter } from '../report';
+
+const EMOJI = /(?![©®™‼⁉←-⇿])\p{Extended_Pictographic}/u;
+const GLYPH = /(?![©®™‼⁉←-⇿✓-✖])(?:\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F)/u;
+
+// sloplint check30 (gate 30a)
+function checkEmojiIcons(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const lines = new Set<number>();
+ let n = 0;
+ const quoted = (doc.cache.emojiQuoted ??= new Map<string, Finding[]>()) as Map<string, Finding[]>;
+ const flag = (line: number, what: string, key?: string): void => {
+ if (lines.has(line) || n >= 8) return;
+ lines.add(line);
+ n++;
+ const found = r.report('emoji-decoration', doc.file, line, what);
+ if (key && found) { const list = quoted.get(key); if (list) list.push(found); else quoted.set(key, [found]); }
+ };
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ const iconish = /icon|card|step|tier|feature|value|prop|badge/i.test(cls);
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ const content = stripTags(inner.inner, false, 4).replace(/\s+/g, ' ').trim();
+ if (content && content.length <= 4 && EMOJI.test(content) && (iconish || !/<[a-z]/.test(inner.inner))) {
+ flag(t.line, 'an emoji icon "' + content + '" in <' + t.name + ' class="' + trunc(cls, 28) + '">', content);
+ lines.add(doc.lineOf(t.end + inner.inner.search(EMOJI)));
+ continue;
+ }
+ if (!/^(h[1-6]|button|a|label|th|summary|option|legend|dt)$/.test(t.name) || /<(p|div|ul|ol|table|section)\b/i.test(inner.inner)) continue;
+ const text = textOf(doc, i);
+ const at = inner.inner.search(GLYPH);
+ if (!text || at < 0) continue;
+ flag(doc.lineOf(t.end + at), 'an emoji in <' + t.name + '> "' + trunc(text, 32) + '"', trunc(text, 32));
+ }
+ const raw = doc.raw;
+ const body = doc.masked;
+ for (const m of body.matchAll(/>\s*((?:\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F)[^<>{}\n]{0,40})/gu)) flag(doc.lineOf(m.index! + m[0].length - m[1].length), 'text opens with an emoji: "' + trunc(m[1].trim(), 32) + '"', trunc(m[1].trim(), 32));
+ for (const m of body.matchAll(/placeholder\s*=\s*["']([^"']*)["']/g)) if (GLYPH.test(m[1])) flag(doc.lineOf(m.index!), 'an emoji in a placeholder "' + trunc(m[1], 28) + '"', trunc(m[1], 28));
+ if (doc.kind !== 'html') for (const m of raw.matchAll(/(["'`])\s*((?:(?:\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F?)\u200D?){1,3})\s*\1/gu)) flag(doc.lineOf(m.index!), 'an emoji passed as an icon: ' + m[2]);
+ }
+}
+
+const ICON_LIBS = new Map<string, RegExp>([
+ ['material', /material-icons|material-symbols/i],
+ ['heroicons', /heroicon/i],
+ ['lucide', /lucide/i],
+ ['phosphor', /phosphor|\bph-(?:bold|fill|light|duotone|[a-z]+-[a-z]+)/i],
+ ['font-awesome', /font-?awesome|\bfa-(solid|regular|brands|light)\b/i],
+ ['feather', /feather-icons|\bfeather\b/i],
+ ['tabler', /tabler-icons/i],
+ ['bootstrap-icons', /bootstrap-icons|\bbi-[a-z]/i],
+]);
+
+/** The class attributes, stylesheet and script references, and @import and url() targets of a context: where an icon library shows, prose left out. */
+function iconSurfaces(ctx: LintContext): string {
+ const out: string[] = [];
+ for (const doc of ctx.docs) {
+ for (const t of [...doc.tags, ...doc.comps]) {
+ if (t.close) continue;
+ const cls = getAttr(t.attrs, 'class') ?? getAttr(t.attrs, 'className');
+ if (cls) out.push(cls);
+ if (t.name === 'link' || t.name === 'script' || t.name === 'use') out.push(getAttr(t.attrs, 'href') ?? getAttr(t.attrs, 'src') ?? '');
+ }
+ for (const call of doc.virtuals) out.push(call.toks.join(' '));
+ for (const toks of doc.classAt.values()) out.push(toks.join(' '));
+ for (const m of doc.scripts.matchAll(/\b(?:import\s*(?:\(\s*)?|require\s*\(\s*|from\s+)['"]([^'"\n]+)['"]/g)) out.push(m[1]);
+ }
+ for (const f of ctx.cssFiles) for (const m of f.raw.matchAll(/@import\s+(?:url\()?['"]?([^'")\s;]+)|url\(\s*['"]?([^'")]+)/g)) out.push(m[1] ?? m[2]);
+ return out.join('\n');
+}
+
+// sloplint check30 (gate 30b)
+function checkIconLibraries(ctx: LintContext, r: Reporter): void {
+ const hay = iconSurfaces(ctx);
+ const found = [...ICON_LIBS].filter(([, re]) => re.test(hay)).map(([name]) => name);
+ if (found.length < 2) return;
+ const file = ctx.docs[0]?.file || ctx.cssFiles[0]?.file;
+ if (file) r.report('two-icon-libraries', file, 1, 'icon libraries mixed on one page: ' + found.join(' and '));
+}
+
+// sloplint check33 (gate 33)
+function checkUnlabeledDecoration(ctx: LintContext, r: Reporter): void {
+ const labeled = (a: string): boolean => (getAttr(a, 'aria-hidden') || '').trim().toLowerCase() === 'true' || getAttr(a, 'aria-label') != null
+ || getAttr(a, 'aria-labelledby') != null
+ || ['img', 'presentation', 'none'].includes((getAttr(a, 'role') || '').toLowerCase());
+ for (const doc of ctx.docs) {
+ const { parent } = treeOf(doc);
+ const labeledAt: boolean[] = [];
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close) continue;
+ labeledAt[i] = labeled(t.attrs);
+ if (t.name !== 'svg' && t.name !== 'canvas') continue;
+ const titled = t.name === 'svg' && !t.selfClosing && /<title\b[^>]*>\s*\S/i.test(innerOf(doc, i)?.inner || '');
+ let inLabeled = false;
+ for (let p = parent[i]; p >= 0 && !inLabeled; p = parent[p]) inLabeled = labeledAt[p];
+ if (!labeledAt[i] && !inLabeled && !titled) {
+ r.report('unlabeled-decoration', doc.file, t.line, '<' + t.name + '> with neither aria-hidden="true" nor a label');
+ }
+ }
+ }
+}
+
+const localTokens = (rule: MergedRule): Tokens => {
+ const local: Tokens = {};
+ for (const d of rule.decls) if (d.prop.startsWith('--')) local[d.prop] = d.value;
+ return local;
+};
+const bgDecl = (rule: MergedRule) => rule.decls.find((d) => d.prop === 'background-color') || rule.decls.find((d) => d.prop === 'background' && !/gradient|url\(/i.test(d.value));
+const withinAStep = (a: Color, b: Color): boolean => {
+ const x = oklchOf(a), y = oklchOf(b);
+ return Math.abs(x.L - y.L) < 0.05 && Math.abs(x.C - y.C) < 0.05;
+};
+
+// sloplint check40_41 (gates 40 and 41), the per-rule pairs
+function checkContrastPairs(ctx: LintContext, r: Reporter): void {
+ const colorOf = (value: string, local: Tokens): Color | null => parseColor(resolveVars(value, ctx.tokens, local).trim());
+ for (const rule of mergedRules(ctx)) {
+ const local = localTokens(rule);
+ const colorD = rule.decls.find((d) => d.prop === 'color');
+ const bgD = bgDecl(rule);
+ if (colorD && bgD && !/::selection|::placeholder|::-moz/.test(rule.selector)) {
+ const fg = colorOf(colorD.value, local);
+ const bg = colorOf(bgD.value, local);
+ if (fg && bg && fg.alpha >= 1 && bg.alpha >= 1) {
+ const sizeD = rule.decls.find((d) => d.prop === 'font-size');
+ const weightD = rule.decls.find((d) => d.prop === 'font-weight');
+ const sizePx = sizeD ? pxOf(resolveVars(sizeD.value, ctx.tokens, local)) : null;
+ const weightRaw = weightD ? resolveVars(weightD.value, ctx.tokens, local).trim().toLowerCase() : '400';
+ const weight = /^(bold|bolder)$/.test(weightRaw) ? 700 : parseInt(weightRaw, 10) || 400;
+ const large = sizePx != null && (sizePx >= 24 || (sizePx >= 18 && weight >= 700));
+ const threshold = large ? 3.0 : 4.5;
+ const ratio = contrastRatio(fg, bg);
+ if (ratio < threshold - CONTRAST_SLACK) {
+ r.report('low-contrast', rule.file, colorD.line, ratio.toFixed(2) + ':1 under the ' + threshold + ':1 threshold on ' + rule.selector, { suspected: true });
+ }
+ if (/btn|button|cta|pill|chip/i.test(rule.selector) && withinAStep(fg, bg)) {
+ r.report('gray-on-color', rule.file, colorD.line, 'button text within a step of its fill on ' + rule.selector + ' (lightness differs by ' + Math.abs(oklchOf(fg).L - oklchOf(bg).L).toFixed(3) + ')', { suspected: true });
+ }
+ }
+ }
+ const faceProp = Object.keys(local).find((k) => /(face|fill|bg)$/.test(k));
+ const inkProp = Object.keys(local).find((k) => /(ink|text)$/.test(k));
+ if (!faceProp || !inkProp) continue;
+ const face = colorOf(local[faceProp], local);
+ const ink = colorOf(local[inkProp], local);
+ if (face && ink && face.alpha >= 1 && ink.alpha >= 1 && withinAStep(face, ink)) {
+ r.report('gray-on-color', rule.file, rule.line, inkProp + ' sits within a step of ' + faceProp + ' on ' + rule.selector, { suspected: true });
+ }
+ }
+}
+
+// sloplint check40_41 (gate 41), the accent ink token and the dark surfaces
+function checkSurfaceInk(ctx: LintContext, r: Reporter): void {
+ const file = ctx.cssFiles[0]?.file || ctx.docs[0]?.file;
+ const accent = ctx.tokens['--color-accent'], accentInk = ctx.tokens['--color-accent-ink'];
+ if (file && accent && !accentInk) {
+ const used = ctx.rules.some((rule) => !isTokenRule(rule) && rule.decls.some((d) => /^background(-color)?$/.test(d.prop) && /var\(\s*--color-accent\s*[),]/.test(d.value)));
+ if (used) r.report('gray-on-color', file, 1, 'the accent fills a surface but --color-accent-ink is not defined', { suspected: true, fix: 'define --color-accent-ink and set it on text over the accent' });
+ } else if (file && accent && accentInk) {
+ const a = parseColor(resolveVars(accent, ctx.tokens));
+ const i = parseColor(resolveVars(accentInk, ctx.tokens));
+ if (a && i && contrastRatio(a, i) < 4.5 - CONTRAST_SLACK) r.report('gray-on-color', file, 1, '--color-accent-ink against --color-accent is only ' + contrastRatio(a, i).toFixed(2) + ':1', { suspected: true, fix: 'an accent ink at 4.5:1 or better against the accent' });
+ }
+ const sectionish = /section|panel|hero|footer|band|block|col\b|__col|card|cta|dark|invert/i;
+ for (const rule of mergedRules(ctx)) {
+ if (!sectionish.test(rule.selector) || /:hover|:focus|:active|::|@font-face/.test(rule.selector)) continue;
+ const bgD = bgDecl(rule);
+ if (!bgD) continue;
+ const bg = parseColor(resolveVars(bgD.value, ctx.tokens, localTokens(rule)).trim());
+ if (!bg || bg.alpha < 1) continue;
+ const L = oklchOf(bg).L;
+ if (L < 0.5 && !rule.decls.some((d) => d.prop === 'color')) {
+ r.report('gray-on-color', rule.file, bgD.line, 'a dark surface (lightness ' + (L * 100).toFixed(0) + '%) on ' + rule.selector + ' sets no text colour', { suspected: true, fix: 'swap the text to the paper colour in the same rule' });
+ }
+ }
+}
+
+// sloplint check49 (gates 49a and 49b)
+function checkWrappingLabels(ctx: LintContext, r: Reporter): void {
+ const nowrap = selectorNames(ctx.rules.filter((rule) => rule.decls.some((d) => d.prop === 'white-space' && /nowrap/.test(d.value))).map((rule) => rule.selector));
+ const covered = (cls: string, tag: string): boolean => nowrap.tags.has(tag) || cls.split(/\s+/).some((c) => c && nowrap.classes.has(c));
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ const button = t.name === 'button' || (t.name === 'a' && /btn|cta|button|nav/i.test(cls))
+ || (/(^|\s)(btn|button)(\s|$|__|--)/i.test(cls) && !/^(section|header|footer|main|article|aside|nav|form|ul|ol)$/.test(t.name));
+ const link = !button && t.name === 'a' && (/tab|crumb/i.test(cls) || ancestorsOf(doc, i).includes('footer'));
+ if (!button && !link) continue;
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ const label = stripTags(inner.inner, false, 40).replace(/\s+/g, ' ').trim();
+ if (label.length <= 24 || covered(cls, t.name)) continue;
+ if (button) r.report('button-label-wraps', doc.file, t.line, 'the long label "' + trunc(label, 36) + '" on <' + t.name + '> can wrap, and nothing sets nowrap', { suspected: true });
+ else r.report('link-wraps', doc.file, t.line, 'the long link "' + trunc(label, 36) + '" can wrap, and nothing sets nowrap');
+ }
+ }
+}
+
+const STOCK = /(?:images|plus)\.unsplash\.com\/(premium_photo|photo)-[\w-]+|images\.pexels\.com\/photos\/\d+|cdn\.pixabay\.com\/photo\//g;
+
+// sloplint check76 (gate 76): the stock hotlinks and the empty <img>; the library-credit half needs hallmark's photo index
+function checkImages(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ let stock = 0, plus = 0;
+ for (const m of doc.src.matchAll(STOCK)) {
+ const host = /unsplash/.test(m[0]) ? 'Unsplash' : /pexels/.test(m[0]) ? 'Pexels' : 'Pixabay';
+ if (m[1] === 'premium_photo') { if (!plus++) r.report('stock-photo-hotlink', doc.file, doc.lineOf(m.index!), 'an Unsplash+ photo hotlinked, which needs a paid licence'); }
+ else if (!stock++) r.report('stock-photo-hotlink', doc.file, doc.lineOf(m.index!), 'a photo hotlinked from ' + host + ', whose terms bar images picked by an AI tool', { suspected: true });
+ }
+ if (doc.kind !== 'html') continue;
+ for (const m of doc.src.matchAll(/<img\b([^>]*)>/gi)) {
+ const src = getAttr(m[1], 'src');
+ if ((src == null || !src.trim() || src.trim() === '#') && !getAttr(m[1], 'srcset') && !hasAttr(m[1], 'data-src')) {
+ r.report('broken-image', doc.file, doc.lineOf(m.index!), 'an <img> with no source', { fix: 'the real file, or remove the element' });
+ break;
+ }
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ checkEmojiIcons(ctx, r);
+ checkIconLibraries(ctx, r);
+ checkUnlabeledDecoration(ctx, r);
+ checkContrastPairs(ctx, r);
+ checkSurfaceInk(ctx, r);
+ checkWrappingLabels(ctx, r);
+ checkImages(ctx, r);
+}
diff --git a/lib/design-lint/rules/chrome-copy.ts b/lib/design-lint/rules/chrome-copy.ts
new file mode 100644
index 000000000..268d29d2c
--- /dev/null
+++ b/lib/design-lint/rules/chrome-copy.ts
@@ -0,0 +1,168 @@
+/**
+ * Chrome rules, the copy half (sloplint gate 19, the hero half of gate 42 and
+ * the two-filled-buttons half of F4; Nutlope/hallmark, MIT, see NOTICE.md),
+ * rewritten in gstack's voice. Rule ids: aphoristic-cadence,
+ * generic-hero-copy, generic-cta-copy, em-dash-overuse, template-footer-line,
+ * two-primary-buttons. The prose mask these rules read is maskedProse in
+ * ../html.ts. Placeholder names, brands, lorem and buzzwords are the copy
+ * tier's (rules/copy.ts) and are not reported here.
+ */
+import { styleFor, type LintContext } from '../context';
+import { resolveVars } from '../css';
+import { ancestorsOf, getAttr, innerOf, maskedProse, textOf, treeOf, type Doc, type Tag } from '../html';
+import { trunc, type Reporter } from '../report';
+
+
+// sloplint TELLS19 (gate 19), less the lines the copy tier owns
+const HERO_TELLS: Array<[RegExp, string]> = [
+ [/\bwhether you['’]?re\b/i, 'a filler opener'],
+ [/\bbuilt for the modern\b/i, 'a filler opener'],
+ [/\bin today['’]s\b/i, 'a filler opener'],
+ [/\bquietly (?:trusted|in use)\b/i, 'the quiet-proof line'],
+ [/\bwe['’]?ve got you covered\b/i, 'a stock line'],
+ [/\bsay goodbye to\b/i, 'a stock line'],
+ [/\bno credit card required\b/i, 'a template line'],
+ [/\beverything you need to\b/i, 'a stock line'],
+ [/\ball in one place\b/i, 'a stock line'],
+ [/\ball-in-one solution\b/i, 'a stock line'],
+ [/\bwelcome to\b/i, 'a stock opener'],
+ [/\bmade with\s*(?:♥|❤|\u{1f9e1}|\u{1f49b}|\u{1f49a}|\u{1f499}|\u{1f49c}|\u{1f5a4}|\u{1f90d}|&hearts;|&#9829;|&#10084;|<3)/iu, 'the made-with-a-heart line'],
+];
+const FOOTER_LINE = /\ball rights reserved\b/i;
+const STOCK_LINK = /^(learn more|read more|find out more|click here|more info|see more)$/i;
+
+// sloplint check19Tells (gate 19)
+function checkHeroCopy(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const prose = maskedProse(doc);
+ const lines = new Set<number>();
+ const hero = heroRange(doc);
+ const tell = (rule: string, idx: number, what: string, text: string, heading = false): void => {
+ const line = doc.lineOf(idx);
+ if (lines.has(line)) return;
+ lines.add(line);
+ const inHero = !heading || (hero != null && idx >= hero[0] && idx < hero[1]);
+ r.report(rule, doc.file, line, `${what}: "${trunc(text, 40)}"`, inHero ? {} : { suspected: true, fix: 'a heading in the product\'s own voice; below the hero this is a suspicion, so a waiver can answer it' });
+ };
+ for (const [re, what] of HERO_TELLS) {
+ const all = [...prose.matchAll(new RegExp(re.source, re.flags + 'g'))];
+ const inHero = all.find((m) => hero && m.index! >= hero[0] && m.index! < hero[1]);
+ const m = inHero ?? all[0];
+ if (!m) continue;
+ const line = doc.lineOf(m.index!);
+ if (lines.has(line)) continue;
+ lines.add(line);
+ r.report('generic-hero-copy', doc.file, line, `${what}: "${trunc(m[0], 40)}"`, inHero ? {} : { suspected: true, fix: 'a line in the product\'s own voice; in body copy this is a suspicion, so a waiver can answer it' });
+ }
+ const footer = FOOTER_LINE.exec(prose);
+ if (footer) tell('template-footer-line', footer.index, 'a stock footer line', footer[0]);
+ const stock: Array<{ t: Tag; label: string }> = [];
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close) continue;
+ if (t.name === 'a') {
+ const label = textOf(doc, i).replace(/[\u2192\u203a\u00bb]|->/g, '').trim();
+ if (STOCK_LINK.test(label)) stock.push({ t, label });
+ continue;
+ }
+ if (!/^h[1-6]$/.test(t.name)) continue;
+ const text = textOf(doc, i);
+ if (/^Meet\s+[A-Z][\w-]*[.!]?$/.test(text)) tell('generic-hero-copy', t.pos, 'the "Meet <Name>" heading', text, true);
+ else if (/^[A-Z][a-z]+\.\s+[A-Z][a-z]+\.\s+[A-Z][a-z]+\.$/.test(text)) tell('generic-hero-copy', t.pos, 'the three-word triad heading', text, true);
+ }
+ if (stock.length >= 2) {
+ r.report('generic-cta-copy', doc.file, stock[0].t.line, `the stock link label "${stock[0].label}" on ${stock.length} links`, { fix: 'say where each link goes: the thing it opens, in its own noun' });
+ }
+ }
+}
+
+const DASH = /\w\s--\s\w|[\u2014\u2013]|&mdash;|&ndash;|&#8212;|&#8211;/g;
+const CADENCE = /(^|[.!?]\s+)(not|no)\s+[a-z][^.!?\n]{0,40}[.]\s+(just|only|a|an)?\s*[a-z][^.!?\n]{0,40}[.]/gi;
+
+// sloplint checkCopyTell (gate 19): the cadence and the dashes; the buzzwords are the copy tier's
+function checkCadenceAndDashes(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const prose = maskedProse(doc);
+ const dashes = [...prose.matchAll(DASH)].filter((m) => !(/\d/.test(prose[m.index! - 1] || '') && /\d/.test(prose[m.index! + m[0].length] || '')));
+ if (dashes.length >= 3) {
+ const at = dashes[0].index ?? 0;
+ const around = prose.slice(Math.max(0, at - 16), at + 16).replace(/\s+/g, ' ').trim();
+ r.report('em-dash-overuse', doc.file, doc.lineOf(at), `${dashes.length} dashes carry the prose (first: "${trunc(around, 40)}")`);
+ }
+ const cadence = prose.match(CADENCE);
+ if (cadence && cadence.length >= 3) {
+ const first = cadence[0].trim();
+ r.report('aphoristic-cadence', doc.file, doc.lineOf(Math.max(0, prose.indexOf(first))), `the rebuttal cadence ${cadence.length} times ("${trunc(first, 40)}")`, { fix: 'once is voice, three times is a tic: say what the product does, in its own nouns' });
+ }
+ }
+}
+
+const SECOND_CTA = /^(learn more|see how it works|watch (the )?demo|get started|book a demo)$/i;
+
+/** The source range the hero copy lives in: the section or header holding the h1, else the h1's parent; null without an h1. A tell here is the Floor, elsewhere it is suspected. */
+function heroRange(doc: Doc): [number, number] | null {
+ const h1 = doc.tags.findIndex((t) => !t.close && t.name === 'h1');
+ if (h1 < 0) return null;
+ const heroIdx = heroIndexOf(doc, h1);
+ const holder = heroIdx >= 0 ? heroIdx : treeOf(doc).parent[h1];
+ if (holder < 0) return null;
+ const inner = innerOf(doc, holder);
+ return inner ? [doc.tags[holder].end, inner.endPos] : null;
+}
+
+/** The <section> or <header> that holds the h1, by tag index; -1 when none does. */
+// sloplint heroIndexOf
+export function heroIndexOf(doc: Doc, h1Idx: number): number {
+ for (let i = h1Idx - 1; i >= 0; i--) {
+ const t = doc.tags[i];
+ if (t.close || !/^(section|header)$/.test(t.name)) continue;
+ const inner = innerOf(doc, i);
+ if (inner && inner.endPos > doc.tags[h1Idx].pos) return i;
+ }
+ return -1;
+}
+
+interface HeroControl { t: Tag; cls: string; label: string }
+
+/** Whether a control's resting background is a fill (not none, transparent or the paper). */
+function isFilled(ctx: LintContext, c: HeroControl): boolean {
+ let raw: string | null = null;
+ for (const d of styleFor(ctx, c.cls, c.t.name, true)) if (d.prop === 'background-color' || d.prop === 'background') raw = d.value;
+ if (!raw || /--color-paper\b/.test(raw)) return false;
+ const bg = resolveVars(raw, ctx.tokens);
+ return !/^(none|transparent|inherit|initial|unset)$/i.test(bg.trim()) && !/transparent/i.test(bg);
+}
+
+// sloplint check42TwoButton (gate 19 and F4)
+function checkHeroActions(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const h1 = doc.tags.findIndex((t) => !t.close && t.name === 'h1');
+ if (h1 < 0) continue;
+ const heroIdx = heroIndexOf(doc, h1);
+ const hero = heroIdx >= 0 ? innerOf(doc, heroIdx) : null;
+ if (!hero) continue;
+ const controls: HeroControl[] = [];
+ for (let i = heroIdx + 1; i < doc.tags.length && doc.tags[i].pos < hero.endPos; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !(t.name === 'button' || t.name === 'a')) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ if (t.name === 'a' && !/btn|cta|button/i.test(cls)) continue;
+ if (ancestorsOf(doc, i).includes('nav')) continue;
+ controls.push({ t, cls, label: textOf(doc, i).trim() });
+ }
+ if (controls.length < 2) continue;
+ const firstFilled = isFilled(ctx, controls[0]);
+ if (firstFilled && isFilled(ctx, controls[1])) {
+ r.report('two-primary-buttons', doc.file, controls[1].t.line, `two filled buttons side by side in the hero: "${trunc(controls[0].label, 20)}" and "${trunc(controls[1].label, 20)}"`);
+ continue;
+ }
+ if (!firstFilled || !SECOND_CTA.test(controls[1].label)) continue;
+ r.report('generic-cta-copy', doc.file, controls[1].t.line, `the stock second action in the hero: "${trunc(controls[0].label, 20)}" then "${controls[1].label}"`, { fix: 'one action in the hero, or a second that names where it goes' });
+ }
+}
+
+export function runChromeCopy(ctx: LintContext, r: Reporter): void {
+ checkHeroCopy(ctx, r);
+ checkCadenceAndDashes(ctx, r);
+ checkHeroActions(ctx, r);
+}
diff --git a/lib/design-lint/rules/chrome-eyebrow.ts b/lib/design-lint/rules/chrome-eyebrow.ts
new file mode 100644
index 000000000..a22f37b3b
--- /dev/null
+++ b/lib/design-lint/rules/chrome-eyebrow.ts
@@ -0,0 +1,139 @@
+/**
+ * Chrome rules, the eyebrow half (sloplint gate 54; Nutlope/hallmark, MIT, see
+ * NOTICE.md), rewritten in gstack's voice. Rule id: kicker-above-heading. The
+ * eyebrow is short inert type before a heading that only announces it; a
+ * caption, a table head, a form label, a nav label, a byline, a unit after
+ * its figure, a real filename, a live status chip and a link that goes
+ * somewhere real are not eyebrows.
+ */
+import { fontPx, styleFor, trackingEm, valueOf, type LintContext } from '../context';
+import { escapeRe, ancestorsOf, directChildren, getAttr, innerOf, plainText, type Child } from '../html';
+import { trunc, type Reporter } from '../report';
+
+const EYEBROW_CONTAINER = /^(div|header|footer|section|article|aside|hgroup|li|main|figure|a|body|blockquote)$/;
+const EYEBROW_SKIP_TAGS = /^(figcaption|label|legend|caption|th|dt|summary|option|code|kbd|button|select|nav|time)$/;
+/** Shared with the Tailwind reader of the same rule, so both tiers agree on what an eyebrow is. */
+export const EYEBROW_ANCESTOR_SKIP = /^(form|fieldset|table|thead|tbody|nav|menu|dl|select|figcaption|label|button)$/;
+export const EYEBROW_BLOCKY = /<(p|ul|ol|hr|h[1-6]|img|table|figure|section|article|blockquote|form|dl)\b/i;
+const EYEBROW_CLASS = /\b(eyebrow|kicker|overline|superhead|suphead|rubric|strap(line)?|pre-?(title|head(ing)?)|section-?label|num-?label|chapter|ordinal|topic|category|dept)\b|__(num|label|tag|kicker|chip|badge|meta|index|caps|micro)\b|\b(tag|chip|badge|meta|caps|micro|label|index)\b/i;
+export const EYEBROW_ANNOUNCE = /^(features?|benefits?|introducing|new|how it works?|the (process|tour)|our (process|story|work|team|approach|values?)|why (us|choose|we)|pricing|plans?|faq|questions?|testimonials?|reviews?|trusted by|as seen in|what we do|about( us)?|services?|solutions?|use cases?|get started|contact|team|work|projects?|gallery|blog|news|resources?|examples?|overview)$/i;
+
+// sloplint capsRatio
+export function capsRatio(s: string): number {
+ const letters = s.replace(/[^A-Za-z]/g, '');
+ if (!letters) return 0;
+ return (letters.match(/[A-Z]/g) || []).length / letters.length;
+}
+
+// sloplint eyebrowHeadingBearing (gate 54)
+function eyebrowHeadingBearing(ctx: LintContext, B: Child, aPx: number | null): boolean {
+ if (/^h[1-6]$/.test(B.name)) return true;
+ if (/<h[1-6][\s>]/i.test(B.html)) return true;
+ const cls = getAttr(B.open, 'class') || '';
+ if (!/__(title|display|head(line)?|h\d)\b|hero__/i.test(cls)) return false;
+ const bPx = fontPx(ctx, styleFor(ctx, cls, B.name));
+ return bPx != null && aPx != null && bPx >= 1.5 * aPx;
+}
+
+/** The text of A when A is an eyebrow before B; null when A carries a fact, a destination or an identifier. */
+// sloplint eyebrowHit (gate 54)
+function eyebrowHit(ctx: LintContext, A: Child, B: Child, inOrderedList: boolean): { text: string } | null {
+ if (EYEBROW_SKIP_TAGS.test(A.name)) return null;
+ if (/(^|\s)for\s*=/i.test(A.open)) return null;
+ if (/role\s*=\s*["']status|aria-live|aria-current|aria-hidden\s*=\s*["']true/i.test(A.open)) return null;
+ const inner = A.html.slice(A.open.length);
+ if (EYEBROW_BLOCKY.test(inner) || /<br\b/i.test(inner)) return null;
+ if (/<time\b[^>]*\sdatetime\s*=/i.test(A.html)) return null;
+ if (/<img\b[^>]*\salt\s*=\s*["'][^"']+/i.test(A.html)) return null;
+
+ const ownHref = A.name === 'a' ? getAttr(A.open, 'href') : null;
+ if (ownHref && !/^#?$/.test(ownHref.trim())) return null;
+ const innerHref = /<a\b[^>]*\shref\s*=\s*["']([^"']*)["']/i.exec(inner);
+ if (innerHref && !/^#?$/.test(innerHref[1].trim())) return null;
+
+ const text = plainText(A.html);
+ if (!text) return null;
+ const words = text.split(/[\s·/|\u2014\u2013]+/).filter(Boolean);
+ if (words.length > 7 || text.length > 56) return null;
+ if (/[\w/-]+\.[a-z]{1,4}$/i.test(text)) return null;
+
+ if (/^[\d.,]+\s*(?:[%°+]|[a-z]{1,3})$/i.test(text)) return null;
+ const stripped = text.replace(/^\s*(?:no\.?\s*)?\d{1,3}(?:\s*[·./\u2014\u2013-]\s*|\s+|$)/i, '').trim();
+ if ((stripped.match(/\d/g) || []).length >= 2) return null;
+
+ if (inOrderedList && stripped && !EYEBROW_ANNOUNCE.test(stripped)) return null;
+
+ const cls = getAttr(A.open, 'class') || '';
+ const aDecls = styleFor(ctx, cls, A.name);
+ const pos = valueOf(ctx, aDecls, 'position');
+ if (pos && /absolute|fixed/.test(pos)) return null;
+ const aPx = fontPx(ctx, aDecls);
+ if (!eyebrowHeadingBearing(ctx, B, aPx)) return null;
+
+ if (EYEBROW_CLASS.test(cls)) return { text };
+ let signals = 0;
+ const tt = valueOf(ctx, aDecls, 'text-transform');
+ if ((tt && /uppercase/.test(tt)) || (capsRatio(text) >= 0.6 && /[A-Z]/.test(text))) signals++;
+ const tr = trackingEm(ctx, aDecls, aPx || 16);
+ if (tr != null && tr >= 0.04) signals++;
+ if (aPx != null && aPx <= 15) signals++;
+ const ff = valueOf(ctx, aDecls, 'font-family');
+ if (ff && /mono|--font-label/i.test(ff)) signals++;
+ const fv = valueOf(ctx, aDecls, 'font-variant-caps');
+ if (fv && /small-caps/.test(fv)) signals++;
+ if (signals >= 2) return { text };
+ if (EYEBROW_ANNOUNCE.test(stripped)) return { text };
+ return null;
+}
+
+// sloplint check54 (gate 54)
+function checkEyebrow(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !EYEBROW_CONTAINER.test(t.name)) continue;
+ const ancestors = ancestorsOf(doc, i);
+ if (ancestors.some((n) => EYEBROW_ANCESTOR_SKIP.test(n))) continue;
+ const inOl = ancestors.includes('ol');
+ const kids = directChildren(doc, i);
+ for (let k = 0; k < kids.length - 1; k++) {
+ const A = kids[k];
+ let B: Child | null = null;
+ for (let j = k + 1; j < Math.min(kids.length, k + 3); j++) {
+ const c = kids[j];
+ if (c.name === 'hr' || /aria-hidden\s*=\s*["']true/i.test(c.open)) continue;
+ B = c;
+ break;
+ }
+ if (!B) continue;
+ const hit = eyebrowHit(ctx, A, B, inOl);
+ if (!hit) continue;
+ r.report('kicker-above-heading', doc.file, doc.tags[A.idx]?.line || t.line, 'the eyebrow "' + trunc(hit.text, 32) + '" before <' + B.name + '>', { fix: 'cut it; the heading already says this. Where the heading is figurative, the label becomes the heading' });
+ break;
+ }
+ }
+ }
+}
+
+// sloplint check54Unheaded (gate 54)
+function checkUnheadedSection(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !/^(section|article)$/.test(t.name)) continue;
+ const labelledBy = getAttr(t.attrs, 'aria-labelledby');
+ if (!labelledBy) continue;
+ const body = innerOf(doc, i);
+ if (!body || /<h[1-6][\s>]/i.test(body.inner)) continue;
+ const idRe = new RegExp('<([a-z][\\w-]*)\\b[^>]*\\sid\\s*=\\s*["\']' + escapeRe(labelledBy.split(/\s+/)[0]) + '["\'][^>]*>', 'i');
+ const m = idRe.exec(body.inner);
+ if (!m || /^h[1-6]$/i.test(m[1])) continue;
+ r.report('kicker-above-heading', doc.file, doc.lineOf(body.endPos - body.inner.length + m.index), 'a section labelled by <' + m[1].toLowerCase() + '> with no heading element', { fix: 'promote the label to a heading; a label doing heading duty is a heading' });
+ }
+ }
+}
+
+export function runEyebrow(ctx: LintContext, r: Reporter): void {
+ checkEyebrow(ctx, r);
+ checkUnheadedSection(ctx, r);
+}
diff --git a/lib/design-lint/rules/chrome.ts b/lib/design-lint/rules/chrome.ts
new file mode 100644
index 000000000..be0670926
--- /dev/null
+++ b/lib/design-lint/rules/chrome.ts
@@ -0,0 +1,325 @@
+/**
+ * Chrome rules of the design lint (sloplint gates 19 42 46a 47a 47b 47c 54 63 68 69 70 85; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: aphoristic-cadence, generic-hero-copy, generic-cta-copy, em-dash-overuse, template-footer-line, template-nav, template-footer, invented-proof, drawn-browser-chrome, device-frame, imitation-material, kicker-above-heading, template-punctuation, wireframe-slots, repeated-fact, fake-send, email-band-close.
+ * Gate 19 lives in rules/chrome-copy.ts (with the two-filled-buttons half of F4), gate 54 in rules/chrome-eyebrow.ts.
+ * hallmark's theme stamp does not exist here: the nav and footer shapes always report, and the
+ * visitor's job comes from --job alone.
+ */
+import type { LintContext } from '../context';
+import { lineIndex } from '../css';
+import { closeIndex, getAttr, innerOf, maskedProse, openTags, plainText, textOf, treeOf, type Doc, type Tag } from '../html';
+import { trunc, type Reporter } from '../report';
+import { runChromeCopy } from './chrome-copy';
+import { runEyebrow } from './chrome-eyebrow';
+
+// sloplint check42 (gate 42)
+function checkNavShape(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const navIdx = doc.tags.findIndex((t) => !t.close && (t.name === 'nav' || (t.name === 'header' && /banner|nav/i.test(t.attrs))));
+ if (navIdx === -1) continue;
+ const inner = innerOf(doc, navIdx);
+ if (!inner) continue;
+ const links = (inner.inner.match(/<a\b/gi) || []).length;
+ const navTag = doc.tags[navIdx];
+ const navCls = (getAttr(navTag.attrs, 'class') || '').split(/\s+/)[0];
+ const hairline = ctx.rules.some((rule) => ((navCls && rule.selector.includes(navCls)) || /(^|[\s,])(nav|header)\b/.test(rule.selector))
+ && rule.decls.some((d) => /^border(-bottom)?$/.test(d.prop) && /\b1px\b/.test(d.value)));
+ const hasCta = /btn|cta|button/i.test(inner.inner);
+ if (links >= 4 && links <= 6 && hairline && hasCta) {
+ r.report('template-nav', doc.file, navTag.line, 'the reflex nav shape: ' + links + ' inline links, a button and a 1px hairline under');
+ }
+ }
+}
+
+// sloplint check42Footer (gate 42)
+function checkFooterShape(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const idx = doc.tags.findIndex((t) => !t.close && t.name === 'footer');
+ if (idx === -1) continue;
+ const inner = innerOf(doc, idx);
+ if (!inner) continue;
+ const uls = (inner.inner.match(/<ul\b/gi) || []).length;
+ const fourEqualCol = ctx.rules.some((rule) => /footer/i.test(rule.selector) && rule.decls.some((d) =>
+ d.prop === 'grid-template-columns'
+ && (/repeat\(\s*4\s*,/.test(d.value) || /^(1fr|minmax\([^)]*\))(\s+(1fr|minmax\([^)]*\))){3,}$/.test(d.value.trim()))));
+ let linkGroups = 0;
+ const end = closeIndex(doc, idx);
+ for (const el of openTags(doc, /^(ul|div|p|nav)$/, idx + 1, end)) {
+ const column = el.tag.name === 'ul' || /col|column|links|group/.test(getAttr(el.tag.attrs, 'class') || '');
+ if (column && openTags(doc, /^a$/, el.idx + 1, closeIndex(doc, el.idx)).length >= 3) linkGroups++;
+ }
+ if (uls >= 4 || (fourEqualCol && linkGroups >= 3)) {
+ r.report('template-footer', doc.file, doc.tags[idx].line, 'the reflex footer shape: ' + (uls >= 4 ? uls + ' link columns' : 'four equal columns of links'));
+ }
+ }
+}
+
+const PROOF_SHAPES = [
+ /\b\d+(\.\d+)?\s*[x×]\s*faster\b/i,
+ /trusted by [\d,.]+\s*\+?/i,
+ /\b99\.9+\s*%/,
+ /\b[\d,]{4,}\s*\+\s*(teams|users|customers|developers|companies|creators)\b/i,
+ /\b\d+(\.\d+)?\s*%\s*(faster|uptime|conversion|accuracy|retention|growth|fewer|less|more)\b/i,
+ /\+\s*\d+(\.\d+)?\s*%\s*(conversion|growth|revenue|retention)\b/i,
+ /\bsaves?\s+\d+\s+hours?\b/i,
+];
+
+// sloplint check46 (gate 46a)
+function checkInventedProof(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const prose = maskedProse(doc);
+ const lines = new Set<number>();
+ for (const re of PROOF_SHAPES) {
+ const m = re.exec(prose);
+ if (!m) continue;
+ const line = doc.lineOf(m.index);
+ if (lines.has(line)) continue;
+ lines.add(line);
+ r.report('invented-proof', doc.file, line, 'the metric "' + m[0].trim() + '" has no source on the page', { suspected: true, fix: 'the number the user supplied, or drop the claim' });
+ }
+ }
+}
+
+const CHROME_47: Array<[string, string, RegExp]> = [
+ ['drawn-browser-chrome', 'a drawn browser bar', /(browser|window|mac|osx)[-_]?(bar|chrome|dots|controls)|traffic[-_]?light|title[-_]?bar|window[-_]?(dots|buttons)|url[-_]?(bar|pill)/i],
+ ['device-frame', 'a device frame', /phone[-_]?(frame|mock(up)?)|device[-_]?frame|\bnotch\b|terminal[-_]?(chrome|frame|bar|dots|header)|(ide|editor)[-_]?(chrome|frame)|(browser|window)[-_]?frame/i],
+];
+
+// sloplint check47 (gates 47a and 47b)
+function checkDrawnChrome(ctx: LintContext, r: Reporter): void {
+ for (const [rule, what, re] of CHROME_47) {
+ for (const doc of ctx.docs) {
+ for (const t of doc.tags) {
+ if (t.close) continue;
+ const cls = getAttr(t.attrs, 'class');
+ const m = cls ? re.exec(cls) : null;
+ if (m) { r.report(rule, doc.file, t.line, what + ' drawn in CSS: class "' + m[0] + '" (class="' + trunc(cls!, 32) + '")'); break; }
+ }
+ }
+ for (const cssRule of ctx.rules) {
+ const m = re.exec(cssRule.selector);
+ if (m) { r.report(rule, cssRule.file, cssRule.line, what + ' drawn in CSS: selector ' + cssRule.selector); break; }
+ }
+ }
+}
+
+const PLACEHOLDER_IMG = /placehold\.co|via\.placeholder\.com|source\.unsplash\.com\/random|dummyimage\.com/i;
+
+// sloplint check47Placeholders (gate 47c)
+function checkPlaceholderImages(ctx: LintContext, r: Reporter): void {
+ const fix = 'a real asset, or a labelled slot in the page\'s own colours';
+ for (const doc of ctx.docs) {
+ const m = PLACEHOLDER_IMG.exec(doc.src);
+ if (m) r.report('imitation-material', doc.file, doc.lineOf(m.index), 'a placeholder image service (' + m[0] + ') stands in for a picture', { fix });
+ }
+ for (const c of ctx.cssFiles) {
+ const m = PLACEHOLDER_IMG.exec(c.raw);
+ if (m) r.report('imitation-material', c.file, lineIndex(c.raw)(m.index), 'a placeholder image service (' + m[0] + ') stands in for a picture', { fix });
+ }
+}
+
+const TEXT_TAGS = new Set(['p', 'span', 'li', 'small', 'a', 'div', 'figcaption', 'td', 'th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'time', 'dd', 'dt', 'cite', 'strong', 'em', 'b', 'label', 'button', 'summary']);
+const TICKER = /marquee|ticker|tape|crawl/i;
+
+// sloplint check63 (gate 63)
+function checkTemplatePunctuation(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const dotLines = new Set<number>(), arrowLines = new Set<number>();
+ const { parent } = treeOf(doc);
+ const inTicker = new Uint8Array(doc.tags.length);
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ inTicker[i] = (parent[i] >= 0 && inTicker[parent[i]]) || (!t.close && !t.selfClosing && TICKER.test(getAttr(t.attrs, 'class') || '') ? 1 : 0);
+ }
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !TEXT_TAGS.has(t.name) || inTicker[i]) continue;
+ const inner = innerOf(doc, i);
+ if (!inner || /<(p|div|li|section|article|ul|ol|table)\b/i.test(inner.inner)) continue;
+ const text = textOf(doc, i);
+ if (!text) continue;
+ const dots = (text.match(/\s[·•]\s/g) || []).length;
+ if (dots >= 2 && !dotLines.has(t.line)) {
+ dotLines.add(t.line);
+ r.report('template-punctuation', doc.file, t.line, 'middle dots join a meta string: "' + trunc(text, 50) + '"', { fix: 'line breaks, columns or hairlines; one dot in a byline at most' });
+ }
+ if ((t.name === 'a' || t.name === 'button') && /(\u2192|->|\u203a|\u00bb|\u27f6)\s*$/.test(text) && !arrowLines.has(t.line)) {
+ arrowLines.add(t.line);
+ r.report('template-punctuation', doc.file, t.line, 'an arrow glued to the label "' + trunc(text, 40) + '"', { fix: 'a verb as the label; the link already says it goes somewhere' });
+ }
+ if (/^[A-Z]{3,}\s+-\s+\S/.test(text) && text.length < 60) {
+ r.report('template-punctuation', doc.file, t.line, 'a WORD - fragment label "' + trunc(text, 40) + '"', { fix: 'say it as a sentence or a heading' });
+ }
+ }
+ let dotCount = 0;
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || !/^(span|i|b|em|s)$/.test(t.name)) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ if (!/(^|\s)(dot|status-dot|indicator|bullet|pip|blip)(\s|$|__|-)/i.test(cls)) continue;
+ if (/aria-live|role\s*=\s*"status"/i.test(t.attrs)) continue;
+ if (textOf(doc, i)) continue;
+ dotCount++;
+ if (dotCount === 3) r.report('template-punctuation', doc.file, t.line, 'decorative status dots (' + cls.trim() + ') repeated across the page', { fix: 'delete them; a dot means live state, and only where it is one' });
+ }
+ }
+}
+
+// sloplint check68 (gate 68); the no-slot-script half (F18) is render-only and not ported
+function checkWireframeSlots(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ const { parent } = treeOf(doc);
+ const slots: Array<{ i: number; t: Tag }> = [];
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || !/\bdata-slot\s*=/.test(t.attrs)) continue;
+ const inner = t.selfClosing ? null : innerOf(doc, i);
+ if (inner && /<img\b[^>]*\bsrc\s*=\s*["'][^"']+["']/i.test(inner.inner)) continue;
+ if (inner && (inner.inner.match(/<[a-z][\w-]*\b[^>]*>\s*[^<\s]/gi) || []).length >= 6) continue;
+ let hiddenUp = false;
+ for (let k = parent[i]; k >= 0 && !hiddenUp; k = parent[k]) if (/(?:^|\s)hidden(?:\s|=|$)/.test(doc.tags[k].attrs)) hiddenUp = true;
+ if (hiddenUp) continue;
+ slots.push({ i, t });
+ }
+ if (slots.length > 5) r.report('wireframe-slots', doc.file, slots[5].t.line, slots.length + ' empty slots on one page', { fix: 'two to four slots carry a page; set the rest in type, with names and facts in a list or table' });
+ const byRun = new Map<number, number>();
+ for (const sl of slots) {
+ const p = parent[sl.i];
+ const gp = p >= 0 ? parent[p] : -1;
+ const ggp = gp >= 0 ? parent[gp] : -1;
+ for (const key of new Set([p, gp, ggp])) { if (key < 0) continue; byRun.set(key, (byRun.get(key) || 0) + 1); }
+ }
+ for (const [key, n] of byRun) {
+ if (n < 4) continue;
+ r.report('wireframe-slots', doc.file, doc.tags[key].line, n + ' empty slots in one row or grid', { fix: 'a set the page has no pictures of is set in type, with one slot at most' });
+ break;
+ }
+ }
+}
+
+const FACT = /(?:[£$€¥]\s?\d[\d,.]*|(?<![\d,.])\d[\d,.]*\s?(?:%|(?:pm|am|MAD|kg|g|ml|km|mi|miles)\b)|\b\d{1,2}:\d{2}\b)/gi;
+const REGION = /^(section|header|footer|article|aside|nav|form|dialog)$/;
+
+// sloplint check69 (gate 69)
+function checkRepeatedFact(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ const bodyAt = doc.tags.findIndex((t) => !t.close && t.name === 'body');
+ const { parent } = treeOf(doc);
+ const seen = new Map<string, Set<number | string>>();
+ const regionOf = (i: number): number | string => {
+ const t = doc.tags[i];
+ const chain: number[] = [];
+ for (let p = t.close || t.selfClosing ? parent[i] : i; p >= 0; p = parent[p]) chain.push(p);
+ chain.reverse();
+ const region = chain.find((p) => REGION.test(doc.tags[p].name));
+ if (region != null) return region;
+ const band = chain.find((p, k) => k > 0 && /^(body|main)$/.test(doc.tags[chain[k - 1]].name) && doc.tags[p].name !== 'main');
+ return band ?? 'root';
+ };
+ for (let i = Math.max(bodyAt, 0); i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ const next = doc.tags[i + 1];
+ if (/^(script|style|template|noscript)$/.test(t.name) && !t.close) continue;
+ const chunk = doc.masked.slice(t.end, next ? next.pos : doc.masked.length)
+ .replace(/&pound;/g, '£').replace(/&euro;/g, '€').replace(/&nbsp;|&#160;/g, ' ');
+ if (!chunk.trim()) continue;
+ const region = regionOf(i);
+ for (const f of chunk.match(FACT) || []) {
+ const k = f.replace(/\s+/g, '').toLowerCase();
+ if (!seen.has(k)) seen.set(k, new Set());
+ seen.get(k)!.add(region);
+ }
+ }
+ const loud = [...seen].map(([k, s]) => [k, s.size] as const).filter(([, n]) => n >= 4).sort((a, b) => b[1] - a[1]);
+ if (loud.length) r.report('repeated-fact', doc.file, 1, 'the same fact printed in ' + loud[0][1] + ' sections: ' + loud.slice(0, 3).map(([k, n]) => k + ' (' + n + ')').join(', '));
+ }
+}
+
+const SUCCESS = /\b(sent|thanks|thank you|reserved|booked|on the list|subscribed|in touch|received|confirmed|ordered|chosen|on its way|signed up|all set|you're in|you are in|done)\b/i;
+const NEGATED = /\b(not|nothing|no|never|isn't|wasn't|didn't|cannot|can't|failed|try again|soon)\b/i;
+const REQUEST = /\bfetch\s*\(|XMLHttpRequest|navigator\.sendBeacon|\.submit\s*\(\s*\)|axios|\$\.ajax/;
+const JS_STRING = /(["'`])((?:(?!\1)[^\\\n]|\\.)*)\1/g;
+
+// sloplint check70 (gate 70); string literals are paired in sequence so a short literal earlier in the script cannot desync the scan
+function checkFakeSend(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const js = doc.scripts || '';
+ if (!/<form\b|type\s*=\s*["']submit/i.test(doc.src) || !js.trim()) continue;
+ let hit: string | null = null;
+ for (const x of js.matchAll(JS_STRING)) {
+ if (x[2].length < 4 || x[2].length > 140) continue;
+ const words = x[2].trim().split(/\s+/);
+ if (words.length >= 2 && SUCCESS.test(words.slice(0, 4).join(' ')) && !NEGATED.test(x[2])) { hit = x[0]; break; }
+ }
+ if (!hit || REQUEST.test(js)) continue;
+ const at = (doc.scripts === doc.raw ? doc.raw : doc.src).indexOf(hit);
+ r.report('fake-send', doc.file, doc.lineOf(at >= 0 ? at : 0), 'a script prints success ("' + trunc(hit.replace(/["'`]/g, ''), 30) + '") with no request behind it', { suspected: true });
+ }
+}
+
+const NATIVE_LIST_JOB = /subscribe|join|attend|listen|visit|newsletter|waitlist/i;
+const ASKS = /\b(book|enquir|inquir|request|contact|walkthrough|demo|quote|reserve|apply|start|create|order|buy|download|try|sign ?in|log ?in|continue)/i;
+const LIST_WORDS = /newsletter|updates|subscribe|the list|mailing/i;
+
+/** Whether the form opened at idx is an email sign-up: one or two fields, one of them email, under a button that does not book, order or ask. */
+function isEmailSignup(doc: Doc, idx: number): boolean {
+ const inner = innerOf(doc, idx);
+ if (!inner) return false;
+ const html = inner.inner;
+ const end = closeIndex(doc, idx);
+ const buttons = [...openTags(doc, /^button$/, idx + 1, end).map((b) => plainText(b.inner)),
+ ...doc.tags.slice(idx + 1, end).filter((t) => !t.close && t.name === 'input' && /^submit$/i.test(getAttr(t.attrs, 'type') || '')).map((t) => getAttr(t.attrs, 'value') || '')].join(' ');
+ if (ASKS.test(buttons) && !LIST_WORDS.test(buttons)) return false;
+ const fields: string[] = [];
+ for (const m of html.matchAll(/<(input|textarea|select)\b([^>]*)>/gi)) {
+ const type = (getAttr(m[2], 'type') || 'text').toLowerCase();
+ if (m[1].toLowerCase() === 'input' && /^(hidden|submit|checkbox|radio|button|reset|image)$/.test(type)) continue;
+ if (type === 'password' || /\bpassword\b/i.test(getAttr(m[2], 'autocomplete') || '')) return false;
+ fields.push(type + ' ' + [getAttr(m[2], 'name'), getAttr(m[2], 'id'), getAttr(m[2], 'placeholder'), getAttr(m[2], 'autocomplete')].filter(Boolean).join(' '));
+ }
+ return fields.length >= 1 && fields.length <= 2 && fields.some((f) => /^email\b/.test(f) || /e-?mail/i.test(f));
+}
+
+interface Open { t: Tag; i: number }
+
+// gate 85, written for the static tier: the render tier's email-band close, read from the markup
+function checkEmailBandClose(ctx: LintContext, r: Reporter): void {
+ if (ctx.job && NATIVE_LIST_JOB.test(ctx.job)) return;
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ const opens: Open[] = doc.tags.map((t, i) => ({ t, i })).filter(({ t }) => !t.close && !t.selfClosing);
+ const endOf = (o: Open): number => innerOf(doc, o.i)?.endPos ?? doc.src.length;
+ const footer = opens.filter(({ t }) => t.name === 'footer').pop() ?? null;
+ const limit = footer ? footer.t.pos : doc.src.length;
+ const before = opens.filter((o) => /^(section|form|article)$/.test(o.t.name) && o.t.pos < limit && endOf(o) <= limit).pop() ?? null;
+ for (const box of [before, footer]) {
+ if (!box) continue;
+ const end = endOf(box);
+ const form = opens.filter((o) => o.t.name === 'form' && o.i >= box.i && o.t.pos < end).find((o) => isEmailSignup(doc, o.i));
+ if (!form) continue;
+ const cls = getAttr(form.t.attrs, 'class');
+ const name = cls ? '<form class="' + trunc(cls, 24) + '">' : '<form>';
+ const where = box === footer ? 'in the footer' : 'as its last section';
+ const job = ctx.job ? ' on a ' + ctx.job + ' page' : ', and no job was named (--job)';
+ r.report('email-band-close', doc.file, form.t.line, 'the page closes on an email sign-up ' + name + ' ' + where + job);
+ return;
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ runChromeCopy(ctx, r);
+ runEyebrow(ctx, r);
+ checkNavShape(ctx, r);
+ checkFooterShape(ctx, r);
+ checkInventedProof(ctx, r);
+ checkDrawnChrome(ctx, r);
+ checkPlaceholderImages(ctx, r);
+ checkTemplatePunctuation(ctx, r);
+ checkWireframeSlots(ctx, r);
+ checkRepeatedFact(ctx, r);
+ checkFakeSend(ctx, r);
+ checkEmailBandClose(ctx, r);
+}
diff --git a/lib/design-lint/rules/color.ts b/lib/design-lint/rules/color.ts
new file mode 100644
index 000000000..a29b81d1d
--- /dev/null
+++ b/lib/design-lint/rules/color.ts
@@ -0,0 +1,265 @@
+/**
+ * Colour rules of the design lint (sloplint gates 2a 2b 7a 7b 22 23 29 48 65 74; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: purple-blue-gradient, gradient-text, pure-black-white, absolute-surface-token, zero-chroma-neutrals, accent-footprint, glow-wash, cream-palette, framework-palette, literal-outside-tokens (48).
+ *
+ * hallmark's theme stamp is gone: no colour posture is ever declared, no
+ * genre exempts a page, no theme is pinned by name, so every check here runs
+ * in its strict form.
+ */
+import { bannedGradient, COLOR_LITERAL, oklchOf, parseColor } from '../color';
+import type { LintContext } from '../context';
+import { mergedRules } from '../context';
+import { firstFamily, GENERIC_FAMILIES, isTokenRule, pxOf, resolveVars, splitTop, type CssDecl, type MergedRule, type Tokens } from '../css';
+import type { Reporter } from '../report';
+import { trunc } from '../report';
+
+const COLOR_FN = /#[0-9a-fA-F]{3,8}\b|oklch\([^)]*\)|rgba?\([^)]*\)|hsla?\([^)]*\)/g;
+
+// sloplint gradientHues (gate 2)
+function gradientHues(value: string, tokens: Tokens): number[] {
+ const hues: number[] = [];
+ for (const m of resolveVars(value, tokens).matchAll(COLOR_FN)) {
+ const c = parseColor(m[0]);
+ if (!c || c.alpha <= 0.05) continue;
+ const ok = oklchOf(c);
+ if (ok.C > 0.04) hues.push(ok.H);
+ }
+ return hues;
+}
+
+interface GradientText { r: MergedRule; clip: CssDecl; grad: CssDecl | undefined }
+
+// sloplint gradientTextRules (gate 2b)
+function gradientTextRules(ctx: LintContext): GradientText[] {
+ const out: GradientText[] = [];
+ for (const r of mergedRules(ctx)) {
+ const clip = r.decls.find((d) => /background-clip/.test(d.prop) && /\btext\b/i.test(d.value));
+ if (!clip) continue;
+ const grad = r.decls.find((d) => /^background(-image)?$/.test(d.prop) && /gradient\(/i.test(d.value));
+ const transparent = r.decls.find((d) => (d.prop === 'color' || d.prop === '-webkit-text-fill-color') && /transparent/i.test(d.value));
+ if (grad || transparent) out.push({ r, clip, grad });
+ }
+ return out;
+}
+
+// sloplint withoutPatterns (gate 2): repeating gradients draw stripes and grain, not a wash
+function withoutPatterns(value: string): string {
+ let out = '', i = 0;
+ const re = /repeating-(?:linear|radial|conic)-gradient\(/gi;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(value))) {
+ out += value.slice(i, m.index);
+ let depth = 1, k = m.index + m[0].length;
+ while (k < value.length && depth > 0) { if (value[k] === '(') depth++; else if (value[k] === ')') depth--; k++; }
+ i = k; re.lastIndex = k;
+ }
+ return out + value.slice(i);
+}
+
+// sloplint check2 (gates 2a, 2b)
+function check2(ctx: LintContext, r: Reporter): void {
+ const textRules = new Set<string>();
+ for (const { r: rule, clip, grad } of gradientTextRules(ctx)) {
+ textRules.add(rule.selector);
+ const banned = grad ? bannedGradient(gradientHues(grad.value, ctx.tokens), ctx.tokens) : null;
+ if (banned) r.report('purple-blue-gradient', rule.file, clip.line, `${banned} gradient text on ${rule.selector}`);
+ else r.report('gradient-text', rule.file, clip.line, `gradient text on ${rule.selector}`);
+ }
+ for (const rule of ctx.rules) {
+ if (textRules.has(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (!/gradient\(/i.test(d.value)) continue;
+ const washes = withoutPatterns(d.value);
+ if (!/gradient\(/i.test(washes)) continue;
+ const banned = bannedGradient(gradientHues(washes, ctx.tokens), ctx.tokens);
+ if (banned) r.report('purple-blue-gradient', rule.file, d.line, `${banned} gradient on ${rule.selector}`, { fix: 'one anchor hue; drop the gradient' });
+ }
+ }
+}
+
+// sloplint check7 (gates 7a, 7b)
+function check7(ctx: LintContext, r: Reporter): void {
+ const props = /^(color|background|background-color|border-color|outline-color)$|^--color-/;
+ for (const rule of ctx.rules) {
+ if (rule.selector === '@font-face') continue;
+ for (const d of rule.decls) {
+ if (!props.test(d.prop)) continue;
+ const c = parseColor(resolveVars(d.value, ctx.tokens).trim());
+ if (!c || c.alpha < 1) continue;
+ const isWhite = c.r > 0.999 && c.g > 0.999 && c.b > 0.999;
+ const isBlack = c.r < 0.001 && c.g < 0.001 && c.b < 0.001;
+ if (!isWhite && !isBlack) continue;
+ const viaToken = d.prop.startsWith('--') || /var\(/.test(d.value);
+ r.report(viaToken ? 'absolute-surface-token' : 'pure-black-white', rule.file, d.line,
+ `${d.prop}: ${trunc(d.value, 28)} on ${rule.selector} is pure ${isBlack ? 'black (#000)' : 'white (#fff)'}`);
+ }
+ }
+}
+
+// sloplint check22 (gate 22)
+function check22(ctx: LintContext, r: Reporter): void {
+ const MASK_PROPS = /(^|-)mask(-image|-composite|-mode)?$|^filter$|^backdrop-filter$/;
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (MASK_PROPS.test(d.prop)) continue;
+ const re = /oklch\(\s*([\d.]+%?)\s+([\d.]+)\s+[\d.]+(?:deg)?\s*(?:\/\s*([\d.]+%?))?\s*\)/g;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(d.value))) {
+ const chroma = parseFloat(m[2]);
+ const alpha = m[3] ? (m[3].endsWith('%') ? parseFloat(m[3]) / 100 : parseFloat(m[3])) : 1;
+ if (chroma === 0 && alpha >= 1) r.report('zero-chroma-neutrals', rule.file, d.line, `zero-chroma ${m[0]} as ${d.prop} on ${rule.selector}`);
+ }
+ }
+ }
+}
+
+// sloplint check23 (gate 23): no colour posture is ever declared, so every large accent fill is a finding
+function check23(ctx: LintContext, r: Reporter): void {
+ const ACC = /var\(\s*--color-accent(?:-2)?\s*[,)]/;
+ const SURFACE = /(^|[\s,>~+])(body|html|main|section|header|footer|aside)(\b|$)|\bhero\b|__hero|banner|\bstrip\b|\bband\b/i;
+ const big = (decls: CssDecl[]) => decls.some((d) =>
+ (/^(min-)?height$/.test(d.prop) && (parseFloat((/([\d.]+)\s*(vh|dvh|svh)/.exec(d.value) || [])[1] || '0') >= 40 || (pxOf(d.value) ?? 0) >= 320)) ||
+ (d.prop === 'inset' && /^0(px)?(\s|$)/.test(d.value.trim())));
+ for (const rule of ctx.rules) {
+ if (isTokenRule(rule) || rule.keyframes) continue;
+ for (const d of rule.decls) {
+ if (!/^background(-color|-image)?$/.test(d.prop) || !ACC.test(d.value)) continue;
+ if (/\/\s*0?\.[0-2]\d*/.test(d.value)) continue;
+ if (SURFACE.test(rule.selector) || big(rule.decls)) {
+ r.report('accent-footprint', rule.file, d.line, `accent background on the viewport-scale rule "${trunc(rule.selector, 44)}"`,
+ { fix: 'retreat the accent to actions and one signal; a large fill belongs to the paper or a field token' });
+ }
+ }
+ const col = rule.decls.find((d) => d.prop === 'color' && ACC.test(d.value));
+ const fsDecl = rule.decls.find((d) => d.prop === 'font-size');
+ if (!col || !fsDecl) continue;
+ const rv = resolveVars(fsDecl.value, ctx.tokens);
+ const clampMax = /,\s*([^,()]+)\)\s*$/.exec(rv);
+ const maxPx = pxOf(rv) ?? (clampMax ? pxOf(clampMax[1].trim()) : null);
+ if ((maxPx != null && maxPx >= 48) || /--text-display\b/.test(fsDecl.value)) {
+ r.report('accent-footprint', rule.file, col.line, `display-size text set in the accent on "${trunc(rule.selector, 44)}"`,
+ { fix: 'set display type in ink; the accent marks small signals' });
+ }
+ }
+}
+
+const lengthPx = (x: string): number | null => (x === '0' ? 0 : pxOf(x));
+
+// sloplint check29Glow (gate 29): no atmospheric exemption
+function check29Glow(ctx: LintContext, r: Reporter): void {
+ const seen = new Set<string>();
+ const once = (key: string, file: string, line: number, ev: string, fix: string) => {
+ if (seen.has(key)) return;
+ seen.add(key);
+ r.report('glow-wash', file, line, ev, { fix });
+ };
+ for (const rule of mergedRules(ctx)) {
+ if (isTokenRule(rule)) continue;
+ const local: Tokens = {};
+ for (const d of rule.decls) if (d.prop.startsWith('--')) local[d.prop] = d.value;
+ const name = trunc(rule.selector, 36);
+ const bf = rule.decls.find((d) => /^(-webkit-)?backdrop-filter$/.test(d.prop) && /blur\(/i.test(d.value));
+ if (bf) {
+ const bgD = rule.decls.filter((d) => /^background(-color)?$/.test(d.prop)).pop();
+ const rv = bgD ? resolveVars(bgD.value, ctx.tokens, local).trim() : '';
+ const c = parseColor(rv);
+ const mixed = /color-mix\([^)]*\b(white|black|--color-(paper|ink))\b[^)]*\btransparent\b/i.exec(rv);
+ const nearWhite = !!c && c.r > 0.85 && c.g > 0.85 && c.b > 0.85;
+ const nearBlack = c ? c.r < 0.15 && c.g < 0.15 && c.b < 0.15 : !!mixed && /^(black|--color-ink)$/i.test(mixed[1]);
+ if ((c && c.alpha < 0.95 && (nearWhite || nearBlack)) || (!c && mixed)) {
+ once('glass:' + rule.selector, rule.file, bf.line, `glass panel: backdrop-filter blur over a translucent ${nearBlack ? 'black' : 'white'} on ${name}`, 'a solid or grained surface; elevation by lightness');
+ }
+ }
+ for (const d of rule.decls) {
+ if (d.prop !== 'box-shadow') continue;
+ for (const part of splitTop(resolveVars(d.value, ctx.tokens, local))) {
+ const cm = COLOR_LITERAL.exec(part);
+ if (!cm) continue;
+ const c = parseColor(cm[0]);
+ if (!c || c.alpha <= 0.05 || oklchOf(c).C <= 0.04) continue;
+ const lens = part.replace(cm[0], ' ').replace(/\binset\b/, ' ').trim().split(/\s+/).filter(Boolean).map(lengthPx);
+ if (lens.length >= 3 && lens[0] === 0 && lens[1] === 0 && lens[2] != null && lens[2] > 20) {
+ once('glow:' + rule.selector, rule.file, d.line, `coloured zero-offset glow (blur ${Math.round(lens[2])}px) on ${name}`, 'shadows carry offset and blur in a neutral; colour is not depth');
+ break;
+ }
+ }
+ }
+ if (!/::(before|after)/.test(rule.selector) || !rule.decls.some((d) => d.prop === 'position' && /absolute|fixed/.test(d.value))) continue;
+ const f = rule.decls.find((d) => d.prop === 'filter' && /blur\(\s*(\d+(?:\.\d+)?)px/i.test(d.value));
+ const n = f ? parseFloat(/blur\(\s*(\d+(?:\.\d+)?)px/i.exec(f.value)![1]) : 0;
+ if (f && n > 40) once('orb:' + rule.selector, rule.file, f.line, `blurred orb: filter blur(${n}px) on the positioned ${name}`, 'delete the wash; a surface is paper or ground, not a light show');
+ }
+}
+
+const HIGH_CONTRAST_SERIF = /bodoni|didot|didone|playfair|fraunces|instrument serif|cormorant|dm serif|libre caslon display|abril|prata|gloock|newsreader|editorial new|gt sectra|canela|freight|yeseva|rozha|boska|melodrama/i;
+
+// sloplint check65 (gate 65): the look is never pinned by name here
+function check65(ctx: LintContext, r: Reporter): void {
+ const paper = parseColor(resolveVars(ctx.tokens['--color-paper'] || '', ctx.tokens));
+ const accent = parseColor(resolveVars(ctx.tokens['--color-accent'] || '', ctx.tokens));
+ if (!paper || !accent) return;
+ const p = oklchOf(paper), a = oklchOf(accent);
+ const cream = p.L >= 0.9 && p.C >= 0.006 && p.H >= 55 && p.H <= 105;
+ const clay = a.C >= 0.08 && a.H >= 15 && a.H <= 55;
+ const disp = firstFamily(resolveVars(ctx.tokens['--font-display'] || '', ctx.tokens));
+ if (!cream || !clay || !HIGH_CONTRAST_SERIF.test(disp)) return;
+ r.report('cream-palette', ctx.cssFiles[0]?.file || ctx.docs[0]?.file || ctx.key, 1,
+ `the default tasteful look: cream paper (L ${Math.round(p.L * 100)}%, hue ${Math.round(p.H)}), ${disp} as the display and a clay accent (hue ${Math.round(a.H)})`);
+}
+
+const TAILWIND_HEX = /#(0f172a|1e293b|6366f1|8b5cf6|3b82f6|f8fafc|64748b)\b/i;
+
+// sloplint check65Tailwind (gate 74, the token half; palette utility classes belong to the Tailwind rules)
+function check74Tokens(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ if (!isTokenRule(rule) || rule.selector === '@font-face') continue;
+ for (const d of rule.decls) {
+ const m = TAILWIND_HEX.exec(d.value);
+ if (m) r.report('framework-palette', rule.file, d.line, `Tailwind's default ${m[0]} as ${d.prop}`);
+ }
+ }
+}
+
+const COLOR_LIT_TEST = /#[0-9a-fA-F]{3,8}\b|(?<![\w-])rgba?\(|(?<![\w-])hsla?\(|(?<![\w-])oklch\(/;
+
+// sloplint check48 (gate 48); hallmark's scaffold placeholder ("FILL ME") has no counterpart here.
+// hallmark lints pages its own skill scaffolded, which always carry a token block; gstack also meets
+// handwritten pages with no tokens at all, where a literal bypasses nothing, so the rule needs a
+// --color-* or --font-* token to exist before a literal counts as a bypass.
+function check48(ctx: LintContext, r: Reporter): void {
+ if (!Object.keys({ ...ctx.twTokens, ...ctx.tokens }).some((k) => /^--(color|font)-/.test(k))) return;
+ for (const rule of ctx.rules) {
+ if (isTokenRule(rule)) continue;
+ for (const d of rule.decls) {
+ if (d.prop.startsWith('--')) continue;
+ if (d.prop === 'font-family') {
+ if (d.value.includes('var(') || GENERIC_FAMILIES.has(firstFamily(d.value))) continue;
+ r.report('literal-outside-tokens', rule.file, d.line, `font-family literal "${trunc(d.value, 36)}" on ${rule.selector}`);
+ continue;
+ }
+ if (!COLOR_LIT_TEST.test(d.value)) continue;
+ for (const m of d.value.matchAll(COLOR_FN)) {
+ const c = parseColor(m[0]);
+ if (!c || c.alpha === 0) continue;
+ r.report('literal-outside-tokens', rule.file, d.line, `colour literal ${trunc(m[0], 30)} outside the token block (${d.prop} on ${trunc(rule.selector, 30)})`);
+ }
+ }
+ }
+ for (const doc of ctx.docs) {
+ for (const m of doc.src.matchAll(/style\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
+ const lit = new RegExp(COLOR_FN.source).exec(m[1] ?? m[2]);
+ if (lit && parseColor(lit[0])) r.report('literal-outside-tokens', doc.file, doc.lineOf(m.index!), `inline style colour literal ${trunc(lit[0], 30)}`);
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ check2(ctx, r);
+ check7(ctx, r);
+ check22(ctx, r);
+ check23(ctx, r);
+ check29Glow(ctx, r);
+ check65(ctx, r);
+ check74Tokens(ctx, r);
+ check48(ctx, r);
+}
diff --git a/lib/design-lint/rules/component.ts b/lib/design-lint/rules/component.ts
new file mode 100644
index 000000000..0d3127c8c
--- /dev/null
+++ b/lib/design-lint/rules/component.ts
@@ -0,0 +1,118 @@
+/**
+ * Component rules of the design lint (sloplint checkTailwind and
+ * checkComponentText; Nutlope/hallmark, MIT, see NOTICE.md), rewritten in
+ * gstack's voice: the Tailwind form of gates 2a 2b 3 6a 10a 11 12 29 48 54 64
+ * 67 and 74 read off utility class strings in pages and components, plus
+ * emoji icons and template punctuation (30a, 63) in component text.
+ */
+import type { LintContext } from '../context';
+import { oneLine, relPath, trunc, type Finding, type Reporter } from '../report';
+import { compInner, twEyebrow, twGlow, twGradient, twGroup, twMonoIsMaterial, twPlain, twText, twTiles, twTokens, twTrackedCaps, twWhere, twDataText, type TwItem } from '../tailwind';
+
+const EMOJI_ICON = /(?![©®™‼⁉←-⇿])\p{Extended_Pictographic}/u;
+
+/** Findings already on the record, keyed rule|file|line, so a Tailwind tell on a line the stylesheet rules already reported is not repeated; O(1) per lookup however many labels a page holds. */
+function reported(r: Reporter): Set<string> {
+ return new Set(r.findings.map((x) => `${x.rule}|${x.file}|${x.line}`));
+}
+
+/** The tells one class string carries on its own: motion, gradient, glow, literals, a moving image, tracked caps, the eyebrow, mono costume. */
+function reportItem(ctx: LintContext, r: Reporter, it: TwItem, monoOk: boolean, seen: Set<string>): void {
+ const { doc, info: f } = it;
+ const where = twWhere(it);
+ const file = oneLine(relPath(doc.file, r.cwd));
+ const had = (rule: string) => seen.has(`${rule}|${file}|${it.line}`);
+ if (f.tAll) r.report('layout-transition', doc.file, it.line, `${f.tAll} on ${where}`, { fix: 'name the properties: transition-colors, transition-opacity or transition-transform' });
+ if (f.bounce || f.overshoot) r.report('bounce-easing', doc.file, it.line, `${f.bounce ? 'bounce' : 'overshoot easing'} ${f.bounce || f.overshoot} on ${where}`, { fix: 'an exponential ease-out on UI state; no bounce or overshoot' });
+ const g = twGradient(ctx, f);
+ if (g && g.banned) r.report('purple-blue-gradient', doc.file, it.line, `${g.banned} gradient${g.text ? ' text' : ''} (${g.list}) on ${where}`);
+ else if (g && g.text) r.report('gradient-text', doc.file, it.line, `gradient text (${g.list}) on ${where}`);
+ const glow = f.bblur && f.glass ? `glass: ${f.bblur} over ${f.glass}`
+ : f.blur >= 40 && f.pos && (f.fill || f.grad || f.stops.length) ? `blurred orb: ${f.blurTok} on a filled ${f.pos} element`
+ : twGlow(ctx, f);
+ if (glow) r.report('glow-wash', doc.file, it.line, `${glow} on ${where}`);
+ if (f.colours.length || f.font) {
+ const what = [f.colours.length ? `colour literal ${f.colours[0].tok}` : null, f.font ? `font-family literal ${f.font}` : null].filter(Boolean).join(' and ');
+ const certain = !!f.font || f.colours.some((c) => !c.oklch);
+ r.report('literal-outside-tokens', doc.file, it.line, `${what} in a class on ${where}`, { fix: 'lift the value into the token block (@theme or :root) and use its utility name', suspected: !certain });
+ }
+ if ((f.hScale || f.hRotate) && /^(?:img|picture|image)$/i.test(it.tag)) r.report('hover-tells', doc.file, it.line, `${f.hScale || f.hRotate} on ${where}: the image moves on hover`, { fix: 'imagery sits still; give the container the feedback' });
+ const caps = twTrackedCaps(it, twGroup(ctx));
+ if (caps && !had('wide-tracking')) {
+ const text = it.virtual ? '' : twText(it);
+ r.report('wide-tracking', doc.file, it.line, `${text ? `"${trunc(text, 24)}" ` : ''}${caps.what}${caps.size != null ? ` at ${caps.size}px` : ''}${caps.em != null ? ` tracked ${caps.em}em` : ''} on ${where}`, { fix: 'sentence case in the body face, a step smaller, untracked: drop uppercase and the tracking-* class' });
+ }
+ const eyebrow = twEyebrow(it);
+ if (eyebrow && !had('kicker-above-heading')) {
+ r.report('kicker-above-heading', doc.file, it.line, `eyebrow ${eyebrow.text ? `"${trunc(eyebrow.text, 24)}" ` : ''}before <${eyebrow.next}> (${eyebrow.signal} at ${it.frame.size}px)`);
+ }
+ if (!monoOk && f.mono && !it.virtual && !it.frame.code && !/^(?:code|pre|kbd|samp|time|var)$/.test(it.tag) && it.frame.size != null && it.frame.size <= 14) {
+ const text = twText(it);
+ if (/[A-Za-z]/.test(text) && !twDataText(text)) r.report('monospace-costume', doc.file, it.line, `font-mono on "${trunc(text, 24)}" at ${it.frame.size}px (${where})`, { fix: 'labels in the body face at a smaller size and normal case; font-mono only for code and figures' });
+ }
+}
+
+/** The tells a file carries as a whole: a default palette, hover scale everywhere, a vh hero, three icon tiles. */
+function reportFile(r: Reporter, list: TwItem[]): void {
+ const doc = list[0].doc;
+ const pal = new Map<string, TwItem>();
+ let palAt: TwItem | null = null;
+ for (const it of list) for (const p of it.info.pal) if (!pal.has(p)) { pal.set(p, it); if (pal.size === 5) palAt = it; }
+ if (palAt) r.report('framework-palette', doc.file, palAt.line, `a framework default palette instead of the page's tokens: ${pal.size} distinct palette classes (${[...pal.keys()].slice(0, 4).join(' ')})`, { fix: "extend the Tailwind theme with the page's tokens and use those names" });
+ const scaled = list.filter((it) => it.info.hScale);
+ if (scaled.length >= 3) r.report('hover-tells', doc.file, scaled[2].line, `hover scale on ${scaled.length} elements in this file (${scaled.slice(0, 3).map((it) => it.info.hScale).join(', ')})`, { fix: 'one hover signal per element; not every card grows' });
+ const first = new Set(['section', 'header'].map((n) => doc.tags.findIndex((t) => !t.close && t.name === n)).filter((x) => x >= 0));
+ const byIdx = new Map<number, TwItem>();
+ for (const it of list) if (it.idx >= 0) byIdx.set(it.idx, it);
+ for (const it of list) {
+ if (it.info.vh && !it.virtual && (first.has(it.idx) || it.info.hero)) r.report('vh-height', doc.file, it.line, `hero sized in vh: ${it.info.vh} on ${twWhere(it)}`, { fix: 'min-h-dvh or min-h-svh' });
+ if (it.info.cols3 && it.idx >= 0) {
+ const n = twTiles(it, byIdx);
+ if (n >= 3) r.report('template-cards', doc.file, it.line, `icon-tile row: ${n} children of ${twWhere(it)} open on an icon in a rounded filled tile above an h3`, { fix: 'vary the column widths or drop the icon tiles' });
+ }
+ }
+}
+
+// sloplint checkTailwind (gates 10a 12 2a 2b 29 48 11 67 54 64 74 6a 3)
+function checkTailwind(ctx: LintContext, r: Reporter): void {
+ const tw = twGroup(ctx);
+ if (!tw.items.length) return;
+ const monoOk = twMonoIsMaterial(twTokens(ctx));
+ const byDoc = new Map<string, TwItem[]>();
+ const seen = reported(r);
+ for (const it of tw.items) {
+ if (!byDoc.has(it.file)) byDoc.set(it.file, []);
+ byDoc.get(it.file)!.push(it);
+ const before = r.findings.length;
+ reportItem(ctx, r, it, monoOk, seen);
+ for (let k = before; k < r.findings.length; k++) seen.add(`${r.findings[k].rule}|${r.findings[k].file}|${r.findings[k].line}`);
+ }
+ for (const list of byDoc.values()) reportFile(r, list);
+}
+
+// sloplint checkComponentText (gates 63 30a)
+function checkComponentText(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ for (let c = 0; c < doc.comps.length; c++) {
+ const t = doc.comps[c];
+ if (t.close || t.selfClosing) continue;
+ const inner = compInner(doc, c);
+ if (!inner || /<(?:p|div|li|section|article|ul|ol|table)\b/i.test(inner)) continue;
+ const text = twPlain(doc, inner);
+ if (!text) continue;
+ if (/(?:link|button|btn|cta)$/i.test(t.name) && /(→|->|›|»|⟶)\s*$/.test(text)) r.report('template-punctuation', doc.file, t.line, `arrow glued to the label "${trunc(text, 40)}" (<${t.name}>)`, { fix: 'a verb as the label; the link already says it goes somewhere' });
+ if ((text.match(/\s[·•]\s/g) || []).length >= 2) r.report('template-punctuation', doc.file, t.line, `middle-dot meta string "${trunc(text, 50)}"`, { fix: 'line breaks, columns or hairlines; one dot in a byline at most' });
+ if (text.length <= 4 && EMOJI_ICON.test(text)) {
+ const recorded = (doc.cache.emojiQuoted as Map<string, Finding[]> | undefined)?.get(text) ?? [];
+ const icon = recorded.find((f) => f.line === t.line) ?? recorded[0];
+ if (icon) { recorded.splice(recorded.indexOf(icon), 1); const outer = r.findings.indexOf(icon); if (outer >= 0) r.findings.splice(outer, 1); }
+ r.report('emoji-decoration', doc.file, t.line, `emoji icon "${text}" in <${t.name}>`, { fix: 'one icon library or custom SVG' });
+ }
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ checkTailwind(ctx, r);
+ checkComponentText(ctx, r);
+}
diff --git a/lib/design-lint/rules/copy.ts b/lib/design-lint/rules/copy.ts
new file mode 100644
index 000000000..a41d598fa
--- /dev/null
+++ b/lib/design-lint/rules/copy.ts
@@ -0,0 +1,43 @@
+/**
+ * The copy tier: gstack-design-craft's content-realism and ship-floor tells
+ * (lib/design-craft.ts, Elaya-derived, MIT) under the lint's contract. The
+ * craft check counts occurrences without positions, so these report at the
+ * document's first line with the count as evidence until Phase 2 folds the
+ * patterns into the lint. Tells the static tier already reports with a line
+ * (transition: all under layout-transition, 100vh under vh-height) are left
+ * to it.
+ */
+import { checkCraft } from '../../design-craft';
+import type { LintContext } from '../context';
+import type { Doc } from '../html';
+import type { Reporter } from '../report';
+import { ruleMeta } from './ids';
+
+const STATIC_OWNS = new Set(['transition-all', 'vh-height']);
+
+/** The elements the craft check reads from open tag to close tag with a lazy scan. */
+const SPANNED = new Set(['script', 'style', 'template', 'nav']);
+
+/** The page as the craft check reads it: an open script, style, template or nav tag that nothing closes after it is blanked, so each lazy scan to its close finds one and the page costs its length. */
+function craftSource(doc: Doc): string {
+ const lastClose = new Map<string, number>();
+ for (const t of doc.tags) if (t.close && SPANNED.has(t.name)) lastClose.set(t.name, t.pos);
+ let out = '', from = 0;
+ for (const t of doc.tags) {
+ if (t.close || !SPANNED.has(t.name) || t.pos < (lastClose.get(t.name) ?? -1)) continue;
+ out += doc.src.slice(from, t.pos) + ' ';
+ from = t.pos + 1;
+ }
+ return out + doc.src.slice(from);
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ for (const f of checkCraft(craftSource(doc))) {
+ if (STATIC_OWNS.has(f.id) || !ruleMeta(f.id)) continue;
+ const title = ruleMeta(f.id)!.title;
+ r.report(f.id, doc.file, 1, f.count === 1 ? title : `${title}, ${f.count} times`, { fix: f.fix, source: 'copy' });
+ }
+ }
+}
diff --git a/lib/design-lint/rules/finish.ts b/lib/design-lint/rules/finish.ts
new file mode 100644
index 000000000..215303505
--- /dev/null
+++ b/lib/design-lint/rules/finish.ts
@@ -0,0 +1,347 @@
+/**
+ * Finish rules of the design lint (sloplint gates F1-F9 F15 F16 F21-F24; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: straight-quotes, three-dot-ellipsis, balanced-display-head, two-primary-buttons, icon-coin, display-figures-tabular, stamped-recipe, scroll-choreography-mix, fake-avatar, stock-person-photo, page-invariants, unthemed-browser-surfaces, skipped-heading, justified-text, missing-lang, hairline-under-shadow.
+ * Everything here is polish except fake-avatar, which blocks. F17 to F20 are render-only and
+ * live in the render tier; the title and description halves of F23 are the copy tier's.
+ */
+import { mergedRules, type LintContext } from '../context';
+import { HEADING_SEL, isTokenRule, lineIndex, pxOf, resolveVars, splitTop, type MergedRule } from '../css';
+import { getAttr, maskedProse, openTags, plainText } from '../html';
+import { trunc, type Reporter } from '../report';
+import { twVariants } from '../tailwind';
+
+/** The largest px, rem or em length in a value, at a 16px root; null when it has none. */
+// sloplint maxPxIn
+function maxPxIn(value: string): number | null {
+ let best: number | null = null;
+ for (const m of value.matchAll(/(-?\d*\.?\d+)(px|rem|em)/g)) {
+ const px = m[2] === 'px' ? parseFloat(m[1]) : parseFloat(m[1]) * 16;
+ if (best == null || px > best) best = px;
+ }
+ return best;
+}
+
+// sloplint baseSelector
+const baseSelector = (sel: string): string => sel.replace(/::?[a-z-]+(\([^)]*\))?/gi, '').replace(/\s+/g, ' ').trim();
+
+const firstFile = (ctx: LintContext): string | null => ctx.cssFiles[0]?.file || ctx.docs[0]?.file || null;
+
+
+// sloplint checkF1 (F1)
+function checkStraightQuotes(ctx: LintContext, r: Reporter): void {
+ const dq = /(?:"|&quot;|&#0?34;)(?=[A-Za-z])|[A-Za-z](?:"|&quot;|&#0?34;)/g;
+ const ap = /[A-Za-z](?:'|&#0?39;|&apos;)(?=[A-Za-z])/g;
+ for (const doc of ctx.docs) {
+ const prose = maskedProse(doc);
+ const hits = [...prose.matchAll(dq), ...prose.matchAll(ap)].sort((a, b) => a.index! - b.index!);
+ if (!hits.length) continue;
+ const at = hits[0].index!;
+ const around = prose.slice(Math.max(0, at - 16), at + 16).replace(/\s+/g, ' ').trim();
+ r.report('straight-quotes', doc.file, doc.lineOf(at), hits.length + ' straight quote' + (hits.length === 1 ? '' : 's') + ' in prose (first: ' + trunc(around, 40) + ')', { fix: 'typographic quotes: \u201C \u201D \u2019' });
+ }
+}
+
+// sloplint checkF2 (F2)
+function checkEllipsis(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const prose = maskedProse(doc);
+ const hits = [...prose.matchAll(/\.{3,}/g)];
+ if (hits.length) r.report('three-dot-ellipsis', doc.file, doc.lineOf(hits[0].index!), hits.length + ' three-dot ellips' + (hits.length === 1 ? 'is' : 'es') + ' in prose', { fix: 'the ellipsis character (\u2026)' });
+ }
+}
+
+// sloplint checkF3 (F3)
+function checkBalancedHeads(ctx: LintContext, r: Reporter): void {
+ const H12 = /(^|[\s,>+~(])h[12]\b/i;
+ const targets: MergedRule[] = [];
+ let satisfied = false;
+ for (const rule of mergedRules(ctx)) {
+ const isH12 = H12.test(rule.selector);
+ const isDisplayClass = HEADING_SEL.test(rule.selector) && rule.decls.some((d) => d.prop === 'font-size' && (maxPxIn(resolveVars(d.value, ctx.tokens)) ?? 0) >= 40);
+ if (!isH12 && !isDisplayClass) continue;
+ targets.push(rule);
+ if (rule.decls.some((d) => /^text-wrap(-style)?$/.test(d.prop) && /balance/.test(d.value))) satisfied = true;
+ }
+ if (targets.length && !satisfied) {
+ r.report('balanced-display-head', targets[0].file, targets[0].line, 'no text-wrap: balance on any display head (' + targets.length + ' head rules, the first ' + trunc(targets[0].selector, 32) + ')', { fix: 'text-wrap: balance on the h1 and h2 level heads' });
+ }
+}
+
+// sloplint checkF4 (F4): the recipe count; the side-by-side half is rules/chrome-copy.ts
+function checkPrimaryRecipes(ctx: LintContext, r: Reporter): void {
+ const BTN = /\b(btn|button|cta)\b|__(btn|button|cta)\b/i;
+ const filled = new Map<string, { rule: MergedRule; line: number }>();
+ for (const rule of mergedRules(ctx)) {
+ if (isTokenRule(rule) || /:hover|:active|:focus|:disabled|\.is-|\[disabled/i.test(rule.selector)) continue;
+ const first = baseSelector(rule.selector.split(',')[0]);
+ if (!BTN.test(first)) continue;
+ for (const d of rule.decls) {
+ if (!/^background(-color)?$/.test(d.prop)) continue;
+ if (/transparent|none/i.test(resolveVars(d.value, ctx.tokens))) continue;
+ if (/var\(\s*--color-(?!paper|rule|muted|focus)[\w-]+/.test(d.value) && !filled.has(first)) filled.set(first, { rule, line: d.line });
+ }
+ }
+ if (filled.size < 2) return;
+ const sels = [...filled.keys()];
+ const second = filled.get(sels[1])!;
+ r.report('two-primary-buttons', second.rule.file, second.line, filled.size + ' filled primary-button recipes on one page: ' + trunc(sels.join(' and '), 52));
+}
+
+// sloplint checkF5 (F5)
+function checkIconCoins(ctx: LintContext, r: Reporter): void {
+ for (const rule of mergedRules(ctx)) {
+ if (isTokenRule(rule) || !/icon|\bico\b/i.test(rule.selector)) continue;
+ const radius = rule.decls.find((d) => d.prop === 'border-radius');
+ if (!radius) continue;
+ const rv = resolveVars(radius.value, ctx.tokens);
+ const pct = /(\d+(?:\.\d+)?)%/.exec(rv);
+ if (!((pct && parseFloat(pct[1]) >= 50) || (maxPxIn(rv) ?? 0) >= 999)) continue;
+ const bg = rule.decls.find((d) => /^background(-color)?$/.test(d.prop) && !/^(none|transparent)$/i.test(resolveVars(d.value, ctx.tokens).trim()));
+ if (!bg) continue;
+ const small = rule.decls.some((d) => (d.prop === 'width' || d.prop === 'height') && (pxOf(resolveVars(d.value, ctx.tokens)) ?? 999) <= 64);
+ if (small) r.report('icon-coin', rule.file, bg.line, 'an icon in a coloured coin: ' + trunc(rule.selector, 40), { fix: 'drop the tinted coin; the icon at text size in currentColor' });
+ }
+}
+
+// sloplint checkF6 (F6)
+function checkTabularFigures(ctx: LintContext, r: Reporter): void {
+ const NUM_SEL = /\b(stat(?!ement)|price|table|figure|count|num)[\w-]*/i;
+ const hasTnum = (rule: { decls: MergedRule['decls'] }): boolean => rule.decls.some((d) => d.prop === 'font-variant-numeric' || (d.prop === 'font-feature-settings' && /tnum/.test(d.value)));
+ if (ctx.rules.some((rule) => /^(html|body|:root)\b/i.test(rule.selector.trim()) && hasTnum(rule))) return;
+ const bySel = mergedRules(ctx);
+ const covered = new Set(bySel.filter(hasTnum).map((rule) => baseSelector(rule.selector)));
+ const warned = new Set<string>();
+ for (const rule of bySel) {
+ if (isTokenRule(rule) || !NUM_SEL.test(rule.selector)) continue;
+ const base = baseSelector(rule.selector);
+ if (warned.has(base) || covered.has(base)) continue;
+ const size = rule.decls.find((d) => d.prop === 'font-size');
+ if (!size || (maxPxIn(resolveVars(size.value, ctx.tokens)) ?? 0) < 24) continue;
+ warned.add(base);
+ r.report('display-figures-tabular', rule.file, size.line, 'figures on ' + trunc(base, 36) + ' at display size without tabular numerals');
+ }
+}
+
+// sloplint checkF7 (F7)
+function checkStampedRecipe(ctx: LintContext, r: Reporter): void {
+ const byKey = new Map<string, { sels: Set<string>; rule: MergedRule }>();
+ for (const rule of mergedRules(ctx)) {
+ if (isTokenRule(rule) || /::(before|after)/.test(rule.selector)) continue;
+ const get = (re: RegExp): string => {
+ const d = rule.decls.filter((x) => re.test(x.prop)).pop();
+ return d ? resolveVars(d.value, ctx.tokens).replace(/\s+/g, ' ').trim() : '';
+ };
+ const border = get(/^border$/) || [get(/^border-width$/), get(/^border-style$/), get(/^border-color$/)].filter(Boolean).join(' ');
+ const radius = get(/^border-radius$/);
+ const surface = get(/^background(-color)?$/);
+ const shadow = get(/^box-shadow$/);
+ if (!radius || (!border && !surface && !shadow)) continue;
+ const key = [border, radius, surface, shadow].join(' | ');
+ if (!byKey.has(key)) byKey.set(key, { sels: new Set(), rule });
+ for (const part of rule.selector.split(',')) byKey.get(key)!.sels.add(baseSelector(part));
+ }
+ for (const v of byKey.values()) {
+ if (v.sels.size < 6) continue;
+ r.report('stamped-recipe', v.rule.file, v.rule.line, 'one container recipe on ' + v.sels.size + ' selectors (' + trunc([...v.sels].slice(0, 4).join(', '), 48) + ' and more)', { fix: 'vary weight, radius or fill by role; not every box is the same box' });
+ }
+}
+
+// sloplint checkF7Pills (F7)
+function checkPillRadius(ctx: LintContext, r: Reporter): void {
+ const CONTROLISH = /btn|button|cta|input|select|textarea|switch|toggle|control|chip|pill|tag|badge|status/i;
+ const sels = new Set<string>();
+ let where: { rule: MergedRule; line: number } | null = null;
+ for (const rule of mergedRules(ctx)) {
+ if (isTokenRule(rule)) continue;
+ const d = rule.decls.filter((x) => x.prop === 'border-radius').pop();
+ if (!d || !/^(9999px|999px|50rem)$/.test(resolveVars(d.value, ctx.tokens).trim())) continue;
+ for (const part of rule.selector.split(',')) {
+ const b = baseSelector(part);
+ if (!b || CONTROLISH.test(b)) continue;
+ sels.add(b);
+ where = where || { rule, line: d.line };
+ }
+ }
+ if (sels.size >= 5 && where) r.report('stamped-recipe', where.rule.file, where.line, 'the pill radius on ' + sels.size + ' non-control selectors (' + trunc([...sels].slice(0, 4).join(', '), 48) + ')', { fix: 'pills on controls, tags and badges; boxes and media take the card radius' });
+}
+
+// sloplint checkF8 (F8)
+function checkScrollChoreography(ctx: LintContext, r: Reporter): void {
+ const famOf = (sel: string): string => {
+ const m = /\.([a-z][\w-]*)/i.exec(sel) || /(^|[\s>+~])([a-z][\w-]*)/i.exec(sel);
+ const name = m ? (m[1] || m[2]) : sel;
+ return name.split('__')[0].split('--')[0].toLowerCase();
+ };
+ const NAVISH = /^(nav|header|topbar|masthead|banner)$/;
+ type Site = { rule: MergedRule | typeof ctx.rules[number]; line: number };
+ const timeline = new Map<string, Site>(), sticky = new Map<string, Site>(), animated = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule)) continue;
+ for (const d of rule.decls) {
+ if (d.prop === 'animation-timeline' && !/^(none|auto)$/i.test(d.value.trim()) && !timeline.has(famOf(rule.selector))) timeline.set(famOf(rule.selector), { rule, line: d.line });
+ if (d.prop === 'animation' || d.prop === 'animation-name') animated.add(famOf(rule.selector));
+ if (d.prop === 'position' && /sticky/i.test(d.value)) sticky.set(famOf(rule.selector), { rule, line: d.line });
+ }
+ }
+ const families = new Map(timeline);
+ for (const [fam, v] of sticky) if (!families.has(fam) && animated.has(fam) && !NAVISH.test(fam)) families.set(fam, v);
+ if (families.size < 2) return;
+ const names = [...families.keys()];
+ const second = families.get(names[1])!;
+ r.report('scroll-choreography-mix', second.rule.file, second.line, families.size + ' scroll-choreography patterns on one page (' + trunc(names.join(', '), 44) + ')', { fix: 'one scroll pattern a page; cut the rest' });
+}
+
+const FAKE_AVATAR = /(i\.pravatar\.cc|pravatar\.cc|api\.dicebear\.com|dicebear\.com|randomuser\.me|thispersondoesnotexist\.com|ui-avatars\.com)/i;
+/** Each URL token is scanned once (a scheme is only tried at a token start), so a run of scheme prefixes costs its length. */
+const UNSPLASH_URL = /(?<![^"'()\s])https?:\/\/[^"'()\s]*unsplash\.com[^"'()\s]*/gi;
+const PERSONY = /person|face|portrait|people|headshot/i;
+
+// sloplint checkF9 (F9)
+function checkAvatars(ctx: LintContext, r: Reporter): void {
+ const scan = (text: string, file: string, lineAt: (i: number) => number): void => {
+ const f = FAKE_AVATAR.exec(text);
+ if (f) r.report('fake-avatar', file, lineAt(f.index), 'a generated-face service (' + f[1] + ') stands in for a person', { fix: 'the real person\'s own photo, initials, or no portrait; a generated stranger is fabricated social proof' });
+ for (const m of text.matchAll(UNSPLASH_URL)) {
+ if (PERSONY.test(m[0])) r.report('stock-person-photo', file, lineAt(m.index!), 'a stock person-keyword URL ' + trunc(m[0], 44), { fix: 'faces as social proof need real people; a stock face is a stranger' });
+ }
+ };
+ for (const doc of ctx.docs) scan(doc.src, doc.file, (i) => doc.lineOf(i));
+ for (const c of ctx.cssFiles) scan(c.raw, c.file, lineIndex(c.raw));
+}
+
+// sloplint trackCount
+function trackCount(v: string): number {
+ const t = v.replace(/\[[^\]]*\]/g, ' ').trim();
+ const rep = /^repeat\(\s*(\d+)/.exec(t);
+ if (rep) return Number(rep[1]);
+ let depth = 0, n = 0, inTok = false;
+ for (const ch of t) {
+ if (ch === '(') depth++;
+ else if (ch === ')') depth--;
+ if (depth === 0 && /\s/.test(ch)) inTok = false;
+ else if (!inTok) { inTok = true; n++; }
+ }
+ return n;
+}
+
+// sloplint checkF15 (F15)
+function checkPageInvariants(ctx: LintContext, r: Reporter): void {
+ const file = firstFile(ctx);
+ if (!file) return;
+ const widths = new Map<number, string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || rule.media || !/container|wrap|inner|shell|content|section|page|main/i.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'max-width') continue;
+ const px = maxPxIn(resolveVars(d.value, ctx.tokens));
+ if (px && px >= 900) widths.set(px, rule.selector);
+ }
+ }
+ if (widths.size > 1) r.report('page-invariants', file, 1, widths.size + ' container widths on one page (' + [...widths.keys()].join(', ') + 'px)', { fix: 'one container width, applied the same way in every section' });
+ const gaps = new Map<string, string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || rule.media || /hero|masthead|fold|\b(?:app|ui|demo|sample|screen|product|mock|device|console|editor|window)(?:\b|__|--)|\[data-slot/i.test(rule.selector)) continue;
+ const cols = rule.decls.find((d) => d.prop === 'grid-template-columns' && trackCount(d.value) > 1 && !/^repeat\(\s*auto/.test(d.value.trim()));
+ if (!cols) continue;
+ const gap = rule.decls.find((d) => /^(gap|column-gap)$/.test(d.prop));
+ if (!gap) continue;
+ const v = resolveVars(gap.value, ctx.tokens).split(/\s+/).pop()!;
+ const px = maxPxIn(v);
+ if (px != null && px >= 24) gaps.set(v, rule.selector);
+ }
+ if (gaps.size > 2) r.report('page-invariants', file, 1, gaps.size + ' different column gaps across multi-column sections (' + [...gaps.keys()].join(', ') + ')', { fix: 'one column gap for every multi-column section' });
+}
+
+// sloplint checkF16 (F16)
+function checkBrowserSurfaces(ctx: LintContext, r: Reporter): void {
+ const file = firstFile(ctx);
+ if (!file || ctx.tokensOnly || !ctx.tokens['--color-accent']) return;
+ const classes = ctx.docs.map((d) => [...d.src.matchAll(/class(?:Name)?\s*=\s*["']([^"']*)["']/gi)].map((m) => m[1]).join(' ')).join(' ');
+ const missing: string[] = [];
+ if (!/::selection/.test(ctx.allCss) && !twVariants(ctx).has('selection') && !/(?<![\w-])selection:/.test(classes)) missing.push('::selection');
+ if (!/scrollbar-color|::-webkit-scrollbar/.test(ctx.allCss) && !/(?<![\w-])\[?scrollbar/.test(classes)) missing.push('scrollbar-color');
+ const hasInputs = ctx.docs.some((d) => /<(input|textarea)\b/i.test(d.src));
+ if (hasInputs && !/caret-color/.test(ctx.allCss) && !/(?<![\w-])caret-/.test(classes)) missing.push('caret-color');
+ if (missing.length) r.report('unthemed-browser-surfaces', file, 1, 'browser surfaces left unthemed: ' + missing.join(', '), { fix: 'theme the parts you did not draw from the palette' });
+}
+
+// sloplint checkF21 (F21)
+function checkHeadingLevels(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ let prev = 0;
+ for (const head of openTags(doc, /^h[1-6]$/)) {
+ const level = Number(head.tag.name.slice(1));
+ if (prev && level > prev + 1) {
+ r.report('skipped-heading', doc.file, head.tag.line, 'h' + prev + ' is followed by h' + level + ' ("' + trunc(plainText(head.inner), 32) + '")', { fix: 'step the levels one at a time; size a head with CSS, never with its level' });
+ break;
+ }
+ prev = level;
+ }
+ }
+}
+
+// sloplint checkF22 (F22)
+function checkJustifiedText(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ const j = rule.decls.find((d) => d.prop === 'text-align' && /^justify\b/.test(d.value.trim()));
+ if (j && !rule.decls.some((d) => d.prop === 'hyphens' && /auto/.test(d.value))) { r.report('justified-text', rule.file, j.line, 'justified text without hyphenation on ' + rule.selector); return; }
+ }
+ for (const doc of ctx.docs) {
+ const m = /class(?:Name)?\s*=\s*["'][^"']*(?<![\w-])text-justify(?![\w-])/.exec(doc.src);
+ if (m && !/(?<![\w-])hyphens-auto(?![\w-])/.test(doc.src)) { r.report('justified-text', doc.file, doc.lineOf(m.index), 'justified text without hyphenation (text-justify)', { fix: 'hyphens-auto, or left-aligned' }); return; }
+ }
+}
+
+// sloplint checkF23 (F23), the lang half; the title and description are the copy tier's
+function checkLang(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ if (doc.kind !== 'html') continue;
+ const html = /<html\b([^>]*)>/i.exec(doc.src);
+ if (!html) continue;
+ if (!getAttr(html[1], 'lang')) r.report('missing-lang', doc.file, doc.lineOf(html.index), '<html> names no lang');
+ }
+}
+
+// sloplint checkF24 (F24)
+function checkHairlineUnderShadow(ctx: LintContext, r: Reporter): void {
+ const wide = (value: string): boolean => splitTop(resolveVars(value, ctx.tokens)).some((layer) => {
+ if (/\binset\b/.test(layer)) return false;
+ const len = [...layer.replace(/(?:oklch|oklab|rgba?|hsla?|color|color-mix)\([^)]*\)/g, '').matchAll(/(-?\d*\.?\d+)(px|rem|em)?(?=\s|$)/g)].map((m) => parseFloat(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1));
+ return len.length >= 3 && len[2] + Math.min(0, len[3] || 0) >= 24;
+ });
+ for (const rule of ctx.rules) {
+ const sh = rule.decls.find((d) => d.prop === 'box-shadow' && d.value.trim() !== 'none');
+ if (!sh || !wide(sh.value)) continue;
+ const edge = rule.decls.find((d) => /^border(?:-(?:top|right|bottom|left|inline|block)(?:-(?:start|end))?)?$/.test(d.prop) && /(?:^|\s)(?:1px|0\.5px|thin|var\(--rule-hair\))(?:\s|$)/.test(d.value) && !/\b(?:none|transparent)\b/.test(d.value));
+ if (edge) { r.report('hairline-under-shadow', rule.file, sh.line, 'a hairline border under a wide soft shadow on ' + rule.selector); return; }
+ }
+ for (const doc of ctx.docs) {
+ for (const t of [...doc.tags, ...doc.comps]) {
+ if (t.close) continue;
+ const toks = (getAttr(t.attrs, 'class') ?? getAttr(t.attrs, 'className') ?? '').split(/\s+/);
+ if (!toks.includes('border') || !(toks.includes('shadow-xl') || toks.includes('shadow-2xl'))) continue;
+ r.report('hairline-under-shadow', doc.file, t.line, 'a hairline border under a wide soft shadow (border with shadow-xl or shadow-2xl)');
+ return;
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ checkStraightQuotes(ctx, r);
+ checkEllipsis(ctx, r);
+ checkBalancedHeads(ctx, r);
+ checkPrimaryRecipes(ctx, r);
+ checkIconCoins(ctx, r);
+ checkTabularFigures(ctx, r);
+ checkStampedRecipe(ctx, r);
+ checkPillRadius(ctx, r);
+ checkScrollChoreography(ctx, r);
+ checkAvatars(ctx, r);
+ checkPageInvariants(ctx, r);
+ checkBrowserSurfaces(ctx, r);
+ checkHeadingLevels(ctx, r);
+ checkJustifiedText(ctx, r);
+ checkLang(ctx, r);
+ checkHairlineUnderShadow(ctx, r);
+}
diff --git a/lib/design-lint/rules/ids.ts b/lib/design-lint/rules/ids.ts
new file mode 100644
index 000000000..89ee67eff
--- /dev/null
+++ b/lib/design-lint/rules/ids.ts
@@ -0,0 +1,181 @@
+/**
+ * The design lint's rule table: every rule id the lint can print, its tier,
+ * the sloplint gate it was ported from, and its default fix. Rule modules
+ * report by id; the reporter refuses an id that is not here, so the table is
+ * the contract (docs/design-lint.md lists it; test/design-lint.test.ts holds
+ * the two in step).
+ *
+ * Tiers reuse gstack's severity words, not hallmark's: Floor -> blocks (never
+ * waivable), Reflex -> ask (waivable on the record), Finish -> polish (printed,
+ * never blocks). Three house rules hallmark holds at Floor stay at ask here on
+ * purpose: the eyebrow (a figure caption or plan name above a heading is often
+ * right), the 80-word screen (a Read-mode page legitimately exceeds it) and
+ * the dash (gstack's rule is overuse, not a ban). Ids that match a
+ * lib/design-catalog.ts entry carry the catalog's id so Phase 2 can mark those
+ * rows detect: 'lint'.
+ *
+ * Gate numbers refer to Nutlope/hallmark references/gates.md at 7ec8682 (MIT).
+ */
+
+export type Tier = 'blocks' | 'ask' | 'polish';
+
+export interface RuleMeta {
+ tier: Tier;
+ /** The sloplint gate (or gstack-design-craft id) this rule was ported from. */
+ gate: string;
+ /** One line naming the tell. */
+ title: string;
+ /** The default fix printed after `| fix:` when the rule gives none. */
+ fix: string;
+ /** Rules that only make sense on a whole page are skipped under --scope component. */
+ pageOnly?: boolean;
+ /** The render tier reports this rule; the static tier never does. */
+ render?: boolean;
+}
+
+export const RULES: Record<string, RuleMeta> = {
+ // ── Colour and surface ──
+ 'purple-blue-gradient': { tier: 'blocks', gate: '2a', title: 'purple-to-blue, purple-to-pink or cyan-on-dark gradient', fix: 'one anchor hue and solid ink' },
+ 'gradient-text': { tier: 'ask', gate: '2b', title: 'gradient text', fix: 'solid ink; carry emphasis with weight or a display face' },
+ 'pure-black-white': { tier: 'blocks', gate: '7a', title: '#000 or #fff as a colour outside the token block', fix: 'tint toward the anchor hue: chroma 0.005 or more' },
+ 'absolute-surface-token': { tier: 'ask', gate: '7b', title: 'a surface token that resolves to pure black or white', fix: 'tint the paper' },
+ 'zero-chroma-neutrals': { tier: 'ask', gate: '22', title: 'zero-chroma oklch() neutrals', fix: 'give the neutrals chroma 0.005 or more' },
+ 'accent-footprint': { tier: 'ask', gate: '23', title: 'accent colour past about 5% of a viewport', fix: 'retreat the accent to actions and one signal' },
+ 'glow-wash': { tier: 'ask', gate: '29', title: 'glow and wash: blurred orbs, a radial halo or a zero-offset coloured glow', fix: 'a solid or grained surface; elevation by lightness, shadows with offset and blur' },
+ 'cream-palette': { tier: 'ask', gate: '65', title: 'the cream paper, serif display and terracotta accent look', fix: 'move one axis: the accent first, the paper second, the display last', pageOnly: true },
+ 'framework-palette': { tier: 'ask', gate: '74', title: 'a framework default palette (Tailwind indigo-500, slate-900 and kin) as a token or utility', fix: 'a colour mixed for the page in OKLCH' },
+ // ── Type ──
+ 'overused-font': { tier: 'ask', gate: '1', title: 'a training-data display face (Inter, Roboto, Fraunces, Playfair Display, Space Grotesk and the rest of gstack\'s catalog) or a system stack as the display', fix: 'a display face chosen for the page' },
+ 'banned-font': { tier: 'ask', gate: 'catalog', title: 'a face gstack bans in any role (Papyrus, Comic Sans, Impact, Lobster, Raleway, Courier New and the rest of lib/design-catalog.ts BANNED_FONTS)', fix: 'a face chosen for the page; the body face for body and labels' },
+ 'line-length': { tier: 'ask', gate: '25', title: 'running prose outside 45 to 75 characters a line', fix: 'max-width: 65ch', pageOnly: true },
+ 'font-family-count': { tier: 'ask', gate: '37', title: 'more than three font families', fix: 'display, body and one outlier' },
+ 'italic-word-in-heading': { tier: 'blocks', gate: '38i', title: 'one italic word inside an otherwise roman heading', fix: 'a line break, or the whole head set one way' },
+ 'italic-serif-display': { tier: 'ask', gate: '38ii', title: 'an italic display system', fix: 'roman display, or declare it on --font-display with font-synthesis: none' },
+ 'accented-word': { tier: 'ask', gate: '38iii', title: 'one word in a heading set apart by colour, weight, a highlight or an underline', fix: 'the whole head one way; a line break; a second line at a second size' },
+ 'caps-leading': { tier: 'blocks', gate: '55a', title: 'an uppercase display head that can wrap with line-height under 1.0', fix: 'line-height 1.0 at least (1.02 to 1.08 recommended)', pageOnly: true },
+ 'caps-lockup-leading': { tier: 'ask', gate: '55b', title: 'a single-line caps lockup under 1.02', fix: 'line-height 1.02, or make sure it cannot wrap at 320px', pageOnly: true },
+ 'monospace-costume': { tier: 'ask', gate: '64', title: 'monospace on labels, captions or small type when the content is not code', fix: 'labels in the body face, a step smaller, normal case' },
+ 'tiny-text': { tier: 'ask', gate: '75', title: 'running text under 12px, functional text under 11px, or prose leaded under 1.3', fix: 'body 16px at 1.5 to 1.65; labels one step smaller', render: true },
+ 'wide-tracking': { tier: 'blocks', gate: '67', title: 'the tracked-caps label: small text set uppercase or letter-spaced past 0.03em', fix: 'the body face, a step smaller, sentence case, untracked' },
+ // ── Structure and layout ──
+ 'template-cards': { tier: 'ask', gate: '3', title: 'three equal icon-above-heading tiles, an icon in a rounded tile, or a thick coloured side stripe', fix: 'vary widths and heights, inline icons, hairline or no border', pageOnly: true },
+ 'nested-cards': { tier: 'blocks', gate: '4', title: 'a card inside a card', fix: 'one containment layer' },
+ 'vh-height': { tier: 'blocks', gate: '6a', title: 'a hero sized in vh', fix: 'dvh or svh' },
+ 'raw-spacing': { tier: 'blocks', gate: '24a', title: 'a raw padding, margin or gap length where a --space-* token exists', fix: 'the token' },
+ 'off-scale-spacing': { tier: 'ask', gate: '24b', title: 'spacing off the page\'s scale', fix: 'the scale; three optical nudges at most' },
+ 'overflow-x-unclipped': { tier: 'ask', gate: '34', title: 'overflow-x missing on html and body, or a 100vw width', fix: 'overflow-x: clip on both; width: 100%', pageOnly: true },
+ 'horizontal-scroll': { tier: 'blocks', gate: '34', title: 'horizontal scroll at a width between 320 and 1920', fix: 'find the element wider than its viewport and cap it', render: true, pageOnly: true },
+ 'hero-balance': { tier: 'ask', gate: '44a/44c', title: 'the hero\'s content sits off centre for its screen, or its visual stands apart from the text', fix: 'centre the content in its screen; put the visual beside the text', render: true, pageOnly: true },
+ 'hero-fold': { tier: 'blocks', gate: '44b', title: "the headline's bottom or the hero's first action below the 800px fold at 1280 wide; the lede and the visual are not measured", fix: 'pull the display clamp down, tighten leading, a two-line lede, trim padding', render: true, pageOnly: true },
+ 'wide-container': { tier: 'blocks', gate: '44d', title: 'at 1920x1080 the container has no max-width, gutters under 120px, or a grid gains columns', fix: 'cap 1360 to 1520px and centre; hold column counts; cap vw visuals', pageOnly: true },
+ 'bare-fr-track': { tier: 'blocks', gate: '50', title: 'an image-bearing grid track on bare 1fr', fix: 'minmax(0, 1fr)', pageOnly: true },
+ 'display-head-unwrapped': { tier: 'blocks', gate: '50', title: 'a display head without overflow-wrap: break-word and min-width: 0', fix: 'overflow-wrap: break-word; min-width: 0 (never anywhere)', pageOnly: true },
+ 'radio-tab-jump': { tier: 'blocks', gate: '53', title: 'CSS-only radio tabs at position: absolute; top: 0 with no JS guard', fix: 'radios in flow at zero size, or a handler with preventScroll' },
+ 'double-sticky': { tier: 'blocks', gate: '56', title: 'two position: sticky; top: 0 elements', fix: 'top: var(--banner-height) on the second', pageOnly: true },
+ 'screen-word-budget': { tier: 'ask', gate: '58', title: 'more than about 80 words in one 900px window, or a hero with more than two text blocks before its actions', fix: 'headline, one sentence, actions; a section is a head block, then its composition', pageOnly: true },
+ 'section-gap': { tier: 'ask', gate: '59', title: 'a gap under 120px between sections at 1440, every gap the same, or more than nine sections', fix: '120px at least, varied; six to nine sections a page', pageOnly: true, render: true },
+ 'heading-rhythm': { tier: 'ask', gate: '71', title: 'a heading nearer what precedes it than what it heads', fix: 'at least twice the space above a head as below it', render: true, pageOnly: true },
+ 'cramped-padding': { tier: 'ask', gate: '72', title: 'text closer than 8px (or half an em) to the side of its filled box', fix: 'pad the box; a 16px gutter', render: true },
+ 'thin-section': { tier: 'ask', gate: '77', title: 'a section below the hero with no mass: a narrow body on a wide canvas', fix: 'widen the body, add a visual, set a statement, or merge the section', render: true, pageOnly: true },
+ 'small-section-heads': { tier: 'ask', gate: '78', title: 'the median h2 below the hero renders under 40px at 1440', fix: 'h2 at the section size, item titles at the title size', render: true, pageOnly: true },
+ 'dead-band': { tier: 'ask', gate: '79', title: 'more than 160px of nothing between the hero\'s lowest content and the fold', fix: 'centre the content and grow the visual or the head; never fill with copy', render: true, pageOnly: true },
+ 'hand-drawn-svg': { tier: 'ask', gate: '80', title: 'an inline SVG of 120px or more with three curves or fills and no text: a drawn illustration', fix: 'a photograph, the product built, or type at scale', render: true, pageOnly: true },
+ 'empty-picture': { tier: 'ask', gate: '81', title: 'a slot or gradient block of 300x200px or more showing nothing but its wash', fix: 'the user\'s image, a credited photograph, or the product at full fidelity', render: true, pageOnly: true },
+ 'counting-marks': { tier: 'ask', gate: '82', title: '24 or more identical marks standing for a quantity', fix: 'set the number in type', render: true, pageOnly: true },
+ 'photo-wall': { tier: 'ask', gate: '83', title: 'photographs cover more than a third of the page below the hero', fix: 'keep the strongest pictures, set big; carry the rest in type, figures, the product, a table', render: true, pageOnly: true },
+ 'email-band-close': { tier: 'ask', gate: '85', title: 'the page ends on an email sign-up form on a page whose job is not subscribe, join, attend, listen or visit', fix: 'end on what the visitor came to do, or on the last strong section', pageOnly: true },
+ // ── Chrome and copy ──
+ 'aphoristic-cadence': { tier: 'blocks', gate: '19', title: 'the rebuttal cadence three or more times ("Not a feature. A platform.")', fix: 'say what the product does, in its own nouns' },
+ 'generic-hero-copy': { tier: 'blocks', gate: '19', title: 'a filler opener ("Built for the modern team", "In today\'s landscape") or "quietly trusted by"', fix: 'say what the product does, in its own nouns' },
+ 'generic-cta-copy': { tier: 'ask', gate: '19/42', title: 'a stock second action beside the primary (Learn more, Get started, Book a demo)', fix: 'one action, or a second that names where it goes', pageOnly: true },
+ 'em-dash-overuse': { tier: 'ask', gate: '19', title: 'em or en dashes carrying the prose', fix: 'a comma, a colon, a full stop or a line break' },
+ 'template-footer-line': { tier: 'ask', gate: '19', title: 'a stock footer line (All rights reserved)', fix: 'the page\'s own line, or nothing' },
+ 'template-nav': { tier: 'ask', gate: '42', title: 'the reflex nav: wordmark left, inline links, a button right, hairline under', fix: 'decide the nav and build another shape, or keep it on the record', pageOnly: true },
+ 'template-footer': { tier: 'ask', gate: '42', title: 'the reflex footer: four link columns, a social row, a copyright', fix: 'decide the footer and build another shape, or keep it on the record', pageOnly: true },
+ 'invented-proof': { tier: 'blocks', gate: '46a', title: 'an invented metric, testimonial, logo wall or case-study count', fix: 'the user\'s number, a text slot, or nothing' },
+ 'drawn-browser-chrome': { tier: 'blocks', gate: '47a', title: 'a hand-drawn browser bar (traffic lights, URL pill) or OS window title bar', fix: 'a real screenshot in a <figure>, or no chrome' },
+ 'device-frame': { tier: 'ask', gate: '47b', title: 'a phone, laptop, terminal or editor frame', fix: 'one frame with real content inside, or none', pageOnly: true },
+ 'imitation-material': { tier: 'ask', gate: '47c', title: 'styled divs standing in for a product, a photo edge or a physical object', fix: 'the product built inside a slot, a real asset, or nothing', pageOnly: true },
+ 'kicker-above-heading': { tier: 'ask', gate: '54', title: 'the eyebrow: short inert type before a heading that only announces it', fix: 'open the section another way; where the heading is figurative, the label becomes the heading', pageOnly: true },
+ 'template-punctuation': { tier: 'blocks', gate: '63', title: 'template punctuation: middle-dot meta strings, an arrow glued to link text, decorative status dots', fix: 'line breaks, columns, hairlines; a verb as the label' },
+ 'wireframe-slots': { tier: 'ask', gate: '68', title: 'more than five empty slots on one page, or four or more in one row', fix: 'set the set in type; a slot that stays holds a real photo or the product', pageOnly: true },
+ 'repeated-fact': { tier: 'ask', gate: '69', title: 'one fact (a price, a time, a count) printed in four or more sections', fix: 'say each fact once, where it does work', pageOnly: true },
+ 'fake-send': { tier: 'blocks', gate: '70', title: 'a form that prints success with no request behind it', fix: 'validate, post nowhere and say so plainly until the endpoint exists' },
+ // ── Motion and interaction ──
+ 'layout-transition': { tier: 'blocks', gate: '10a', title: 'transition: all, or animating width, height, top or left', fix: 'list the properties; transform and opacity' },
+ 'spacing-transition': { tier: 'ask', gate: '10b', title: 'transitioning margin or padding', fix: 'transform' },
+ 'hover-tells': { tier: 'ask', gate: '11', title: 'the same lift on every card, two effects on one element, an image scaling on hover, or a hover on something inert', fix: 'one signal per element, on the container, not the image' },
+ 'bounce-easing': { tier: 'ask', gate: '12', title: 'bounce or overshoot easing on UI state', fix: 'an exponential ease-out' },
+ 'focus-ring-fade': { tier: 'blocks', gate: '15', title: 'a focus ring that fades in', fix: 'instant: exclude outline and box-shadow from the transition' },
+ 'tooltip-focus-delay': { tier: 'blocks', gate: '17', title: 'a tooltip whose focus delay equals its hover delay', fix: 'hover 800 to 1000ms, focus 0' },
+ 'autorotate-no-pause': { tier: 'blocks', gate: '18', title: 'auto-rotating content with no pause on hover and focus', fix: 'pause on hover and focus; a visible pause control past 5 seconds' },
+ 'missing-focus-visible': { tier: 'blocks', gate: '26a', title: 'an interactive element with no :focus-visible ring, or an outline removed with nothing in its place', fix: 'a ring at 3:1 or better, instant' },
+ 'missing-states': { tier: 'ask', gate: '26b', title: 'no :active or :disabled state', fix: 'all the states a control can be in' },
+ 'missing-reduced-motion': { tier: 'blocks', gate: '27', title: 'a keyframe or transform transition without a prefers-reduced-motion fallback', fix: 'add @media (prefers-reduced-motion: reduce)' },
+ 'autoplay-unmuted': { tier: 'blocks', gate: '28a', title: 'a video autoplaying without muted', fix: 'autoplay muted loop playsinline', pageOnly: true },
+ 'lazy-lcp': { tier: 'blocks', gate: '28a', title: 'loading="lazy" on the first image or the hero video', fix: 'fetchpriority="high" on the LCP image', pageOnly: true },
+ 'video-without-poster': { tier: 'ask', gate: '28b', title: 'a video without poster or a priority hint', fix: 'add them', pageOnly: true },
+ 'input-state-shift': { tier: 'blocks', gate: '39a', title: 'input states that break: a border that changes width, a focus ring built from border, disabled by opacity alone', fix: 'constant border, outline, shared height, three disabled channels' },
+ 'control-height': { tier: 'ask', gate: '39b', title: 'control height outside 44 to 52px on a marketing page', fix: 'the number', pageOnly: true },
+ 'content-hidden-at-rest': { tier: 'blocks', gate: '62', title: 'a reveal class hiding content until JavaScript runs', fix: 'visible by default; hide only under a .js class, or animate from visible with @starting-style' },
+ // ── Assets and access ──
+ 'emoji-decoration': { tier: 'blocks', gate: '30a', title: 'an emoji standing in for an icon', fix: 'one icon library, custom SVG, or typography' },
+ 'two-icon-libraries': { tier: 'ask', gate: '30b', title: 'two icon libraries on one page', fix: 'one library' },
+ 'unlabeled-decoration': { tier: 'blocks', gate: '33', title: 'a decorative <svg>, <canvas> or CSS-art element with neither aria-hidden="true" nor a label', fix: 'hide it or name it' },
+ 'broken-image': { tier: 'blocks', gate: '76', title: 'an <img> with no source or one that does not load', fix: 'the real file' },
+ 'stock-photo-hotlink': { tier: 'blocks', gate: '76', title: 'a stock-site photo hotlink', fix: 'the user\'s image, or a library photograph credited on the page' },
+ 'text-occlusion': { tier: 'blocks', gate: '73', title: 'text painted under another element', fix: 'give the text its own space, or its own surface above the cover', render: true },
+ 'low-contrast': { tier: 'blocks', gate: '40', title: 'text, an icon, a focus ring or a field edge under its contrast threshold', fix: 'fix the pair; body 4.5:1, large text and edges 3:1' },
+ 'gray-on-color': { tier: 'blocks', gate: '41', title: 'button text within a step of its fill, or grey text on a coloured surface', fix: 'the paired ink token' },
+ 'literal-outside-tokens': { tier: 'blocks', gate: '48', title: 'a colour or font-family literal outside the token block', fix: 'lift it into the tokens' },
+ 'button-label-wraps': { tier: 'blocks', gate: '49a', title: 'a button label or primary nav link that wraps', fix: 'shorten it; white-space: nowrap', pageOnly: true },
+ 'link-wraps': { tier: 'ask', gate: '49b', title: 'a footer link, tab or breadcrumb that wraps', fix: 'shorten it', pageOnly: true },
+ // ── Finish (polish) ──
+ 'straight-quotes': { tier: 'polish', gate: 'F1', title: 'straight quotes in prose', fix: 'curly quotes' },
+ 'three-dot-ellipsis': { tier: 'polish', gate: 'F2', title: 'three dots for an ellipsis', fix: 'the ellipsis character' },
+ 'balanced-display-head': { tier: 'polish', gate: 'F3', title: 'a display head without text-wrap: balance', fix: 'text-wrap: balance' },
+ 'two-primary-buttons': { tier: 'polish', gate: 'F4', title: 'two filled primary buttons on one page, or side by side', fix: 'one filled primary; the second as a text or outline action' },
+ 'icon-coin': { tier: 'polish', gate: 'F5', title: 'an icon in a coloured coin', fix: 'the icon inline, bare' },
+ 'display-figures-tabular': { tier: 'polish', gate: 'F6', title: 'display-size figures without tabular numerals', fix: 'font-variant-numeric: tabular-nums' },
+ 'stamped-recipe': { tier: 'polish', gate: 'F7', title: 'one container recipe stamped on six or more selectors, or the pill radius on five or more non-controls', fix: 'vary the recipe; pills on controls, tags and badges only', pageOnly: true },
+ 'scroll-choreography-mix': { tier: 'polish', gate: 'F8', title: 'more than one scroll-choreography pattern', fix: 'one pattern a page', pageOnly: true },
+ 'fake-avatar': { tier: 'blocks', gate: 'F9', title: 'a fake-human avatar hotlink', fix: 'the user\'s people, initials, or no portrait' },
+ 'stock-person-photo': { tier: 'polish', gate: 'F9', title: 'a person-keyword stock photo URL', fix: 'the user\'s photograph' },
+ 'page-invariants': { tier: 'polish', gate: 'F15', title: 'page invariants broken: primary button style, container width, column gap or radius drifting', fix: 'one recipe for each', pageOnly: true },
+ 'unthemed-browser-surfaces': { tier: 'polish', gate: 'F16', title: 'no ::selection, caret-color or scrollbar-color on a page with a committed palette', fix: 'theme the browser surfaces', pageOnly: true },
+ 'text-sliver': { tier: 'polish', gate: 'F17', title: 'a text block squeezed into a sliver at 1440', fix: 'give the block room or merge the columns', render: true },
+ 'tiny-slot': { tier: 'polish', gate: 'F18', title: 'a slot rendering under 40px in either dimension', fix: 'size the slot for what it will hold', render: true },
+ 'font-weight-count': { tier: 'polish', gate: 'F19', title: 'more than three font weights in running use', fix: 'three weights', render: true },
+ 'lonely-grid-item': { tier: 'polish', gate: 'F20', title: 'a grid or wrapping row leaving one item alone on its last row', fix: 'change the count or the columns', render: true, pageOnly: true },
+ 'skipped-heading': { tier: 'polish', gate: 'F21', title: 'a heading level skipped', fix: 'step the levels one at a time' },
+ 'justified-text': { tier: 'polish', gate: 'F22', title: 'justified text without hyphens: auto', fix: 'hyphens: auto, or left-aligned' },
+ 'missing-lang': { tier: 'polish', gate: 'F23', title: 'a document without lang', fix: 'lang on <html>' },
+ 'hairline-under-shadow': { tier: 'polish', gate: 'F24', title: 'a hairline border under a wide soft shadow on one surface', fix: 'the shadow or the border, not both' },
+ // ── Copy tier (gstack-design-craft, Elaya-derived; same ids) ──
+ 'placeholder-name': { tier: 'blocks', gate: 'craft', title: 'a placeholder name (John Doe)', fix: 'use a supplied name, or one that fits the product in sample data' },
+ 'placeholder-brand': { tier: 'blocks', gate: 'craft', title: 'a placeholder brand (Acme, Nexus)', fix: 'use a supplied customer, or a fitting name in sample data' },
+ 'lorem': { tier: 'blocks', gate: 'craft', title: 'lorem ipsum placeholder text', fix: 'write real copy' },
+ 'marketing-buzzword': { tier: 'ask', gate: 'craft', title: 'a marketing buzzword', fix: 'say the specific thing' },
+ 'round-number': { tier: 'blocks', gate: 'craft', title: 'a round invented number', fix: 'use the supplied figure, or drop the claim' },
+ 'needs-proof': { tier: 'blocks', gate: 'craft', title: 'a [Needs proof] marker left in the page', fix: 'supply the proof or remove the claim before publishing' },
+ 'oops': { tier: 'ask', gate: 'craft', title: '"oops" as an error message', fix: 'say what happened and what to do' },
+ 'scroll-listener': { tier: 'ask', gate: 'craft', title: 'a scroll event listener', fix: 'use IntersectionObserver; read scroll inside requestAnimationFrame for a scroll-linked effect' },
+ 'dead-link': { tier: 'ask', gate: 'craft', title: 'a dead link (href="#")', fix: 'link it, or render the control disabled' },
+ 'alert': { tier: 'ask', gate: 'craft', title: 'alert() for a message', fix: 'show the message inline' },
+ 'img-no-alt': { tier: 'blocks', gate: 'craft', title: 'an <img> without alt', fix: 'add alt text (alt="" when decorative)' },
+ 'missing-title': { tier: 'blocks', gate: 'craft', title: 'a document without a <title>', fix: 'add a <title>', pageOnly: true },
+ 'missing-meta-description': { tier: 'ask', gate: 'craft', title: 'no meta description', fix: 'add <meta name="description">', pageOnly: true },
+ 'missing-favicon': { tier: 'polish', gate: 'craft', title: 'a document without a favicon', fix: 'add a favicon <link rel="icon">', pageOnly: true },
+ 'missing-skip-link': { tier: 'ask', gate: 'craft', title: 'no skip link reaching <main>', fix: 'add a "Skip to content" link first in <body> whose #id exists on <main>', pageOnly: true },
+ 'missing-aria-current': { tier: 'ask', gate: 'craft', title: 'route navigation without aria-current', fix: 'mark the current nav link aria-current="page"', pageOnly: true },
+ // ── The lint's own bookkeeping ──
+ 'waiver': { tier: 'ask', gate: 'waiver', title: 'a waiver the lint refused', fix: 'fix the finding, or waive it with the rule id and a reason about this page' },
+ 'house-style': { tier: 'polish', gate: 'waiver', title: 'more than three rules waived on one page', fix: 'lock the choices into DESIGN.md so later pages inherit them instead of re-arguing them' },
+ 'render': { tier: 'blocks', gate: 'render', title: 'the page did not render, so its render rules did not run', fix: 'fix the page or the URL and rerun; an unrendered page is never a pass' },
+ 'internal-error': { tier: 'ask', gate: 'lint', title: 'a rule family threw, or a page or stylesheet could not be read, so the lint did not run on it', fix: 'report the error with the page that caused it; a page the lint could not read is not a pass' },
+};
+
+
+export function ruleMeta(id: string): RuleMeta | null {
+ return Object.prototype.hasOwnProperty.call(RULES, id) ? RULES[id] : null;
+}
diff --git a/lib/design-lint/rules/index.ts b/lib/design-lint/rules/index.ts
new file mode 100644
index 000000000..a68b4f985
--- /dev/null
+++ b/lib/design-lint/rules/index.ts
@@ -0,0 +1,36 @@
+/**
+ * The rule families of the static tier, in the order they run. Each family
+ * module exports one `run(ctx, r)` that reads the context and reports by rule
+ * id (lib/design-lint/rules/ids.ts). Add a family here, nowhere else, and
+ * before `component`: it reconciles against what the stylesheet families
+ * already reported (a Tailwind tell on a line type or chrome named, an emoji
+ * tile assets saw), so it reads their findings and must run after them.
+ */
+import type { LintContext } from '../context';
+import type { Reporter } from '../report';
+import { run as runColor } from './color';
+import { run as runType } from './type';
+import { run as runStructure } from './structure';
+import { run as runChrome } from './chrome';
+import { run as runMotion } from './motion';
+import { run as runAssets } from './assets';
+import { run as runFinish } from './finish';
+import { run as runComponent } from './component';
+import { run as runCopy } from './copy';
+
+export type RuleRunner = (ctx: LintContext, r: Reporter) => void;
+
+export interface RuleFamily { name: string; run: RuleRunner }
+
+export const FAMILIES: RuleFamily[] = [
+ { name: 'color', run: runColor },
+ { name: 'type', run: runType },
+ { name: 'structure', run: runStructure },
+ { name: 'chrome', run: runChrome },
+ { name: 'motion', run: runMotion },
+ { name: 'assets', run: runAssets },
+ { name: 'finish', run: runFinish },
+ { name: 'component', run: runComponent },
+ { name: 'copy', run: runCopy },
+];
+
diff --git a/lib/design-lint/rules/motion.ts b/lib/design-lint/rules/motion.ts
new file mode 100644
index 000000000..627163c6f
--- /dev/null
+++ b/lib/design-lint/rules/motion.ts
@@ -0,0 +1,392 @@
+/**
+ * Motion and interaction rules of the design lint (sloplint gates 10a 10b 11 12 15 17 18 26a 26b 27 28a 28b 39a 39b 62;
+ * Nutlope/hallmark, MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: layout-transition, spacing-transition,
+ * hover-tells, bounce-easing, focus-ring-fade, tooltip-focus-delay, autorotate-no-pause, missing-focus-visible,
+ * missing-states, missing-reduced-motion, autoplay-unmuted, lazy-lcp, video-without-poster, input-state-shift,
+ * control-height, content-hidden-at-rest.
+ */
+import { isTokenRule, pxOf, resolveVars, selectorIsInteractive, splitTop, stripComments } from '../css';
+import { mergedRules, type LintContext, type SharedStyles } from '../context';
+import { getAttr, hasAttr } from '../html';
+import { trunc, type Reporter } from '../report';
+import { twGroup, twVariants, type TwItem } from '../tailwind';
+
+const baseSelector = (sel: string): string => sel.replace(/::?[a-z-]+(\([^)]*\))?/gi, '').replace(/\s+/g, ' ').trim();
+
+const stripVariants = (cls: string): string => cls.replace(/^(?:[\w-]+:)+/, '');
+
+const firstFile = (ctx: LintContext): string => ctx.cssFiles[0]?.file || ctx.docs[0]?.file || '?';
+
+const SHARED_ONCE = new WeakMap<SharedStyles, Set<string>>();
+
+/** True the first time a key is seen across the contexts that share one project's styles; always true when nothing is shared. */
+function once(ctx: LintContext, key: string): boolean {
+ if (!ctx.shared) return true;
+ let seen = SHARED_ONCE.get(ctx.shared);
+ if (!seen) { seen = new Set(); SHARED_ONCE.set(ctx.shared, seen); }
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+}
+
+const HARD_PROP = /(?<![\w-])(width|height|top|left|right|bottom|inset(?:-[a-z-]+)?|flex-basis|grid-template-columns)(?![\w-])/;
+const SOFT_PROP = /(?<![\w-])(margin(?:-[a-z]+)?|padding(?:-[a-z]+)?)(?![\w-])/;
+
+// sloplint check10 and check10Motion (gates 10a, 10b)
+function layoutTransitions(ctx: LintContext, r: Reporter): void {
+ const fix = 'animate transform or opacity instead';
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (d.prop === 'transition' && /(^|,)\s*all[\s,]|^all$|^all\s/.test(d.value.trim())) r.report('layout-transition', rule.file, d.line, `transition: all on ${rule.selector}`, { fix: 'list the transitioned properties' });
+ if (d.prop === 'transition-property' && /\ball\b/.test(d.value)) r.report('layout-transition', rule.file, d.line, `transition-property: all on ${rule.selector}`, { fix: 'list the transitioned properties' });
+ }
+ if (/skip|sr-only|visually-hidden/i.test(rule.selector)) continue;
+ if (rule.keyframes) {
+ for (const d of rule.decls) {
+ if (/^(min|max)-/.test(d.prop)) continue;
+ if (HARD_PROP.test(d.prop)) r.report('layout-transition', rule.file, d.line, `@keyframes ${rule.keyframes} animates ${d.prop}`, { fix });
+ else if (SOFT_PROP.test(d.prop)) r.report('spacing-transition', rule.file, d.line, `@keyframes ${rule.keyframes} animates ${d.prop}`, { fix });
+ }
+ continue;
+ }
+ for (const d of rule.decls) {
+ if (d.prop !== 'transition' && d.prop !== 'transition-property') continue;
+ const hard = HARD_PROP.exec(d.value);
+ const soft = SOFT_PROP.exec(d.value);
+ if (hard) r.report('layout-transition', rule.file, d.line, `transitioning ${hard[1]} on ${rule.selector}`, { fix });
+ else if (soft) r.report('spacing-transition', rule.file, d.line, `transitioning ${soft[1]} on ${rule.selector}`, { fix });
+ }
+ }
+}
+
+const IMAGE_SEL = /(^|[\s>+~,])(img|picture|figure|video)\b|__(img|image|photo|thumb|cover)\b|\.(img|image|photo|thumb|cover)\b/i;
+
+// sloplint check11 and check11Lift (gate 11)
+function hoverTells(ctx: LintContext, r: Reporter): void {
+ const byScale = new Map<string, Array<{ sel: string; file: string; line: number }>>();
+ for (const rule of ctx.rules) {
+ if (!/:hover/.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'transform') continue;
+ const m = /scale\(\s*([\d.]+)\s*\)/.exec(d.value);
+ if (!m || parseFloat(m[1]) === 1) continue;
+ if (!byScale.has(m[1])) byScale.set(m[1], []);
+ byScale.get(m[1])!.push({ sel: rule.selector, file: rule.file, line: d.line });
+ }
+ }
+ for (const [k, list] of byScale) {
+ const distinct = new Set(list.map((x) => x.sel));
+ if (distinct.size >= 2) r.report('hover-tells', list[0].file, list[0].line, `the same hover scale(${k}) on ${distinct.size} selectors`, { fix: 'one hover signal per element' });
+ }
+ for (const rule of ctx.rules) {
+ if (!/:hover/.test(rule.selector) || !IMAGE_SEL.test(rule.selector)) continue;
+ const t = rule.decls.find((d) => d.prop === 'transform' && /scale|rotate/.test(d.value));
+ if (t) r.report('hover-tells', rule.file, t.line, `an image transforms on hover (${rule.selector})`, { fix: 'imagery sits still; give the container the feedback' });
+ }
+ const lifts = new Map<string, { file: string; line: number }>();
+ for (const m of mergedRules(ctx)) {
+ if (!/:hover/.test(m.selector)) continue;
+ const t = m.decls.find((d) => (d.prop === 'transform' && /translateY\(\s*-\s*\d/.test(resolveVars(d.value, ctx.tokens))) || (d.prop === 'translate' && /^0(px)?\s+-\d/.test(resolveVars(d.value, ctx.tokens))));
+ if (!t || !m.decls.some((d) => d.prop === 'box-shadow')) continue;
+ for (const part of m.selector.split(',')) lifts.set(baseSelector(part), { file: m.file, line: t.line });
+ }
+ if (lifts.size < 3) return;
+ const third = [...lifts.values()][2];
+ r.report('hover-tells', third.file, third.line, `the hover lift (translateY plus shadow) on ${lifts.size} selectors (${trunc([...lifts.keys()].slice(0, 3).join(', '), 44)})`, { fix: 'one signal per element; the same lift on every card is the template' });
+}
+
+const UI_SEL = /:hover|:active|:focus|\b(btn|button|modal|dialog|tooltip|dropdown|menu|popover|toast|tab|input|select|switch|toggle|accordion)\b/i;
+
+// sloplint check12 (gate 12), with no genre exemption: every spring on UI state is reported
+function bounceEasing(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ if (!UI_SEL.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (!/transition|animation/.test(d.prop)) continue;
+ const value = resolveVars(d.value, ctx.tokens);
+ for (const m of value.matchAll(/cubic-bezier\(\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\)/g)) {
+ const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
+ if (y1 > 1.05 || y2 > 1.05 || y1 < -0.05 || y2 < -0.05) r.report('bounce-easing', rule.file, d.line, `overshoot easing ${m[0]} on ${rule.selector}`);
+ }
+ const named = /^animation(-name)?$/.test(d.prop) ? /(?<![\w-])[\w-]*(bounce|spring|elastic|wobble|jello|rubber)[\w-]*/i.exec(value) : null;
+ if (named) r.report('bounce-easing', rule.file, d.line, `bounce animation ${named[0]} on ${rule.selector}`);
+ }
+ }
+}
+
+// sloplint check15 and check15Fade (gate 15)
+function focusRingFade(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ if (!/:focus(-visible|-within)?\b/.test(rule.selector)) continue;
+ const withinOnly = !/:focus(-visible)?(?![\w-])/.test(rule.selector);
+ for (const d of rule.decls) {
+ if (d.prop === 'transition' && (withinOnly ? /outline|box-shadow|\ball\b/ : /outline|box-shadow|opacity|\ball\b/).test(d.value)) {
+ r.report('focus-ring-fade', rule.file, d.line, `the focus ring transitions in on ${rule.selector}`, { fix: 'remove the transition; a ring appears instantly' });
+ }
+ }
+ }
+ const focusProps = new Map<string, Set<string>>();
+ for (const rule of ctx.rules) {
+ if (!/:focus-visible/.test(rule.selector)) continue;
+ for (const part of rule.selector.split(',')) {
+ if (!/:focus-visible/.test(part)) continue;
+ const base = baseSelector(part).replace(/^\*$/, '');
+ const set = focusProps.get(base) || new Set<string>();
+ for (const d of rule.decls) {
+ if (d.prop === 'box-shadow') set.add('box-shadow');
+ if (/^outline/.test(d.prop)) set.add('outline');
+ }
+ focusProps.set(base, set);
+ }
+ }
+ if (!focusProps.size) return;
+ const global = focusProps.get('') || new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || /:focus|:hover|:active/.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'transition' && d.prop !== 'transition-property') continue;
+ for (const prop of ['box-shadow', 'outline']) {
+ if (!new RegExp(`(^|[\\s,])${prop}(-[a-z]+)?\\b`).test(d.value)) continue;
+ const own = rule.selector.split(',').some((p) => (focusProps.get(baseSelector(p)) || new Set<string>()).has(prop));
+ if (!global.has(prop) && !own) continue;
+ r.report('focus-ring-fade', rule.file, d.line, `${trunc(rule.selector, 32)} transitions ${prop} while :focus-visible sets it, so the ring fades in`, { fix: 'transition the hover property only, or draw the ring with a property that is not transitioned' });
+ break;
+ }
+ }
+ }
+}
+
+// sloplint check17 (gate 17)
+function tooltipDelay(ctx: LintContext, r: Reporter): void {
+ const tips = ctx.rules.filter((rule) => /tooltip|tip\b/i.test(rule.selector));
+ const delayed = (sel: RegExp): { file: string; line: number } | null => {
+ for (const rule of tips) {
+ if (!sel.test(rule.selector)) continue;
+ const d = rule.decls.find((x) => /^transition(-delay)?$/.test(x.prop) && splitTop(x.value).some((part) => {
+ const ms = [...part.matchAll(/(?<![\w.-])(\d*\.?\d+)(ms|s)\b/g)].map((m) => m[2] === 'ms' ? Number(m[1]) : Number(m[1]) * 1000);
+ return (x.prop === 'transition-delay' ? ms[0] : ms[1]) >= 100;
+ }));
+ if (d) return { file: rule.file, line: d.line };
+ }
+ return null;
+ };
+ const focus = delayed(/:focus/);
+ if (focus && delayed(/:hover/)) r.report('tooltip-focus-delay', focus.file, focus.line, 'the tooltip waits as long on focus as on hover', { suspected: true });
+}
+
+// sloplint check18 (gate 18)
+function autorotate(ctx: LintContext, r: Reporter): void {
+ const paused = ctx.rules.some((rule) => /:hover|:focus|\[data-loop\]/.test(rule.selector) && rule.decls.some((d) => d.prop === 'animation-play-state' && /paused/.test(d.value)));
+ if (paused) return;
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || !/carousel|marquee|ticker|rotate|slider|scroll|auto/i.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (/^animation(-iteration-count)?$/.test(d.prop) && /\binfinite\b/.test(d.value)) {
+ r.report('autorotate-no-pause', rule.file, d.line, `an infinite animation on ${rule.selector} with no paused state on hover or focus`, { suspected: true });
+ }
+ }
+ }
+}
+
+// sloplint check26 (gates 26a, 26b); ctx.shared carries a project's global state styles
+/** An outline value that takes the ring away: none, or a zero width; `0.25rem solid` is a ring. */
+const OUTLINE_REMOVED = /^(?:none|0(?:px|rem|em)?)(?![\w.%])/i;
+
+function focusAndStates(ctx: LintContext, r: Reporter): void {
+ const hasInteractive = ctx.docs.some((doc) => /<(a|button|input|select|textarea)\b|role\s*=\s*["']button/i.test(doc.src))
+ || ctx.rules.some((rule) => selectorIsInteractive(rule.selector));
+ if (!hasInteractive) return;
+ const has = (pseudo: string) => ctx.rules.some((rule) => rule.selector.includes(pseudo));
+ const tv = twVariants(ctx);
+ const shared = ctx.shared;
+ const file = firstFile(ctx);
+ if (!has(':focus-visible') && !has(':focus') && !shared?.focus && ![...tv].some((v) => /^focus(?:-visible|-within)?$/.test(v)) && once(ctx, '26a')) {
+ r.report('missing-focus-visible', file, 1, 'no :focus-visible style anywhere: keyboard users cannot see where they are');
+ }
+ const ringDecl = (d: { prop: string; value: string }) => (/^outline(-style|-width|-color)?$/.test(d.prop) && !OUTLINE_REMOVED.test(d.value.trim())) || (d.prop === 'box-shadow' && !/^none\b/i.test(d.value.trim()));
+ const ringAnywhere = ctx.rules.some((rule) => /:focus/.test(rule.selector) && rule.decls.some(ringDecl)) || !!shared?.focus || [...tv].some((v) => /^focus(?:-visible|-within)?$/.test(v));
+ if (!ringAnywhere) {
+ const removed = ctx.rules.find((rule) => /:focus/.test(rule.selector) && rule.decls.some((d) => /^outline(-style)?$/.test(d.prop) && OUTLINE_REMOVED.test(d.value.trim())));
+ const outlineD = removed?.decls.find((d) => /^outline(-style)?$/.test(d.prop));
+ if (removed && outlineD && once(ctx, '26a:removed')) r.report('missing-focus-visible', removed.file, outlineD.line, `${outlineD.prop}: ${outlineD.value.trim()} on ${trunc(removed.selector, 40)} with nothing in its place: keyboard users cannot see where they are`, { fix: 'a :focus-visible ring at 3:1 or better, instant; never remove an outline without putting one back' });
+ }
+ if (!has(':active') && !shared?.active && !tv.has('active') && once(ctx, '26b:active')) {
+ r.report('missing-states', file, 1, 'no :active style anywhere', { fix: 'every state a control can be in: hover, active, focus-visible, disabled' });
+ }
+ const hasFormish = ctx.docs.some((doc) => /<(button|input|select|textarea)\b/i.test(doc.src));
+ if (hasFormish && !has(':disabled') && !shared?.disabled && !tv.has('disabled') && !tv.has('aria-disabled') && !ctx.rules.some((rule) => /\[disabled\]|aria-disabled/.test(rule.selector)) && once(ctx, '26b:disabled')) {
+ r.report('missing-states', file, 1, 'no :disabled style anywhere', { fix: 'every state a control can be in: hover, active, focus-visible, disabled' });
+ }
+}
+
+/** The first Tailwind element that moves: an animate-* utility, or a transition on a transform utility. */
+function twMotion(ctx: LintContext): { item: TwItem; what: string } | null {
+ for (const item of twGroup(ctx).items) {
+ const base = item.info.classes.map(stripVariants);
+ const animate = base.find((c) => /^animate-(?!none$)/.test(c));
+ if (animate) return { item, what: animate };
+ if (base.some((c) => /^transition(-transform|-all)?$/.test(c)) && base.some((c) => /^-?(scale|translate|rotate|skew)-/.test(c))) return { item, what: 'a transition on a transform' };
+ }
+ return null;
+}
+
+// sloplint check27 (gate 27); ctx.shared.reducedMotion is the project's fallback
+function reducedMotion(ctx: LintContext, r: Reporter): void {
+ const moves = (decls: Array<{ prop: string; value: string }>) => decls.some((d) => /^(transform|translate|scale|rotate)$/.test(d.prop) && !/^none\b/.test(d.value.trim()));
+ const hasMotion = ctx.rules.some((rule) => rule.keyframes)
+ || ctx.rules.some((rule) => rule.decls.some((d) => /^transition/.test(d.prop) && /transform/.test(d.value)))
+ || (ctx.rules.some((rule) => rule.decls.some((d) => /^transition/.test(d.prop) && /(^|[\s,])all\b/.test(d.value))) && ctx.rules.some((rule) => /:(hover|active|focus)/.test(rule.selector) && moves(rule.decls)));
+ const tw = twMotion(ctx);
+ if (!hasMotion && !tw) return;
+ const tv = twVariants(ctx);
+ const hasFallback = ctx.rules.some((rule) => rule.media && /prefers-reduced-motion/i.test(rule.media))
+ || ctx.cssFiles.some((f) => /prefers-reduced-motion/i.test(stripComments(f.raw)))
+ || ctx.docs.some((doc) => doc.styles.some((s) => /prefers-reduced-motion/i.test(stripComments(s.css))))
+ || tv.has('motion-reduce') || tv.has('motion-safe') || !!ctx.shared?.reducedMotion;
+ if (hasFallback || !once(ctx, '27')) return;
+ if (!hasMotion && tw) {
+ r.report('missing-reduced-motion', tw.item.file, tw.item.line, `motion utilities (${tw.what}) with no motion-reduce: or motion-safe: variant anywhere`, { fix: 'add motion-reduce: fallbacks, or put the motion behind motion-safe:' });
+ return;
+ }
+ const kf = ctx.rules.find((rule) => rule.keyframes);
+ r.report('missing-reduced-motion', kf ? kf.file : firstFile(ctx), kf ? kf.line : 1, 'motion present and no prefers-reduced-motion block anywhere');
+}
+
+// sloplint check28 (gates 28a, 28b)
+function media(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ let firstMedia = true, seenH1 = false, heroPassed = false;
+ for (const t of doc.tags) {
+ if (t.close) { if (seenH1 && (t.name === 'section' || t.name === 'header')) heroPassed = true; continue; }
+ if (t.name === 'h1') seenH1 = true;
+ if (t.name === 'video') {
+ if (hasAttr(t.attrs, 'autoplay') && !hasAttr(t.attrs, 'muted')) r.report('autoplay-unmuted', doc.file, t.line, 'a video autoplays without muted, so browsers block it or it plays sound unasked');
+ if (!getAttr(t.attrs, 'poster')) r.report('video-without-poster', doc.file, t.line, 'a video with no poster frame', { fix: 'a poster frame; below the fold it may also load lazily' });
+ if ((getAttr(t.attrs, 'loading') || '').toLowerCase() === 'lazy' && firstMedia) r.report('lazy-lcp', doc.file, t.line, 'the first video loads lazily and is likely the largest paint', { fix: 'never lazy on the LCP video; preload its poster with fetchpriority="high"', suspected: true });
+ firstMedia = false;
+ }
+ if (t.name === 'img') {
+ if (firstMedia && !heroPassed && (getAttr(t.attrs, 'loading') || '').toLowerCase() === 'lazy') r.report('lazy-lcp', doc.file, t.line, 'the first image loads lazily and is likely the largest paint', { suspected: true });
+ firstMedia = false;
+ }
+ }
+ }
+}
+
+const INPUT_SEL = /(^|[\s,>+~])(input|textarea|select)\b|__input|__field|\.(input|field)\b/;
+
+// sloplint check39 (gate 39a)
+function inputStates(ctx: LintContext, r: Reporter): void {
+ const hasInputs = ctx.docs.some((doc) => /<(input|textarea|select)\b/i.test(doc.src)) || ctx.rules.some((rule) => /(^|[\s,>+~])(input|textarea|select)\b/.test(rule.selector));
+ if (!hasInputs) return;
+ const widthOf = (v: string) => { const m = /(\d+(?:\.\d+)?)px/.exec(v); return m ? parseFloat(m[1]) : null; };
+ let baseW: number | null = null;
+ for (const rule of ctx.rules) {
+ if (!INPUT_SEL.test(rule.selector) || /:hover|:focus|:active|:disabled|:checked|\[(?:disabled|aria-invalid|aria-disabled|data-state)/.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'border' && d.prop !== 'border-width') continue;
+ const w = widthOf(d.value);
+ if (w != null && baseW == null) baseW = w;
+ }
+ }
+ for (const rule of ctx.rules) {
+ if (!INPUT_SEL.test(rule.selector) || !/:hover|:focus|\.is-error|\[aria-invalid/.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'border' && d.prop !== 'border-width') continue;
+ const w = widthOf(d.value);
+ if (w != null && baseW != null && w !== baseW) r.report('input-state-shift', rule.file, d.line, `the border goes from ${baseW}px to ${w}px on ${rule.selector}, so the field shifts`, { fix: 'keep the border width constant; move the state to outline' });
+ }
+ if (/:focus/.test(rule.selector) && rule.decls.some((d) => /^border(-color)?$/.test(d.prop)) && !rule.decls.some((d) => (/^outline/.test(d.prop) && !OUTLINE_REMOVED.test(d.value.trim())) || (d.prop === 'box-shadow' && !/^none\b/i.test(d.value.trim())))) {
+ r.report('input-state-shift', rule.file, rule.line, `the focus state is drawn with border on ${rule.selector}`, { fix: 'a focus ring with outline, not border' });
+ }
+ }
+ for (const rule of ctx.rules) {
+ if (!/:disabled|\[disabled\]/.test(rule.selector)) continue;
+ if (rule.decls.some((d) => d.prop === 'opacity') && !rule.decls.some((d) => d.prop === 'cursor' && /not-allowed/.test(d.value))) {
+ r.report('input-state-shift', rule.file, rule.line, `disabled by opacity alone on ${rule.selector}`, { fix: 'three disabled channels: fill, ink and cursor: not-allowed, plus the disabled attribute' });
+ }
+ }
+}
+
+const CONTROL_SEL = /(^|[\s,>+~(])(button|input|select|textarea)\b|\.(btn|button|cta|input|field|control)\b/i;
+const CONTROL_SKIP = /:hover|:focus|:active|:disabled|:checked|\[type=["']?(radio|checkbox|range|hidden|color|file)|sr-only|visually-hidden|icon|close|toggle|switch|chip|tag|badge|pill|__dot|__mark/i;
+
+// gate 39b, static half (sloplint measures 39b in the render tier only): a control whose CSS fixes its height outside 44 to 52px
+function controlHeight(ctx: LintContext, r: Reporter): void {
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule) || !CONTROL_SEL.test(rule.selector) || CONTROL_SKIP.test(rule.selector)) continue;
+ if (rule.media && /max-width/i.test(rule.media)) continue;
+ const multiline = /(^|[\s,>+~(])textarea\b/i.test(rule.selector);
+ for (const d of rule.decls) {
+ if (!/^(min-)?height$/.test(d.prop) || (multiline && d.prop === 'min-height')) continue;
+ const px = pxOf(resolveVars(d.value, ctx.tokens));
+ if (px == null || (px >= 44 && px <= 52) || seen.has(rule.selector)) continue;
+ seen.add(rule.selector);
+ r.report('control-height', rule.file, d.line, `${d.prop}: ${trunc(d.value, 20)} (${px}px) on ${rule.selector}: controls stand 44 to 52px`, { fix: 'min-height: 48px' });
+ }
+ }
+}
+
+// sloplint HIDE_OK (gate 62): states and parts that are hidden at rest by nature
+const HIDE_OK = /tooltip|popover|menu|dropdown|modal|dialog|toast|overlay|backdrop|sheet|drawer|panel|:hover|:focus|:checked|:target|\[open|\[aria-(?:expanded|selected|current|pressed)|::before|::after|\.is-|\[hidden|\[aria-hidden|sr-only|visually-hidden|skip|placeholder|::marker|\[data-slot/i;
+const REVEALISH = /reveal|fade|animate|aos|in-view|inview|appear|enter|rise|slide|stagger|observe|lazy/i;
+
+// sloplint startingStyleText (gate 62): the selectors every @starting-style block declares, plus the selector it sits under, as whole comma parts (a substring test let `.reveal-wrap` in one block silence `.reveal`); a block inside one already taken is part of it, so an unclosed block costs the rest of the sheet once
+function startingSelectors(css: string): Set<string> {
+ const out = new Set<string>();
+ const add = (text: string) => { for (const part of splitTop(text)) if (part.trim()) out.add(part.trim().replace(/\s+/g, ' ')); };
+ let taken = 0;
+ for (const m of css.matchAll(/@starting-style\s*\{/gi)) {
+ if (m.index! < taken) continue;
+ let depth = 1, k = m.index! + m[0].length;
+ while (k < css.length && depth > 0) { if (css[k] === '{') depth++; else if (css[k] === '}') depth--; k++; }
+ taken = k;
+ for (const s of css.slice(m.index! + m[0].length, k).matchAll(/([^{};]+)\{/g)) add(s[1]);
+ const open = css.lastIndexOf('{', m.index! - 1), close = css.lastIndexOf('}', m.index! - 1);
+ if (open > close) add(css.slice(Math.max(close + 1, 0), open));
+ }
+ return out;
+}
+
+// sloplint check62 (gate 62)
+function hiddenAtRest(ctx: LintContext, r: Reporter): void {
+ const starting = startingSelectors(ctx.allCss);
+ const jsScoped = (sel: string) => /(^|[\s,])(html|body)?\.js\b|\[data-js|\.no-js|html\.has-js/i.test(sel);
+ const animated = new Map<string, Array<{ selector: string; decls: Array<{ prop: string; value: string }> }>>();
+ for (const rule of ctx.rules) if (rule.keyframes) {
+ if (!animated.has(rule.keyframes)) animated.set(rule.keyframes, []);
+ animated.get(rule.keyframes)!.push(rule);
+ }
+ const animatesVisible = (name: string) => (animated.get(name) || []).some((rule) => /to|100%/.test(rule.selector) && rule.decls.some((d) => d.prop === 'opacity' && parseFloat(d.value) === 1));
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || (rule.media && /\bprint\b/i.test(rule.media)) || rule.selector === '@font-face') continue;
+ const hidden = rule.decls.find((d) => (d.prop === 'opacity' && parseFloat(resolveVars(d.value, ctx.tokens)) === 0) || (d.prop === 'visibility' && /hidden/.test(d.value)));
+ if (!hidden) continue;
+ if (HIDE_OK.test(rule.selector.replace(/:not\([^)]*\)/g, '')) || jsScoped(rule.selector) || (starting.size > 0 && splitTop(rule.selector).some((part) => starting.has(part.trim().replace(/\s+/g, ' '))))) continue;
+ const revealish = REVEALISH.test(rule.selector) || rule.decls.some((d) => d.prop === 'transform' && /translate|scale/.test(d.value));
+ if (!revealish) continue;
+ const anim = rule.decls.find((d) => d.prop === 'animation' || d.prop === 'animation-name');
+ const animName = anim ? anim.value.split(/\s+/).find((w) => animated.has(w)) : null;
+ if (animName && animatesVisible(animName)) continue;
+ if (seen.has(rule.selector)) continue;
+ seen.add(rule.selector);
+ r.report('content-hidden-at-rest', rule.file, hidden.line, `${rule.selector} is hidden at rest (${hidden.prop}: ${hidden.value}) and needs a script to appear`);
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ layoutTransitions(ctx, r);
+ hoverTells(ctx, r);
+ bounceEasing(ctx, r);
+ focusRingFade(ctx, r);
+ tooltipDelay(ctx, r);
+ autorotate(ctx, r);
+ focusAndStates(ctx, r);
+ reducedMotion(ctx, r);
+ media(ctx, r);
+ inputStates(ctx, r);
+ controlHeight(ctx, r);
+ hiddenAtRest(ctx, r);
+}
diff --git a/lib/design-lint/rules/structure.ts b/lib/design-lint/rules/structure.ts
new file mode 100644
index 000000000..f4a5dac42
--- /dev/null
+++ b/lib/design-lint/rules/structure.ts
@@ -0,0 +1,425 @@
+/**
+ * Structure rules of the design lint (sloplint gates 3 4 6a 24a 24b 34 44d 50 53 56 58; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: template-cards, nested-cards, vh-height, raw-spacing,
+ * off-scale-spacing, overflow-x-unclipped, wide-container, bare-fr-track, display-head-unwrapped, radio-tab-jump,
+ * double-sticky, screen-word-budget. Gate 59 (section-gap) has no static check: the render tier owns it (render-probe-space.ts glGaps), as it owns
+ * the render halves of 34 (horizontal-scroll) and 44d.
+ */
+import { COLOR_LITERAL, oklchOf, parseColor } from '../color';
+import { isTokenRule, pxOf, resolveVars, selectorNames, type MergedRule } from '../css';
+import { memo, mergedRules, type LintContext } from '../context';
+import { getAttr, innerOf, stripTags, textOf, treeOf, wordsOf, type Doc } from '../html';
+import { trunc, type Reporter } from '../report';
+import { twGroup } from '../tailwind';
+import { heroIndexOf } from './chrome-copy';
+
+const SPACING_PROP = /^(padding|margin|gap|row-gap|column-gap)(-[a-z]+)?$/;
+
+const selectorClasses = (sel: string): string[] => (sel.match(/\.[a-zA-Z][\w-]*/g) || []).map((c) => c.slice(1));
+
+const stripVariants = (cls: string): string => cls.replace(/^(?:[\w-]+:)+/, '');
+
+/** The inner HTML of every open element in the context whose class attribute carries one of the classes. */
+function innerHtmlWithClass(ctx: LintContext, classes: string[]): string[] {
+ if (!classes.length) return [];
+ const byClass = memo(ctx, 'innerByClass', () => {
+ const index = new Map<string, string[]>();
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ for (const c of new Set((getAttr(t.attrs, 'class') || '').split(/\s+/).filter(Boolean))) {
+ let list = index.get(c);
+ if (!list) index.set(c, list = []);
+ list.push(inner.inner);
+ }
+ }
+ }
+ return index;
+ });
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const c of classes) for (const inner of byClass.get(c) ?? []) if (!seen.has(inner)) { seen.add(inner); out.push(inner); }
+ return out;
+}
+
+const EQUAL_TRACK = String.raw`(?:1fr|minmax\(\s*0(?:px)?\s*,\s*1fr\s*\))`;
+const THREE_EQUAL = [new RegExp(String.raw`^repeat\(\s*3\s*,\s*${EQUAL_TRACK}\s*\)$`), new RegExp(String.raw`^${EQUAL_TRACK}(?:\s+${EQUAL_TRACK}){2}$`)];
+
+// sloplint check3 (gate 3)
+function iconTiles(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (d.prop !== 'grid-template-columns') continue;
+ const v = resolveVars(d.value, ctx.tokens).trim();
+ if (!THREE_EQUAL.some((re) => re.test(v))) continue;
+ const classes = selectorClasses(rule.selector);
+ const tiles = (!ctx.docs.length && !classes.length)
+ || innerHtmlWithClass(ctx, classes).some((inner) => (/class\s*=\s*["'][^"']*icon/i.test(inner) || /<svg\b/i.test(inner)) && /<h[2-6]\b/i.test(inner));
+ if (tiles) r.report('template-cards', rule.file, d.line, `three equal columns of icon-above-heading tiles on ${rule.selector}`, { fix: 'vary the column widths, or set the icons inline and drop the tiles' });
+ }
+ }
+}
+
+// sloplint check3Stripe (gate 3)
+function sideStripes(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (!/^border-(left|right|inline-start|inline-end)$/.test(d.prop)) continue;
+ const m = /(\d+(?:\.\d+)?)px/.exec(d.value);
+ if (!m || parseFloat(m[1]) < 3 || /transparent|none/i.test(d.value)) continue;
+ const col = COLOR_LITERAL.exec(resolveVars(d.value, ctx.tokens));
+ const parsed = col ? parseColor(col[0]) : null;
+ const ok = parsed ? oklchOf(parsed) : null;
+ if (parsed && ok && (parsed.alpha <= 0.05 || (ok.C < 0.04 && ok.L > 0.6))) continue;
+ r.report('template-cards', rule.file, d.line, `a ${m[1]}px coloured side stripe (${d.prop}: ${trunc(d.value, 32)}) on ${rule.selector}`, { fix: 'a hairline all round, no border, or an accent square' });
+ }
+ }
+}
+
+const CARD_WORD = /(^|-)card(--[\w-]+)?$/i;
+const CONTAINERISH = /(grid|list|rail|row|wrap|deck|group|stack|container|section|scroller|track)/i;
+
+// sloplint check4 (gate 4)
+function nestedCards(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const { parent } = treeOf(doc);
+ const cardAt: boolean[] = [];
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ cardAt[i] = cls.split(/\s+/).some((c) => { const base = c.split('--')[0]; return !!base && CARD_WORD.test(base) && !CONTAINERISH.test(base); });
+ if (!cardAt[i]) continue;
+ for (let p = parent[i]; p >= 0; p = parent[p]) {
+ if (!cardAt[p]) continue;
+ r.report('nested-cards', doc.file, t.line, `a card inside a card: class="${trunc(cls, 40)}"`);
+ break;
+ }
+ }
+ }
+}
+
+// sloplint heroClasses (gate 6a): the classes of the section or header that holds the h1
+function heroClasses(ctx: LintContext): Set<string> {
+ const out = new Set<string>();
+ for (const doc of ctx.docs) {
+ const h1 = doc.tags.findIndex((t) => !t.close && t.name === 'h1');
+ const hero = h1 < 0 ? -1 : heroIndexOf(doc, h1);
+ if (hero < 0) continue;
+ for (const c of (getAttr(doc.tags[hero].attrs, 'class') || '').split(/\s+/)) if (c) out.add(c);
+ }
+ return out;
+}
+
+// sloplint check6a (gate 6a)
+function vhHero(ctx: LintContext, r: Reporter): void {
+ const heroCls = heroClasses(ctx);
+ const isHero = (sel: string) => /hero/i.test(sel) || [...heroCls].some((c) => sel.includes('.' + c));
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule) || !isHero(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (!/^(min-)?height$/.test(d.prop)) continue;
+ const v = resolveVars(d.value, ctx.tokens);
+ if (!/\d\s*vh\b/i.test(v) || seen.has(rule.selector)) continue;
+ seen.add(rule.selector);
+ r.report('vh-height', rule.file, d.line, `the hero is sized in vh: ${d.prop}: ${trunc(v, 24)} on ${rule.selector}`);
+ }
+ }
+}
+
+// sloplint check24 (gate 24b)
+function offScaleSpacing(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (!SPACING_PROP.test(d.prop)) continue;
+ for (const m of d.value.matchAll(/(-?\d+(?:\.\d+)?)px/g)) {
+ const v = Math.abs(parseFloat(m[1]));
+ if (v > 2 && (v % 4 !== 0 || !Number.isInteger(v))) {
+ r.report('off-scale-spacing', rule.file, d.line, `${d.prop}: ${trunc(d.value, 28)} on ${rule.selector} is off the 4px scale`, { fix: 'a step of the 4px spacing scale' });
+ }
+ }
+ }
+ }
+}
+
+// sloplint check24a (gate 24a)
+/** Raw spacing lengths named per file before the rest fold into one count. */
+const RAW_SPACING_PER_FILE = 8;
+
+function rawSpacing(ctx: LintContext, r: Reporter): void {
+ const spaceVals = new Map<number, string>();
+ for (const [k, v] of Object.entries(ctx.tokens)) {
+ if (!/^--space-/.test(k)) continue;
+ const px = pxOf(resolveVars(v, ctx.tokens));
+ if (px != null && px > 0) spaceVals.set(px, k);
+ }
+ if (!spaceVals.size) return;
+ const counts = new Map<string, number>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule)) continue;
+ for (const d of rule.decls) {
+ if (!SPACING_PROP.test(d.prop)) continue;
+ const raw = d.value.replace(/var\([^)]*\)/g, ' ');
+ for (const m of raw.matchAll(/(?<![\w.-])(-?\d*\.?\d+)(px|rem)\b/g)) {
+ const px = Math.abs(pxOf(m[1] + m[2]) ?? 0);
+ const token = spaceVals.get(px);
+ if (!px || !token) continue;
+ const n = (counts.get(rule.file) || 0) + 1;
+ counts.set(rule.file, n);
+ if (n <= RAW_SPACING_PER_FILE) r.report('raw-spacing', rule.file, d.line, `${d.prop}: ${trunc(d.value, 28)} on ${trunc(rule.selector, 32)} where ${token} exists`, { fix: `var(${token})` });
+ break;
+ }
+ }
+ }
+ for (const [file, n] of counts) if (n > RAW_SPACING_PER_FILE) r.report('raw-spacing', file, 1, `${n - RAW_SPACING_PER_FILE} more raw spacing lengths in this file have a matching --space-* token`, { fix: 'the tokens' });
+}
+
+/** An HTML file that is only an app shell: no styles, a module script, no local stylesheet. */
+const isShell = (d: Doc): boolean => d.kind === 'html' && !d.styles.length
+ && /<script\b[^>]*type\s*=\s*["']module["'][^>]*\bsrc\s*=\s*["'][^"']+\.(?:tsx?|jsx?|mjs|vue|svelte)["']/i.test(d.src)
+ && ![...d.src.matchAll(/<link\b[^>]*>/gi)].some((m) => /rel\s*=\s*["']stylesheet/i.test(m[0]) && !/href\s*=\s*["']https?:/i.test(m[0]));
+
+// sloplint check34, static half (gate 34); the render tier owns horizontal-scroll
+function overflowX(ctx: LintContext, r: Reporter): void {
+ const clipped = new Set<string>();
+ let hidden: { file: string; line: number; sel: string } | null = null;
+ for (const rule of ctx.rules) {
+ if (!/(^|[\s,])(html|body)\b/.test(rule.selector)) continue;
+ const targets = rule.selector.split(',').map((p) => (/^\s*(html|body)\s*$/.exec(p) || [])[1]).filter((t): t is string => !!t);
+ for (const d of rule.decls) {
+ if (d.prop !== 'overflow-x' && d.prop !== 'overflow') continue;
+ if (/\bclip\b/.test(d.value)) for (const t of targets) clipped.add(t);
+ else if (/\bhidden\b/.test(d.value)) hidden = { file: rule.file, line: d.line, sel: rule.selector };
+ }
+ }
+ const hiddenUtil: Array<{ file: string; line: number; tag: string; util: string }> = [];
+ for (const it of twGroup(ctx).items) {
+ if (it.idx < 0 || !/^(html|body)$/.test(it.tag)) continue;
+ const base = it.info.classes.map(stripVariants);
+ if (base.some((c) => c === 'overflow-x-clip' || c === 'overflow-clip')) clipped.add(it.tag);
+ const util = base.find((c) => c === 'overflow-x-hidden');
+ if (util) hiddenUtil.push({ file: it.file, line: it.line, tag: it.tag, util });
+ }
+ for (const it of hiddenUtil) r.report('overflow-x-unclipped', it.file, it.line, `${it.util} on <${it.tag}>: hidden breaks position: sticky`, { fix: 'overflow-x-clip on both html and body, never hidden' });
+ const pageish = ctx.docs.some((d) => (d.kind === 'html' && !isShell(d)) || (d.kind !== 'html' && d.tags.some((t) => !t.close && (t.name === 'html' || t.name === 'body'))));
+ const file = ctx.cssFiles[0]?.file || ctx.docs[0]?.file;
+ const both = clipped.has('html') && clipped.has('body');
+ if (!both && hidden) {
+ r.report('overflow-x-unclipped', hidden.file, hidden.line, `overflow-x: hidden on ${hidden.sel}: hidden breaks position: sticky`, { fix: 'overflow-x: clip on both html and body, never hidden' });
+ } else if (!both && file && ctx.docs.length && pageish && !hiddenUtil.length) {
+ r.report('overflow-x-unclipped', file, 1, clipped.size ? `overflow-x: clip on ${[...clipped][0]} only` : 'no overflow-x: clip on html and body', { fix: 'overflow-x: clip on both html and body' });
+ }
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (/^(width|min-width)$/.test(d.prop) && /(^|[^\w.-])100vw\b/.test(d.value)) {
+ r.report('overflow-x-unclipped', rule.file, d.line, `${d.prop}: ${trunc(d.value, 28)} on ${rule.selector}: 100vw counts the scrollbar and overflows`, { fix: 'width: 100% with the container\'s padding' });
+ }
+ }
+ }
+}
+
+// sloplint check50 (gate 50)
+function bareFrTrack(ctx: LintContext, r: Reporter): void {
+ for (const rule of ctx.rules) {
+ for (const d of rule.decls) {
+ if (d.prop !== 'grid-template-columns') continue;
+ let flat = resolveVars(d.value, ctx.tokens);
+ for (let k = 0; k < 4 && /\((?:[^()]*)\)/.test(flat); k++) flat = flat.replace(/(calc|min|max|clamp|var|fit-content)\(([^()]*)\)/g, 'X');
+ flat = flat.replace(/minmax\([^()]*\)/g, 'MM');
+ const bare = /(?<![\w.-])\d*\.?\d+fr\b/.exec(flat);
+ if (!bare) continue;
+ const holdsImages = innerHtmlWithClass(ctx, selectorClasses(rule.selector)).some((inner) => /<(img|picture|video)\b/i.test(inner));
+ if (holdsImages) r.report('bare-fr-track', rule.file, d.line, `a bare ${bare[0]} track holds images on ${rule.selector}: the image's min-content width can push the grid past its box`);
+ }
+ }
+}
+
+// sloplint check50Wrap (gate 50)
+function displayHeadUnwrapped(ctx: LintContext, r: Reporter): void {
+ const wrapping = ctx.rules.filter((rule) => rule.decls.some((d) =>
+ (d.prop === 'overflow-wrap' && /anywhere|break-word/.test(d.value))
+ || (d.prop === 'word-break' && /break-word|break-all/.test(d.value))
+ || (d.prop === 'hyphens' && /auto/.test(d.value)))).map((rule) => rule.selector);
+ const everywhere = wrapping.some((sel) => /^\*|:where\(|html|body/.test(sel));
+ const wrap = selectorNames(wrapping);
+ const wrapCovered = (cls: string, tag: string) => everywhere || wrap.tags.has(tag) || cls.split(/\s+/).some((c) => c && wrap.classes.has(c));
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ if (!/^h[12]$/.test(t.name) && !/hero__(title|display)|section__title|__display/.test(cls)) continue;
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ const text = stripTags(inner.inner).replace(/\s+/g, ' ').trim();
+ const risky = text.split(' ').find((word) => word.split('-').some((seg) => seg.replace(/[^\w]/g, '').length >= 16));
+ if (risky && !wrapCovered(cls, t.name)) {
+ r.report('display-head-unwrapped', doc.file, t.line, `the display head holds "${trunc(risky, 30)}" with no overflow-wrap: at 320px that word overflows`);
+ }
+ }
+ }
+}
+
+// sloplint check53 (gate 53)
+function radioTabJump(ctx: LintContext, r: Reporter): void {
+ const guarded = ctx.docs.some((doc) => /preventScroll/.test(doc.scripts));
+ for (const rule of ctx.rules) {
+ if (!/input\[type=["']?radio["']?\]|\.(radio|tab-input|tab-radio)\b/i.test(rule.selector)) continue;
+ const abs = rule.decls.some((d) => d.prop === 'position' && /absolute|fixed/.test(d.value));
+ const topZero = rule.decls.some((d) => d.prop === 'top' && /^0(px|rem)?$/.test(d.value.trim()));
+ if (abs && topZero && !guarded) {
+ r.report('radio-tab-jump', rule.file, rule.line, `radio tabs at position: absolute; top: 0 on ${rule.selector} with no script guard: focusing a radio scrolls the page to the top`);
+ }
+ }
+}
+
+// sloplint check56 (gate 56)
+function doubleSticky(ctx: LintContext, r: Reporter): void {
+ const bySelector = new Map<string, MergedRule>();
+ for (const m of mergedRules(ctx)) {
+ if (m.decls.some((d) => d.prop === 'position' && /sticky/.test(d.value))
+ && m.decls.some((d) => d.prop === 'top' && /^(0|0px|0rem|-1px)$/.test(resolveVars(d.value, ctx.tokens).trim())) && !bySelector.has(m.selector)) bySelector.set(m.selector, m);
+ }
+ const sticky = [...bySelector.values()];
+ if (sticky.length < 2) return;
+ const sels = sticky.map((m) => m.selector).join(' and ');
+ r.report('double-sticky', sticky[1].file, sticky[1].line, `two elements stick at top: 0 (${trunc(sels, 52)}): the second slides under the first`);
+}
+
+const countWords = (t: string): number => t.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
+
+/** Words the visitor never sees: screen-reader-only, aria-hidden, hidden and credits blocks. */
+function hiddenWordCount(doc: Doc): number {
+ let words = 0, hiddenEnd = -1;
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || t.pos < hiddenEnd) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ const hiddenish = /(^|\s)(sr-only|visually-hidden|screen-reader-text|skip|skip-link)(\s|$)/i.test(cls)
+ || /aria-hidden\s*=\s*["']?true/i.test(t.attrs) || /(^|\s)hidden(\s|=|$)/i.test(t.attrs) || /(^|\s)data-credits(\s|=|$)/i.test(t.attrs);
+ if (!hiddenish) continue;
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ words += countWords(textOf(doc, i));
+ hiddenEnd = inner.endPos;
+ }
+ return words;
+}
+
+// sloplint check58Static (gate 58); the render tier measures the 900px window
+function wordBudget(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const h1 = doc.tags.findIndex((t) => !t.close && t.name === 'h1');
+ if (h1 >= 0) {
+ const words = wordsOf(innerOf(doc, h1)?.inner || '');
+ if (words.length > 7) r.report('screen-word-budget', doc.file, doc.tags[h1].line, `the h1 runs ${words.length} words ("${trunc(words.join(' '), 40)}")`, { fix: 'seven words or fewer, 50 characters or fewer' });
+ const heroIdx = heroIndexOf(doc, h1);
+ const hero = heroIdx >= 0 ? innerOf(doc, heroIdx) : null;
+ if (hero) {
+ for (let i = h1 + 1; i < doc.tags.length && doc.tags[i].pos < hero.endPos; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.name !== 'p') continue;
+ const pw = wordsOf(innerOf(doc, i)?.inner || '');
+ if (pw.length > 12) r.report('screen-word-budget', doc.file, t.line, `the hero paragraph runs ${pw.length} words`, { fix: 'one sentence, twelve words or fewer' });
+ break;
+ }
+ }
+ }
+ const sections = doc.tags.filter((t) => !t.close && t.name === 'section').length;
+ const fullPage = sections >= 5 || doc.tags.some((t) => !t.close && t.name === 'footer');
+ if (!fullPage || doc.kind !== 'html') continue;
+ const total = countWords(doc.text) - hiddenWordCount(doc);
+ if (total > 450) r.report('screen-word-budget', doc.file, 1, `${total} visible words on the page (450 at most)`, { fix: 'cut copy: one idea per screen; sections become objects' });
+ }
+}
+
+/** The px of a media query's min-width clause (px, em or rem), or null when it has none. */
+function minWidthPx(media: string | null): number | null {
+ if (!media) return null;
+ const m = /min-width\s*:\s*(\d+(?:\.\d+)?)(px|em|rem)|width\s*>=\s*(\d+(?:\.\d+)?)(px|em|rem)/i.exec(media);
+ if (!m) return null;
+ return pxOf((m[1] ?? m[3]) + (m[2] ?? m[4]));
+}
+
+/** How many columns a grid-template-columns value lays down; null when the count depends on the viewport (auto-fit, auto-fill) or on a var. */
+function columnCount(value: string): number | null {
+ if (/auto-fi(t|ll)|var\(/.test(value)) return null;
+ let repeated = 0;
+ const v = value.replace(/repeat\(\s*(\d+)\s*,\s*((?:[^()]|\([^()]*\))*)\)/g, (_, count: string, tracks: string) => {
+ repeated += parseInt(count, 10) * tracks.replace(/\([^()]*\)/g, 'X').replace(/\[[^\]]*\]/g, ' ').trim().split(/\s+/).filter(Boolean).length;
+ return ' ';
+ });
+ if (/repeat\(/.test(v)) return null;
+ return repeated + v.replace(/\([^()]*\)/g, 'X').replace(/\[[^\]]*\]/g, ' ').trim().split(/\s+/).filter(Boolean).length;
+}
+
+/** Whether some container is capped: a max-width paired with auto margins, a max-width of 900px or more, or a Tailwind container or max-w utility. */
+function containerCapped(ctx: LintContext): boolean {
+ for (const m of mergedRules(ctx)) {
+ const cap = m.decls.find((d) => d.prop === 'max-width' || d.prop === 'max-inline-size')
+ ?? m.decls.find((d) => (d.prop === 'width' || d.prop === 'inline-size') && /^(min|clamp)\(/.test(resolveVars(d.value, ctx.tokens).trim()) && /\d(px|rem|em|ch)\b/.test(d.value));
+ if (!cap || /^(none|100%|100vw)$/.test(cap.value.trim())) continue;
+ const px = pxOf(resolveVars(cap.value, ctx.tokens));
+ const centred = m.decls.some((d) => /^margin(-inline|-left|-right)?$/.test(d.prop) && /\bauto\b/.test(d.value));
+ if (centred || (px != null && px >= 900)) return true;
+ }
+ return twGroup(ctx).items.some((it) => it.info.classes.map(stripVariants).some((c) => c === 'container' || /^max-w-(?!none$|full$|screen$|\[100)/.test(c)));
+}
+
+const VISUAL_SEL = /(^|[\s,>+~(])(img|picture|video|figure|svg|canvas)\b|__(media|visual|image|img|photo|figure|art|cover|illustration)\b|\.(media|visual|image|img|photo|figure|art|cover|illustration|orb|blob)\b/i;
+
+// gate 44d, static half (sloplint measures 44d in the render tier only): what the CSS alone proves about 1920px
+function wideContainer(ctx: LintContext, r: Reporter): void {
+ if (!ctx.docs.some((d) => d.kind === 'html') || containerCapped(ctx)) return;
+ const merged = mergedRules(ctx);
+ const columnsBelow = (selector: string): number => {
+ let n = 0;
+ for (const m of merged) {
+ if (m.selector !== selector || (minWidthPx(m.media) ?? 0) > 1440) continue;
+ for (const d of m.decls) if (d.prop === 'grid-template-columns') n = Math.max(n, columnCount(resolveVars(d.value, ctx.tokens)) ?? 0);
+ }
+ return n;
+ };
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule)) continue;
+ const wide = minWidthPx(rule.media);
+ for (const d of rule.decls) {
+ if (d.prop === 'grid-template-columns' && wide != null && wide > 1440) {
+ const n = columnCount(resolveVars(d.value, ctx.tokens));
+ const below = columnsBelow(rule.selector);
+ if (n != null && below > 0 && n > below && !seen.has('cols:' + rule.selector)) {
+ seen.add('cols:' + rule.selector);
+ r.report('wide-container', rule.file, d.line, `no container has a max-width, and ${rule.selector} gains columns at ${rule.media} (${below} to ${n})`, { fix: 'cap the container at 1360 to 1520px and centre it; hold the column count' });
+ }
+ }
+ if (!/^(width|height|inline-size|block-size|flex-basis)$/.test(d.prop) || !VISUAL_SEL.test(rule.selector)) continue;
+ const v = resolveVars(d.value, ctx.tokens);
+ const capped = /clamp\(|min\(/.test(v) || rule.decls.some((x) => /^max-(width|height|inline-size|block-size)$/.test(x.prop));
+ if (/\d\s*vw\b/i.test(v) && !capped && !seen.has('vw:' + rule.selector)) {
+ seen.add('vw:' + rule.selector);
+ r.report('wide-container', rule.file, d.line, `no container has a max-width, and ${rule.selector} is sized in vw with no cap (${d.prop}: ${trunc(v, 24)})`, { fix: 'cap the container at 1360 to 1520px; give the visual a max-width or a clamp()' });
+ }
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ iconTiles(ctx, r);
+ sideStripes(ctx, r);
+ nestedCards(ctx, r);
+ vhHero(ctx, r);
+ offScaleSpacing(ctx, r);
+ rawSpacing(ctx, r);
+ overflowX(ctx, r);
+ bareFrTrack(ctx, r);
+ displayHeadUnwrapped(ctx, r);
+ radioTabJump(ctx, r);
+ doubleSticky(ctx, r);
+ wordBudget(ctx, r);
+ wideContainer(ctx, r);
+}
diff --git a/lib/design-lint/rules/type.ts b/lib/design-lint/rules/type.ts
new file mode 100644
index 000000000..4c923f690
--- /dev/null
+++ b/lib/design-lint/rules/type.ts
@@ -0,0 +1,469 @@
+/**
+ * Type rules of the design lint (sloplint gates 1 25 37 38i 38ii 38iii 55a 55b 64 67; Nutlope/hallmark,
+ * MIT, see NOTICE.md), rewritten in gstack's voice. Rule ids: overused-font, line-length, font-family-count, italic-word-in-heading, italic-serif-display, accented-word, caps-leading, caps-lockup-leading, monospace-costume, wide-tracking.
+ *
+ * Gate 75 (tiny text) is render-only and lives in the render tier.
+ */
+import { BANNED_FONTS, OVERUSED_FONTS_DISPLAY } from '../../design-catalog';
+import type { LintContext } from '../context';
+import { fontPx, memo, mergedRules, styleFor, trackingEm, valueOf } from '../context';
+import { CONTROL_TRACK_MAX_EM, GENERIC_FAMILIES, HEADING_SEL, LABEL_PX, MONO_FACE, TRACKED_EM, famKey, firstFamily, isTokenRule, pxOf, resolveVars, selectorNames, tokenSites, type CssDecl, type CssRule, type MergedRule } from '../css';
+import { ancestorsOf, closeIndex, getAttr, innerOf, openTags, plainText, stripTags, textOf, type Doc } from '../html';
+import type { Reporter } from '../report';
+import { trunc } from '../report';
+import { twMonoIsMaterial } from '../tailwind';
+import { capsRatio } from './chrome-eyebrow';
+
+/** A selector without its pseudo-classes and pseudo-elements, whitespace folded. */
+const baseSelector = (sel: string): string => sel.replace(/::?[a-z-]+(\([^)]*\))?/gi, '').replace(/\s+/g, ' ').trim();
+
+const em3 = (em: number): string => String(Math.round(em * 1000) / 1000);
+
+/** The declaration a token's value was read from (the same choice buildTokens makes), for the finding's file and line. */
+function tokenSite(ctx: LintContext, prop: string): { file: string; line: number } {
+ const site = memo(ctx, 'tokenSites', () => tokenSites(ctx.rules)).get(prop);
+ return site ? { file: site.file, line: site.line } : { file: ctx.rules[0]?.file ?? ctx.key, line: 1 };
+}
+
+/** gstack's own catalog of training-data display faces, plus the system stacks sloplint names. */
+const OVERUSED = [...OVERUSED_FONTS_DISPLAY, 'system-ui', '-apple-system', 'helvetica neue', 'segoe ui'].map((f) => f.toLowerCase());
+
+/** gstack's catalog of faces banned in any role (Papyrus, Comic Sans, Impact and kin). */
+const BANNED_WORDS = BANNED_FONTS.map((f) => f.toLowerCase());
+
+/** The catalog names a family by its stem ("Comic Sans", "Cormorant", "DM Serif"); a declaration says "Comic Sans MS", "Cormorant Garamond" or "DM Serif Display". A stem matches the whole name or its first words, never a longer word ("Inter" is not "Interstate"). */
+function namesFace(fam: string, stems: readonly string[]): boolean {
+ const k = famKey(fam);
+ const words = fam.toLowerCase().replace(/[\s_-]+/g, ' ').trim();
+ return stems.some((s) => k === famKey(s) || words.startsWith(s + ' '));
+}
+const isBanned = (fam: string): boolean => namesFace(fam, BANNED_WORDS);
+
+// gstack's own: a banned face anywhere, display or body (lib/design-catalog.ts BANNED_FONTS)
+function bannedFont(ctx: LintContext, r: Reporter): void {
+ const seen = new Set<string>();
+ const flag = (fam: string, file: string, line: number, where: string) => {
+ if (!isBanned(fam) || seen.has(fam + where)) return;
+ seen.add(fam + where);
+ r.report('banned-font', file, line, `"${fam}" (${where})`);
+ };
+ for (const [prop, val] of Object.entries(ctx.tokens)) {
+ if (!/^--font-/.test(prop)) continue;
+ const site = tokenSite(ctx, prop);
+ flag(firstFamily(resolveVars(val, ctx.tokens)), site.file, site.line, prop);
+ }
+ for (const rule of ctx.rules) {
+ if (isTokenRule(rule)) continue;
+ for (const d of rule.decls) if (d.prop === 'font-family' && !d.value.includes('var(')) flag(firstFamily(d.value), rule.file, d.line, rule.selector);
+ }
+}
+
+// sloplint check1 (gate 1)
+function check1(ctx: LintContext, r: Reporter): void {
+ const seen = new Set<string>();
+ const flag = (fam: string, file: string, line: number, where: string) => {
+ if (!namesFace(fam, OVERUSED) || seen.has(fam + where)) return;
+ seen.add(fam + where);
+ r.report('overused-font', file, line, `"${fam}" as the display face (${where})`);
+ };
+ for (const [prop, val] of Object.entries(ctx.tokens)) {
+ if (!/^--font-(display|heading|title|hero)/.test(prop)) continue;
+ const site = tokenSite(ctx, prop);
+ flag(firstFamily(resolveVars(val, ctx.tokens)), site.file, site.line, prop);
+ }
+ for (const rule of ctx.rules) {
+ if (isTokenRule(rule) || !HEADING_SEL.test(rule.selector)) continue;
+ for (const d of rule.decls) if (d.prop === 'font-family') flag(firstFamily(resolveVars(d.value, ctx.tokens)), rule.file, d.line, rule.selector);
+ }
+}
+
+// sloplint shortProse (gate 25): every paragraph under the selector is one or two short sentences; answered once per class, since a sheet may name the same class in many rules
+function shortProse(ctx: LintContext, sel: string): boolean {
+ const cls = [...sel.matchAll(/\.([\w-]+)/g)].map((m) => m[1]).pop();
+ if (!cls) return false;
+ const known = memo(ctx, 'shortProse25', () => new Map<string, boolean>());
+ const hit = known.get(cls);
+ if (hit !== undefined) return hit;
+ const short = shortProseOf(ctx, cls);
+ known.set(cls, short);
+ return short;
+}
+
+/** The open tags of a document by class, indexed once. */
+function byClass(doc: Doc): Map<string, number[]> {
+ const cached = doc.cache.byClass as Map<string, number[]> | undefined;
+ if (cached) return cached;
+ const index = new Map<string, number[]>();
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing) continue;
+ for (const c of (getAttr(t.attrs, 'class') || '').split(/\s+/)) if (c) { const list = index.get(c); if (list) list.push(i); else index.set(c, [i]); }
+ }
+ doc.cache.byClass = index;
+ return index;
+}
+
+function shortProseOf(ctx: LintContext, cls: string): boolean {
+ const texts: string[] = [];
+ for (const doc of ctx.docs) {
+ for (const idx of byClass(doc).get(cls) ?? []) {
+ const el = innerOf(doc, idx);
+ if (!el) continue;
+ const paras = doc.tags[idx].name === 'p' ? [el.inner] : openTags(doc, /^p$/, idx + 1, closeIndex(doc, idx)).map((p) => p.inner);
+ for (const p of paras) texts.push(stripTags(p).replace(/\s+/g, ' ').trim());
+ }
+ }
+ return texts.length > 0 && texts.every((t) => t.length <= 200 && (t.match(/[.!?](?:\s|$)/g) || []).length <= 2);
+}
+
+// sloplint check25 (gate 25), the static half: the measure declared in ch
+function check25(ctx: LintContext, r: Reporter): void {
+ const proseish = /(^|[\s,>+~(])p\b|lede|prose|copy|__body|__text|__desc|paragraph/i;
+ for (const rule of ctx.rules) {
+ if (!proseish.test(rule.selector) || HEADING_SEL.test(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'max-width') continue;
+ const m = /^([\d.]+)ch$/.exec(resolveVars(d.value, ctx.tokens).trim());
+ if (!m) continue;
+ const ch = parseFloat(m[1]);
+ if (ch >= 45 && ch <= 75) continue;
+ const floor = /lede|hero|caption|figcaption|__line|__sub|subhead|tagline/i.test(rule.selector) || shortProse(ctx, rule.selector) ? 28 : 45;
+ if (ch < floor || ch > 75) {
+ r.report('line-length', rule.file, d.line, `a measure of ${ch}ch on ${rule.selector} (${floor} to 75ch reads well)`,
+ { fix: `max-width between ${floor === 28 ? '28' : '45'} and 75ch${floor === 28 ? ' for a one-sentence lede or caption' : ''}` });
+ }
+ }
+ }
+}
+
+// sloplint check37 (gate 37)
+function check37(ctx: LintContext, r: Reporter): void {
+ const families = new Map<string, { file: string; line: number }>();
+ const keys = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.selector === '@font-face') continue;
+ for (const d of rule.decls) {
+ if (d.prop !== 'font-family' && !/^--font-/.test(d.prop)) continue;
+ if (/^--font-/.test(d.prop) && !isTokenRule(rule)) continue;
+ const fam = firstFamily(resolveVars(d.value, ctx.tokens));
+ if (!fam || GENERIC_FAMILIES.has(fam) || fam.startsWith('var(')) continue;
+ const key = famKey(fam);
+ if (!keys.has(key)) { keys.add(key); families.set(fam, { file: rule.file, line: d.line }); }
+ }
+ }
+ if (families.size <= 3) return;
+ const fourth = [...families.values()][3];
+ r.report('font-family-count', fourth.file, fourth.line, `${families.size} font families: ${trunc([...families.keys()].join(', '), 56)}`);
+}
+
+// sloplint check38a (gates 38i, 38ii)
+function check38a(ctx: LintContext, r: Reporter): void {
+ const inlineLast = (sel: string) => sel.split(',').every((p) => /^(?:em|i|b|strong|span|mark)(?![\w-])/.test(baseSelector(p).split(/[\s>+~]+/).pop() || ''));
+ for (const rule of ctx.rules) {
+ if (!HEADING_SEL.test(rule.selector) || inlineLast(rule.selector)) continue;
+ for (const d of rule.decls) {
+ if (d.prop === 'font-style' && /italic|oblique/.test(d.value)) r.report('italic-serif-display', rule.file, d.line, `italic display type on ${rule.selector}`);
+ }
+ }
+ const normSel = ctx.rules.filter((rule) => /(^|[\s,>+~])(em|i)\b/.test(rule.selector)
+ && rule.decls.some((d) => d.prop === 'font-style' && /normal/.test(d.value))).flatMap((rule) => rule.selector.split(',').map((x) => x.trim()));
+ const norm = selectorNames(normSel), bareNorm = normSel.some((sel) => /^(em|i)$/.test(sel));
+ const normalised = (level: string, classes: string[]) => bareNorm || norm.tags.has('h' + level) || classes.some((c) => norm.classes.has(c));
+ for (const doc of ctx.docs) {
+ for (const head of openTags(doc, /^h[1-6]$/)) {
+ const level = head.tag.name.slice(1);
+ const classes = (getAttr(head.tag.attrs, 'class') || '').split(/\s+/).filter(Boolean);
+ if (normalised(level, classes)) continue;
+ const headLen = textOf(doc, head.idx).length;
+ const tag = openTags(doc, /^(em|i)$/, head.idx + 1, closeIndex(doc, head.idx)).find((t) => {
+ const italic = textOf(doc, t.idx);
+ return /[A-Za-z0-9]/.test(italic) && !/aria-hidden/i.test(t.tag.attrs) && italic.length < 0.8 * headLen;
+ });
+ if (!tag) continue;
+ r.report('italic-word-in-heading', doc.file, head.tag.line, `an <${tag.tag.name}> inside an otherwise roman <h${level}>`);
+ }
+ }
+}
+
+const ACCENT38 = /(?:^|[\s,])((?:h[1-3]|\.display|\.headline|\.title|[.\w-]*__(?:title|display|headline))[^\s,>+~]*)\s*(?:>|\s)\s*(em|i|b|strong|span|mark|\.[\w-]+)(?::nth-child\([^)]*\))?(?:::?[\w-]+)?\s*$/i;
+const INHERITED38 = /^(inherit|currentcolor|unset|initial|normal)$/i;
+const MARK38 = /^(color|background|background-color|-webkit-text-stroke|font-weight|text-decoration|text-decoration-color|border-bottom|box-shadow|font-style)$/;
+const marks38 = (rule: CssRule): CssDecl[] => rule.decls.filter((d) => MARK38.test(d.prop) && !INHERITED38.test(d.value.trim()));
+
+/** The rules that mark one word of a heading apart from the rest: by selector shape, or by a classed span inside an h1 to h3 that covers under 80% of the head. */
+// sloplint accentedHeads (gate 38iii)
+function accentedHeads(ctx: LintContext): CssRule[] {
+ const out: CssRule[] = [];
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule) || !ACCENT38.test(rule.selector)) continue;
+ if (!marks38(rule).length || seen.has(rule.selector)) continue;
+ seen.add(rule.selector);
+ out.push(rule);
+ }
+ const norm = (v: string | null) => String(v || '').replace(/\s+/g, ' ').trim().toLowerCase();
+ const byClass = memo(ctx, 'rulesByClass38', () => {
+ const index = new Map<string, CssRule[]>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || isTokenRule(rule)) continue;
+ for (const part of rule.selector.split(',')) {
+ if (/::?(before|after)\b/.test(part)) continue;
+ const base = baseSelector(part);
+ if (!/^\.[\w-]+$/.test(base)) continue;
+ const list = index.get(base.slice(1)) ?? [];
+ list.push(rule);
+ index.set(base.slice(1), list);
+ }
+ }
+ return index;
+ });
+ for (const doc of ctx.docs) {
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || !/^h[1-3]$/.test(t.name)) continue;
+ const inner = innerOf(doc, i);
+ if (!inner) continue;
+ const headLen = textOf(doc, i).replace(/\s+/g, '').length || 1;
+ const spans = openTags(doc, /^(span|em|strong|b|i|mark)$/, i + 1, closeIndex(doc, i), (s) => !!(getAttr(s.attrs, 'class') || '').trim())
+ .map((el) => ({ classes: (getAttr(el.tag.attrs, 'class') || '').split(/\s+/).filter(Boolean), text: plainText(el.inner) }));
+ const covered = new Map<string, number>();
+ for (const x of spans) for (const cls of x.classes) covered.set(cls, (covered.get(cls) ?? 0) + x.text.replace(/\s+/g, '').length);
+ const cover = (cls: string) => (covered.get(cls) ?? 0) / headLen;
+ const headDecls = styleFor(ctx, getAttr(t.attrs, 'class'), t.name, true);
+ const own = (prop: string) => valueOf(ctx, headDecls, prop) ?? (prop === 'color' ? resolveVars('var(--color-ink)', ctx.tokens) : null);
+ for (const m of spans) {
+ if (!/[A-Za-z0-9]/.test(m.text)) continue;
+ for (const cls of m.classes) {
+ if (cover(cls) >= 0.8) continue;
+ for (const rule of byClass.get(cls) ?? []) {
+ if (seen.has(rule.selector)) continue;
+ if (rule.decls.some((d) => (d.prop === 'display' && /^(block|flex|grid|table)/.test(d.value.trim())) || (d.prop === 'position' && /absolute|fixed/.test(d.value)))) continue;
+ const marking = marks38(rule);
+ if (!marking.length) continue;
+ if (marking.every((d) => /^(color|font-weight)$/.test(d.prop) && own(d.prop) != null && norm(resolveVars(d.value, ctx.tokens)) === norm(own(d.prop)))) continue;
+ seen.add(rule.selector);
+ out.push(rule);
+ }
+ }
+ }
+ }
+ }
+ return out;
+}
+
+// sloplint check38c (gate 38iii); hallmark's hero-signature exemption read the stamp, so every accented word reports here
+function check38c(ctx: LintContext, r: Reporter): void {
+ for (const rule of accentedHeads(ctx)) r.report('accented-word', rule.file, rule.line, `one word of a heading set apart (${rule.selector})`);
+}
+
+// sloplint check55 (gates 55a, 55b)
+function check55(ctx: LintContext, r: Reporter): void {
+ for (const rule of mergedRules(ctx)) {
+ if (!rule.decls.some((d) => d.prop === 'text-transform' && /uppercase/.test(d.value))) continue;
+ const lhD = rule.decls.find((d) => d.prop === 'line-height');
+ if (!lhD) continue;
+ const lhV = resolveVars(lhD.value, ctx.tokens).trim();
+ const lh = /%$/.test(lhV) ? parseFloat(lhV) / 100 : /(?:px|r?em)$/i.test(lhV) ? NaN : parseFloat(lhV);
+ if (Number.isNaN(lh) || lh >= 1.02) continue;
+ const bigType = rule.decls.some((d) => d.prop === 'font-size' && (pxOf(resolveVars(d.value, ctx.tokens)) ?? 0) >= 28);
+ if (!HEADING_SEL.test(rule.selector) && !bigType) continue;
+ const nowrap = rule.decls.some((d) => d.prop === 'white-space' && /nowrap/.test(d.value));
+ if (!nowrap && lh >= 1.0) continue;
+ r.report(nowrap ? 'caps-lockup-leading' : 'caps-leading', rule.file, lhD.line, `uppercase at line-height ${lh} on ${rule.selector}: the caps collide`);
+ }
+}
+
+
+// sloplint check64 (gate 64); twMonoIsMaterial is sloplint's monoIsMaterial: a mono face declared as the display, body or outlier is the page's material, not a costume
+function check64(ctx: LintContext, r: Reporter): void {
+ if (twMonoIsMaterial(ctx.tokens)) return;
+ const monoFam = (v: string) => MONO_FACE.test(firstFamily(resolveVars(v, ctx.tokens)));
+ const LABELISH = /label|caption|meta|eyebrow|kicker|tag\b|badge|chip|small|folio|footnote|legend|\bth\b|thead|figcaption|overline|dateline|byline|credit|note\b/i;
+ const DATAISH = /code|pre\b|kbd|samp|num|figure|stat|price|value|data|tabular|counter|timer|clock|coord|amount|total|score|version|hash|\bid\b|sku|time|date|hour|utc|\beta\b|\blot\b|edition|ref\b|dimension|measure|reading|plate-?no|tag-?no|url|uri\b|path|endpoint|command|cmd|snippet|install/i;
+ const seen = new Set<string>();
+ for (const rule of ctx.rules) {
+ if (rule.keyframes || rule.selector === '@font-face' || isTokenRule(rule)) continue;
+ if (!LABELISH.test(rule.selector) || DATAISH.test(rule.selector)) continue;
+ const fam = rule.decls.find((d) => d.prop === 'font-family' || (d.prop === 'font' && /var\(--font|mono/i.test(d.value)));
+ if (!fam) continue;
+ const raw = fam.prop === 'font' ? (/var\(--font-[\w-]+\)/.exec(fam.value) || [fam.value])[0] : fam.value;
+ if (!monoFam(raw)) continue;
+ const key = baseSelector(rule.selector);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ r.report('monospace-costume', rule.file, fam.line, `monospace as the label voice on ${rule.selector}`);
+ }
+}
+
+// sloplint fontSizePxOf (gate 67)
+function fontSizePxOf(rule: MergedRule, ctx: LintContext): number | null {
+ const fs = rule.decls.find((d) => d.prop === 'font-size');
+ if (fs) return pxOf(resolveVars(fs.value, ctx.tokens));
+ const f = rule.decls.find((d) => d.prop === 'font');
+ if (!f) return null;
+ const m = /(?:^|\s)(\d+(?:\.\d+)?(?:px|rem|em))(?:\/[\d.]+(?:px|rem|em)?)?\s/.exec(resolveVars(f.value, ctx.tokens) + ' ');
+ return m ? pxOf(m[1]) : null;
+}
+
+const LABEL67 = /label|caption|meta|eyebrow|kicker|tag\b|badge|chip|small|folio|footnote|legend|\bth\b|thead|figcaption|overline|dateline|byline|credit|note\b|\bnav\b|menu|link|pill|status|unit|smallcaps|count|placard/i;
+const CONTROL67 = /btn|button|cta|\.sign\b|plate|control/i;
+const EXEMPT67_NAME = /^(wordmark|marquee|ticker|logo|brand|abbr|logo-?(mark|type|text)|brand-?(mark|name|type))$/i;
+const EXEMPT67_PART = /(^|[-_])(wordmark|marquee|ticker|logotype|logo|brand)([-_]|$)|(^|[-_])(slab|nav|site|head|header|masthead|bar)[-_]+mark([-_]|$)/i;
+const exemptName67 = (n: string): boolean => !!n && (EXEMPT67_NAME.test(n.split('--')[0].split('__').pop() || '') || EXEMPT67_PART.test(n));
+const SCROLLER67 = /(^|[-_])(marquee|ticker)([-_]|$)/i;
+
+// sloplint exempt67 (gate 67): wordmarks, logos, marquees and tickers may be set in capitals
+function exempt67(sel: string): boolean {
+ return sel.split(',').some((part) => {
+ const comps = baseSelector(part).split(/[\s>+~]+/).filter(Boolean);
+ const comp = comps[comps.length - 1] || '';
+ const names = (comp.match(/\.[a-zA-Z_][\w-]*/g) || []).map((c) => c.slice(1));
+ names.push((/^[a-zA-Z][\w-]*/.exec(comp) || [''])[0]);
+ if (names.some(exemptName67)) return true;
+ return comps.slice(0, -1).some((c) => (c.match(/\.[a-zA-Z_][\w-]*/g) || []).some((x) => SCROLLER67.test(x.slice(1))));
+ });
+}
+
+/** The merged rules that can pass a value down, indexed by each selector part's base, so a lookup probes the subject's own prefixes instead of walking every rule of the sheet. */
+type Ancestors67 = Map<string, MergedRule[]>;
+
+function ancestors67(bySel: MergedRule[]): Ancestors67 {
+ const byBase: Ancestors67 = new Map();
+ for (const o of bySel) {
+ if (/:hover|:focus|:active/.test(o.selector) || (o.media && /max-width/i.test(o.media))) continue;
+ for (const ob of o.selector.split(',').map(baseSelector)) {
+ if (!ob) continue;
+ const list = byBase.get(ob);
+ if (list) list.push(o); else byBase.set(ob, [o]);
+ }
+ }
+ return byBase;
+}
+
+// sloplint inherited67 (gate 67): the nearest ancestor selector's value for a property; the longest prefix of the subject that ends before a combinator and declares it
+function inherited67(up: Ancestors67, sel: string, prop: string): string | null {
+ const base = baseSelector(sel);
+ for (let k = base.length - 1; k > 0; k--) {
+ if (!/[\s>+~]/.test(base[k])) continue;
+ const rules = up.get(base.slice(0, k));
+ if (!rules) continue;
+ for (const o of rules) {
+ const d = o.decls.filter((x) => x.prop === prop).pop();
+ if (d) return d.value;
+ }
+ }
+ return null;
+}
+
+const isSmallCaps67 = (prop: string, v: string): boolean => (/^font-variant(-caps)?$/.test(prop) && /\b(all-)?(small|petite)-caps\b/.test(v))
+ || (prop === 'font-feature-settings' && /\b(smcp|c2sc)\b/.test(v));
+
+interface Caps67 { upper: boolean; smallCaps: boolean; em: number | null; px: number | null }
+
+/** What a rule says about case and tracking, its own declarations first and the nearest ancestor's where it is silent. */
+function caps67(ctx: LintContext, bySel: Ancestors67, rule: MergedRule): Caps67 | null {
+ const isUpper = (v: string | null) => v != null && /uppercase/.test(resolveVars(v, ctx.tokens));
+ const ownTT = rule.decls.filter((d) => d.prop === 'text-transform').pop();
+ const ownUpper = ownTT ? isUpper(ownTT.value) : null;
+ const ownSmallCaps = rule.decls.some((d) => isSmallCaps67(d.prop, resolveVars(d.value, ctx.tokens)));
+ const px = fontSizePxOf(rule, ctx);
+ const ownEm = trackingEm(ctx, rule.decls, px || 16);
+ if (!(ownUpper === true || ownSmallCaps || (ownEm != null && ownEm > TRACKED_EM))) return null;
+ const upper = ownUpper != null ? ownUpper : isUpper(inherited67(bySel, rule.selector, 'text-transform'));
+ const smallCaps = ownSmallCaps || ['font-variant', 'font-variant-caps', 'font-feature-settings'].some((prop) => {
+ const v = inherited67(bySel, rule.selector, prop);
+ return v != null && isSmallCaps67(prop, resolveVars(v, ctx.tokens));
+ });
+ let em = ownEm;
+ if (em == null) {
+ const v = inherited67(bySel, rule.selector, 'letter-spacing');
+ if (v != null) em = trackingEm(ctx, [{ prop: 'letter-spacing', value: v, line: 0 }], px || 16);
+ }
+ return { upper, smallCaps, em, px };
+}
+
+// sloplint check67 (gate 67), the CSS half
+function check67(ctx: LintContext, r: Reporter): void {
+ const bySel = mergedRules(ctx);
+ const displayish = (rule: MergedRule) => HEADING_SEL.test(rule.selector) || /display|title|headline|bill|poster|banner/i.test(rule.selector)
+ || rule.decls.some((d) => (d.prop === 'font-family' || d.prop === 'font') && /--font-display/.test(d.value)) || (fontSizePxOf(rule, ctx) || 0) >= 28;
+ const upperDisplay = bySel.some((rule) => displayish(rule) && !LABEL67.test(rule.selector) && rule.decls.some((d) => d.prop === 'text-transform' && /uppercase/.test(d.value)));
+ const seen = new Set<string>();
+ const up = ancestors67(bySel);
+ for (const rule of bySel) {
+ if (isTokenRule(rule) || exempt67(rule.selector) || /::first-letter\s*(,|$)/.test(rule.selector)) continue;
+ const caps = caps67(ctx, up, rule);
+ if (!caps) continue;
+ const { upper, smallCaps, em, px } = caps;
+ const tracked = em != null && em > TRACKED_EM;
+ const subject = rule.selector.split(',').map((p) => baseSelector(p).split(/[\s>+~]+/).filter(Boolean).pop() || '');
+ const bigToken = rule.decls.some((d) => d.prop === 'font-size' && /--text-(display|section|title)|clamp\(\s*(?:[2-9]|\d{2,})(?:\.\d+)?rem/.test(d.value));
+ const labelish = subject.some((s) => LABEL67.test(s)) ? !((px != null && px >= 28) || bigToken)
+ : LABEL67.test(rule.selector) && !subject.every((s) => /^h[1-6]\b/i.test(s)) && (px == null || px < 20);
+ const control = CONTROL67.test(rule.selector);
+ if (HEADING_SEL.test(rule.selector) && !labelish && !control) continue;
+ const key = baseSelector(rule.selector);
+ if (seen.has(key)) continue;
+ const small = px != null && px <= LABEL_PX;
+ const at = px != null ? ` at ${Math.round(px)}px` : '';
+ const tracking = tracked ? ` tracked ${em3(em)}em` : '';
+ if (control && !labelish) {
+ if (!upper && !smallCaps) { if (!(tracked && small)) continue; }
+ else if (upperDisplay && (em == null || em <= CONTROL_TRACK_MAX_EM)) continue;
+ seen.add(key);
+ r.report('wide-tracking', rule.file, rule.line, !upper && !smallCaps ? `${rule.selector}: a control tracked ${em3(em!)}em${at}` : upperDisplay ? `${rule.selector}: an uppercase control tracked ${em3(em!)}em` : `${rule.selector}: an uppercase control on a page whose display is not uppercase`,
+ { fix: 'controls follow the display voice: sentence case here, or tracking 0.04em at most where the display itself is uppercase' });
+ continue;
+ }
+ const isCaps = upper || smallCaps;
+ if ((isCaps && (labelish || smallCaps || tracked || small)) || (tracked && (labelish || small))) {
+ seen.add(key);
+ const what = smallCaps ? 'small caps' : upper ? 'uppercase' : 'letter-spaced';
+ r.report('wide-tracking', rule.file, rule.line, `${rule.selector}: ${what}${tracking}${at} in a label role`);
+ }
+ }
+}
+
+const CAPS_TAGS = /^(p|span|small|a|li|div|figcaption|td|th|dt|dd|label|time|cite|strong|b|em|button|summary)$/;
+
+// sloplint check67Html (gate 67), the markup half: text typed in capitals at label size or tracked
+function check67Html(ctx: LintContext, r: Reporter): void {
+ for (const doc of ctx.docs) {
+ const seen = new Set<string>();
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close || t.selfClosing || !CAPS_TAGS.test(t.name)) continue;
+ const cls = getAttr(t.attrs, 'class') || '';
+ if (cls.split(/\s+/).some(exemptName67)) continue;
+ if (ancestorsOf(doc, i).some((n) => /^(svg|pre|code|abbr|kbd|samp)$/.test(n))) continue;
+ const inner = innerOf(doc, i);
+ if (!inner || /<(p|div|ul|ol|h[1-6]|table|section|article|svg|img|abbr|code|kbd)\b/i.test(inner.inner)) continue;
+ const text = textOf(doc, i);
+ const letters = text.replace(/[^A-Za-z]/g, '');
+ if (letters.length < 5 || capsRatio(text) < 0.95 || /^[A-Z]{2,5}$/.test(text) || /^\(?\s*(CC0|CC BY(-SA|-NC|-ND)*( [0-9.]+)?|PD|GFDL)\b/.test(text)) continue;
+ const decls = styleFor(ctx, cls, t.name);
+ const px = fontPx(ctx, decls);
+ const em = trackingEm(ctx, decls, px || 16);
+ const tracked = em != null && em > TRACKED_EM;
+ if (!((px != null && px <= LABEL_PX) || tracked)) continue;
+ const key = cls || t.name;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ r.report('wide-tracking', doc.file, t.line, `"${trunc(text, 32)}" typed in capitals${px != null ? ` at ${Math.round(px)}px` : ''}${tracked ? ` tracked ${em3(em)}em` : ''} (<${t.name}${cls ? ` class="${trunc(cls, 24)}"` : ''}>)`,
+ { fix: 'sentence case in the body face; capitals survive only as a wordmark or as the display voice' });
+ }
+ }
+}
+
+export function run(ctx: LintContext, r: Reporter): void {
+ check1(ctx, r);
+ bannedFont(ctx, r);
+ check25(ctx, r);
+ check37(ctx, r);
+ check38a(ctx, r);
+ check38c(ctx, r);
+ check55(ctx, r);
+ check64(ctx, r);
+ check67(ctx, r);
+ check67Html(ctx, r);
+}
diff --git a/lib/design-lint/static.ts b/lib/design-lint/static.ts
new file mode 100644
index 000000000..7824ee2c0
--- /dev/null
+++ b/lib/design-lint/static.ts
@@ -0,0 +1,353 @@
+/**
+ * The static tier: collect files, group them into contexts (a page with the
+ * stylesheets it links, or a directory of components), build the token table,
+ * run every rule family, then apply the page's waivers.
+ *
+ * Ported from Nutlope/hallmark's sloplint.mjs (collectFiles, buildContext,
+ * shareProjects; MIT, see NOTICE.md).
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import type { LintContext, SharedStyles, CssFile } from './context';
+import { buildTokens, isTokenRule, parseCss, stripComments, type CssRule, type Tokens } from './css';
+import { docKindOf, getAttr, parseDoc, type Doc } from './html';
+import { oneLine, relPath, Reporter, type Finding } from './report';
+import { FAMILIES } from './rules';
+import { setTwTokens, twVariants } from './tailwind';
+import { applyWaivers, findWaivers, resolveWaivers, suspectedRules, type WaiverSet } from './waivers';
+
+export interface StaticOptions {
+ scope?: 'page' | 'component';
+ job?: string | null;
+ cwd?: string;
+ /** Receives a line for every file skipped or rule that threw; defaults to stderr. */
+ warn?: (line: string) => void;
+}
+
+export interface StaticResult {
+ files: string[];
+ contexts: LintContext[];
+ findings: Finding[];
+}
+
+/** A source file the lint did not read, and why; it is reported, because a page the lint could not read is not a pass. */
+export interface Skipped { file: string; kind: 'unreadable' | 'unparseable' | 'oversize'; why: string }
+
+/** The static tier before waivers: every context with the findings its rule families reported, so a caller can add the render tier's findings and settle the page's waivers once over both. */
+export interface RawStaticResult {
+ files: string[];
+ contexts: LintContext[];
+ raw: Finding[][];
+ /** One internal-error finding per skipped source file. */
+ skipped: Finding[];
+}
+
+const BUILD_DIRS = new Set(['dist', 'build', 'coverage']);
+
+/** A source file past this size is a bundle or a generated artefact, not a page to read; it is skipped with a warning so the lint answers in bounded time. */
+export const MAX_FILE_BYTES = 2 * 1024 * 1024;
+
+/** Every .css page and component file under the paths; node_modules, dot folders and (below the top) build output are skipped, a link cycle is walked once, and a file over MAX_FILE_BYTES is skipped with a warning. */
+export function collectFiles(paths: string[], warn: (l: string) => void = () => {}, skipped: Skipped[] = []): string[] {
+ const files: string[] = [];
+ const seen = new Set<string>();
+ const visit = (p: string, top: boolean) => {
+ let abs = path.resolve(p);
+ let st: fs.Stats;
+ try { abs = fs.realpathSync(abs); st = fs.statSync(abs); } catch { warn(`design-lint: cannot read ${p}`); if (top) skipped.push({ file: abs, kind: 'unreadable', why: 'it cannot be read' }); return; }
+ if (seen.has(abs)) return;
+ if (st.isDirectory()) {
+ seen.add(abs);
+ const base = path.basename(abs);
+ if (base === 'node_modules' || base.startsWith('.') || (!top && BUILD_DIRS.has(base))) return;
+ for (const e of fs.readdirSync(abs).sort()) visit(path.join(abs, e), false);
+ return;
+ }
+ if (path.extname(abs).toLowerCase() !== '.css' && !docKindOf(abs)) return;
+ seen.add(abs);
+ if (st.size > MAX_FILE_BYTES) {
+ const why = `${Math.round(st.size / 1024 / 1024)} MB, over the ${MAX_FILE_BYTES / 1024 / 1024} MB limit`;
+ warn(`design-lint: skipped ${p} (${why})`);
+ skipped.push({ file: abs, kind: 'oversize', why });
+ return;
+ }
+ files.push(abs);
+ };
+ for (const p of paths) visit(p, true);
+ return files;
+}
+
+/**
+ * A local stylesheet reference as a path: relative to the referring file, or
+ * for a root-relative href (`/css/site.css`, the common form on a real site)
+ * relative to the lint root the page was found under. Schemes and
+ * protocol-relative URLs are not local.
+ */
+export function resolveRef(href: string | null, from: string, root: string | null, bound: string | null = null): string | null {
+ if (!href || /^(?:[a-z]+:|\/\/)/i.test(href)) return null;
+ const ref = href.split(/[?#]/)[0];
+ if (!ref) return null;
+ const within = (abs: string, top: string) => abs === top || abs.startsWith(top + path.sep);
+ const inside = (abs: string, top: string) => {
+ if (!within(abs, top)) return false;
+ try { return within(fs.realpathSync(abs), realDir(top)); } catch { return true; }
+ };
+ if (ref.startsWith('/')) {
+ if (!root) return null;
+ const abs = path.join(root, ref);
+ return inside(abs, root) ? abs : null;
+ }
+ const abs = path.resolve(from, ref);
+ const top = projectRoot(from) ?? bound;
+ return top && !inside(abs, top) ? null : abs;
+}
+
+export function importsOf(css: string, from: string, root: string | null = null, bound: string | null = null): string[] {
+ const out: string[] = [];
+ for (const m of stripComments(css).matchAll(/@import\s+(?:url\(\s*)?["']?([^"')\s;]+)["']?\s*\)?/gi)) {
+ const ref = resolveRef(m[1], from, root, bound);
+ if (ref) out.push(ref);
+ }
+ return out;
+}
+
+export function linksOf(doc: Doc, from: string, root: string | null = null, bound: string | null = null): string[] {
+ const out: string[] = [];
+ for (const t of doc.tags) {
+ if (t.close || t.name !== 'link' || !/stylesheet/i.test(getAttr(t.attrs, 'rel') || '')) continue;
+ const ref = resolveRef(getAttr(t.attrs, 'href'), from, root, bound);
+ if (ref) out.push(ref);
+ }
+ return out;
+}
+
+/** The lint root a file was collected under: the longest top-level directory that contains it, else its own directory. */
+const rootOf = (file: string, roots: string[]): string =>
+ roots.filter((r) => file.startsWith(r + path.sep)).sort((a, b) => b.length - a.length)[0] ?? path.dirname(file);
+
+interface CssRead { raw: string; rules: CssRule[]; imports: string[] }
+
+/** Stylesheets read once per run: a bundle shared by forty pages is parsed once, not forty times. */
+class CssCache {
+ private readonly files = new Map<string, CssRead | null>();
+ constructor(readonly roots: string[], readonly warn: (l: string) => void, readonly skipped: Skipped[] = [], readonly bound: string | null = null) {}
+ read(f: string): CssRead | null {
+ if (this.files.has(f)) return this.files.get(f)!;
+ let out: CssRead | null = null;
+ try {
+ const size = fs.statSync(f).size;
+ if (size > MAX_FILE_BYTES) { const why = `${Math.round(size / 1024 / 1024)} MB, over the ${MAX_FILE_BYTES / 1024 / 1024} MB limit`; this.warn(`design-lint: skipped ${f} (${why})`); this.skipped.push({ file: f, kind: 'oversize', why }); this.files.set(f, null); return null; }
+ const raw = fs.readFileSync(f, 'utf8');
+ out = { raw, rules: parseCss(raw, f), imports: importsOf(raw, path.dirname(f), rootOf(f, this.roots), this.bound) };
+ } catch (e) {
+ const code = (e as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT') this.warn(`design-lint: skipped ${f}, not found`);
+ else { const why = code ? `it cannot be read (${code})` : `it could not be parsed (${(e as Error).message})`; this.warn(`design-lint: skipped ${f}, ${why}`); this.skipped.push({ file: f, kind: code ? 'unreadable' : 'unparseable', why }); }
+ }
+ this.files.set(f, out);
+ return out;
+ }
+}
+
+/** Follow @import and <link rel=stylesheet> from the group's files to every local .css they reach. */
+function attachStylesheets(cssFiles: CssFile[], rules: CssRule[], pending: string[], inGroup: Set<string>, cache: CssCache): void {
+ while (pending.length) {
+ const p = pending.shift()!;
+ if (inGroup.has(p) || path.extname(p).toLowerCase() !== '.css') continue;
+ inGroup.add(p);
+ const got = cache.read(p);
+ if (!got) continue;
+ cssFiles.push({ file: p, raw: got.raw });
+ for (const rule of got.rules) rules.push(rule);
+ pending.push(...got.imports);
+ }
+}
+
+export function buildContext(key: string, cssList: string[], docList: Doc[], opts: StaticOptions, cache: CssCache): LintContext {
+ const cssFiles: CssFile[] = [];
+ const rules: CssRule[] = [];
+ const inGroup = new Set<string>([...cssList, ...docList.map((d) => d.file)]);
+ const pending: string[] = [];
+ for (const f of cssList) {
+ const got = cache.read(f);
+ cssFiles.push({ file: f, raw: got?.raw ?? '' });
+ if (got) { for (const rule of got.rules) rules.push(rule); pending.push(...got.imports); }
+ }
+ for (const doc of docList) {
+ const root = rootOf(doc.file, cache.roots);
+ for (const st of doc.styles) {
+ try { for (const rule of parseCss(st.css, doc.file, st.lineOffset)) rules.push(rule); } catch (e) { cache.warn(`design-lint: skipped a <style> block in ${doc.file}, it could not be parsed (${(e as Error).message})`); cache.skipped.push({ file: doc.file, kind: 'unparseable', why: `a <style> block could not be parsed (${(e as Error).message})` }); continue; }
+ pending.push(...importsOf(st.css, path.dirname(doc.file), root, cache.bound));
+ }
+ pending.push(...linksOf(doc, path.dirname(doc.file), root, cache.bound));
+ }
+ attachStylesheets(cssFiles, rules, pending, inGroup, cache);
+ const allCss = cssFiles.map((c) => c.raw).join('\n') + '\n' + docList.map((d) => d.styles.map((st) => st.css).join('\n')).join('\n');
+ return {
+ key, rules, tokens: buildTokens(rules), docs: docList, cssFiles, allCss,
+ scope: opts.scope ?? 'page', job: opts.job ?? null,
+ tokensOnly: !docList.length && rules.length > 0 && rules.every(isTokenRule),
+ shared: null, twTokens: null, cache: {},
+ };
+}
+
+/** The .css files a page reaches through <link> and @import, transitively. */
+function linkedCss(page: Doc, cache: CssCache): Set<string> {
+ const linked = new Set<string>();
+ const root = rootOf(page.file, cache.roots);
+ const queue = [...linksOf(page, path.dirname(page.file), root, cache.bound), ...page.styles.flatMap((st) => importsOf(st.css, path.dirname(page.file), root, cache.bound))];
+ while (queue.length) {
+ const q = queue.shift()!;
+ if (linked.has(q) || path.extname(q).toLowerCase() !== '.css') continue;
+ const got = cache.read(q);
+ if (!got) continue;
+ linked.add(q);
+ queue.push(...got.imports);
+ }
+ return linked;
+}
+
+/**
+ * One context per page (with its own stylesheets), plus one per directory for
+ * components and unlinked CSS. A stylesheet some page links, from any
+ * directory, belongs to that page and is not linted again on its own.
+ */
+export function groupContexts(files: string[], opts: StaticOptions, warn: (l: string) => void, roots: string[] = [], skipped: Skipped[] = []): LintContext[] {
+ const cache = new CssCache(roots, warn, skipped, realDir(opts.cwd ?? process.cwd()));
+ const groups = new Map<string, { css: string[]; pages: Doc[]; parts: Doc[] }>();
+ for (const f of files) {
+ const dir = path.dirname(f);
+ if (!groups.has(dir)) groups.set(dir, { css: [], pages: [], parts: [] });
+ const g = groups.get(dir)!;
+ if (path.extname(f).toLowerCase() === '.css') { g.css.push(f); continue; }
+ try {
+ const doc = parseDoc(f, fs.readFileSync(f, 'utf8'));
+ (doc.kind === 'html' ? g.pages : g.parts).push(doc);
+ } catch (e) {
+ const kind = (e as NodeJS.ErrnoException).code ? 'unreadable' : 'unparseable';
+ const why = kind === 'unreadable' ? `it cannot be read (${(e as NodeJS.ErrnoException).code})` : `it could not be parsed (${(e as Error).message})`;
+ warn(`design-lint: skipped ${f}, ${why}`);
+ skipped.push({ file: f, kind, why });
+ }
+ }
+ const linkedBy = new Map<Doc, Set<string>>();
+ const owned = new Set<string>();
+ for (const g of groups.values()) for (const page of g.pages) {
+ const linked = linkedCss(page, cache);
+ linkedBy.set(page, linked);
+ for (const c of linked) owned.add(c);
+ }
+ const contexts: LintContext[] = [];
+ for (const [dir, g] of groups) {
+ const free = g.css.filter((c) => !owned.has(c));
+ if (!g.pages.length) { if (free.length || g.parts.length) contexts.push(buildContext(dir, free, g.parts, opts, cache)); continue; }
+ const used = new Set<string>();
+ for (const page of g.pages) {
+ const linked = linkedBy.get(page)!;
+ const own = g.pages.length === 1 ? g.css.filter((c) => !owned.has(c) || linked.has(c)) : g.css.filter((c) => linked.has(c));
+ own.forEach((c) => used.add(c));
+ contexts.push(buildContext(page.file, own, [page], opts, cache));
+ }
+ const rest = free.filter((c) => !used.has(c));
+ if (rest.length || g.parts.length) contexts.push(buildContext(dir, rest, g.parts, opts, cache));
+ }
+ return contexts;
+}
+
+/** The nearest directory above dir holding a package.json or a .git entry: the project a relative stylesheet href may not climb out of. Null outside any project, where a relative href is bounded by the working directory the lint runs in instead (only .css files are read, and only their declarations are printed). */
+function projectRoot(dir: string): string | null {
+ for (let d = dir; ; d = path.dirname(d)) {
+ if (fs.existsSync(path.join(d, 'package.json')) || fs.existsSync(path.join(d, '.git'))) return d;
+ if (path.dirname(d) === d) return null;
+ }
+}
+
+/**
+ * Within one package, a directory of components without its own stylesheet
+ * borrows the project's tokens and its global state styles, so a focus ring
+ * declared once in globals.css is not reported missing on every component.
+ */
+export function shareProjects(contexts: LintContext[]): void {
+ const byRoot = new Map<string, LintContext[]>();
+ for (const ctx of contexts) {
+ const root = projectRoot(fs.existsSync(ctx.key) && fs.statSync(ctx.key).isDirectory() ? ctx.key : path.dirname(ctx.key));
+ if (!root) continue;
+ if (!byRoot.has(root)) byRoot.set(root, []);
+ byRoot.get(root)!.push(ctx);
+ }
+ for (const list of byRoot.values()) {
+ const parts = list.filter((c) => !c.cssFiles.length && c.docs.length && c.docs.every((d) => d.kind !== 'html'));
+ if (!parts.length || parts.length === list.length) continue;
+ const tokens: Tokens = {};
+ const shared: SharedStyles = { focus: false, active: false, disabled: false, reducedMotion: false };
+ for (const c of list) {
+ Object.assign(tokens, c.tokens);
+ const tv = twVariants(c);
+ const sel = (re: RegExp) => c.rules.some((r) => re.test(r.selector));
+ shared.focus = shared.focus || sel(/:focus/) || [...tv].some((v) => /^focus/.test(v));
+ shared.active = shared.active || sel(/:active/) || tv.has('active');
+ shared.disabled = shared.disabled || sel(/:disabled|\[disabled\]|aria-disabled/) || tv.has('disabled') || tv.has('aria-disabled');
+ shared.reducedMotion = shared.reducedMotion || /prefers-reduced-motion/i.test(stripComments(c.allCss)) || tv.has('motion-reduce') || tv.has('motion-safe');
+ }
+ for (const c of list) c.shared = shared;
+ for (const c of parts) setTwTokens(c, { ...tokens, ...c.tokens });
+ }
+}
+
+/**
+ * The waiver comments of a context, in its documents and every stylesheet it reads, weighed against what its rules found.
+ * A stylesheet's claims answer for that stylesheet on every page that links it. A context that is one html page keeps
+ * page semantics under either scope: its claims answer for the page and the stylesheets it links. In a directory of
+ * components (under either scope) each file's claims answer for that file alone, weighed against its own text and its
+ * own suspected rules, with the house-style count per file.
+ */
+export function contextWaivers(ctx: LintContext, cwd: string, findings: Finding[] = []): WaiverSet {
+ const sheets = ctx.cssFiles.flatMap((c) => findWaivers(c.file, c.raw));
+ if (ctx.docs.length <= 1 && ctx.docs.every((d) => d.kind === 'html')) return resolveWaivers([...ctx.docs.flatMap((d) => findWaivers(d.file, d.raw)), ...sheets], ctx.docs.map((d) => d.text).join(' '), cwd, suspectedRules(findings));
+ const sets = [
+ ...ctx.docs.map((d) => { const file = oneLine(relPath(d.file, cwd)); return resolveWaivers(findWaivers(d.file, d.raw), d.text, cwd, suspectedRules(findings.filter((f) => f.file === file)), true); }),
+ resolveWaivers(sheets, '', cwd, suspectedRules(findings)),
+ ];
+ return { accepted: new Map(sets.flatMap((s) => [...s.accepted])), refused: sets.flatMap((s) => s.refused) };
+}
+
+/** A context's findings with its waivers applied: waived grades, refusals and the house-style note. */
+export function settleContext(ctx: LintContext, findings: Finding[], cwd: string): Finding[] {
+ return applyWaivers(findings, contextWaivers(ctx, cwd, findings));
+}
+
+/** Run every rule family over every context, without waivers. */
+export function lintStaticRaw(paths: string[], opts: StaticOptions = {}): RawStaticResult {
+ const warn = opts.warn ?? ((l: string) => console.error(l));
+ const cwd = realDir(opts.cwd ?? process.cwd());
+ const skippedFiles: Skipped[] = [];
+ const files = collectFiles(paths, warn, skippedFiles);
+ const roots = paths.map((p) => { try { const real = fs.realpathSync(p); return fs.statSync(real).isDirectory() ? real : path.dirname(real); } catch { return null; } }).filter((p): p is string => p !== null);
+ const contexts = groupContexts(files, opts, warn, roots, skippedFiles);
+ shareProjects(contexts);
+ const raw: Finding[][] = [];
+ for (const ctx of contexts) {
+ const reporter = new Reporter(ctx.scope, cwd);
+ for (const family of FAMILIES) {
+ try { family.run(ctx, reporter); } catch (e) {
+ warn(`design-lint: internal error in ${family.name} rules for ${ctx.key}: ${(e as Error).message}`);
+ reporter.report('internal-error', ctx.docs[0]?.file ?? ctx.cssFiles[0]?.file ?? ctx.key, 1, `the ${family.name} rules threw and did not run: ${(e as Error).message}`);
+ }
+ }
+ raw.push(reporter.findings);
+ ctx.cache = {};
+ for (const doc of ctx.docs) doc.cache = {};
+ }
+ const skippedReporter = new Reporter(opts.scope ?? 'page', cwd);
+ for (const s of new Map(skippedFiles.map((s) => [s.file + '|' + s.why, s])).values()) skippedReporter.report('internal-error', s.file, 1, `skipped: ${s.why}; a page the lint could not read is not a pass`, { fix: s.kind === 'unreadable' ? 'check the path' : s.kind === 'unparseable' ? 'fix the markup the parser stopped on' : 'split the file, or lint the page that links it' });
+ return { files, contexts, raw, skipped: skippedReporter.findings };
+}
+
+/** A directory's real path, so a cwd or lint root reached through a symlink still matches the files collected under it. */
+export const realDir = (p: string): string => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
+
+export function lintStatic(paths: string[], opts: StaticOptions = {}): StaticResult {
+ const cwd = realDir(opts.cwd ?? process.cwd());
+ const { files, contexts, raw, skipped } = lintStaticRaw(paths, opts);
+ return { files, contexts, findings: [...contexts.flatMap((ctx, i) => settleContext(ctx, raw[i], cwd)), ...skipped] };
+}
diff --git a/lib/design-lint/tailwind.ts b/lib/design-lint/tailwind.ts
new file mode 100644
index 000000000..df556b0f2
--- /dev/null
+++ b/lib/design-lint/tailwind.ts
@@ -0,0 +1,657 @@
+/**
+ * Tailwind reading for the design lint: utility class strings in HTML and
+ * component files (class, className, :class, class:list and the cn/clsx/cva
+ * helper calls), parsed into the facts the rules ask about (background and
+ * text colours, gradients, sizes, tracking, case, families, variants), plus
+ * the tells the component rules read off them (gradient, glow, tracked caps,
+ * eyebrow, mono costume, icon tiles).
+ *
+ * Ported from Nutlope/hallmark's sloplint.mjs (twParse, twInfo, twGroup,
+ * twGradient, twGlow, tw67, tw54, twTiles and kin; MIT, see NOTICE.md).
+ */
+import type { LintContext } from './context';
+import { memo } from './context';
+import { bannedGradient, COLOR_LITERAL, oklchOf, parseColor, type Color } from './color';
+import { CONTROL_TRACK_MAX_EM, GENERIC_FAMILIES, LABEL_PX, MONO_FACE, TRACKED_EM, firstFamily, pxOf, resolveVars, splitTop, type Tokens } from './css';
+import { braceEnd, closeIndex, clsLits, directChildren, getAttr, innerOf, plainText, treeOf, type Doc, type Tag } from './html';
+import { trunc } from './report';
+import { EYEBROW_ANCESTOR_SKIP, EYEBROW_ANNOUNCE, EYEBROW_BLOCKY } from './rules/chrome-eyebrow';
+
+export const TW_SIZE: Record<string, number> = { xs: 12, sm: 14, base: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 30, '4xl': 36, '5xl': 48, '6xl': 60, '7xl': 72, '8xl': 96, '9xl': 128 };
+const TW_TRACK: Record<string, number> = { tighter: -0.05, tight: -0.025, normal: 0, wide: 0.025, wider: 0.05, widest: 0.1 };
+const TW_HUE: Record<string, number> = { red: 25, orange: 47, amber: 70, yellow: 86, lime: 131, green: 150, emerald: 163, teal: 183, cyan: 215, sky: 237, blue: 260, indigo: 277, violet: 293, purple: 304, fuchsia: 322, pink: 354, rose: 16 };
+const TW_COLOURS = 'slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose';
+export const TW_PAL = new RegExp(`^(?:bg|text|border(?:-[xytrblse])?|ring(?:-offset)?|outline|decoration|divide|from|via|to|fill|stroke|shadow|accent|caret|placeholder|inset-shadow|inset-ring|drop-shadow)-(?:${TW_COLOURS})-(?:50|[1-9]00|950)(?:\\/(?:\\d{1,3}|\\[[^\\]]*\\]))?$`);
+const TW_SHADE = new RegExp(`^(${TW_COLOURS})-(?:50|[1-9]00|950)(?:\\/\\S*)?$`);
+const TW_ACCENT = /^text-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:500|600|700)(?:\/\S*)?$/;
+const TW_PURPLE = /^(?:purple|violet|fuchsia|indigo)$/;
+const TW_BLUE = /^(?:blue|sky|cyan|indigo)$/;
+const TW_PINK = /^(?:pink|rose)$/;
+const TW_GREY = /^(?:slate|gray|zinc|neutral|stone)$/;
+const TW_NONFILL = /^bg-(?:none|transparent|inherit|current|fixed|local|scroll|cover|contain|auto|center|top|bottom|left|right|no-repeat|repeat(?:-[\w-]+)?|(?:left|right|top|bottom)-(?:top|bottom|left|right)|clip-[\w-]+|origin-[\w-]+|blend-[\w-]+|gradient-to-[\w-]+|(?:linear|radial|conic)(?:-.*)?|size-.*|position-.*|\[(?:url|length|position|size|image|(?:repeating-)?(?:linear|radial|conic)-gradient)[^\]]*\].*)$/;
+const TW_GLASS = /^bg-(?:white|black|(?:slate|gray|zinc|neutral|stone)-(?:50|100|900|950)|paper|ink|background|foreground)\/(\d{1,2}|\[(?:0?\.\d+|\d{1,2}%)\])$/;
+const TW_LOGO = /logo|brand|wordmark/i;
+const TW_COLOR_LIT = /#[0-9a-fA-F]{3,8}\b|oklch\([^)]*\)|rgba?\([^)]*\)|hsla?\([^)]*\)/g;
+
+export interface TwParsed { variants: string[]; base: string; neg: boolean }
+
+/** One utility split into its variants (group-/peer- prefixes and /names dropped), its base and a leading minus. */
+export function twParse(tok: string): TwParsed {
+ const variants: string[] = [];
+ let depth = 0, cur = '';
+ for (const ch of tok) {
+ if (ch === '[' || ch === '(') depth++;
+ else if ((ch === ']' || ch === ')') && depth > 0) depth--;
+ if (ch === ':' && depth === 0) { variants.push(cur); cur = ''; } else cur += ch;
+ }
+ let base = cur;
+ if (base.startsWith('!')) base = base.slice(1);
+ if (base.endsWith('!')) base = base.slice(0, -1);
+ const neg = base.length > 1 && base.startsWith('-');
+ if (neg) base = base.slice(1);
+ return { variants: variants.map((v) => v.replace(/^(?:group|peer)-/, '').replace(/\/[\w-]+$/, '')), base, neg };
+}
+
+/** The tokens utilities resolve against: the project's shared tokens for a component directory, else the context's own. */
+export const twTokens = (ctx: LintContext): Tokens => ctx.twTokens ?? ctx.tokens;
+
+const twValue = (tok: Tokens, v: string): string => resolveVars(v, tok).trim().replace(/^(-?)\./, '$10.');
+
+/** The px size a text-* utility sets: the scale, an arbitrary value, or a --text-* token. */
+export function twSize(ctx: LintContext, b: string): number | null {
+ const tok = twTokens(ctx);
+ let m = /^text-(xs|sm|base|lg|[2-9]?xl)(?:\/\S+)?$/.exec(b);
+ if (m) return TW_SIZE[m[1]];
+ m = /^text-(?:\[(?:length:)?([^\]]+)\]|\((?:length:)?(--[\w-]+)\))(?:\/\S+)?$/.exec(b);
+ let v: string | null = m ? (m[1] ? m[1].replace(/_/g, ' ') : `var(${m[2]})`) : null;
+ if (!m) {
+ m = /^text-([a-z][\w-]*?)(?:\/\S+)?$/.exec(b);
+ v = m ? tok[`--text-${m[1]}`] ?? null : null;
+ }
+ if (!v) return null;
+ const r = twValue(tok, v);
+ const cl = /^clamp\(\s*([^,]+),/.exec(r);
+ return pxOf(cl ? twValue(tok, cl[1]) : r);
+}
+
+export interface TwTrack { em: number | null; px: number | null }
+
+/** The tracking a tracking-* utility sets, in em when it says em, else in px. */
+export function twTrack(ctx: LintContext, b: string, neg: boolean): TwTrack | null {
+ const tok = twTokens(ctx);
+ let m = /^tracking-(tighter|tight|normal|wide|wider|widest)$/.exec(b);
+ let v: string | null = null;
+ if (m) v = `${TW_TRACK[m[1]]}em`;
+ else if ((m = /^tracking-(?:\[([^\]]+)\]|\((--[\w-]+)\))$/.exec(b))) v = m[1] ? m[1].replace(/_/g, ' ') : `var(${m[2]})`;
+ else if ((m = /^tracking-([a-z][\w-]*)$/.exec(b)) && tok[`--tracking-${m[1]}`]) v = tok[`--tracking-${m[1]}`];
+ if (v == null) return null;
+ const r = twValue(tok, v);
+ const e = /^(-?\d*\.?\d+)em$/.exec(r);
+ const px = e ? null : pxOf(r);
+ if (e) { const em = parseFloat(e[1]); return { em: neg ? -em : em, px: null }; }
+ if (px == null) return null;
+ return { em: null, px: neg ? -px : px };
+}
+
+/** The OKLCH hue of a colour that has one: opaque enough and chroma past 0.04. */
+export const twHue = (c: Color | null): number | null => {
+ if (!c || c.alpha <= 0.05) return null;
+ const ok = oklchOf(c);
+ return ok.C > 0.04 ? ok.H : null;
+};
+
+export interface TwStop {
+ kind: 'token' | 'palette' | 'literal' | 'other';
+ hue: number | null;
+ /** The stop's colour name or value as written after from-/via-/to-. */
+ value: string;
+ /** The whole utility. */
+ tok: string;
+ /** The palette family (violet, sky …) for a palette stop. */
+ pal: string | null;
+}
+
+/** One gradient stop (from-x, via-x, to-x) as a kind and a hue; a percentage position is no stop. */
+export function twStop(ctx: LintContext, v: string, tok: string): TwStop | null {
+ if (/^\[?-?\d*\.?\d+%\]?$/.test(v)) return null;
+ const tokens = twTokens(ctx);
+ const pm = TW_SHADE.exec(v);
+ if (pm) return { tok, value: v, kind: 'palette', pal: pm[1], hue: TW_GREY.test(pm[1]) ? null : TW_HUE[pm[1]] };
+ if (/^(?:white|black|transparent|current|inherit)(?:\/\S*)?$/.test(v)) return { tok, value: v, kind: 'other', pal: null, hue: null };
+ if (v.startsWith('(')) return { tok, value: v, kind: 'token', pal: null, hue: twHue(parseColor(twValue(tokens, `var${v.replace(/\/\S*$/, '').replace(/^\((?:color:)?/, '(')}`))) };
+ if (v.startsWith('[')) {
+ const inner = v.slice(1, v.lastIndexOf(']')).replace(/_/g, ' ');
+ return { tok, value: v, kind: /var\(/.test(inner) ? 'token' : 'literal', pal: null, hue: twHue(parseColor(twValue(tokens, inner))) };
+ }
+ const tv = tokens[`--color-${v.replace(/\/\S*$/, '')}`];
+ return { tok, value: v, kind: 'token', pal: null, hue: tv ? twHue(parseColor(twValue(tokens, tv))) : null };
+}
+
+/** The named family inside font-[…], or null for a token, a weight or a generic family. */
+export function twFamily(v: string): string | null {
+ if (/var\(/.test(v)) return null;
+ const named = v.replace(/^family-name:/, '');
+ if (named === v && !/^['"]/.test(v) && /^(?:\d|weight:|number:)/.test(v)) return null;
+ const fam = firstFamily(named.replace(/_/g, ' '));
+ return !fam || GENERIC_FAMILIES.has(fam) ? null : fam;
+}
+
+export interface TwColourLiteral { tok: string; oklch: boolean }
+export interface TwShadow { v: string; tok: string }
+
+/** What one element's class string says. */
+export interface TwInfo {
+ classes: string[];
+ /** The first bg-* fill utility. */
+ bg: string | null;
+ /** The first text-* colour utility. */
+ text: string | null;
+ stops: TwStop[];
+ /** Text clipped to a background and made transparent. */
+ gradientText: boolean;
+ sizePx: number | null;
+ trackingEm: number | null;
+ upper: boolean;
+ smallCaps: boolean;
+ mono: boolean;
+ variants: Set<string>;
+ normalCase: boolean;
+ /** The first saturated palette text colour (text-indigo-600 and kin). */
+ accent: string | null;
+ /** transition-all, or a transition naming a layout property. */
+ tAll: string | null;
+ bounce: string | null;
+ overshoot: string | null;
+ hScale: string | null;
+ hRotate: string | null;
+ grad: boolean;
+ clip: boolean;
+ clear: boolean;
+ bblur: string | null;
+ glass: string | null;
+ blur: number;
+ blurTok: string | null;
+ pos: string | null;
+ fill: boolean;
+ shadows: TwShadow[];
+ shadowCol: string | null;
+ vh: string | null;
+ oxHidden: string | null;
+ oxClip: boolean;
+ colours: TwColourLiteral[];
+ font: string | null;
+ pal: string[];
+ rounded: boolean;
+ cols3: boolean;
+ animate: string | null;
+ transform: boolean;
+ transition: boolean;
+ hero: boolean;
+ padded: boolean;
+}
+
+function twLiterals(b: string, tok: string, f: TwInfo): void {
+ for (const m of b.matchAll(/\[([^\]]+)\]/g)) {
+ const v = m[1].replace(/url\([^)]*\)/gi, ' ').replace(/_/g, ' ');
+ const fam = /^font-family:(.+)$/.exec(v);
+ if (fam && !/var\(/.test(fam[1]) && !GENERIC_FAMILIES.has(firstFamily(fam[1]))) f.font = f.font || tok;
+ for (const c of v.matchAll(TW_COLOR_LIT)) {
+ const col = parseColor(c[0]);
+ if (col && col.alpha > 0) f.colours.push({ tok, oklch: /^oklch/i.test(c[0]) });
+ }
+ }
+}
+
+interface TwAcc { sizeV: number | null; tracks: Array<{ r: TwTrack; plain: boolean }> }
+
+/** Case, size, tracking and family utilities; true when the token was one of them. */
+function twReadType(ctx: LintContext, b: string, tok: string, p: TwParsed, f: TwInfo, acc: TwAcc): boolean {
+ const plain = !p.variants.length;
+ if (b === 'uppercase') { f.upper = true; return true; }
+ if (b === 'normal-case') { if (plain) f.normalCase = true; return true; }
+ if (b === 'small-caps' || /^\[font-variant(?:-caps)?:[^\]]*(?:small|petite)-caps/.test(b) || /^\[font-feature-settings:[^\]]*(?:smcp|c2sc)/.test(b)) { f.smallCaps = true; return true; }
+ if (b.startsWith('text-')) {
+ const px = twSize(ctx, b);
+ if (px != null) {
+ if (plain) f.sizePx = px; else acc.sizeV = acc.sizeV == null ? px : Math.min(acc.sizeV, px);
+ return true;
+ }
+ if (b === 'text-transparent') { f.clear = true; return true; }
+ if (!/^text-(?:left|center|right|justify|start|end|wrap|nowrap|balance|pretty|ellipsis|clip)$/.test(b)) f.text = f.text || tok;
+ if (TW_ACCENT.test(b)) f.accent = f.accent || tok;
+ return true;
+ }
+ if (b.startsWith('tracking-')) {
+ const r = twTrack(ctx, b, p.neg);
+ if (r) acc.tracks.push({ r, plain });
+ return true;
+ }
+ if (b === 'font-mono') { f.mono = true; return true; }
+ if (b.startsWith('font-')) {
+ const arb = /^font-\[(.+)\]$/.exec(b);
+ const fam = arb ? twFamily(arb[1]) : null;
+ if (fam) { f.font = f.font || tok; if (MONO_FACE.test(fam)) f.mono = true; }
+ const named = !arb && /^font-([a-z][\w-]*)$/.exec(b);
+ const tv = named ? twTokens(ctx)[`--font-${named[1]}`] : undefined;
+ if (tv && MONO_FACE.test(firstFamily(resolveVars(tv, twTokens(ctx))))) f.mono = true;
+ return true;
+ }
+ return false;
+}
+
+/** Motion, gradient, surface, shadow, size and layout utilities. */
+function twReadSurface(ctx: LintContext, b: string, tok: string, p: TwParsed, f: TwInfo): void {
+ const hover = p.variants.includes('hover');
+ if (b === 'transition-all' || /^transition-\[[^\]]*\b(?:all|width|height|top|left|right|bottom|inset)\b/.test(b) || /^\[transition(?:-property)?:[^\]]*\b(?:all|width|height|top|left)\b/.test(b)) {
+ f.tAll = f.tAll || tok; f.transition = true;
+ return;
+ }
+ if (/^transition(?:-transform)?$/.test(b)) { f.transition = true; if (b !== 'transition') f.transform = true; return; }
+ if (b.startsWith('animate-')) {
+ if (b !== 'animate-none') f.animate = f.animate || tok;
+ if (b === 'animate-bounce') f.bounce = f.bounce || tok;
+ return;
+ }
+ const ez = /^ease-\[cubic-bezier\(([^)]*)\)\]$/.exec(b);
+ if (ez) {
+ const n = ez[1].split(/[,_\s]+/).filter(Boolean).map(Number);
+ if (n.length === 4 && [n[1], n[3]].some((y) => y > 1.05 || y < -0.05)) f.overshoot = f.overshoot || tok;
+ return;
+ }
+ if (/^(?:scale|translate|rotate|skew)-/.test(b)) {
+ f.transform = true;
+ if (hover && /^scale-/.test(b) && !/^scale-(?:[xy]-)?100$/.test(b)) f.hScale = f.hScale || tok;
+ if (hover && /^rotate-/.test(b) && b !== 'rotate-0') f.hRotate = f.hRotate || tok;
+ return;
+ }
+ if (/^bg-(?:gradient-to-|linear-|radial|conic)|^bg-\[(?:repeating-)?(?:linear|radial|conic)-gradient/.test(b) || /^\[background(?:-image)?:[^\]]*gradient\(/.test(b)) f.grad = true;
+ const st = /^(?:from|via|to)-(.+)$/.exec(b);
+ if (st) { const s = twStop(ctx, st[1], tok); if (s) f.stops.push(s); return; }
+ if (b === 'bg-clip-text' || /^\[(?:-webkit-)?background-clip:text\]$/.test(b)) { f.clip = true; return; }
+ if (b === '[-webkit-text-fill-color:transparent]') { f.clear = true; return; }
+ if (/^backdrop-blur(?:-|$)/.test(b) || /^\[(?:-webkit-)?backdrop-filter:[^\]]*blur/.test(b)) { f.bblur = f.bblur || tok; return; }
+ const bl = /^blur-(?:(2xl|3xl)|\[(\d*\.?\d+)(px|rem)\])$/.exec(b);
+ if (bl) {
+ const px = bl[1] ? (bl[1] === '2xl' ? 40 : 64) : parseFloat(bl[2]) * (bl[3] === 'rem' ? 16 : 1);
+ if (px > f.blur) { f.blur = px; f.blurTok = tok; }
+ return;
+ }
+ if (b === 'absolute' || b === 'fixed') { f.pos = f.pos || b; return; }
+ if (b.startsWith('bg-')) {
+ const gm = TW_GLASS.exec(b);
+ if (gm) {
+ const v = gm[1].replace(/^\[|\]$/g, '');
+ const a = v.endsWith('%') ? parseFloat(v) / 100 : v.includes('.') ? parseFloat(v) : parseFloat(v) / 100;
+ if (a < 0.95) f.glass = f.glass || tok;
+ }
+ if (!TW_NONFILL.test(b)) { f.fill = true; f.bg = f.bg || tok; }
+ return;
+ }
+ if (b.startsWith('shadow-')) {
+ const sm = /^shadow-\[(.+)\]$/.exec(b);
+ if (sm) f.shadows.push({ v: sm[1], tok });
+ else if (!/^shadow-(?:2xs|xs|sm|md|lg|xl|2xl|inner|none)$/.test(b)) f.shadowCol = f.shadowCol || b.slice(7);
+ return;
+ }
+ if (/^(?:min-)?h-(?:screen|\[[^\]]*\d\s*vh[^\]]*\])$/.test(b)) { f.vh = f.vh || tok; return; }
+ if (b === 'overflow-x-hidden') { f.oxHidden = f.oxHidden || tok; return; }
+ if (b === 'overflow-x-clip' || b === 'overflow-clip') { f.oxClip = true; return; }
+ if (/^rounded(?:-|$)/.test(b)) { if (b !== 'rounded-none') f.rounded = true; return; }
+ if (b === 'grid-cols-3') { f.cols3 = true; return; }
+ if (/^p[xytrblse]?-/.test(b)) { f.padded = true; return; }
+}
+
+/** Read one class string into its facts; the variants it uses land in the shared set as well as on the info. */
+export function twInfo(ctx: LintContext, toks: string[], variants: Set<string>): TwInfo {
+ const f: TwInfo = {
+ classes: toks, bg: null, text: null, stops: [], gradientText: false, sizePx: null, trackingEm: null, upper: false, smallCaps: false, mono: false, variants: new Set<string>(),
+ normalCase: false, accent: null, tAll: null, bounce: null, overshoot: null, hScale: null, hRotate: null, grad: false, clip: false, clear: false,
+ bblur: null, glass: null, blur: 0, blurTok: null, pos: null, fill: false, shadows: [], shadowCol: null, vh: null, oxHidden: null, oxClip: false,
+ colours: [], font: null, pal: [], rounded: false, cols3: false, animate: null, transform: false, transition: false, hero: false, padded: false,
+ };
+ const acc: TwAcc = { sizeV: null, tracks: [] };
+ for (const tok of toks) {
+ if (tok.includes('__')) continue;
+ const p = twParse(tok);
+ const b = p.base;
+ if (!b) continue;
+ for (const v of p.variants) { variants.add(v); f.variants.add(v); }
+ if (TW_PAL.test(b)) f.pal.push(b.replace(/\/.*$/, ''));
+ if (b.includes('[')) twLiterals(b, tok, f);
+ if (/hero/i.test(b)) f.hero = true;
+ if (!twReadType(ctx, b, tok, p, f, acc)) twReadSurface(ctx, b, tok, p, f);
+ }
+ if (f.sizePx == null) f.sizePx = acc.sizeV;
+ let emV: number | null = null;
+ for (const { r, plain } of acc.tracks) {
+ const em = r.em != null ? r.em : (r.px ?? 0) / (f.sizePx || 16);
+ if (plain) f.trackingEm = em; else emV = emV == null ? em : Math.max(emV, em);
+ }
+ if (f.trackingEm == null) f.trackingEm = emV;
+ f.gradientText = f.clip && f.clear;
+ return f;
+}
+
+const TW_CLASS_ATTR = /(?:^|\s)(class|className|:class|v-bind:class|x-bind:class|class:list)\s*=\s*/g;
+
+const cutGlued = (seg: string, after: boolean, before: boolean): string => {
+ let s = seg;
+ if (after) s = s.replace(/^\S+/, '');
+ if (before) s = s.replace(/\S+$/, '');
+ return s;
+};
+
+/** Class tokens of a Svelte/Astro attribute value with {expressions} inside it, glued halves dropped. */
+function twInterp(val: string): string[] {
+ const parts: string[] = [];
+ let i = 0, seg = '', after = false;
+ while (i < val.length) {
+ if (val[i] === '{') {
+ parts.push(cutGlued(seg, after, true));
+ const e = braceEnd(val, i);
+ parts.push(clsLits(val.slice(i + 1, e)).join(' '));
+ i = e + 1; seg = ''; after = true;
+ continue;
+ }
+ seg += val[i++];
+ }
+ parts.push(cutGlued(seg, after, false));
+ return parts.join(' ').split(/\s+/).filter(Boolean);
+}
+
+/** Every class token on a tag: the JSX scanner's record, or the class-bearing attributes of the raw tag text. */
+export function twTokensOf(doc: Doc, t: Tag): string[] {
+ if (doc.kind === 'jsx') return doc.classAt.get(t.pos) || [];
+ const tag = doc.raw.slice(t.pos, t.end);
+ if (!tag.includes('class')) return [];
+ const out: string[] = [];
+ for (const m of tag.matchAll(TW_CLASS_ATTR)) {
+ const i = (m.index as number) + m[0].length;
+ const q = tag[i];
+ let val: string;
+ let dyn = m[1] !== 'class' && m[1] !== 'className';
+ if (q === '"' || q === "'") { const e = tag.indexOf(q, i + 1); val = tag.slice(i + 1, e < 0 ? tag.length : e); }
+ else if (q === '{') { val = tag.slice(i + 1, braceEnd(tag, i)); dyn = true; }
+ else val = (/^[^\s>]*/.exec(tag.slice(i)) || [''])[0];
+ for (const tok of dyn ? clsLits(val) : val.includes('{') ? twInterp(val) : val.split(/\s+/)) out.push(tok);
+ }
+ for (const d of tag.matchAll(/(?:^|\s)class:(?!list\b)([\w-]+)/g)) out.push(d[1]);
+ return out.filter(Boolean);
+}
+
+/** What an element inherits from its ancestors: size, tracking, case, and the contexts that exempt it. */
+export interface TwFrame {
+ size: number | null;
+ em: number | null;
+ upper: boolean;
+ caps: boolean;
+ noLabel: boolean;
+ code: boolean;
+ eyeSkip: boolean;
+ inOl: boolean;
+ logo: boolean;
+ logoSelf: boolean;
+}
+
+const TW_ROOT: TwFrame = { size: null, em: null, upper: false, caps: false, noLabel: false, code: false, eyeSkip: false, inOl: false, logo: false, logoSelf: false };
+
+function twFrame(parent: TwFrame, t: { name: string; attrs: string }, f: TwInfo | null): TwFrame {
+ const logo = (f ? f.classes : []).some((x) => TW_LOGO.test(x)) || TW_LOGO.test(getAttr(t.attrs, 'aria-label') || '');
+ return {
+ size: f && f.sizePx != null ? f.sizePx : parent.size,
+ em: f && f.trackingEm != null ? f.trackingEm : parent.em,
+ upper: f ? f.upper || (!f.normalCase && parent.upper) : parent.upper,
+ caps: (f != null && f.smallCaps) || parent.caps,
+ noLabel: parent.noLabel || /^(?:svg|pre|code|abbr|kbd|samp)$/.test(t.name),
+ code: parent.code || /^(?:pre|code|kbd|samp)$/.test(t.name),
+ eyeSkip: parent.eyeSkip || EYEBROW_ANCESTOR_SKIP.test(t.name),
+ inOl: parent.inOl || t.name === 'ol',
+ logo: parent.logo || (t.name === 'a' && logo),
+ logoSelf: logo,
+ };
+}
+
+export interface TwItem {
+ file: string;
+ line: number;
+ /** Tag index in the doc, or -1 for a component tag or a helper-call site. */
+ idx: number;
+ /** The tag name, the component name, or the helper's name for a call site. */
+ tag: string;
+ info: TwInfo;
+ doc: Doc;
+ /** Index into doc.comps for a component tag, else null. */
+ comp: number | null;
+ /** A cn()/clsx()/cva() call site rather than an element. */
+ virtual: boolean;
+ attrs: string;
+ frame: TwFrame;
+ text: string | null;
+}
+
+export interface TwGroup {
+ items: TwItem[];
+ variants: Set<string>;
+ /** An h1 or h2 set uppercase, which excuses uppercase controls. */
+ upperDisplay: boolean;
+}
+
+/** Give a component context the project's tokens and drop the Tailwind facts read before they were known. */
+export function setTwTokens(ctx: LintContext, tokens: Tokens): void {
+ ctx.twTokens = tokens;
+ delete ctx.cache.tw;
+}
+
+/** Every class-bearing element, component tag and helper call in the context, parsed. */
+export function twGroup(ctx: LintContext): TwGroup {
+ return memo(ctx, 'tw', () => {
+ const tw: TwGroup = { items: [], variants: new Set<string>(), upperDisplay: false };
+ const add = (it: TwItem) => {
+ tw.items.push(it);
+ if (/^h[12]$/.test(it.tag) && it.info.upper) tw.upperDisplay = true;
+ };
+ for (const doc of ctx.docs) {
+ const { parent } = treeOf(doc);
+ const frames: TwFrame[] = [];
+ for (let i = 0; i < doc.tags.length; i++) {
+ const t = doc.tags[i];
+ if (t.close) continue;
+ const toks = twTokensOf(doc, t);
+ const info = toks.length ? twInfo(ctx, toks, tw.variants) : null;
+ const frame = twFrame(parent[i] >= 0 ? frames[parent[i]] : TW_ROOT, t, info);
+ frames[i] = frame;
+ if (info) add({ file: doc.file, line: t.line, idx: i, tag: t.name, info, doc, comp: null, virtual: false, attrs: t.attrs, frame, text: null });
+ }
+ for (let c = 0; c < doc.comps.length; c++) {
+ const t = doc.comps[c];
+ if (t.close) continue;
+ const toks = twTokensOf(doc, t);
+ if (!toks.length) continue;
+ const info = twInfo(ctx, toks, tw.variants);
+ add({ file: doc.file, line: t.line, idx: -1, tag: t.name, info, doc, comp: c, virtual: false, attrs: t.attrs, frame: twFrame(TW_ROOT, t, info), text: null });
+ }
+ for (const v of doc.virtuals) {
+ const info = twInfo(ctx, v.toks, tw.variants);
+ add({ file: doc.file, line: doc.lineOf(v.pos), idx: -1, tag: v.name, info, doc, comp: null, virtual: true, attrs: '', frame: twFrame(TW_ROOT, { name: v.name, attrs: '' }, info), text: null });
+ }
+ }
+ return tw;
+ });
+}
+
+/** The Tailwind variants (hover, focus-visible, motion-reduce …) used anywhere in the context. */
+export function twVariants(ctx: LintContext): Set<string> {
+ return twGroup(ctx).variants;
+}
+
+/** Where a finding points: the helper call, or the element with the start of its class string. */
+export function twWhere(it: TwItem): string {
+ return it.virtual ? `${it.tag}() class string` : `<${it.tag} class="${trunc(it.info.classes.join(' '), 32)}">`;
+}
+
+/** Component tags paired once per document: for each open tag the index of its own close tag, -1 when none closes it. */
+function compCloses(doc: Doc): Int32Array {
+ const cached = doc.cache.compCloses as Int32Array | undefined;
+ if (cached) return cached;
+ const closes = new Int32Array(doc.comps.length).fill(-1);
+ const open = new Map<string, number[]>();
+ for (let i = 0; i < doc.comps.length; i++) {
+ const t = doc.comps[i];
+ if (t.selfClosing) continue;
+ if (!t.close) { const s = open.get(t.name); if (s) s.push(i); else open.set(t.name, [i]); continue; }
+ const s = open.get(t.name);
+ if (s?.length) closes[s.pop()!] = i;
+ }
+ doc.cache.compCloses = closes;
+ return closes;
+}
+
+/** The source between a component tag and its matching close; empty when nothing closes it. */
+export function compInner(doc: Doc, c: number): string {
+ const k = compCloses(doc)[c];
+ return k < 0 ? '' : doc.src.slice(doc.comps[c].end, doc.comps[k].pos);
+}
+
+/** Visible text of a fragment, with template expressions blanked in Vue, Svelte and Astro files. */
+export function twPlain(doc: Doc, html: string): string {
+ let s = html;
+ if (doc.kind !== 'html' && doc.kind !== 'jsx') for (let k = 0; k < 3 && /\{[^{}]*\}/.test(s); k++) s = s.replace(/\{[^{}]*\}/g, ' ');
+ return plainText(s);
+}
+
+/** The element's visible text, read once. */
+export function twText(it: TwItem): string {
+ if (it.text == null) {
+ let inner = '';
+ if (it.idx >= 0) inner = innerOf(it.doc, it.idx)?.inner || '';
+ else if (it.comp != null) inner = compInner(it.doc, it.comp);
+ it.text = twPlain(it.doc, inner);
+ }
+ return it.text;
+}
+
+export interface TwGradient { banned: string | null; text: boolean; list: string }
+
+/** The gradient an element's stops describe: its banned pairing if any, whether it is text, and the stop classes. */
+export function twGradient(ctx: LintContext, f: TwInfo): TwGradient | null {
+ if (!f.stops.length || (!f.grad && f.stops.length < 2)) return null;
+ const names = f.stops.map((s) => s.pal).filter((p): p is string => p != null);
+ let banned: string | null = null;
+ for (const a of names) {
+ if (!TW_PURPLE.test(a)) continue;
+ if (names.some((x) => x !== a && TW_BLUE.test(x))) { banned = 'purple-to-blue'; break; }
+ if (names.some((x) => x !== a && TW_PINK.test(x))) { banned = 'purple-to-pink'; break; }
+ }
+ if (!banned) banned = bannedGradient(f.stops.map((s) => s.hue).filter((h): h is number => h != null), twTokens(ctx));
+ return { banned, text: f.clip && f.clear, list: f.stops.map((s) => s.tok).join(' ') };
+}
+
+const lengthPx = (x: string): number | null => (x === '0' ? 0 : pxOf(x));
+
+/** A zero-offset coloured shadow of 8px blur or more: a glow. */
+export function twGlow(ctx: LintContext, f: TwInfo): string | null {
+ const tokens = twTokens(ctx);
+ for (const s of f.shadows) {
+ for (const part of splitTop(resolveVars(s.v.replace(/_/g, ' '), tokens))) {
+ const cm = COLOR_LITERAL.exec(part);
+ const lens = (cm ? part.replace(cm[0], ' ') : part).replace(/\binset\b/, ' ').trim().split(/\s+/).filter(Boolean).map(lengthPx);
+ if (lens.length < 3 || lens[0] !== 0 || lens[1] !== 0 || lens[2] == null || lens[2] < 8) continue;
+ let chroma = 0;
+ if (cm) {
+ const c = parseColor(cm[0]);
+ if (c && c.alpha > 0.05) chroma = oklchOf(c).C;
+ } else if (f.shadowCol) {
+ const name = f.shadowCol.replace(/\/\S*$/, '');
+ const pm = TW_SHADE.exec(name);
+ const tv = tokens[`--color-${name}`];
+ chroma = pm ? (TW_GREY.test(pm[1]) ? 0 : 0.2) : tv ? (twHue(parseColor(resolveVars(tv, tokens).trim())) != null ? 0.2 : 0) : 0;
+ }
+ if (chroma > 0.04) return `glow: ${s.tok}${cm ? '' : ` with shadow-${f.shadowCol}`}`;
+ }
+ }
+ return null;
+}
+
+/** Whether a mono face is one of the page's declared families, so font-mono labels are material, not costume. */
+export function twMonoIsMaterial(tokens: Tokens): boolean {
+ const mono = (v: string | undefined) => !!v && MONO_FACE.test(firstFamily(resolveVars(v, tokens)));
+ return mono(tokens['--font-display']) || mono(tokens['--font-body']) || mono(tokens['--font-outlier']);
+}
+
+/** Text that reads as data (a version, a shortcut, a command, a path, a time): mono is material there. */
+export function twDataText(s: string): boolean {
+ const t = s.trim();
+ if (t.length > 200) return false;
+ const letters = (t.match(/[A-Za-z]/g) || []).length;
+ const digits = (t.match(/\d/g) || []).length;
+ if (digits >= letters) return true;
+ if (/^v?\d+(?:\.\d+)+/.test(t) || /[⌘⌥⇧⌃⎋↵]|^(?:ctrl|cmd|alt|shift|option)\s*[+-]/i.test(t)) return true;
+ if (/[{}();=<>]|^\$\s|^(?:npm|npx|pnpm|yarn|bun|git|curl|cd|ls|brew|pip|docker|node) |^--?[a-z]|[\w-]+\.[a-z][a-z0-9]{0,3}$|^[#.]?[a-z]+(?:[-_][a-z0-9]+)+$|^[a-z]+[A-Z]\w*$|^\/[\w/.-]*$|^https?:/.test(t)) return true;
+ return digits > 0 && /^(?:\d{1,2}:\d{2}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+\d)/i.test(t);
+}
+
+export interface TwTrackedCaps { what: string; size: number | null; em: number | null }
+
+/** The tracked-caps label: small text set uppercase, small caps or letter-spaced past 0.03em, outside logos, code and display heads. */
+export function twTrackedCaps(it: TwItem, tw: TwGroup): TwTrackedCaps | null {
+ const f = it.info, fr = it.frame;
+ if (!(f.upper || f.smallCaps || (f.trackingEm != null && f.trackingEm > TRACKED_EM))) return null;
+ if (fr.logo || fr.logoSelf || fr.noLabel) return null;
+ const size = fr.size, em = fr.em;
+ if ((size != null && size >= 24) || (size == null && /^h[1-6]$/.test(it.tag))) return null;
+ const caps = fr.upper || fr.caps;
+ const small = size != null && size <= LABEL_PX;
+ const tracked = em != null && em > TRACKED_EM;
+ const control = /^(?:button|input)$/.test(it.tag) || /(?:button|btn|cta)$/i.test(it.tag) || (it.tag === 'a' && f.fill && f.padded) || /role\s*=\s*["']?button/i.test(it.attrs);
+ if (tw.upperDisplay && control && (em == null || em <= CONTROL_TRACK_MAX_EM)) return null;
+ if (!((caps && (small || tracked)) || (tracked && small))) return null;
+ return { what: fr.caps ? 'small caps' : fr.upper ? 'uppercase' : 'letter-spaced', size, em: tracked && em != null ? Math.round(em * 1000) / 1000 : null };
+}
+
+export interface TwEyebrow { text: string; next: string; signal: string }
+
+/** The eyebrow: a short, small, uppercase, tracked or accent-coloured line immediately before an h1 to h3. */
+export function twEyebrow(it: TwItem): TwEyebrow | null {
+ const f = it.info, fr = it.frame, doc = it.doc;
+ if (it.idx < 0 || !/^(?:p|span|div|small)$/.test(it.tag) || fr.eyeSkip) return null;
+ if (!(f.upper || (f.trackingEm != null && f.trackingEm > TRACKED_EM) || f.accent)) return null;
+ if (fr.size == null || fr.size > 14) return null;
+ const t = doc.tags[it.idx];
+ if (/role\s*=\s*["']?status|aria-live|aria-current|aria-hidden\s*=\s*["']?true/i.test(t.attrs)) return null;
+ const c = closeIndex(doc, it.idx);
+ const nx = c > it.idx && !doc.tags[c].close ? doc.tags[c] : doc.tags[c + 1];
+ if (!nx || nx.close || !/^h[1-3]$/.test(nx.name)) return null;
+ const inner = c > it.idx ? doc.src.slice(t.end, doc.tags[c].pos) : '';
+ if (EYEBROW_BLOCKY.test(inner) || /<br\b|<time\b/i.test(inner)) return null;
+ const href = /<a\b[^>]*\shref\s*=\s*["']([^"']*)["']/i.exec(inner);
+ if (href && !/^#?$/.test(href[1].trim())) return null;
+ const text = twPlain(doc, inner);
+ const signal = [f.upper ? 'uppercase' : null, f.trackingEm != null && f.trackingEm > TRACKED_EM ? `tracked ${Math.round(f.trackingEm * 1000) / 1000}em` : null, f.accent].filter(Boolean).join(', ');
+ if (!text) return doc.kind !== 'html' && c > it.idx && doc.raw.slice(t.end, doc.tags[c].pos).includes('{') ? { text: '', next: nx.name, signal } : null;
+ const words = text.split(/[\s·/|\u2014\u2013]+/).filter(Boolean);
+ if (words.length > 7 || text.length > 56 || /[\w/-]+\.[a-z]{1,4}$/i.test(text)) return null;
+ const stripped = text.replace(/^\s*(?:no\.?\s*)?\d{1,3}(?:\s*[·./\u2014\u2013-]\s*|\s+|$)/i, '').trim();
+ if ((stripped.match(/\d/g) || []).length >= 2) return null;
+ if (fr.inOl && stripped && !EYEBROW_ANNOUNCE.test(stripped)) return null;
+ return { text, next: nx.name, signal };
+}
+
+/** How many direct children of a grid open on an icon alone in a rounded filled tile above an h3. */
+export function twTiles(it: TwItem, byIdx: Map<number, TwItem>): number {
+ const doc = it.doc;
+ let tiles = 0;
+ for (const k of directChildren(doc, it.idx)) {
+ if (!/<h3\b/i.test(k.html)) continue;
+ const end = closeIndex(doc, k.idx);
+ for (let j = k.idx + 1; j < end; j++) {
+ const t = doc.tags[j];
+ if (t.close) continue;
+ if (/^h[1-6]$/.test(t.name)) break;
+ const ti = byIdx.get(j);
+ if (!ti || !ti.info.rounded || !ti.info.fill) continue;
+ const inner = innerOf(doc, j);
+ if (inner && /<svg\b|<[A-Z][\w.]*Icon\b|<Icon\b|<i\b[^>]*class/.test(inner.inner) && !twPlain(doc, inner.inner)) { tiles++; break; }
+ }
+ }
+ return tiles;
+}
diff --git a/lib/design-lint/waivers.ts b/lib/design-lint/waivers.ts
new file mode 100644
index 000000000..4f05c1f32
--- /dev/null
+++ b/lib/design-lint/waivers.ts
@@ -0,0 +1,145 @@
+/**
+ * Waivers on the record. A page answers a finding with a comment that names
+ * the rule and gives a reason about this page:
+ *
+ * <!-- gstack-lint-disable kicker-above-heading: the chapter number is the reader's bookmark through a 40-page spec -->
+ * /* gstack-lint-disable section-gap: the ledger separates its rows with rules, not air *\/
+ * // gstack-lint-disable template-nav: the three links are the product's three modes
+ *
+ * `impeccable-disable <rule>: <reason>` is accepted as an alias, so a comment
+ * that already silences the impeccable engine silences the same tell here.
+ *
+ * What the lint refuses, each as its own `waiver` finding: an unknown rule; a
+ * blocking rule (the Floor is never waivable; the one exception is a blocking
+ * rule the lint could only suspect on this page, which it reports at ask and
+ * which a waiver answers like any ask); a reason under 24 characters,
+ * boilerplate ("by design", "intentional"), reused word for word on another
+ * waiver, or sharing no word of four letters or more with the page's own
+ * text; a second waiver of one rule; a claim on one of the lint's own rules
+ * (waiver, house-style, render, internal-error). More than three waivers on
+ * one page is a house style and belongs in DESIGN.md: reported at polish.
+ *
+ * Adapted from Nutlope/hallmark's sloplint.mjs applyWaivers (MIT, see
+ * NOTICE.md); the guard evidence field is dropped because gstack has no theme
+ * stamp to re-derive it from.
+ */
+import { oneLine, relPath, Reporter, type Finding } from './report';
+import { lineIndex } from './css';
+import { ruleMeta } from './rules/ids';
+
+export interface WaiverClaim {
+ rule: string;
+ reason: string;
+ file: string;
+ line: number;
+}
+
+export interface WaiverSet {
+ /** Waivers accepted, each with its recorded reason: keyed by rule id for a page claim, and by rule@file for a claim that answers for the file it is written in (a stylesheet, or a component), so two linked sheets may each waive the same rule for their own findings. */
+ accepted: Map<string, string>;
+ /** Refused waivers, already shaped as findings. */
+ refused: Finding[];
+}
+
+/** A page claim is keyed by its rule; a claim that answers for its own file by rule@file. */
+const waiverKey = (rule: string, file: string | null): string => (file ? `${rule}@${file}` : rule);
+
+export const WAIVER_MIN_REASON = 24;
+export const WAIVER_MAX = 3;
+
+/** The reason runs to the end of its comment or line, so two waivers on one line are both read. */
+const WAIVER_RE = /(?:gstack-lint-disable|impeccable-disable)\s+([a-z][a-z0-9-]*)\s*:\s*([^\r\n]*?)(?=-->|\*\/|[\r\n]|$)/g;
+const WAIVER_REASON_MAX = 300;
+
+const WAIVER_FILLER = /\b(a|an|the|is|it|this|that|was|are|and|but|so|very|just|really|here|quite|more|most)\b/gi;
+const WAIVER_BOILERPLATE_PHRASES = [
+ 'design choice', 'design decision', 'intentionally', 'intentional', 'by design',
+ 'looks better', 'for the aesthetic', 'aesthetic', 'necessary here', 'necessary',
+ 'the prompt requires it', 'prompt requires', 'the brief requires it', 'brief requires', 'on purpose', 'deliberate', 'deliberately',
+ 'it works', 'works better', 'needed', 'required', 'fine', 'ok', 'okay', 'user agreed', 'agreed',
+];
+
+export function reasonIsBoilerplate(reason: string): boolean {
+ let r = reason.toLowerCase();
+ for (const p of WAIVER_BOILERPLATE_PHRASES) r = r.split(p).join(' ');
+ r = r.replace(WAIVER_FILLER, ' ').replace(/[^a-z0-9]+/g, ' ').trim();
+ return r.length < 12;
+}
+
+/** Every waiver comment in one source file, with its line. */
+export function findWaivers(file: string, source: string): WaiverClaim[] {
+ const out: WaiverClaim[] = [];
+ const lineOf = lineIndex(source);
+ for (const m of source.matchAll(WAIVER_RE)) {
+ const reason = m[2].trim().slice(0, WAIVER_REASON_MAX);
+ out.push({ rule: m[1], reason, file, line: lineOf(m.index!) });
+ }
+ return out;
+}
+
+const pageWordsOf = (text: string): Set<string> =>
+ new Set((text.toLowerCase().replace(WAIVER_RE, ' ').match(/[a-z]{4,}/g) || []));
+
+export const FLOOR_REFUSAL = 'it blocks; the Floor is never waivable';
+export const OWN_RULE_REFUSAL = "the lint's own rule, never waivable";
+
+/** The blocking rules a set of findings only suspected: every finding of the rule sits at ask (report.ts demotes a suspected blocking finding), none was measured. */
+export function suspectedRules(findings: Finding[]): Set<string> {
+ const measured = new Set(findings.filter((f) => f.tier === 'blocks').map((f) => f.rule));
+ return new Set(findings.filter((f) => f.tier === 'ask' && ruleMeta(f.rule)?.tier === 'blocks' && !measured.has(f.rule)).map((f) => f.rule));
+}
+
+/**
+ * Validate the claims of one context against its visible text. The text the
+ * reason must share a word with is the page's own prose, waiver comments
+ * removed, so a reason cannot vouch for itself; a claim written in a
+ * stylesheet answers for that stylesheet on every page that links it, so the
+ * shared-word check does not apply to it (nor to a stylesheet linted on its
+ * own, which has no prose). `suspected` names
+ * the blocking rules this context could only suspect (reported at ask): a
+ * waiver on one of them is weighed like any ask; a waiver on any other
+ * blocking rule, measured or not found, is refused. With `ownFile`, every
+ * claim answers for the file it is written in (a component in a directory
+ * of components), keyed like a stylesheet claim and weighed against
+ * `pageText` as that file's own text.
+ */
+export function resolveWaivers(claims: WaiverClaim[], pageText: string, cwd = process.cwd(), suspected: ReadonlySet<string> = new Set(), ownFile = false): WaiverSet {
+ const accepted = new Map<string, string>();
+ const rep = new Reporter('page', cwd);
+ const pageWords = pageWordsOf(pageText);
+ const reasons = new Map<string, number>();
+ for (const c of claims) reasons.set(c.reason.toLowerCase(), (reasons.get(c.reason.toLowerCase()) || 0) + 1);
+ const refuse = (c: WaiverClaim, why: string) => rep.report('waiver', c.file, c.line, `waiver on ${c.rule} refused: ${why}`,
+ { fix: 'fix the finding, or waive it with the rule id and a reason about this page (24 characters or more, not boilerplate)' });
+ for (const c of claims) {
+ const meta = ruleMeta(c.rule);
+ if (!meta) { refuse(c, 'no such rule'); continue; }
+ if (meta.gate === 'waiver' || meta.gate === 'render' || meta.gate === 'lint') { refuse(c, OWN_RULE_REFUSAL); continue; }
+ if (meta.tier === 'blocks' && !suspected.has(c.rule)) { refuse(c, FLOOR_REFUSAL); continue; }
+ const sheet = /\.css$/i.test(c.file);
+ const key = waiverKey(c.rule, sheet || ownFile ? oneLine(relPath(c.file, cwd)) : null);
+ if (accepted.has(key)) { refuse(c, 'one waiver per rule'); continue; }
+ if (c.reason.length < WAIVER_MIN_REASON) { refuse(c, `reason under ${WAIVER_MIN_REASON} characters`); continue; }
+ if (reasonIsBoilerplate(c.reason)) { refuse(c, 'boilerplate reason'); continue; }
+ if ((reasons.get(c.reason.toLowerCase()) || 0) > 1) { refuse(c, 'reason reused on another waiver'); continue; }
+ const words = c.reason.toLowerCase().match(/[a-z]{4,}/g) || [];
+ if (pageWords.size && !sheet && !words.some((w) => pageWords.has(w))) { refuse(c, 'reason shares no word with the page'); continue; }
+ accepted.set(key, c.reason);
+ }
+ const rulesWaived = [...new Set([...accepted.keys()].map((k) => k.split('@')[0]))];
+ if (rulesWaived.length > WAIVER_MAX) {
+ rep.report('house-style', claims[0].file, claims[0].line, `${rulesWaived.length} rules waived on one page (${rulesWaived.join(', ')}): that is a house style, not a set of exceptions`,
+ { fix: 'lock the choices into DESIGN.md so later pages inherit them instead of re-arguing them' });
+ }
+ return { accepted, refused: rep.findings };
+}
+
+/** Mark waived ask and polish findings; blocking findings never change, and a claim keyed to its file reaches only findings in that file. Returns the findings plus the refusals. */
+export function applyWaivers(findings: Finding[], set: WaiverSet): Finding[] {
+ const out = findings.map((f) => {
+ const reason = set.accepted.get(f.rule) ?? set.accepted.get(waiverKey(f.rule, f.file));
+ if (f.tier === 'blocks' || reason == null) return f;
+ return { ...f, grade: 'waived' as const, waiver: oneLine(reason) };
+ });
+ return [...out, ...set.refused];
+}
diff --git a/licenses/MIT-hallmark.txt b/licenses/MIT-hallmark.txt
new file mode 100644
index 000000000..f4bfc53d8
--- /dev/null
+++ b/licenses/MIT-hallmark.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Hallmark contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/package.json b/package.json
index 7bc2bfa10..c3f15ac7e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gstack",
- "version": "1.91.250",
+ "version": "1.91.251",
"description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.",
"license": "MIT",
"type": "module",
diff --git a/test/design-lint-assets.test.ts b/test/design-lint-assets.test.ts
new file mode 100644
index 000000000..a73456593
--- /dev/null
+++ b/test/design-lint-assets.test.ts
@@ -0,0 +1,161 @@
+/**
+ * The assets rule family of the design lint (lib/design-lint/rules/assets.ts):
+ * for every rule id, one page that is clean for it and one with the tell
+ * planted, checked by id, grade and line.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { lint } from '../lib/design-lint/index';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Fraunces", serif; --font-body: "Public Sans", sans-serif; }';
+
+function page(css: string, body: string): string {
+ return '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+}
+
+const lineOf = (html: string, needle: string): number => {
+ const at = html.indexOf(needle);
+ if (at < 0) throw new Error('needle not in page: ' + needle);
+ return html.slice(0, at).split('\n').length;
+};
+
+function run(html: string, files: Record<string, string> = {}): Finding[] {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-assets-'));
+ tmpDirs.push(dir);
+ fs.writeFileSync(path.join(dir, 'index.html'), html);
+ for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, name), text);
+ return lintStatic([dir], { cwd: dir, warn: (l) => { throw new Error(l); } }).findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const show = (findings: Finding[]) => findings.map(formatFinding);
+
+describe('design-lint assets: icons (gate 30)', () => {
+ test('emoji-decoration blocks on an emoji standing in for an icon, in a tile, a heading or a component string; an SVG icon is clean', () => {
+ const slop = page('', '<main>\n<div class="feature__icon">\u2728</div>\n<h3>\ud83d\ude80 Ship faster</h3>\n<p>\ud83d\udc4b Welcome aboard</p>\n</main>');
+ const hits = only(run(slop), 'emoji-decoration');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['blocks', lineOf(slop, 'feature__icon')], ['blocks', lineOf(slop, 'Ship faster')], ['blocks', lineOf(slop, 'Welcome aboard')]]);
+ expect(hits[0].evidence).toBe('an emoji icon "\u2728" in <div class="feature__icon">');
+ expect(hits[2].evidence).toContain('text opens with an emoji');
+ const tsx = 'export const Icon = () => <Feature icon="\u2728" title="Sync" />;\n';
+ expect(only(run(page('', '<main><p>Ready.</p></main>'), { 'Feature.tsx': tsx }), 'emoji-decoration').map((f) => [f.file, f.evidence])).toEqual([['Feature.tsx', 'an emoji passed as an icon: \u2728']]);
+ expect(only(run(page('', '<main><div class="feature__icon"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M0 0h16v16H0z"/></svg></div><h3>Ship faster</h3></main>')), 'emoji-decoration')).toEqual([]);
+ });
+
+ test('two-icon-libraries asks when two libraries share a page; one library is clean', () => {
+ const mixed = page('', '<main>\n<i class="lucide lucide-check"></i>\n<svg class="heroicon" aria-hidden="true"></svg>\n</main>');
+ const hits = only(run(mixed), 'two-icon-libraries');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([['ask', 1, 'icon libraries mixed on one page: heroicons and lucide']]);
+ expect(only(run(page('', '<main><i class="lucide lucide-check" aria-hidden="true"></i><i class="lucide lucide-x" aria-hidden="true"></i></main>')), 'two-icon-libraries')).toEqual([]);
+ });
+});
+
+describe('design-lint assets: decoration labels (gate 33)', () => {
+ test('unlabeled-decoration blocks on a bare <svg> or <canvas>; aria-hidden, a label, a <title> or a labelled ancestor is clean', () => {
+ const slop = page('', '<main>\n<svg viewBox="0 0 10 10"><circle r="4"/></svg>\n<canvas width="10" height="10"></canvas>\n</main>');
+ const hits = only(run(slop), 'unlabeled-decoration');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([
+ ['blocks', lineOf(slop, '<svg'), '<svg> with neither aria-hidden="true" nor a label'],
+ ['blocks', lineOf(slop, '<canvas'), '<canvas> with neither aria-hidden="true" nor a label'],
+ ]);
+ const clean = page('', '<main><svg aria-hidden="true" viewBox="0 0 10 10"></svg><svg viewBox="0 0 10 10"><title>The depot</title></svg><a href="/x" aria-label="Home"><svg viewBox="0 0 10 10"></svg></a><canvas role="img" aria-label="Days to close"></canvas></main>');
+ expect(show(only(run(clean), 'unlabeled-decoration'))).toEqual([]);
+ });
+});
+
+describe('design-lint assets: contrast (gates 40, 41)', () => {
+ test('low-contrast lands at ask (the static tier suspects, the render tier proves) for text under its threshold; large text at 3:1 and body text at 4.5:1 are clean', () => {
+ const slop = page('.muted {\n color: #999;\n background: #fff;\n}\n.big { font-size: 32px; color: #767676; background: #fff; }', '<main><p class="muted">Faint</p><p class="big">Large</p></main>');
+ const hits = only(run(slop), 'low-contrast');
+ expect(hits.map((f) => [f.tier, f.grade, f.line])).toEqual([['ask', 'ask', lineOf(slop, 'color: #999')]]);
+ expect(hits[0].evidence).toBe('2.85:1 under the 4.5:1 threshold on .muted');
+ expect(only(run(page('.body { color: #595959; background: #fff; }', '<main><p class="body">Readable</p></main>')), 'low-contrast')).toEqual([]);
+ });
+
+ test('gray-on-color lands at ask for button text within a step of its fill, a dark surface that sets no text colour and a missing accent ink; a paired ink is clean', () => {
+ const slop = page('.btn {\n color: #7a7a7a;\n background-color: #777;\n}\n.panel {\n background: #222;\n padding: 1rem;\n}', '<main><button class="btn">Go</button><section class="panel"><p>Dark</p></section></main>');
+ const hits = only(run(slop), 'gray-on-color');
+ expect(hits.map((f) => [f.tier, f.grade, f.line])).toEqual([['ask', 'ask', lineOf(slop, 'color: #7a7a7a')], ['ask', 'ask', lineOf(slop, 'background: #222')]]);
+ expect(hits[0].evidence).toMatch(/^button text within a step of its fill on \.btn/);
+ expect(hits[1].evidence).toBe('a dark surface (lightness 25%) on .panel sets no text colour');
+ const noInk = page('.btn { background: var(--color-accent); color: white; }', '<main><button class="btn">Go</button></main>').replace('--color-accent-ink: oklch(98% 0.01 30); ', '');
+ expect(only(run(noInk), 'gray-on-color').map((f) => f.evidence)).toEqual(['the accent fills a surface but --color-accent-ink is not defined']);
+ expect(only(run(page('.btn { background: var(--color-accent); color: var(--color-accent-ink); } .panel { background: var(--color-ink); color: var(--color-paper); }', '<main><button class="btn">Go</button><section class="panel"><p>Dark</p></section></main>')), 'gray-on-color')).toEqual([]);
+ });
+});
+
+describe('design-lint assets: labels that wrap (gate 49)', () => {
+ test('button-label-wraps lands at ask for a long button or primary nav label with no nowrap; link-wraps asks for a long footer link; nowrap and short labels are clean', () => {
+ const slop = page('', '<nav><a class="nav__link" href="/reports">Download the complete quarterly report</a></nav>\n<main>\n<button>Download the complete quarterly report</button>\n</main>\n<footer>\n<a href="/privacy">Read the complete privacy and cookie policy</a>\n</footer>');
+ const findings = run(slop);
+ const buttons = only(findings, 'button-label-wraps');
+ expect(buttons.map((f) => [f.tier, f.grade, f.line])).toEqual([['ask', 'ask', lineOf(slop, '<nav>')], ['ask', 'ask', lineOf(slop, '<button>')]]);
+ expect(buttons[1].evidence).toMatch(/^the long label "Download the complete quarterly rep…" on <button> can wrap, and nothing sets nowrap$/);
+ const links = only(findings, 'link-wraps');
+ expect(links.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(slop, 'href="/privacy"')]]);
+ const clean = run(page('button, .nav__link { white-space: nowrap; }', '<nav><a class="nav__link" href="/reports">Download the complete quarterly report</a></nav><main><button>Download the complete quarterly report</button></main><footer><a href="/privacy">Privacy</a></footer>'));
+ expect(only(clean, 'button-label-wraps')).toEqual([]);
+ expect(only(clean, 'link-wraps')).toEqual([]);
+ });
+});
+
+describe('design-lint assets: images (gate 76)', () => {
+ test('broken-image blocks on an <img> with no source; srcset or data-src counts as a source', () => {
+ const slop = page('', '<main>\n<img alt="The depot">\n<img src="#" alt="Also empty">\n</main>');
+ const hits = only(run(slop), 'broken-image');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', lineOf(slop, '<img alt'), 'an <img> with no source']]);
+ expect(only(run(page('', '<main><img src="depot.jpg" alt="The depot"><img srcset="a.jpg 1x" alt="Lazy"></main>')), 'broken-image')).toEqual([]);
+ });
+
+ test('stock-photo-hotlink blocks on an Unsplash+ photo and lands at ask for a free stock hotlink; a local photograph is clean', () => {
+ const slop = page('', '<main>\n<img src="https://plus.unsplash.com/premium_photo-1661 ?w=800" alt="Paid">\n<img src="https://images.pexels.com/photos/12345/pexels-photo.jpeg" alt="Free">\n</main>');
+ const hits = only(run(slop), 'stock-photo-hotlink').sort((a, b) => a.line - b.line);
+ expect(hits.map((f) => [f.tier, f.grade, f.line])).toEqual([['blocks', 'blocks', lineOf(slop, 'premium_photo')], ['ask', 'ask', lineOf(slop, 'pexels')]]);
+ expect(hits[0].evidence).toBe('an Unsplash+ photo hotlinked, which needs a paid licence');
+ expect(hits[1].evidence).toBe('a photo hotlinked from Pexels, whose terms bar images picked by an AI tool');
+ expect(only(run(page('', '<main><img src="/img/depot-1280.jpg" alt="The depot"></main>')), 'stock-photo-hotlink')).toEqual([]);
+ });
+});
+
+describe('design-lint assets: fixtures', () => {
+ test('the clean page raises nothing from this family; slopped.html plants the emoji icon and the bare svg', async () => {
+ const assets = new Set(['emoji-decoration', 'two-icon-libraries', 'unlabeled-decoration', 'low-contrast', 'gray-on-color', 'button-label-wraps', 'link-wraps', 'broken-image', 'stock-photo-hotlink']);
+ const clean = await lint([path.join(FIXTURES, 'clean')], { cwd: ROOT });
+ expect(show(clean.findings.filter((f) => assets.has(f.rule)))).toEqual([]);
+ const slopped = await lint([path.join(FIXTURES, 'slopped.html')], { cwd: ROOT });
+ expect(only(slopped.findings, 'emoji-decoration').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', 126, 'an emoji icon "\u2728" in <div class="feature__icon">']]);
+ expect(only(slopped.findings, 'unlabeled-decoration').map((f) => [f.grade, f.line])).toEqual([['blocks', 114]]);
+ });
+});
+
+describe('design-lint assets: third review cycle', () => {
+ test('large text passes at 3:1 and the same colour on body text asks; body text at the 4.5:1 edge is clean', () => {
+ const big = page('.big { font-size: 32px; color: #959595; background: #fff; }', '<main><p class="big">Large text at three to one</p></main>');
+ expect(only(run(big), 'low-contrast')).toEqual([]);
+ const small = page('.small { font-size: 16px; color: #959595; background: #fff; }', '<main><p class="small">Body text at three to one</p></main>');
+ expect(only(run(small), 'low-contrast').map((f) => [f.grade, f.evidence])).toEqual([['ask', '3.00:1 under the 4.5:1 threshold on .small']]);
+ expect(only(run(page('.body { color: #767676; background: #fff; }', '<main><p class="body">Readable</p></main>')), 'low-contrast')).toEqual([]);
+ });
+ test('two-icon-libraries reads class tokens and asset references, not prose: feather-light and bi-weekly are words', () => {
+ const prose = page('', '<main><i class="fa-solid fa-star"></i><p>A feather-light app with our bi-weekly newsletter.</p></main>');
+ expect(only(run(prose), 'two-icon-libraries')).toEqual([]);
+ const mixed = page('', '<main><i class="fa-solid fa-star"></i><i class="bi-star"></i></main>');
+ expect(only(run(mixed), 'two-icon-libraries').map((f) => f.evidence)).toEqual(['icon libraries mixed on one page: font-awesome and bootstrap-icons']);
+ const linked = page('', '<main><i class="fa-solid fa-star"></i><script src="https://unpkg.com/feather-icons"></script></main>');
+ expect(only(run(linked), 'two-icon-libraries').map((f) => f.evidence)).toEqual(['icon libraries mixed on one page: font-awesome and feather']);
+ });
+ test('an svg inside a labelled list item whose end tag is left out is still labelled', () => {
+ const f = run(page('', '<main><ul><li aria-label="Home"><svg viewBox="0 0 10 10"></svg><li aria-label="Away"><svg viewBox="0 0 10 10"></svg></ul></main>'));
+ expect(only(f, 'unlabeled-decoration')).toEqual([]);
+ });
+});
diff --git a/test/design-lint-chrome.test.ts b/test/design-lint-chrome.test.ts
new file mode 100644
index 000000000..38ed7bac0
--- /dev/null
+++ b/test/design-lint-chrome.test.ts
@@ -0,0 +1,269 @@
+/**
+ * The chrome rule family of the design lint (lib/design-lint/rules/chrome.ts,
+ * chrome-copy.ts, chrome-eyebrow.ts): for every rule id, one page that is
+ * clean for it and one with the tell planted, checked by id, grade and line.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { lint } from '../lib/design-lint/index';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Fraunces", serif; --font-body: "Public Sans", sans-serif; }';
+
+/** A page with the css in one <style> and the body as given; the tokens block keeps the other families quiet where it can. */
+function page(css: string, body: string): string {
+ return '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+}
+
+const lineOf = (html: string, needle: string): number => {
+ const at = html.indexOf(needle);
+ if (at < 0) throw new Error('needle not in page: ' + needle);
+ return html.slice(0, at).split('\n').length;
+};
+
+function run(html: string, opts: { job?: string | null; scope?: 'page' | 'component'; files?: Record<string, string> } = {}): Finding[] {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-chrome-'));
+ tmpDirs.push(dir);
+ const { files = {}, ...rest } = opts;
+ fs.writeFileSync(path.join(dir, 'index.html'), html);
+ for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, name), text);
+ return lintStatic([dir], { cwd: dir, warn: (l) => { throw new Error(l); }, ...rest }).findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const show = (findings: Finding[]) => findings.map(formatFinding);
+
+describe('design-lint chrome: copy (gate 19)', () => {
+ test('aphoristic-cadence: the rebuttal cadence three times blocks; once is voice', () => {
+ const tic = page('', '<main>\n<p>Ship it. Not a feature. A platform. Fast. Not a tool. A system. Clean. Not a demo. A product.</p>\n</main>');
+ const hits = only(run(tic), 'aphoristic-cadence');
+ expect(show(hits)).toHaveLength(1);
+ expect(hits[0].grade).toBe('blocks');
+ expect(hits[0].line).toBe(lineOf(tic, 'Not a feature'));
+ expect(hits[0].evidence).toContain('3 times');
+ expect(only(run(page('', '<main><p>Not a feature. A platform. The ledger closes on the second of the month.</p></main>')), 'aphoristic-cadence')).toEqual([]);
+ });
+
+ test('generic-hero-copy: a filler opener, the quiet-proof line and the Meet heading block; plain prose is clean', () => {
+ const slop = page('', '<main>\n<h1>Built for the modern team</h1>\n<p>Quietly trusted by the people who ship.</p>\n<h2>Meet Ledgerline</h2>\n</main>');
+ const hits = only(run(slop), 'generic-hero-copy');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['blocks', lineOf(slop, 'Built for')], ['blocks', lineOf(slop, 'Quietly')], ['blocks', lineOf(slop, 'Meet ')]]);
+ expect(hits[0].evidence).toContain('a filler opener');
+ expect(only(run(page('', '<main><h1>October closed in two days</h1><p>Halvorsen Freight reconciles 1,140 invoices a month.</p></main>')), 'generic-hero-copy')).toEqual([]);
+ });
+
+ test('generic-cta-copy: the stock second action beside a filled primary asks, and so do two "Learn more" links; a second action that names its destination is clean', () => {
+ const css = '.btn { background: var(--color-accent); color: var(--color-accent-ink); } .cta-quiet { color: var(--color-ink); }';
+ const stock = page(css, '<section class="hero">\n<h1>October closed in two days</h1>\n<a class="btn" href="/book">Book the walkthrough</a>\n<a class="cta-quiet" href="/tour">Learn more</a>\n</section>');
+ const hits = only(run(stock), 'generic-cta-copy');
+ expect(show(hits)).toHaveLength(1);
+ expect(hits[0].grade).toBe('ask');
+ expect(hits[0].line).toBe(lineOf(stock, 'Learn more'));
+ const links = page(css, '<main>\n<p><a href="/a">Read more</a></p>\n<p><a href="/b">Read more</a></p>\n</main>');
+ const linkHits = only(run(links), 'generic-cta-copy');
+ expect(linkHits.map((f) => f.line)).toEqual([lineOf(links, '<a href="/a">')]);
+ expect(linkHits[0].evidence).toContain('on 2 links');
+ const named = page(css, '<section class="hero"><h1>October closed in two days</h1><a class="btn" href="/book">Book the walkthrough</a><a class="cta-quiet" href="/method">Read how the close works</a></section>');
+ expect(only(run(named), 'generic-cta-copy')).toEqual([]);
+ });
+
+ test('em-dash-overuse: three dashes ask with the count; two are not overuse', () => {
+ const dashy = page('', '<main>\n<p>The close ran in two days \u2014 not nine \u2014 and the review \u2013 the slow part \u2014 started on the first.</p>\n</main>');
+ const hits = only(run(dashy), 'em-dash-overuse');
+ expect(show(hits)).toHaveLength(1);
+ expect(hits[0].grade).toBe('ask');
+ expect(hits[0].line).toBe(lineOf(dashy, 'two days'));
+ expect(hits[0].evidence).toMatch(/^4 dashes/);
+ expect(only(run(page('', '<main><p>The close ran in two days \u2014 not nine \u2014 and the review started on the first.</p></main>')), 'em-dash-overuse')).toEqual([]);
+ });
+
+ test('template-footer-line: "All rights reserved" asks; the page\'s own footer line is clean', () => {
+ const stock = page('', '<main><h1>Ledgerline</h1></main>\n<footer>\n<p>&copy; 2026 Ledgerline. All rights reserved.</p>\n</footer>');
+ const hits = only(run(stock), 'template-footer-line');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(stock, 'All rights')]]);
+ expect(only(run(page('', '<footer><p>Ledgerline, Bergen. Photographs by Halvorsen Freight.</p></footer>')), 'template-footer-line')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: the reflex nav and footer (gate 42)', () => {
+ test('template-nav: four to six inline links, a button and a 1px hairline ask; three links and no hairline are clean', () => {
+ const css = 'nav { display: flex; border-bottom: 1px solid var(--color-muted); }';
+ const reflex = page(css, '<nav class="nav">\n<a href="/">Ledgerline</a><a href="/method">Method</a><a href="/pricing">Pricing</a><a href="/customers">Customers</a><a href="/docs">Docs</a>\n<a class="btn" href="/book">Book</a>\n</nav>\n<main><h1>Ledgerline</h1></main>');
+ const hits = only(run(reflex), 'template-nav');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(reflex, '<nav')]]);
+ expect(hits[0].evidence).toBe('the reflex nav shape: 6 inline links, a button and a 1px hairline under');
+ expect(only(run(page('nav { display: flex; }', '<nav><a href="/">Ledgerline</a><a href="/method">Method</a><a href="/pricing">Pricing</a></nav><main><h1>Ledgerline</h1></main>')), 'template-nav')).toEqual([]);
+ expect(only(run(reflex, { scope: 'component' }), 'template-nav')).toEqual([]);
+ });
+
+ test('template-footer: four link columns ask; a one-line footer is clean', () => {
+ const col = '<ul><li><a href="/a">A</a></li><li><a href="/b">B</a></li><li><a href="/c">C</a></li></ul>';
+ const reflex = page('', '<main><h1>Ledgerline</h1></main>\n<footer>\n' + col + '\n' + col + '\n' + col + '\n' + col + '\n</footer>');
+ const hits = only(run(reflex), 'template-footer');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(reflex, '<footer')]]);
+ expect(hits[0].evidence).toContain('4 link columns');
+ expect(only(run(page('', '<footer><p>Ledgerline, Bergen.</p></footer>')), 'template-footer')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: proof, drawn chrome and material (gates 46a, 47)', () => {
+ test('invented-proof: a metric the page cannot source lands at ask for a person to confirm; a plain count is clean', () => {
+ const slop = page('', '<main>\n<p>Trusted by 50,000+ teams shipping 10x faster.</p>\n</main>');
+ const hits = only(run(slop), 'invented-proof');
+ expect(hits.map((f) => [f.tier, f.grade, f.line])).toEqual([['ask', 'ask', lineOf(slop, 'Trusted by')]]);
+ expect(only(run(page('', '<main><p>Halvorsen Freight reconciles 1,140 invoices a month.</p></main>')), 'invented-proof')).toEqual([]);
+ });
+
+ test('drawn-browser-chrome blocks on a traffic-light bar class or selector; device-frame asks on a phone frame; a real figure is clean', () => {
+ const drawn = page('.window-frame { border: 1px solid var(--color-muted); }', '<main>\n<div class="browser-bar"><span class="dot"></span></div>\n<div class="phone-frame"></div>\n</main>');
+ const findings = run(drawn);
+ const bar = only(findings, 'drawn-browser-chrome');
+ expect(bar.map((f) => [f.grade, f.line])).toEqual([['blocks', lineOf(drawn, 'browser-bar')]]);
+ expect(bar[0].evidence).toContain('class "browser-bar"');
+ const frame = only(findings, 'device-frame');
+ expect(frame.map((f) => [f.grade, f.line]).sort((a, b) => Number(a[1]) - Number(b[1]))).toEqual([['ask', lineOf(drawn, '.window-frame')], ['ask', lineOf(drawn, 'phone-frame"')]]);
+ const clean = run(page('', '<main><figure><img src="shot.png" alt="The close screen"><figcaption>The close screen.</figcaption></figure></main>'));
+ expect(only(clean, 'drawn-browser-chrome')).toEqual([]);
+ expect(only(clean, 'device-frame')).toEqual([]);
+ });
+
+ test('imitation-material: a placeholder image service asks, in markup or CSS; a real asset is clean', () => {
+ const fake = page('', '<main>\n<img src="https://via.placeholder.com/300" alt="">\n</main>').replace('<style>', '<link rel="stylesheet" href="style.css"><style>');
+ const css = '.hero {\n background: url(https://placehold.co/600x400);\n}\n';
+ const hits = only(run(fake, { files: { 'style.css': css } }), 'imitation-material');
+ expect(hits.map((f) => [f.grade, f.file, f.line]).sort((a, b) => String(a[1]).localeCompare(String(b[1])))).toEqual([['ask', 'index.html', lineOf(fake, 'via.placeholder')], ['ask', 'style.css', 2]]);
+ expect(hits[0].evidence).toMatch(/^a placeholder image service \((placehold\.co|via\.placeholder\.com)\) stands in for a picture$/);
+ expect(only(run(page('', '<main><img src="shot.png" alt="The close screen"></main>')), 'imitation-material')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: the eyebrow (gate 54)', () => {
+ test('kicker-above-heading asks on a labelled span before a heading and on a section labelled by a non-heading; a figcaption before a heading is clean', () => {
+ const slop = page('.eyebrow { text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.1em; }', '<main>\n<section>\n<div>\n<span class="eyebrow">01 / Features</span>\n<h2>What it does</h2>\n</div>\n</section>\n<section aria-labelledby="plans">\n<p id="plans" class="eyebrow">Plans</p>\n<p>Three plans, one ledger.</p>\n</section>\n</main>');
+ const hits = only(run(slop), 'kicker-above-heading');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(slop, '<span class="eyebrow">')], ['ask', lineOf(slop, 'id="plans"')]]);
+ expect(hits[0].evidence).toBe('the eyebrow "01 / Features" before <h2>');
+ expect(hits[1].evidence).toContain('labelled by <p>');
+ expect(only(run(page('', '<main><figure><figcaption>Plate 4</figcaption><h3>Off the grid</h3></figure></main>')), 'kicker-above-heading')).toEqual([]);
+ expect(only(run(slop, { scope: 'component' }), 'kicker-above-heading')).toEqual([]);
+ });
+
+ test('the eyebrow fixtures: six on eyebrow-fail, none on eyebrow-pass', async () => {
+ const fail = await lint([path.join(FIXTURES, 'eyebrow-fail')], { cwd: ROOT });
+ expect(only(fail.findings, 'kicker-above-heading').map((f) => f.line)).toEqual([65, 74, 83, 92, 101, 110]);
+ const pass = await lint([path.join(FIXTURES, 'eyebrow-pass')], { cwd: ROOT });
+ expect(show(only(pass.findings, 'kicker-above-heading'))).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: punctuation, slots, echoes and sends (gates 63, 68, 69, 70)', () => {
+ test('template-punctuation blocks on middle-dot meta strings, a glued arrow and three decorative dots; one dot in a byline is clean', () => {
+ const slop = page('', '<main>\n<p class="meta">Design \u00b7 12 min read \u00b7 March</p>\n<a href="/method">Learn how it works \u2192</a>\n<ul><li><span class="dot"></span>Live</li><li><span class="dot"></span>Beta</li><li><span class="dot"></span>Soon</li></ul>\n</main>');
+ const hits = only(run(slop), 'template-punctuation');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['blocks', lineOf(slop, 'class="meta"')], ['blocks', lineOf(slop, '<a href="/method">')], ['blocks', lineOf(slop, '<ul>')]]);
+ expect(hits.map((f) => f.evidence.split(':')[0].split(' "')[0])).toEqual(['middle dots join a meta string', 'an arrow glued to the label', 'decorative status dots (dot) repeated across the page']);
+ expect(only(run(page('', '<main><p class="byline">Marta Silveira \u00b7 14 March 2026</p><a href="/method">Read the method</a></main>')), 'template-punctuation')).toEqual([]);
+ });
+
+ test('wireframe-slots asks past five empty slots on a page and at four in one row; two slots holding pictures are clean', () => {
+ const slots = (n: number) => Array.from({ length: n }, (_, i) => '<div data-slot="s' + i + '"></div>').join('\n');
+ const many = page('', '<main>\n<section class="team">\n' + slots(6) + '\n</section>\n</main>');
+ const hits = only(run(many), 'wireframe-slots');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([
+ ['ask', lineOf(many, 'data-slot="s5"'), '6 empty slots on one page'],
+ ['ask', lineOf(many, '<section class="team">'), '6 empty slots in one row or grid'],
+ ]);
+ const row = page('', '<main><section><div class="row">\n' + slots(4) + '\n</div></section></main>');
+ expect(only(run(row), 'wireframe-slots').map((f) => f.evidence)).toEqual(['4 empty slots in one row or grid']);
+ expect(only(run(page('', '<main><div data-slot="a"><img src="a.jpg" alt="Mari"></div><div data-slot="b"><img src="b.jpg" alt="Depot"></div></main>')), 'wireframe-slots')).toEqual([]);
+ });
+
+ test('repeated-fact asks when one fact is printed in four sections; the same fact twice is clean', () => {
+ const band = (i: number) => '<section id="s' + i + '"><p>From $49 a month.</p></section>';
+ const echo = page('', '<main>\n' + [1, 2, 3, 4].map(band).join('\n') + '\n</main>');
+ const hits = only(run(echo), 'repeated-fact');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([['ask', 1, 'the same fact printed in 4 sections: $49 (4)']]);
+ expect(only(run(page('', '<main>' + [1, 2].map(band).join('') + '</main>')), 'repeated-fact')).toEqual([]);
+ });
+
+ test('fake-send lands at ask when a script prints success with no request behind it; the same script with fetch() is clean', () => {
+ const script = (send: string) => '<main>\n<form id="f"><input type="email" name="email"><button>Join</button></form>\n<script>\ndocument.getElementById("f").addEventListener("submit", (e) => {\n e.preventDefault();\n ' + send + '\n document.getElementById("f").textContent = "Thanks, you are on the list";\n});\n</script>\n</main>';
+ const fake = page('', script(''));
+ const hits = only(run(fake), 'fake-send');
+ expect(hits.map((f) => [f.tier, f.grade, f.line])).toEqual([['ask', 'ask', lineOf(fake, '"Thanks, you are')]]);
+ expect(hits[0].evidence).toContain('a script prints success');
+ expect(only(run(page('', script('fetch("/api/join", { method: "POST", body: new FormData(e.target) });'))), 'fake-send')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: the email band close (gate 85)', () => {
+ const signup = '<form class="newsletter">\n<label for="e">Email</label><input id="e" type="email" name="email"><button>Subscribe</button>\n</form>';
+ test('email-band-close asks when the last section before the footer is an email sign-up and no job was named; a subscribe job, a booking form and a component context are clean', () => {
+ const close = page('', '<main>\n<section class="story"><h2>Where the seven days went</h2><p>Three days were matching receipts.</p></section>\n<section class="band">\n' + signup + '\n</section>\n</main>\n<footer><p>Ledgerline, Bergen.</p></footer>');
+ const hits = only(run(close), 'email-band-close');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(close, '<form class="newsletter">')]]);
+ expect(hits[0].evidence).toBe('the page closes on an email sign-up <form class="newsletter"> as its last section, and no job was named (--job)');
+ expect(only(run(close, { job: 'buy' }), 'email-band-close')[0].evidence).toContain('on a buy page');
+ expect(only(run(close, { job: 'subscribe' }), 'email-band-close')).toEqual([]);
+ expect(only(run(close, { scope: 'component' }), 'email-band-close')).toEqual([]);
+ const footerForm = page('', '<main><section class="story"><h2>Where the seven days went</h2></section></main>\n<footer>\n' + signup + '\n</footer>');
+ expect(only(run(footerForm), 'email-band-close')[0].evidence).toContain('in the footer');
+ const booking = page('', '<main><section class="close"><form><input type="email" name="email"><button>Book the walkthrough</button></form></section></main><footer><p>Ledgerline, Bergen.</p></footer>');
+ expect(only(run(booking), 'email-band-close')).toEqual([]);
+ const notLast = page('', '<main><section class="band">' + signup + '</section><section class="close"><h2>See your own close</h2><a href="/book">Book the walkthrough</a></section></main><footer><p>Ledgerline, Bergen.</p></footer>');
+ expect(only(run(notLast), 'email-band-close')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: two filled buttons in the hero (F4 half)', () => {
+ test('two-primary-buttons prints at polish for two filled buttons side by side in the hero; a filled primary beside a quiet link is clean', () => {
+ const css = '.btn { background: var(--color-accent); color: var(--color-accent-ink); } .quiet { color: var(--color-ink); text-decoration: underline; }';
+ const two = page(css, '<section class="hero">\n<h1>October closed in two days</h1>\n<a class="btn" href="/book">Book the walkthrough</a>\n<a class="btn" href="/tour">Take the tour</a>\n</section>');
+ const hits = only(run(two), 'two-primary-buttons');
+ expect(hits.map((f) => [f.grade, f.line])).toEqual([['polish', lineOf(two, 'Take the tour')]]);
+ expect(hits[0].evidence).toBe('two filled buttons side by side in the hero: "Book the walkthrough" and "Take the tour"');
+ expect(only(run(page(css, '<section class="hero"><h1>October closed in two days</h1><a class="btn" href="/book">Book the walkthrough</a><a class="quiet" href="/method">Read how the close works</a></section>')), 'two-primary-buttons')).toEqual([]);
+ });
+});
+
+describe('design-lint chrome: fixtures', () => {
+ test('the clean page raises nothing from this family; slopped.html plants the invented metric and the eyebrow', async () => {
+ const chrome = new Set(['aphoristic-cadence', 'generic-hero-copy', 'generic-cta-copy', 'em-dash-overuse', 'template-footer-line', 'template-nav', 'template-footer', 'invented-proof', 'drawn-browser-chrome', 'device-frame', 'imitation-material', 'kicker-above-heading', 'template-punctuation', 'wireframe-slots', 'repeated-fact', 'fake-send', 'email-band-close']);
+ const clean = await lint([path.join(FIXTURES, 'clean')], { cwd: ROOT });
+ expect(show(clean.findings.filter((f) => chrome.has(f.rule)))).toEqual([]);
+ const slopped = await lint([path.join(FIXTURES, 'slopped.html')], { cwd: ROOT });
+ expect(only(slopped.findings, 'invented-proof').map((f) => [f.grade, f.line])).toEqual([['ask', 113]]);
+ expect(only(slopped.findings, 'kicker-above-heading').map((f) => [f.grade, f.line, f.evidence])).toEqual([['ask', 120, 'the eyebrow "01 / FEATURES" before <h2>']]);
+ });
+});
+
+describe('design-lint chrome: third review cycle', () => {
+ test('repeated-fact counts a percentage printed in four sections', () => {
+ const band = (i: number) => '<section id="s' + i + '"><p>Save 30% off this month.</p></section>';
+ const hits = only(run(page('', '<main>\n' + [1, 2, 3, 4].map(band).join('\n') + '\n</main>')), 'repeated-fact');
+ expect(hits.map((f) => [f.grade, f.evidence])).toEqual([['ask', 'the same fact printed in 4 sections: 30% (4)']]);
+ });
+ test('a stock line in the hero blocks; the same line in body copy below the hero is suspected, so it sits at ask and a waiver can answer it', () => {
+ const inHero = page('', '<main>\n<header class="hero"><h1>Ledger</h1><p>Everything you need to close the month.</p></header>\n<section><h2>Notes</h2><p>The books close on the first.</p></section>\n</main>');
+ expect(only(run(inHero), 'generic-hero-copy').map((f) => [f.grade, f.line])).toEqual([['blocks', lineOf(inHero, 'Everything you need')]]);
+ const below = page('', '<main>\n<header class="hero"><h1>Ledger</h1><p>The books close on the first.</p></header>\n<section><h2>Help</h2><p>Whether you\'re logged in or not, your cart stays.</p></section>\n</main>');
+ expect(only(run(below), 'generic-hero-copy').map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(below, 'Whether you')]]);
+ const waived = run('<!-- gstack-lint-disable generic-hero-copy: the help page quotes the cart notice word for word -->\n' + below);
+ expect(only(waived, 'generic-hero-copy').map((f) => f.grade)).toEqual(['waived']);
+ expect(only(waived, 'waiver')).toEqual([]);
+ });
+ test('a region whose list items leave their end tags out still counts facts per section', () => {
+ const band = (i: number) => '<section id="s' + i + '"><ul><li>From $49 a month.<li>Second item</ul></section>';
+ const hits = only(run(page('', '<main>\n' + [1, 2, 3, 4].map(band).join('\n') + '\n</main>')), 'repeated-fact');
+ expect(hits.map((f) => f.evidence)).toEqual(['the same fact printed in 4 sections: $49 (4)']);
+ });
+});
diff --git a/test/design-lint-color.test.ts b/test/design-lint-color.test.ts
new file mode 100644
index 000000000..9f1e4f4a2
--- /dev/null
+++ b/test/design-lint-color.test.ts
@@ -0,0 +1,211 @@
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+/** 1-based line of the first line holding the needle. */
+const lineOf = (text: string, needle: string): number => {
+ const i = text.indexOf(needle);
+ if (i < 0) throw new Error(`needle not in page: ${needle}`);
+ return text.slice(0, i).split('\n').length;
+};
+
+const TOKENS = `:root {
+ --color-paper: oklch(97% 0.01 250);
+ --color-ink: oklch(20% 0.02 250);
+ --color-muted: oklch(45% 0.02 250);
+ --color-accent: oklch(55% 0.15 250);
+ --color-accent-ink: oklch(98% 0.01 250);
+ --font-display: "Literata", Georgia, serif;
+ --font-body: "Public Sans", sans-serif;
+}`;
+
+/** A page whose <style> holds the tokens and the css, and whose <body> holds the markup. */
+const page = (css: string, body = '<h1>Ledger</h1><p>The books close on the first.</p>', tokens = TOKENS): string =>
+ `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Ledger</title>\n<style>\n${tokens}\n${css}\n</style>\n</head>\n<body>\n${body}\n</body>\n</html>\n`;
+
+function lintPage(html: string, name = 'index.html'): { html: string; findings: Finding[]; dir: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-color-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, name);
+ fs.writeFileSync(file, html);
+ return { html, dir, findings: lintStatic([file], { cwd: dir, warn: (l) => { throw new Error(l); } }).findings };
+}
+
+const byRule = (findings: Finding[], rule: string): Finding[] => findings.filter((f) => f.rule === rule);
+const lines = (findings: Finding[]): string[] => findings.map(formatFinding);
+
+describe('design-lint colour: purple-blue-gradient (2a, blocks)', () => {
+ test('a single-hue ramp and a repeating pattern are not findings', () => {
+ const { findings } = lintPage(page('.band { background: linear-gradient(90deg, oklch(60% 0.2 250), oklch(75% 0.15 250)); }\n.grain { background: repeating-linear-gradient(45deg, oklch(60% 0.2 300) 0 2px, oklch(60% 0.2 240) 2px 4px); }'));
+ expect(lines(byRule(findings, 'purple-blue-gradient'))).toEqual([]);
+ });
+ test('purple to blue on a band, purple to pink as text, and cyan on dark paper each block at the declaration', () => {
+ const band = lintPage(page('.band { background: linear-gradient(90deg, oklch(60% 0.2 300), oklch(60% 0.2 240)); }'));
+ const f = byRule(band.findings, 'purple-blue-gradient');
+ expect(f.map((x) => [x.grade, x.line, x.evidence, x.fix])).toEqual([['blocks', lineOf(band.html, '.band {'), 'purple-to-blue gradient on .band', 'one anchor hue; drop the gradient']]);
+ const text = lintPage(page('h1 {\n background: linear-gradient(90deg, oklch(60% 0.2 300), oklch(65% 0.2 350));\n -webkit-background-clip: text;\n color: transparent;\n}'));
+ expect(byRule(text.findings, 'purple-blue-gradient').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(text.html, '-webkit-background-clip'), 'purple-to-pink gradient text on h1']]);
+ expect(byRule(text.findings, 'gradient-text')).toEqual([]);
+ const dark = TOKENS.replace('--color-paper: oklch(97% 0.01 250)', '--color-paper: oklch(18% 0.02 250)');
+ const cyan = lintPage(page('.glow { background: radial-gradient(circle, oklch(70% 0.15 200), transparent); }', undefined, dark));
+ expect(byRule(cyan.findings, 'purple-blue-gradient').map((x) => x.evidence)).toEqual(['cyan-on-dark gradient on .glow']);
+ const light = lintPage(page('.glow { background: radial-gradient(circle, oklch(70% 0.15 200), transparent); }'));
+ expect(byRule(light.findings, 'purple-blue-gradient')).toEqual([]);
+ });
+});
+
+describe('design-lint colour: gradient-text (2b, ask)', () => {
+ test('a solid heading is clean', () => {
+ const { findings } = lintPage(page('h1 { color: var(--color-ink); }'));
+ expect(byRule(findings, 'gradient-text')).toEqual([]);
+ });
+ test('text clipped to a one-hue ramp asks at the background-clip line', () => {
+ const { html, findings } = lintPage(page('h1 {\n background: linear-gradient(90deg, oklch(60% 0.2 250), oklch(70% 0.15 250));\n background-clip: text;\n color: transparent;\n}'));
+ expect(byRule(findings, 'gradient-text').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'background-clip: text'), 'gradient text on h1']]);
+ });
+});
+
+describe('design-lint colour: pure-black-white (7a, blocks) and absolute-surface-token (7b, ask)', () => {
+ test('tinted ink and paper, and a translucent white, are clean', () => {
+ const { findings } = lintPage(page('.card { color: oklch(10% 0.02 250); background: rgb(255 255 255 / 0.6); border-color: oklch(99% 0.005 250); }'));
+ expect(lines([...byRule(findings, 'pure-black-white'), ...byRule(findings, 'absolute-surface-token')])).toEqual([]);
+ });
+ test('#000 written on a rule blocks; a token that resolves to pure white asks, as does every use of it', () => {
+ const { html, findings } = lintPage(page('.card { color: #000; }\n.panel { background: var(--color-sheet); }', undefined, TOKENS + '\n:root { --color-sheet: #ffffff; }'));
+ expect(byRule(findings, 'pure-black-white').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(html, '.card {'), 'color: #000 on .card is pure black (#000)']]);
+ expect(byRule(findings, 'absolute-surface-token').map((x) => [x.grade, x.line, x.evidence])).toEqual([
+ ['ask', lineOf(html, '--color-sheet: #ffffff'), '--color-sheet: #ffffff on :root is pure white (#fff)'],
+ ['ask', lineOf(html, '.panel {'), 'background: var(--color-sheet) on .panel is pure white (#fff)'],
+ ]);
+ });
+});
+
+describe('design-lint colour: zero-chroma-neutrals (22, ask)', () => {
+ test('a neutral with chroma, a translucent grey and a filter value are clean', () => {
+ const { findings } = lintPage(page('.rule { border-color: oklch(85% 0.005 250); background: oklch(50% 0 0 / 0.4); filter: drop-shadow(0 1px oklch(50% 0 0)); }'));
+ expect(byRule(findings, 'zero-chroma-neutrals')).toEqual([]);
+ });
+ test('a zero-chroma oklch token asks at its line', () => {
+ const { html, findings } = lintPage(page('.rule { border-color: var(--color-gray); }', undefined, TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }'));
+ expect(byRule(findings, 'zero-chroma-neutrals').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, '--color-gray:'), 'zero-chroma oklch(55% 0 0) as --color-gray on :root']]);
+ });
+});
+
+describe('design-lint colour: accent-footprint (23, ask)', () => {
+ test('the accent on a button, a faint accent wash and a soft token are clean', () => {
+ const { findings } = lintPage(page('.button { background: var(--color-accent); }\nsection.hero { background: var(--color-accent-soft); }\n.band { background: oklch(from var(--color-accent) l c h / 0.1); }\n.stat { color: var(--color-accent); font-size: 1.5rem; }'));
+ expect(byRule(findings, 'accent-footprint')).toEqual([]);
+ });
+ test('an accent fill on a surface or a tall block, and display-size accent text, each ask with a specific fix', () => {
+ const { html, findings } = lintPage(page('section.hero { background: var(--color-accent); }\n.tall { min-height: 50vh; background: var(--color-accent); }\n.stat { color: var(--color-accent); font-size: clamp(2rem, 5vw, 4rem); }'));
+ expect(byRule(findings, 'accent-footprint').map((x) => [x.grade, x.line, x.evidence, x.fix])).toEqual([
+ ['ask', lineOf(html, 'section.hero {'), 'accent background on the viewport-scale rule "section.hero"', 'retreat the accent to actions and one signal; a large fill belongs to the paper or a field token'],
+ ['ask', lineOf(html, '.tall {'), 'accent background on the viewport-scale rule ".tall"', 'retreat the accent to actions and one signal; a large fill belongs to the paper or a field token'],
+ ['ask', lineOf(html, '.stat {'), 'display-size text set in the accent on ".stat"', 'set display type in ink; the accent marks small signals'],
+ ]);
+ });
+});
+
+describe('design-lint colour: glow-wash (29, ask)', () => {
+ test('an offset neutral shadow, a mild blur and an opaque backdrop are clean', () => {
+ const { findings } = lintPage(page('.card { box-shadow: 0 4px 24px oklch(20% 0.02 250 / 0.2); }\n.hero::before { position: absolute; filter: blur(20px); }\n.nav { backdrop-filter: blur(12px); background: var(--color-paper); }'));
+ expect(byRule(findings, 'glow-wash')).toEqual([]);
+ });
+ test('a glass panel, a coloured zero-offset glow and a blurred orb each ask once', () => {
+ const { html, findings } = lintPage(page('.nav {\n backdrop-filter: blur(12px);\n background: rgb(255 255 255 / 0.1);\n}\n.button { box-shadow: 0 0 40px oklch(60% 0.2 300), 0 0 60px oklch(60% 0.2 300); }\n.hero::before {\n position: absolute;\n filter: blur(80px);\n}'));
+ expect(byRule(findings, 'glow-wash').map((x) => [x.grade, x.line, x.evidence, x.fix])).toEqual([
+ ['ask', lineOf(html, 'backdrop-filter: blur(12px)'), 'glass panel: backdrop-filter blur over a translucent white on .nav', 'a solid or grained surface; elevation by lightness'],
+ ['ask', lineOf(html, '.button {'), 'coloured zero-offset glow (blur 40px) on .button', 'shadows carry offset and blur in a neutral; colour is not depth'],
+ ['ask', lineOf(html, 'filter: blur(80px)'), 'blurred orb: filter blur(80px) on the positioned .hero::before', 'delete the wash; a surface is paper or ground, not a light show'],
+ ]);
+ });
+});
+
+describe('design-lint colour: cream-palette (65, ask)', () => {
+ const cream = TOKENS.replace('--color-paper: oklch(97% 0.01 250)', '--color-paper: oklch(97% 0.012 80)').replace('--color-accent: oklch(55% 0.15 250)', '--color-accent: oklch(52% 0.16 30)');
+ test('cream paper and a clay accent under a display face that is not a high-contrast serif are clean', () => {
+ const { findings } = lintPage(page('', undefined, cream));
+ expect(byRule(findings, 'cream-palette')).toEqual([]);
+ });
+ test('cream paper, Fraunces and a clay accent together ask at line 1', () => {
+ const { findings } = lintPage(page('', undefined, cream.replace('"Literata"', '"Fraunces"')));
+ expect(byRule(findings, 'cream-palette').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', 1, 'the default tasteful look: cream paper (L 97%, hue 80), fraunces as the display and a clay accent (hue 30)']]);
+ });
+});
+
+describe('design-lint colour: framework-palette (74, ask)', () => {
+ test('a colour mixed for the page is clean', () => {
+ const { findings } = lintPage(page(''));
+ expect(byRule(findings, 'framework-palette')).toEqual([]);
+ });
+ test('a Tailwind default swatch as a token asks at its line', () => {
+ const { html, findings } = lintPage(page('', undefined, TOKENS + '\n:root { --color-brand: #6366F1; }'));
+ expect(byRule(findings, 'framework-palette').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, '--color-brand'), "Tailwind's default #6366F1 as --color-brand"]]);
+ });
+});
+
+describe('design-lint colour: literal-outside-tokens (48, blocks)', () => {
+ test('token references, generic families and a fully transparent literal are clean', () => {
+ const { findings } = lintPage(page('.card { color: var(--color-ink); font-family: sans-serif; background: rgba(0, 0, 0, 0); }', '<p style="margin: 0">Ledger</p>'));
+ expect(byRule(findings, 'literal-outside-tokens')).toEqual([]);
+ });
+ test('a colour literal, a font-family literal and an inline style colour each block at their line', () => {
+ const { html, findings } = lintPage(page('.promo { color: #e91e63; }\n.quote { font-family: "Playfair Display", serif; }', '<p style="color: #333">Ledger</p>'));
+ expect(byRule(findings, 'literal-outside-tokens').map((x) => [x.grade, x.line, x.evidence])).toEqual([
+ ['blocks', lineOf(html, '.promo {'), 'colour literal #e91e63 outside the token block (color on .promo)'],
+ ['blocks', lineOf(html, '.quote {'), 'font-family literal ""Playfair Display", serif" on .quote'],
+ ['blocks', lineOf(html, 'style="color: #333"'), 'inline style colour literal #333'],
+ ]);
+ });
+});
+
+// The Tailwind forms of 2a/2b are the component family's (rules/component.ts, test/design-lint-tailwind.test.ts).
+
+describe('design-lint colour: fixtures', () => {
+ const MINE = new Set(['purple-blue-gradient', 'gradient-text', 'pure-black-white', 'absolute-surface-token', 'zero-chroma-neutrals', 'accent-footprint', 'glow-wash', 'cream-palette', 'framework-palette', 'literal-outside-tokens']);
+ test('the clean page has no colour finding', () => {
+ const { findings } = lintStatic([path.join(FIXTURES, 'clean')], { cwd: ROOT });
+ expect(lines(findings.filter((f) => MINE.has(f.rule)))).toEqual([]);
+ });
+ test('slopped.html: the purple-to-blue gradient text blocks, the three literals block, the pure tokens and the zero-chroma grey ask', () => {
+ const file = path.join(FIXTURES, 'slopped.html');
+ const html = fs.readFileSync(file, 'utf8');
+ const { findings } = lintStatic([file], { cwd: ROOT });
+ const mine = findings.filter((f) => MINE.has(f.rule)).map((f) => [f.rule, f.grade, f.line]);
+ expect(mine).toEqual(expect.arrayContaining([
+ ['purple-blue-gradient', 'blocks', lineOf(html, '-webkit-background-clip: text')],
+ ['literal-outside-tokens', 'blocks', lineOf(html, 'linear-gradient(90deg, #8b5cf6, #3b82f6)')],
+ ['literal-outside-tokens', 'blocks', lineOf(html, '.promo { color: #e91e63; }')],
+ ['absolute-surface-token', 'ask', lineOf(html, '--color-paper: #ffffff')],
+ ['absolute-surface-token', 'ask', lineOf(html, '--color-ink: #000000')],
+ ['zero-chroma-neutrals', 'ask', lineOf(html, '--color-gray: oklch(55% 0 0)')],
+ ]));
+ expect(mine.filter((m) => m[0] === 'gradient-text')).toEqual([]);
+ expect(mine.filter((m) => m[0] === 'absolute-surface-token')).toHaveLength(5);
+ expect(mine.filter((m) => m[0] === 'literal-outside-tokens')).toHaveLength(3);
+ });
+ test('the waiver fixture: the black paper and the grey ink are waived on the record, never blocked', () => {
+ const { findings } = lintStatic([path.join(FIXTURES, 'waiver')], { cwd: ROOT });
+ expect(byRule(findings, 'absolute-surface-token').map((f) => f.grade)).toEqual(['waived', 'waived']);
+ expect(byRule(findings, 'zero-chroma-neutrals').map((f) => f.grade)).toEqual(['waived']);
+ expect(byRule(findings, 'pure-black-white')).toEqual([]);
+ });
+});
+
+describe('design-lint colour: the indigo-to-violet ramp (third review cycle)', () => {
+ test('a near single-hue indigo ramp is not the indigo-to-violet gradient; stops twelve degrees apart are', () => {
+ const near = lintPage(page('.band { background: linear-gradient(90deg, oklch(60% 0.2 253), oklch(70% 0.15 258)); }'));
+ expect(lines(byRule(near.findings, 'purple-blue-gradient'))).toEqual([]);
+ const ramp = lintPage(page('.band { background: linear-gradient(90deg, oklch(60% 0.2 275), oklch(70% 0.15 300)); }'));
+ expect(byRule(ramp.findings, 'purple-blue-gradient').map((f) => [f.grade, f.evidence])).toEqual([['blocks', expect.stringContaining('indigo-to-violet')]]);
+ });
+});
diff --git a/test/design-lint-eighth-cycle.test.ts b/test/design-lint-eighth-cycle.test.ts
new file mode 100644
index 000000000..76737f663
--- /dev/null
+++ b/test/design-lint-eighth-cycle.test.ts
@@ -0,0 +1,331 @@
+/**
+ * The eighth review cycle's regressions: the waiver branch keyed to the context's shape rather than the --scope flag
+ * (a lone component beside an unlinked stylesheet answers for its own file; a page under --scope component still
+ * answers for the sheet it links), the bare `<` tails (`<1`, `< `, an unclosed comment), the craft check's lazy
+ * scans over repeated unclosed openers, component tags paired once per file, an arithmetic repeat() count, an
+ * unclosed @starting-style block, the import scan over a gradient class line, the render tier's locator on a class
+ * value holding a `>`, tickers answered from the tree, a tooltip duration that is not a delay, a class attribute of
+ * many tokens, and one emoji-decoration per emoji icon in a component file.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { parseCss, resolveVars, selectorNames } from '../lib/design-lint/css';
+import { parseDoc, parseHtml, stripTags } from '../lib/design-lint/html';
+import { lineOf } from '../lib/design-lint/render';
+import { glAccent, glLayout } from '../lib/design-lint/render-probe';
+import { glHeroSpace, glWide, glWords } from '../lib/design-lint/render-probe-space';
+import { Reporter, type Finding } from '../lib/design-lint/report';
+import { run as runAssets } from '../lib/design-lint/rules/assets';
+import { run as runCopy } from '../lib/design-lint/rules/copy';
+import { lintStatic } from '../lib/design-lint/static';
+import { compInner } from '../lib/design-lint/tailwind';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif; }';
+const HEAD = '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n';
+const GREY = TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }';
+const DASHES = 'The ledger \u2014 the month \u2014 the close \u2014 the depot \u2014 the review \u2014 the rule \u2014 the row \u2014 the sum';
+const CARD = 'export function Card() { return <p>' + DASHES + '</p>; }';
+
+function tree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-cycle8-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+const quiet = { warn: () => {} };
+const only = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+const timed = (fn: () => void): number => { const t = performance.now(); fn(); return performance.now() - t; };
+const lintDir = (files: Record<string, string>, scope?: 'page' | 'component'): { findings: Finding[]; warns: string[] } => {
+ const dir = tree(files);
+ const warns: string[] = [];
+ return { findings: lintStatic([dir], { cwd: dir, warn: (l: string) => warns.push(l), ...(scope ? { scope } : {}) }).findings, warns };
+};
+
+describe('design-lint eighth cycle: the waiver branch follows the context, not the flag', () => {
+ test('a lone component beside an unlinked stylesheet answers for its own file under either scope', () => {
+ for (const scope of ['page', 'component'] as const) {
+ const { findings } = lintDir({ 'Hero.tsx': '// gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey on the depot\nexport function Hero() { return <h1 className="row">The ledger keeps its grey rows grey on the depot</h1>; }', 'theme.css': GREY }, scope);
+ expect(only(findings, 'zero-chroma-neutrals').map((x) => [x.file, x.grade]), scope).toEqual([['theme.css', 'ask']]);
+ }
+ });
+
+ test('default scope, one component: a short claim is refused at its line and the finding stays ask', () => {
+ const { findings } = lintDir({ 'Card.tsx': '// gstack-lint-disable em-dash-overuse: short\n' + CARD });
+ expect(only(findings, 'em-dash-overuse').map((x) => [x.file, x.grade])).toEqual([['Card.tsx', 'ask']]);
+ expect(only(findings, 'waiver').map((x) => [x.file, x.line, x.evidence])).toEqual([['Card.tsx', 1, 'waiver on em-dash-overuse refused: reason under 24 characters']]);
+ });
+
+ test('under --scope component a page claim still answers a finding in the stylesheet it links, and a short one is refused', () => {
+ const page = (reason: string) => '<!-- gstack-lint-disable zero-chroma-neutrals: ' + reason + ' -->\n' + HEAD + '<link rel="stylesheet" href="theme.css"></head><body><main><h1>The ledger</h1><p>The ledger keeps its grey rows grey on the depot.</p></main></body></html>';
+ const ok = lintDir({ 'index.html': page('the ledger keeps its grey rows grey on the depot'), 'theme.css': GREY }, 'component').findings;
+ expect(only(ok, 'waiver')).toEqual([]);
+ expect(only(ok, 'zero-chroma-neutrals').map((x) => [x.file, x.grade])).toEqual([['theme.css', 'waived']]);
+ const bad = lintDir({ 'index.html': page('short'), 'theme.css': GREY }, 'component').findings;
+ expect(only(bad, 'zero-chroma-neutrals').map((x) => [x.file, x.grade])).toEqual([['theme.css', 'ask']]);
+ expect(only(bad, 'waiver').map((x) => [x.file, x.line, x.evidence])).toEqual([['index.html', 1, 'waiver on zero-chroma-neutrals refused: reason under 24 characters']]);
+ });
+});
+
+describe('design-lint eighth cycle: a file costs its length', () => {
+ test('a heading whose tail is thousands of bare < characters lints in linear time', () => {
+ const dir = tree({ 'index.html': HEAD + '</head><body><h1>' + ' x <'.repeat(80_000) });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(5000);
+ }, 60_000);
+
+ test('a page whose tail is a run of <1 or of unclosed comment starts costs its length, and a doctype survives', () => {
+ const dir = tree({
+ 'a.html': HEAD + '</head><body><p>hi</p></body></html>' + '<1'.repeat(200_000),
+ 'b.html': HEAD + '</head><body>' + '<!-- x'.repeat(100_000) + '</body></html>',
+ });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(5000);
+ const doc = parseHtml('x.html', '<!doctype html><p>a < b and 1<2</p><!-- gone');
+ expect(doc.src.startsWith('<!doctype html>')).toBe(true);
+ expect(doc.src.indexOf('<', '<!doctype html>'.length)).toBe(doc.src.indexOf('<p>'));
+ expect(doc.src.includes('<!--')).toBe(false);
+ expect(doc.tags.map((t) => t.name)).toEqual(['p', 'p']);
+ expect(parseHtml('x.html', '<p>Fees are <1% of volume and <b>nothing</b> else</p>').text.replace(/\s+/g, ' ').trim()).toBe('Fees are 1% of volume and nothing else');
+ }, 60_000);
+
+ test('repeated unclosed <script>, <nav>, <style> and <template> openers cost the copy tier their length', () => {
+ for (const tag of ['<script>', '<nav>', '<style>', '<template>']) {
+ const doc = parseHtml('x.html', HEAD + '</head><body>' + tag.repeat(60_000) + '</body></html>');
+ const reporter = new Reporter('page', '/');
+ expect(timed(() => runCopy({ docs: [doc] } as never, reporter)), tag).toBeLessThan(3000);
+ }
+ const doc = parseHtml('x.html', HEAD + '</head><body><nav><a href="/a">A</a><a href="/b">B</a></nav><nav><main id="m"><h1>Hello there</h1></main></body></html>');
+ const reporter = new Reporter('page', '/');
+ runCopy({ docs: [doc] } as never, reporter);
+ expect(reporter.findings.map((f) => f.rule)).toContain('missing-aria-current');
+ }, 60_000);
+
+ test('a template of thousands of unclosed component tags costs its length', () => {
+ const dir = tree({ 'Card.vue': '<template>\n' + '<Foo class="p-4">x\n'.repeat(80_000) + '</template>' });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(3000);
+ const doc = parseDoc('/x/App.vue', '<template><Foo><Bar>in</Bar><Foo>deep</Foo>out</Foo><Baz /></template>');
+ expect(doc.comps.filter((c) => !c.close && !c.selfClosing).map((_, i) => compInner(doc, doc.comps.indexOf(doc.comps.filter((c) => !c.close && !c.selfClosing)[i])))).toEqual(['<Bar>in</Bar><Foo>deep</Foo>out', 'in', 'deep']);
+ expect(compInner(doc, doc.comps.length - 1)).toBe('');
+ });
+
+ test('a huge repeat() count in grid-template-columns neither throws nor allocates', () => {
+ const { findings, warns } = lintDir({
+ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body><section class="grid"><h1>Hi</h1><p>x</p></section></body></html>',
+ 'style.css': TOKENS + '\n.grid { grid-template-columns: 1fr 1fr; }\n@media (min-width: 1600px) { .grid { grid-template-columns: repeat(4294967296, 1fr); } }',
+ });
+ expect(warns.filter((w) => /internal error/.test(w))).toEqual([]);
+ expect(only(findings, 'internal-error')).toEqual([]);
+ expect(only(findings, 'wide-container').map((f) => f.evidence)).toEqual([expect.stringContaining('(2 to 4294967296)')]);
+ const named = lintDir({
+ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body><main><section class="grid"><h1>Hi</h1><p>x</p></section></main></body></html>',
+ 'style.css': TOKENS + '\n.grid { grid-template-columns: repeat(12, 1fr); }\n@media (min-width: 1600px) { .grid { grid-template-columns: repeat(12, [col-start] 1fr) [col-end]; } }',
+ }).findings;
+ expect(only(named, 'wide-container')).toEqual([]);
+ });
+
+ test('unclosed @starting-style blocks cost their length, not the sheet squared', () => {
+ const dir = tree({ 'style.css': '.a { opacity: 0 }\n' + '@starting-style {\n'.repeat(8000) + '.b { color: red }\n'.repeat(8000) });
+ const warns: string[] = [];
+ expect(timed(() => lintStatic([dir], { cwd: dir, warn: (l: string) => warns.push(l) }))).toBeLessThan(2000);
+ expect(warns.filter((w) => /internal error/.test(w))).toEqual([]);
+ });
+
+ test('ten thousand unclosed <em> under headings cost the assets rules their length', () => {
+ const doc = parseDoc('x.html', HEAD + '</head><body>' + '<h2>a <em>x '.repeat(10000) + '</body></html>');
+ const reporter = new Reporter('page', '/');
+ expect(timed(() => runAssets({ docs: [doc], cssFiles: [], rules: [], tokens: {}, twTokens: null, allCss: '', cache: {} } as never, reporter))).toBeLessThan(3000);
+ });
+
+ test('a deeply nested comma selector list costs its length, not parts^depth', () => {
+ const css = 'a,b{'.repeat(40) + 'color:red' + '}'.repeat(40);
+ let rules: ReturnType<typeof parseCss> = [];
+ expect(timed(() => { rules = parseCss(css, 'x.css'); })).toBeLessThan(2000);
+ expect(rules.reduce((n, x) => n + x.selector.length, 0)).toBeLessThan(1_000_000);
+ expect(parseCss('.a, .b { .c, .d { color: red } }', 'x.css').map((x) => x.selector)).toEqual(['.a, .b', ':is(.a, .b) .c, :is(.a, .b) .d']);
+ const amp = '.' + 'a'.repeat(4000) + '{' + '&&&&&&&&&&&&&&&&{color:red}'.repeat(20_000) + '}';
+ let nested: ReturnType<typeof parseCss> = [];
+ expect(timed(() => { nested = parseCss(amp, 'x.css'); })).toBeLessThan(2000);
+ expect(nested.length).toBe(20_001);
+ expect(nested.every((x) => x.selector.length <= 8192)).toBe(true);
+ const long = parseCss('.' + 'a'.repeat(50_000) + ', .b{' + '&{color:red}'.repeat(20_000) + '}', 'x.css');
+ expect(long.length).toBe(20_001);
+ expect(long.every((x) => x.selector.length <= 8192)).toBe(true);
+ expect(long.slice(1).reduce((n, x) => n + x.selector.length, 0)).toBeLessThan(10_000_000);
+ expect(timed(() => selectorNames(long.map((x) => x.selector)))).toBeLessThan(500);
+ });
+
+ test('a huge token value is not expanded into every reference', () => {
+ const tokens = { '--a': 'x'.repeat(1_000_000), '--b': 'blue' };
+ const value = 'var(--a) '.repeat(900).trim();
+ let out = '';
+ expect(timed(() => { out = resolveVars(value, tokens); })).toBeLessThan(200);
+ expect(out).toBe(value);
+ expect(resolveVars('1px solid var(--b)', tokens)).toBe('1px solid blue');
+ });
+
+ test('a stylesheet or <style> block the lint could not parse is an internal-error finding, not a silent pass', () => {
+ const boom = 'a,b{'.repeat(30) + 'color:red' + '}'.repeat(30);
+ const inline = lintDir({ 'index.html': HEAD + '<style>' + boom + ' * { transition: all .3s ease }</style></head><body><main><h1>Hi</h1></main></body></html>' }).findings;
+ expect(only(inline, 'layout-transition').map((f) => f.grade)).toEqual(['blocks']);
+ expect(only(inline, 'internal-error')).toEqual([]);
+ const big = lintDir({ 'index.html': HEAD + '<link rel="stylesheet" href="big.css"></head><body><main><h1>Hi</h1></main></body></html>', 'big.css': '.a{color:red}\n'.repeat(160_000) }).findings;
+ expect(only(big, 'internal-error').map((f) => [f.file, f.grade])).toEqual([['big.css', 'ask']]);
+ const unreadable = lintDir({ 'index.html': HEAD + '<link rel="stylesheet" href="dir.css"></head><body><main><h1>Hi</h1></main></body></html>', 'dir.css/.keep': '' }).findings;
+ expect(only(unreadable, 'internal-error').map((f) => [f.file, f.fix])).toEqual([['dir.css', 'check the path']]);
+ expect(only(unreadable, 'internal-error')[0].evidence).toMatch(/cannot be read \(EISDIR\)/);
+ });
+
+ test('a long gradient className line, or an import word before a long whitespace run, costs the asset scan its length; ES imports still name their libraries', () => {
+ const dir = tree({ 'Hero.tsx': 'export default function Hero(){ return (<div className="' + 'bg-gradient-to-r from-indigo-500 to-violet-500 '.repeat(20_000) + '">x</div>); }' });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(5000);
+ const spaced = tree({ 'Hero.tsx': 'export function Hero() { return <div>x</div>; }\n// import' + ' '.repeat(300_000) + 'x' });
+ expect(timed(() => lintStatic([spaced], { cwd: spaced, ...quiet }))).toBeLessThan(3000);
+ const nav = tree({ 'Nav.tsx': "import { Check } from 'lucide-react';\nimport { StarIcon } from '@heroicons/react/24/solid';\nexport const Nav = () => <nav><Check /><StarIcon /></nav>;\n" });
+ expect(only(lintStatic([nav], { cwd: nav, ...quiet }).findings, 'two-icon-libraries').map((f) => f.evidence)).toEqual(['icon libraries mixed on one page: heroicons and lucide']);
+ }, 60_000);
+
+ test('thousands of distinct families, narrow prose classes, nowrap rules, wrapping rules or em rules beside thousands of elements cost their length', () => {
+ const fams = tree({ 'style.css': Array.from({ length: 40_000 }, (_, i) => `.f${i}{font-family:"Fam${i}"}`).join('\n') });
+ expect(timed(() => lintStatic([fams], { cwd: fams, ...quiet })), 'families').toBeLessThan(10_000);
+ const prose = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body><main>' + '<p class="x">hi</p>\n'.repeat(40_000) + '</main></body></html>', 'style.css': Array.from({ length: 20_000 }, (_, i) => `.copy${i}{max-width:30ch}`).join('\n') });
+ expect(timed(() => lintStatic([prose], { cwd: prose, ...quiet })), 'prose').toBeLessThan(10_000);
+ const nowrap = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body><main>' + '<button class="btn">A long label that certainly wraps around</button>\n'.repeat(8_000) + '</main></body></html>', 'style.css': Array.from({ length: 20_000 }, (_, i) => `.nw${i}{white-space:nowrap}`).join('\n') });
+ expect(timed(() => lintStatic([nowrap], { cwd: nowrap, ...quiet })), 'nowrap').toBeLessThan(10_000);
+ const wrap = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body>' + '<main><h1>Supercalifragilisticexpialidocious here</h1></main>\n'.repeat(8_000) + '</body></html>', 'style.css': Array.from({ length: 60_000 }, (_, i) => `.a${i}{color:red}`).join('\n') });
+ expect(timed(() => lintStatic([wrap], { cwd: wrap, ...quiet })), 'wrap').toBeLessThan(10_000);
+ const em = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="style.css"></head><body><main>' + '<h2>Hello <em>there</em> friend</h2>\n'.repeat(10_000) + '</main></body></html>', 'style.css': Array.from({ length: 10_000 }, (_, i) => `.n${i} em{font-style:normal}`).join('\n') });
+ expect(timed(() => lintStatic([em], { cwd: em, ...quiet })), 'em').toBeLessThan(10_000);
+ }, 60_000);
+
+ test('an unclosed JSX expression at the end of a deep element, or a malformed close tag under it, costs the file its length', () => {
+ const src = 'export default function A(){ return (' + '<div>'.repeat(200) + '{ ' + 'x '.repeat(1_000_000) + ')';
+ expect(timed(() => parseDoc('/x/App.tsx', src))).toBeLessThan(2000);
+ const bad = 'export default function A(){ return (' + '<div>'.repeat(190) + 'x '.repeat(500_000) + '</div foo>' + '</div>'.repeat(189) + '); }';
+ expect(timed(() => parseDoc('/x/App.tsx', bad))).toBeLessThan(500);
+ });
+
+ test('stripTags with a limit stops reading once the limit is passed, and a heading of thousands of classed spans costs its length', () => {
+ const inner = '<p>' + 'lorem ipsum dolor '.repeat(60_000) + '</p>';
+ expect(timed(() => { for (let k = 0; k < 500; k++) stripTags(inner, false, 4); })).toBeLessThan(500);
+ expect(stripTags('<b>x</b> hi', false, 4)).toBe(' x hi');
+ expect(stripTags('<b>x</b> hi there friend', false, 4).length).toBeLessThan(' x hi there friend'.length);
+ expect(stripTags('\u00a0\u{1F680}\u00a0\u{1F680}\u00a0\u{1F680} more', false, 4)).toBe('\u00a0\u{1F680}\u00a0\u{1F680}\u00a0\u{1F680}');
+ const padded = '\u{1F680}\u00a0\u00a0\u00a0\u00a0 hello world';
+ expect(stripTags(padded, false, 4).replace(/\s+/g, ' ').trim().length > 4).toBe(stripTags(padded).replace(/\s+/g, ' ').trim().length > 4);
+ const nested = tree({ 'index.html': HEAD + '</head><body>' + '<div>'.repeat(500) + '<p>' + 'lorem ipsum dolor '.repeat(60_000) + '</p>' + '</div>'.repeat(500) + '</body></html>' });
+ expect(timed(() => lintStatic([nested], { cwd: nested, ...quiet })), 'nested').toBeLessThan(4000);
+ const spans = Array.from({ length: 4000 }, (_, i) => '<span class="c">w' + i + '</span> ').join('');
+ const dir = tree({ 'index.html': HEAD + '</head><body><main><h1>' + spans + '</h1><p>Body.</p></main></body></html>' });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet })), 'spans').toBeLessThan(1500);
+ }, 60_000);
+
+ test('the render locator costs the page its length when a class value holds a >, and refuses a tag that is not one', () => {
+ const src = parseHtml('x.html', '<html><body><div class="' + 'a '.repeat(150_000) + '>"><p>x</p></div></body></html>').src;
+ expect(timed(() => lineOf(src, { tag: 'div', cls: 'a', text: 'zzz' }))).toBeLessThan(2000);
+ const tail = parseHtml('x.html', '<p>hi</p>' + '<1'.repeat(160_000)).src;
+ expect(timed(() => expect(lineOf(tail, { tag: '1', cls: '', text: 'zz' })).toBe(1))).toBeLessThan(500);
+ expect(lineOf('<x>\n<p class="lede big">Hello</p>', { tag: 'p', cls: 'big', text: 'hello' })).toBe(2);
+ expect(lineOf('<x>\n<p data-class="x" class="lede big">Hello</p>', { tag: 'p', cls: 'big', text: 'hello' })).toBe(2);
+ expect(lineOf('<x>\n<p class="lede big">Hello</p>', { tag: 'p', cls: 'x'.repeat(401), text: 'hello' })).toBe(2);
+ }, 60_000);
+
+ test('thousands of ticker elements beside thousands of text elements cost their length', () => {
+ const dir = tree({ 'index.html': HEAD + '</head><body>' + '<i class="ticker"></i><span>x</span>'.repeat(40_000) + '</body></html>' });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(4000);
+ const f = lintDir({ 'index.html': HEAD + '</head><body><div class="ticker"><p><span>One · two · three</span></p></div><p>Four · five · six</p></body></html>' }).findings;
+ expect(only(f, 'template-punctuation').map((x) => x.evidence)).toEqual(['middle dots join a meta string: "Four · five · six"']);
+ }, 60_000);
+
+ test('a class attribute with 700k tokens does not overflow the stack', () => {
+ const { warns } = lintDir({ 'index.html': HEAD + '</head><body><div class="' + 'a '.repeat(700_000) + '"><h1>Hi</h1></div></body></html>\n' });
+ expect(warns.filter((w) => /Maximum call stack/.test(w))).toEqual([]);
+ });
+});
+
+describe('design-lint eighth cycle: rule judgements', () => {
+ test('tooltip-focus-delay reads a delay, not a 0.2s fade', () => {
+ const tip = (t: string) => lintDir({ 'index.html': HEAD + '<style>' + TOKENS + ' .tooltip:hover .tip { transition: ' + t + '; opacity: 1 } .tooltip:focus-within .tip { transition: ' + t + '; opacity: 1 }</style></head><body><main><h1>Hello there</h1><span class="tooltip" tabindex="0">?<span class="tip">Help</span></span></main></body></html>' }).findings;
+ expect(only(tip('opacity 0.2s'), 'tooltip-focus-delay')).toEqual([]);
+ expect(only(tip('opacity 200ms'), 'tooltip-focus-delay')).toEqual([]);
+ expect(only(tip('opacity .5s ease'), 'tooltip-focus-delay')).toEqual([]);
+ expect(only(tip('opacity 1s'), 'tooltip-focus-delay')).toEqual([]);
+ expect(only(tip('opacity 0.2s 0.1s'), 'tooltip-focus-delay').map((f) => f.grade)).toEqual(['ask']);
+ expect(only(tip('opacity 200ms cubic-bezier(0.4, 0, 0.2, 1) 500ms'), 'tooltip-focus-delay').map((f) => f.grade)).toEqual(['ask']);
+ expect(only(tip('opacity 0.2s steps(4, end) 1s'), 'tooltip-focus-delay').map((f) => f.grade)).toEqual(['ask']);
+ expect(only(tip('opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1)'), 'tooltip-focus-delay')).toEqual([]);
+ expect(only(tip('opacity 0.2s 1s'), 'tooltip-focus-delay').map((f) => f.grade)).toEqual(['ask']);
+ expect(only(tip('opacity 200ms 600ms'), 'tooltip-focus-delay').map((f) => f.grade)).toEqual(['ask']);
+ });
+
+ test('one emoji-decoration per emoji icon in a component file, however the parent wraps it', () => {
+ const { findings } = lintDir({ 'Card.tsx': 'export function Card() { return <div>\n<div className="icon"><Icon>\u{1F680}</Icon></div>\n<div className="icon"><Icon>\u{1F680}</Icon></div>\n<div className="feature"><Icon>\u{1F680}</Icon><h3>Fast</h3></div>\n</div>; }' });
+ expect(only(findings, 'emoji-decoration').map((f) => [f.line, f.evidence])).toEqual([[2, 'emoji icon "\u{1F680}" in <Icon>'], [3, 'emoji icon "\u{1F680}" in <Icon>'], [4, 'emoji icon "\u{1F680}" in <Icon>']]);
+ });
+
+ test('the probes read their viewport from the page, not a literal', () => {
+ for (const fn of [glLayout, glAccent]) expect(fn.toString()).not.toMatch(/\b800\b|1280x800/);
+ for (const fn of [glHeroSpace, glWide, glWords]) expect(fn.toString()).not.toMatch(/1440x900|\b900(?:px)?\b|1920x1080|at 1920/);
+ expect([...selectorNames([':is(a, button)']).tags].sort()).toEqual(['a', 'button']);
+ expect([...selectorNames(['nav :where(h1, h2) em']).tags].sort()).toEqual(['em', 'h1', 'h2', 'nav']);
+ });
+
+ test('thousands of nested children under a long parent cost the sheet its length, and a whitespace run does not defeat the stripTags limit', () => {
+ const src = '.' + 'a'.repeat(8000) + '{' + '&{}'.repeat(200_000) + '}';
+ let rules: ReturnType<typeof parseCss> = [];
+ expect(timed(() => { rules = parseCss(src, 'x.css'); }), 'amp').toBeLessThan(3000);
+ expect(rules.length).toBe(200_001);
+ expect(rules.reduce((n, x) => n + x.selector.length, 0)).toBeLessThan(src.length * 8);
+ expect(rules[1].selector.startsWith('.aaaa')).toBe(true);
+ expect(rules[200_000].selector).toBe('&');
+ const kids = Array.from({ length: 200_000 }, (_, k) => `.a${k}{}`).join('');
+ const desc = parseCss('.' + 'a'.repeat(8000) + '{' + kids + '}', 'y.css');
+ expect(desc.reduce((n, x) => n + x.selector.length, 0)).toBeLessThan((kids.length + 8002) * 8);
+ expect(desc[200_000].selector).toBe('.a199999');
+ const ws = ' '.repeat(1_000_000);
+ expect(timed(() => { for (let k = 0; k < 500; k++) stripTags(ws, false, 4); }), 'spaces').toBeLessThan(2000);
+ expect(timed(() => { for (let k = 0; k < 500; k++) stripTags('\u00a0'.repeat(1_000_000), false, 4); }), 'nbsp').toBeLessThan(2000);
+ const label = ' '.repeat(10_000) + 'Start your fourteen day free trial now today';
+ expect(stripTags(label, false, 40).trim()).toBe(stripTags(label).trim());
+ expect(stripTags(' '.repeat(10_000) + '\u{1F680}', false, 4).trim()).toBe('\u{1F680}');
+ for (const n of [4351, 4352, 4353]) expect(stripTags(' '.repeat(n) + '\u{1F600} more text', false, 4).isWellFormed()).toBe(true);
+ expect(stripTags(' '.repeat(5000) + 'hello world', false, 4).trim()).toBe('hello');
+ }, 60_000);
+
+ test('an escaped quote does not rewrite the rest of a sheet, and a declaration string may hold ; or }', () => {
+ const rules = parseCss('.q::before { content: "\\""; } .a { color: red } .b { content: "a;b}c"; color: blue } .c {}', 'x.css');
+ expect(rules.map((x) => x.selector)).toEqual(['.q::before', '.a', '.b', '.c']);
+ expect(rules[2].decls.map((d) => d.prop + '=' + d.value)).toEqual(['content="a;b}c"', 'color=blue']);
+ expect(parseCss(".x { font-family: 'It\\'s'; } .y { color: red }", 'y.css').map((x) => x.selector)).toEqual(['.x', '.y']);
+ });
+
+ test('a @starting-style block waives content-hidden-at-rest only for the selectors it names, whole', () => {
+ const sheet = '@starting-style { .reveal-wrap { opacity: 0 } } .reveal { opacity: 0; transform: translateY(24px) } .reveal-wrap { opacity: 0; transform: translateY(24px) } .fade { opacity: 0; transform: translateY(8px); @starting-style { opacity: 0 } }';
+ const { findings } = lintDir({ 'theme.css': TOKENS + '\n' + sheet, 'index.html': HEAD + '<link rel="stylesheet" href="theme.css"></head><body><main><h1>The ledger</h1><p class="reveal">a</p><p class="reveal-wrap">b</p><p class="fade">c</p></main></body></html>' });
+ expect(only(findings, 'content-hidden-at-rest').map((x) => x.evidence.split(' ')[0])).toEqual(['.reveal']);
+ });
+
+ test('aria-hidden must be "true" to count as hidden decoration', () => {
+ const page = (hidden: string) => HEAD + '</head><body><main><h1>The ledger</h1><svg ' + hidden + ' width="10" height="10"></svg></main></body></html>';
+ expect(only(lintDir({ 'index.html': page('aria-hidden="false"') }).findings, 'unlabeled-decoration').length).toBe(1);
+ expect(only(lintDir({ 'index.html': page('aria-hidden="true"') }).findings, 'unlabeled-decoration').length).toBe(0);
+ });
+
+ test('outside any project a relative stylesheet href is bounded by the working directory', () => {
+ const base = tree({ 'outside/secret.css': '.leak { color: #000; background: #fff }', 'site/index.html': HEAD + '<link rel="stylesheet" href="../outside/secret.css"></head><body><main><h1>The ledger</h1></main></body></html>' });
+ const site = path.join(base, 'site');
+ expect(lintStatic([site], { cwd: site, ...quiet }).findings.some((x) => x.file.includes('secret.css'))).toBe(false);
+ expect(lintStatic([site], { cwd: base, ...quiet }).findings.some((x) => x.file.includes('secret.css'))).toBe(true);
+ const inside = tree({ 'site/css/a.css': '.leak { color: #000; background: #fff }', 'site/index.html': HEAD + '<link rel="stylesheet" href="css/a.css"></head><body><main><h1>The ledger</h1></main></body></html>' });
+ expect(lintStatic([path.join(inside, 'site')], { cwd: path.join(inside, 'site'), ...quiet }).findings.some((x) => x.file.includes('a.css'))).toBe(true);
+ });
+
+ test('the emoji classes spell their variation selector and joiner as escapes', () => {
+ expect(fs.readFileSync(path.join(import.meta.dir, '../lib/design-lint/rules/assets.ts'), 'utf8')).not.toMatch(/[\uFE0F\u200D]/);
+ });
+});
diff --git a/test/design-lint-fifth-cycle.test.ts b/test/design-lint-fifth-cycle.test.ts
new file mode 100644
index 000000000..cb3ef458f
--- /dev/null
+++ b/test/design-lint-fifth-cycle.test.ts
@@ -0,0 +1,239 @@
+/**
+ * The fifth review cycle's regressions: the last comment-blanked reader, hostile inputs that stayed quadratic or blew
+ * the stack (a digit run, 699k rules, unclosed JSX, thousands of tracked labels), per-sheet waivers, the render tier
+ * holding its measured findings against every wrong-shaped field, and the rule judgements the design pass asked for.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import type { RenderResult, RenderSpec } from '../lib/aside-render';
+import { parseDoc } from '../lib/design-lint/html';
+import { lint } from '../lib/design-lint/index';
+import { lintRender, type Runner } from '../lib/design-lint/render';
+import { formatFinding, Reporter, type Finding } from '../lib/design-lint/report';
+import { lintStatic, MAX_FILE_BYTES, resolveRef } from '../lib/design-lint/static';
+import { twDataText } from '../lib/design-lint/tailwind';
+import { FLOOR_REFUSAL, resolveWaivers } from '../lib/design-lint/waivers';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif; }';
+const HEAD = '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n';
+const page = (css: string, body: string): string => HEAD + '<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+
+function tree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-cycle5-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+const quiet = { warn: () => {} };
+const run = (html: string, files: Record<string, string> = {}): Finding[] => { const dir = tree({ 'index.html': html, ...files }); return lintStatic([dir], { cwd: dir, ...quiet }).findings; };
+const only = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+const timed = (fn: () => void): number => { const t = performance.now(); fn(); return performance.now() - t; };
+
+describe('design-lint fifth cycle: dead markup and hostile inputs', () => {
+ test('an emoji placeholder inside an HTML comment is dead', () => {
+ const f = run(page('', '<main><h1>Hi there</h1><p>Text.</p>\n<!-- <input placeholder="🚀 Search"> -->\n</main>'));
+ expect(only(f, 'emoji-decoration')).toEqual([]);
+ const live = run(page('', '<main><h1>Hi there</h1><form><input placeholder="🚀 Search"></form></main>'));
+ expect(only(live, 'emoji-decoration').length).toBe(1);
+ });
+
+ test('a long digit run, a long mono word and a run of scheme prefixes each cost their length', () => {
+ const dir = tree({ 'index.html': page('', '<main><h1>Hi there</h1><p>' + '7'.repeat(200_000) + '</p><p>' + 'https://'.repeat(20_000) + '</p></main>') });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(4000);
+ expect(timed(() => twDataText('a'.repeat(400_000)))).toBeLessThan(500);
+ });
+
+ test('a 2 MB stylesheet of 699k rules lints instead of blowing the stack', () => {
+ const dir = tree({ 'big.css': 'a{}'.repeat(Math.floor(MAX_FILE_BYTES / 3) - 1), 'index.html': HEAD + '<link rel="stylesheet" href="big.css"></head><body><main><h1>Hello there</h1><p>Body.</p></main></body></html>' });
+ expect(() => lintStatic([dir], { cwd: dir, ...quiet })).not.toThrow();
+ });
+
+ test('a JSX file of unclosed elements parses in linear time', () => {
+ const times = [5000, 10000].map((n) => timed(() => parseDoc('Page.tsx', 'export default function P(){ return (<div>' + '<Card className="p-4">text\n'.repeat(n) + '</div>); }')));
+ expect(times[1]).toBeLessThan(Math.max(times[0] * 3, 300));
+ expect(times[1]).toBeLessThan(4000);
+ });
+
+ test('a page of many tracked-caps labels lints in linear time and a well-formed JSX file still yields its classes', () => {
+ const times = [4000, 8000].map((n) => { const dir = tree({ 'index.html': page('', '<main><h1>Hello world</h1>' + '<span class="text-xs uppercase tracking-widest">Label one</span>\n'.repeat(n) + '</main>') }); return timed(() => lintStatic([dir], { cwd: dir, ...quiet })); });
+ expect(times[1]).toBeLessThan(Math.max(times[0] * 2.5, 500));
+ const doc = parseDoc('Page.tsx', 'export default function P(){ return (<div className="p-4"><Card className="rounded-xl">x</Card></div>); }');
+ expect(doc.classAt.size + doc.virtuals.length).toBeGreaterThan(0);
+ });
+
+ test('a fact after an inline close tag is counted in its own section', () => {
+ const sec = (i: number) => '<section><h2>S' + i + '</h2><p><strong>Price:</strong> $5 a month</p></section>';
+ const f = run(page('', '<main><h1>Hi there</h1>' + [0, 1, 2, 3].map(sec).join('') + '</main>'));
+ expect(only(f, 'repeated-fact').length).toBe(1);
+ });
+
+ test('a relative stylesheet href that climbs out of the project attaches nothing; inside the project it attaches', () => {
+ const dir = tree({ 'site/package.json': '{}', 'site/pages/index.html': HEAD + '<link rel="stylesheet" href="../../outside.css"></head><body><main><h1>t</h1><p>Body.</p></main></body></html>', 'outside.css': 'html, body { overflow-x: clip; }' });
+ const r = lintStatic([path.join(dir, 'site')], { cwd: dir, ...quiet });
+ expect(r.contexts[0].cssFiles).toEqual([]);
+ expect(only(r.findings, 'overflow-x-unclipped').length).toBe(1);
+ expect(resolveRef('css/site.css', path.join(dir, 'site'), path.join(dir, 'site'))).toBe(path.join(dir, 'site', 'css/site.css'));
+ expect(resolveRef('../outside.css', path.join(dir, 'site'), path.join(dir, 'site'))).toBeNull();
+ });
+
+ test('an unreadable top-level path beside a readable page is one internal-error finding with its own fix', () => {
+ const dir = tree({ 'index.html': page('', '<main><h1>Hi</h1><p>Body.</p></main>') });
+ const r = lintStatic([dir, path.join(dir, 'nowhere.html')], { cwd: dir, ...quiet });
+ expect(r.files.map((f) => path.basename(f))).toEqual(['index.html']);
+ expect(only(r.findings, 'internal-error').map((f) => [f.grade, f.file, f.line, /cannot be read/.test(f.evidence), f.fix])).toEqual([['ask', 'nowhere.html', 1, true, 'check the path']]);
+ });
+});
+
+describe('design-lint fifth cycle: waivers per sheet and the untested cells', () => {
+ const claim = (rule: string, reason: string) => ({ rule, reason, file: 'a.html', line: 3 });
+ const PAGE_TEXT = 'The manifesto sets long declarative lines. The ledger separates its rows with rules. Three links for the paper modes.';
+
+ test('two linked stylesheets each waive the same rule for themselves; a short second claim is refused for its reason', () => {
+ const sheets = (b: string) => ({
+ 'index.html': HEAD + '<link rel="stylesheet" href="a.css"><link rel="stylesheet" href="b.css"></head><body><main><h1>The ledger</h1><p>The ledger keeps its grey rows grey.</p></main></body></html>',
+ 'a.css': '/* gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey in the theme sheet */\n' + TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }',
+ 'b.css': '/* gstack-lint-disable zero-chroma-neutrals: ' + b + ' */\n:root { --color-gray-print: oklch(45% 0 0); }\n.plate { color: var(--color-gray-print); }',
+ });
+ const both = lintStatic([tree(sheets('the print sheet keeps grey plates grey for the press'))], { cwd: tmpDirs[tmpDirs.length - 1], ...quiet }).findings;
+ expect(only(both, 'waiver')).toEqual([]);
+ expect(only(both, 'zero-chroma-neutrals').map((x) => [x.file, x.grade]).sort()).toEqual([['a.css', 'waived'], ['b.css', 'waived']]);
+ const short = lintStatic([tree(sheets('short'))], { cwd: tmpDirs[tmpDirs.length - 1], ...quiet }).findings;
+ expect(only(short, 'waiver').map((x) => x.evidence)).toEqual(['waiver on zero-chroma-neutrals refused: reason under 24 characters']);
+ expect(only(short, 'zero-chroma-neutrals').map((x) => [x.file, x.grade]).sort()).toEqual([['a.css', 'waived'], ['b.css', 'ask']]);
+ });
+
+ test('a stylesheet claim with a boilerplate reason is refused and its finding stays ask', () => {
+ const dir = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="t.css"></head><body><main><h1>Ledger</h1><p>Rows.</p></main></body></html>', 't.css': '/* gstack-lint-disable zero-chroma-neutrals: this is intentional and by design for the sheet */\n' + TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }\n.row { color: var(--color-gray); }' });
+ const f = lintStatic([dir], { cwd: dir, ...quiet }).findings;
+ expect(only(f, 'waiver').map((x) => x.evidence)).toEqual(['waiver on zero-chroma-neutrals refused: boilerplate reason']);
+ expect(only(f, 'zero-chroma-neutrals').map((x) => x.grade)).toEqual(['ask']);
+ });
+
+ test('a second page claim on an accepted rule is refused as the duplicate even when its reason is short, and three accepted plus one refused is not a house style', () => {
+ const dup = resolveWaivers([claim('gradient-text', 'the ledger separates its rows with rules'), claim('gradient-text', 'short')], PAGE_TEXT);
+ expect([...dup.accepted.keys()]).toEqual(['gradient-text']);
+ expect(dup.refused.map((f) => f.evidence)).toEqual(['waiver on gradient-text refused: one waiver per rule']);
+ const four = resolveWaivers([claim('line-length', 'the manifesto sets long declarative lines'), claim('section-gap', 'the ledger separates its rows with rules'), claim('template-nav', 'three links for the paper modes'), claim('overused-font', 'short')], PAGE_TEXT);
+ expect(four.accepted.size).toBe(3);
+ expect(four.refused.map((f) => f.rule)).toEqual(['waiver']);
+ });
+
+ test('suspected leaves an ask or polish rule at its own tier', () => {
+ const r = new Reporter('page', '/cwd');
+ r.report('section-gap', '/cwd/a.html', 1, 'x', { suspected: true });
+ r.report('text-sliver', '/cwd/a.html', 1, 'x', { suspected: true, source: 'render' });
+ expect(r.findings.map((f) => [f.tier, f.grade])).toEqual([['ask', 'ask'], ['polish', 'polish']]);
+ });
+});
+
+describe('design-lint fifth cycle: render answers of the wrong shape, field by field', () => {
+ const PAGE = HEAD + '</head><body><main><h1>t</h1><p class="faint">Body.</p><a href="#">Go</a></main></body></html>';
+ const SWATCH = path.join(path.resolve(import.meta.dir, '..'), 'test', 'fixtures', 'design-lint', 'render', 'swatch.png');
+ const SETUP = 1, FIRST = 2, FOCUS = 13;
+ const SCROLL = { rule: 'horizontal-scroll', grade: 'fail', evidence: 'the hero overflows' };
+ type Patch = (evals: Record<number, string>, spec: RenderSpec) => void;
+ const runner = (patch: Patch, stdout = ''): Runner => async (spec: RenderSpec): Promise<RenderResult> => {
+ const evals: Record<number, string> = {};
+ const shot = spec.steps.findIndex((s) => s.kind === 'screenshot');
+ if (shot < 0) {
+ evals[SETUP] = '{"lost":[]}';
+ for (let i = FIRST; i <= FOCUS; i++) evals[i] = '[]';
+ patch(evals, spec);
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout };
+ }
+ spec.steps.forEach((s, i) => {
+ if (s.kind !== 'screenshot') return;
+ fs.copyFileSync(SWATCH, s.out);
+ const width = s.width ?? 0;
+ evals[i - 1] = JSON.stringify([{ x: 0, y: 0, w: width / 2, h: width }]);
+ });
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout };
+ };
+ const measured = (f: Finding[]) => only(f, 'horizontal-scroll').map((x) => x.evidence);
+ const noAbort = (f: Finding[]) => only(f, 'render').filter((x) => /could not be measured/.test(x.evidence));
+
+ test('a non-string at.cls, a ring without its colour, a probe without fg and a non-string PAGE_ERRORS entry each keep the measured findings', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const cls = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'nested-cards', grade: 'fail', evidence: 'x', at: { tag: 'p', text: 'Body.', cls: {} } }, SCROLL]); }) });
+ expect(measured(cls.findings)).toEqual(['[320px] the hero overflows']);
+ expect(only(cls.findings, 'nested-cards').map((f) => f.line)).toEqual([4]);
+ expect(noAbort(cls.findings)).toEqual([]);
+
+ const ring = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([SCROLL]); ev[FOCUS] = JSON.stringify([{ key: 'a', path: 'main>a', at: { tag: 'a', text: 'Go' }, bare: false, ratio: 1.2, pad: 2 }]); }) });
+ expect(measured(ring.findings)).toEqual(['[320px] the hero overflows']);
+ expect(noAbort(ring.findings)).toEqual([]);
+ expect(only(ring.findings, 'render').map((f) => /\((.*?)\)/.exec(f.evidence)![1])).toEqual(['focus']);
+
+ const fg = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([SCROLL]); ev[FIRST + 5] = JSON.stringify([{ rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)', probe: { path: 'main>p', threshold: 4.5 } }, { rule: 'low-contrast', grade: 'fail', evidence: 'y', probe: true }]); }) });
+ expect(measured(fg.findings)).toEqual(['[320px] the hero overflows']);
+ expect(only(fg.findings, 'low-contrast').map((f) => f.evidence)).toEqual(['[1280px] computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)', '[1280px] y']);
+ expect(noAbort(fg.findings)).toEqual([]);
+
+ const errs = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([SCROLL]); }, 'PAGE_ERRORS=[1]\n') });
+ expect(measured(errs.findings)).toEqual(['[320px] the hero overflows']);
+ expect(only(errs.findings, 'render')).toEqual([]);
+ });
+
+ test('a malformed entry claiming the render rule is reported as tampering with evidence on the line', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'render', grade: 'x', evidence: 'y' }]); }) });
+ expect(only(r.findings, 'render').map((f) => f.evidence)).toEqual([expect.stringMatching(/does not know \(render\)/)]);
+ expect(formatFinding(only(r.findings, 'render')[0])).toMatch(/^LINT: blocks render \S+:\d+ .+ \| fix: .+$/);
+ });
+
+ test('a short claim on a rule the render tier measured is refused as the Floor after both tiers settle', async () => {
+ const dir = tree({ 'index.html': '<!-- gstack-lint-disable horizontal-scroll: table scrolls -->\n' + PAGE });
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, run: runner((ev) => { ev[FIRST] = JSON.stringify([SCROLL]); }) });
+ expect(only(r.findings, 'waiver').map((f) => f.evidence)).toEqual([`waiver on horizontal-scroll refused: ${FLOOR_REFUSAL}`]);
+ expect(only(r.findings, 'horizontal-scroll').map((f) => f.grade)).toEqual(['blocks']);
+ });
+});
+
+describe('design-lint fifth cycle: rule judgement', () => {
+ test('a textarea taller than 52px is not a control-height finding; a button is', () => {
+ const body = '<main><h1>Hi there</h1><form><textarea></textarea><button>Go</button></form></main>';
+ expect(only(run(page('textarea { min-height: 120px; }', body)), 'control-height')).toEqual([]);
+ expect(only(run(page('button { height: 30px; }', body)), 'control-height').length).toBe(1);
+ });
+
+ test('a border width change on an attribute-selected input is input-state-shift', () => {
+ const f = run(page('input[type="text"] { border: 1px solid #333; } input[type="text"]:focus { border: 2px solid #000; outline: 2px solid red; }', '<main><h1>Hi there</h1><form><input type="text"></form></main>'));
+ expect(only(f, 'input-state-shift').length).toBe(1);
+ });
+
+ test('an <i> holding only a glyph is not an italic word; a word is', () => {
+ expect(only(run(page('', '<main><h1>Our favourite tools <i class="icon">★</i></h1><p>Body.</p></main>')), 'italic-word-in-heading')).toEqual([]);
+ expect(only(run(page('', '<main><h1>Our <i>favourite</i> tools and more</h1><p>Body.</p></main>')), 'italic-word-in-heading').length).toBe(1);
+ });
+
+ test('a bounce keyframe by name on a UI selector is bounce-easing', () => {
+ const f = run(page('@keyframes bounce { from { transform: none } to { transform: translateY(-4px) } } .btn:hover { animation: bounce .4s; }', '<main><h1>Hi there</h1><a class="btn" href="#">Go</a></main>'));
+ expect(only(f, 'bounce-easing').map((x) => x.evidence)).toEqual([expect.stringMatching(/^bounce animation bounce on/)]);
+ });
+
+ test('a single-quoted inline style colour literal is literal-outside-tokens like its double-quoted twin', () => {
+ const single = run(page('', "<main><h1>Hi there</h1><p style='color:#ff0000'>x</p></main>"));
+ const double = run(page('', '<main><h1>Hi there</h1><p style="color:#ff0000">x</p></main>'));
+ expect(only(single, 'literal-outside-tokens').map((x) => x.evidence)).toEqual(only(double, 'literal-outside-tokens').map((x) => x.evidence));
+ expect(only(single, 'literal-outside-tokens').length).toBe(1);
+ });
+
+ test('a glass panel mixed from black names black; a tracked-only control is not called uppercase; emoji icon tiles stop at eight', () => {
+ const glass = run(page('.glass::after { backdrop-filter: blur(8px); background: color-mix(in oklch, black 40%, transparent); }', '<main><h1>Hi there</h1><div class="glass">x</div></main>'));
+ expect(only(glass, 'glow-wash').map((x) => x.evidence)).toEqual([expect.stringMatching(/translucent black/)]);
+ const tracked = run(page('.btn { font-size: 13px; letter-spacing: .06em; }', '<main><h1>Hi there</h1><a class="btn" href="#">Go now</a></main>'));
+ expect(only(tracked, 'wide-tracking').map((x) => x.evidence)).toEqual([expect.stringMatching(/^\.btn: a control tracked 0\.06em at 13px$/)]);
+ const tiles = run(page('', '<main><h1>Hi there</h1>' + Array.from({ length: 12 }, (_, i) => '<div class="card"><span class="icon">🚀</span><h3>T' + i + '</h3></div>').join('\n') + '</main>'));
+ expect(only(tiles, 'emoji-decoration').length).toBe(8);
+ });
+});
diff --git a/test/design-lint-finish.test.ts b/test/design-lint-finish.test.ts
new file mode 100644
index 000000000..63f8ad4fd
--- /dev/null
+++ b/test/design-lint-finish.test.ts
@@ -0,0 +1,200 @@
+/**
+ * The finish rule family of the design lint (lib/design-lint/rules/finish.ts):
+ * for every rule id, one page that is clean for it and one with the tell
+ * planted, checked by id, grade and line. Everything here prints at polish
+ * except fake-avatar, which blocks.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { lint } from '../lib/design-lint/index';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Fraunces", serif; --font-body: "Public Sans", sans-serif; }';
+
+function page(css: string, body: string, htmlAttrs = ' lang="en"'): string {
+ return '<!doctype html>\n<html' + htmlAttrs + '>\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+}
+
+const lineOf = (html: string, needle: string): number => {
+ const at = html.indexOf(needle);
+ if (at < 0) throw new Error('needle not in page: ' + needle);
+ return html.slice(0, at).split('\n').length;
+};
+
+function run(html: string, files: Record<string, string> = {}): Finding[] {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-finish-'));
+ tmpDirs.push(dir);
+ fs.writeFileSync(path.join(dir, 'index.html'), html);
+ for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, name), text);
+ return lintStatic([dir], { cwd: dir, warn: (l) => { throw new Error(l); } }).findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const show = (findings: Finding[]) => findings.map(formatFinding);
+const polishAt = (findings: Finding[], rule: string, line: number) => expect(only(findings, rule).map((f) => [f.grade, f.line])).toEqual([['polish', line]]);
+
+describe('design-lint finish: prose (F1, F2)', () => {
+ test('straight-quotes prints at polish with the count; curly quotes are clean', () => {
+ const slop = page('', '<main>\n<p>Mari said "the close ran itself" and that\'s the review.</p>\n</main>');
+ const hits = only(run(slop), 'straight-quotes');
+ polishAt(hits, 'straight-quotes', lineOf(slop, 'Mari said'));
+ expect(hits[0].evidence).toMatch(/^3 straight quotes in prose \(first: /);
+ expect(only(run(page('', '<main><p>Mari said \u201cthe close ran itself\u201d and that\u2019s the review.</p></main>')), 'straight-quotes')).toEqual([]);
+ });
+
+ test('three-dot-ellipsis prints at polish; the ellipsis character is clean', () => {
+ const slop = page('', '<main>\n<p>Wait for it...</p>\n</main>');
+ polishAt(run(slop), 'three-dot-ellipsis', lineOf(slop, 'Wait for'));
+ expect(only(run(page('', '<main><p>Wait for it\u2026</p></main>')), 'three-dot-ellipsis')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: heads and buttons (F3, F4, F6)', () => {
+ test('balanced-display-head prints at polish when no display head has text-wrap: balance; one balanced head rule is clean', () => {
+ const slop = page('h1 {\n font-size: 3rem;\n}', '<main><h1>October closed in two days</h1></main>');
+ const hits = only(run(slop), 'balanced-display-head');
+ polishAt(hits, 'balanced-display-head', lineOf(slop, 'h1 {'));
+ expect(hits[0].evidence).toBe('no text-wrap: balance on any display head (1 head rules, the first h1)');
+ expect(only(run(page('h1 { font-size: 3rem; text-wrap: balance; }', '<main><h1>October closed in two days</h1></main>')), 'balanced-display-head')).toEqual([]);
+ });
+
+ test('two-primary-buttons prints at polish for two filled primary recipes; one filled recipe and an outline is clean', () => {
+ const slop = page('.btn-book { background: var(--color-accent); }\n.btn-buy {\n background: var(--color-ink);\n}', '<main><a class="btn-book" href="/book">Book</a><a class="btn-buy" href="/buy">Buy</a></main>');
+ const hits = only(run(slop), 'two-primary-buttons');
+ polishAt(hits, 'two-primary-buttons', lineOf(slop, 'background: var(--color-ink)'));
+ expect(hits[0].evidence).toBe('2 filled primary-button recipes on one page: .btn-book and .btn-buy');
+ expect(only(run(page('.btn-book { background: var(--color-accent); } .btn-quiet { background: transparent; border: 1px solid var(--color-accent); }', '<main><a class="btn-book" href="/book">Book</a><a class="btn-quiet" href="/method">Method</a></main>')), 'two-primary-buttons')).toEqual([]);
+ });
+
+ test('display-figures-tabular prints at polish for a display-size stat without tabular numerals; tabular-nums on the selector or the root is clean', () => {
+ const slop = page('.stat__num {\n font-size: 48px;\n}', '<main><p class="stat__num">1,140</p></main>');
+ const hits = only(run(slop), 'display-figures-tabular');
+ polishAt(hits, 'display-figures-tabular', lineOf(slop, 'font-size: 48px'));
+ expect(hits[0].evidence).toBe('figures on .stat__num at display size without tabular numerals');
+ expect(only(run(page('.stat__num { font-size: 48px; font-variant-numeric: tabular-nums; }', '<main><p class="stat__num">1,140</p></main>')), 'display-figures-tabular')).toEqual([]);
+ expect(only(run(page('body { font-variant-numeric: tabular-nums; } .stat__num { font-size: 48px; }', '<main><p class="stat__num">1,140</p></main>')), 'display-figures-tabular')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: surfaces and recipes (F5, F7, F24)', () => {
+ test('icon-coin prints at polish for a small round filled icon box; a bare inline icon is clean', () => {
+ const slop = page('.feature__icon {\n width: 40px;\n border-radius: 50%;\n background: var(--color-accent);\n}', '<main><span class="feature__icon" aria-hidden="true"></span></main>');
+ const hits = only(run(slop), 'icon-coin');
+ polishAt(hits, 'icon-coin', lineOf(slop, 'background: var(--color-accent)'));
+ expect(hits[0].evidence).toBe('an icon in a coloured coin: .feature__icon');
+ expect(only(run(page('.feature__icon { width: 20px; color: currentColor; }', '<main><span class="feature__icon" aria-hidden="true"></span></main>')), 'icon-coin')).toEqual([]);
+ });
+
+ test('stamped-recipe prints at polish for one container recipe on six selectors and for the pill radius on five non-controls; four varied boxes are clean', () => {
+ const recipe = ' { border: 1px solid var(--color-muted); border-radius: 8px; background: var(--color-paper); }';
+ const six = page(['.a', '.b', '.c', '.d', '.e', '.f'].map((s) => s + recipe).join('\n'), '<main><div class="a"></div></main>');
+ const hits = only(run(six), 'stamped-recipe');
+ polishAt(hits, 'stamped-recipe', lineOf(six, '.a {'));
+ expect(hits[0].evidence).toBe('one container recipe on 6 selectors (.a, .b, .c, .d and more)');
+ const pills = page('.card, .panel, .tile, .box, .media {\n border-radius: 9999px;\n}', '<main><div class="card"></div></main>');
+ const pillHits = only(run(pills), 'stamped-recipe');
+ polishAt(pillHits, 'stamped-recipe', lineOf(pills, 'border-radius: 9999px'));
+ expect(pillHits[0].evidence).toBe('the pill radius on 5 non-control selectors (.card, .panel, .tile, .box)');
+ expect(only(run(page('.btn, .chip, .tag, .badge, .pill { border-radius: 9999px; } .a' + recipe + ' .b { border-radius: 4px; background: var(--color-paper); }', '<main><div class="a"></div></main>')), 'stamped-recipe')).toEqual([]);
+ });
+
+ test('hairline-under-shadow prints at polish for a 1px border under a wide soft shadow, in CSS or Tailwind classes; a shadow alone is clean', () => {
+ const slop = page('.card {\n border: 1px solid var(--color-muted);\n box-shadow: 0 10px 30px -5px rgb(0 0 0 / 0.2);\n}', '<main><div class="card"></div></main>');
+ const hits = only(run(slop), 'hairline-under-shadow');
+ polishAt(hits, 'hairline-under-shadow', lineOf(slop, 'box-shadow'));
+ expect(hits[0].evidence).toBe('a hairline border under a wide soft shadow on .card');
+ const tw = page('', '<main>\n<div class="rounded-lg border shadow-xl"></div>\n</main>');
+ expect(only(run(tw), 'hairline-under-shadow').map((f) => [f.grade, f.line])).toEqual([['polish', lineOf(tw, 'shadow-xl')]]);
+ expect(only(run(page('.card { box-shadow: 0 10px 30px -5px rgb(0 0 0 / 0.2); }', '<main><div class="card"></div></main>')), 'hairline-under-shadow')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: motion and people (F8, F9)', () => {
+ test('scroll-choreography-mix prints at polish for two scroll-driven families; one is clean', () => {
+ const slop = page('.reveal { animation: rise linear both; animation-timeline: view(); }\n.bar {\n animation: grow linear both;\n animation-timeline: scroll();\n}', '<main><div class="reveal"></div><div class="bar"></div></main>');
+ const hits = only(run(slop), 'scroll-choreography-mix');
+ polishAt(hits, 'scroll-choreography-mix', lineOf(slop, 'animation-timeline: scroll()'));
+ expect(hits[0].evidence).toBe('2 scroll-choreography patterns on one page (reveal, bar)');
+ expect(only(run(page('.reveal { animation: rise linear both; animation-timeline: view(); }', '<main><div class="reveal"></div></main>')), 'scroll-choreography-mix')).toEqual([]);
+ });
+
+ test('fake-avatar blocks on a generated-face service; stock-person-photo prints at polish for a person-keyword stock URL; a named local portrait is clean', () => {
+ const slop = page('.hero { background-image: url(https://images.unsplash.com/photo-1?portrait); }', '<main>\n<img src="https://i.pravatar.cc/80?u=mari" alt="Mari">\n<img src="https://images.unsplash.com/photo-15?headshot=1" alt="A customer">\n</main>');
+ const findings = run(slop);
+ expect(only(findings, 'fake-avatar').map((f) => [f.tier, f.grade, f.line, f.evidence])).toEqual([['blocks', 'blocks', lineOf(slop, 'pravatar'), 'a generated-face service (i.pravatar.cc) stands in for a person']]);
+ expect(only(findings, 'stock-person-photo').map((f) => [f.grade, f.line]).sort((a, b) => Number(a[1]) - Number(b[1]))).toEqual([['polish', lineOf(slop, 'photo-1?portrait')], ['polish', lineOf(slop, 'headshot')]]);
+ const clean = run(page('', '<main><img src="/people/mari-halvorsen.jpg" alt="Mari Halvorsen"></main>'));
+ expect(only(clean, 'fake-avatar')).toEqual([]);
+ expect(only(clean, 'stock-person-photo')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: page invariants and browser surfaces (F15, F16)', () => {
+ test('page-invariants prints at polish for two container widths and for three column gaps; one width and one gap are clean', () => {
+ const widths = page('.wrap { max-width: 1200px; }\n.container { max-width: 1360px; }', '<main class="wrap"></main>');
+ const w = only(run(widths), 'page-invariants');
+ expect(w.map((f) => [f.grade, f.line, f.evidence])).toEqual([['polish', 1, '2 container widths on one page (1200, 1360px)']]);
+ const gaps = page('.a { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; } .b { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 32px; } .c { display: grid; grid-template-columns: repeat(2, 1fr); gap: 48px; }', '<main></main>');
+ expect(only(run(gaps), 'page-invariants').map((f) => f.evidence)).toEqual(['3 different column gaps across multi-column sections (24px, 32px, 48px)']);
+ expect(only(run(page('.wrap { max-width: 1360px; } .a, .b { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; }', '<main class="wrap"></main>')), 'page-invariants')).toEqual([]);
+ });
+
+ test('unthemed-browser-surfaces prints at polish naming the missing surfaces on a page with an accent; themed CSS or Tailwind surfaces are clean, and a page without an accent is skipped', () => {
+ const slop = page('', '<main><input type="email"></main>');
+ const hits = only(run(slop), 'unthemed-browser-surfaces');
+ expect(hits.map((f) => [f.grade, f.line, f.evidence])).toEqual([['polish', 1, 'browser surfaces left unthemed: ::selection, scrollbar-color, caret-color']]);
+ expect(only(run(page('::selection { background: var(--color-accent); } html { scrollbar-color: var(--color-muted) var(--color-paper); } input { caret-color: var(--color-accent); }', '<main><input type="email"></main>')), 'unthemed-browser-surfaces')).toEqual([]);
+ expect(only(run(page('', '<body class="selection:bg-accent [scrollbar-color:var(--color-muted)_var(--color-paper)]"><main><input type="email" class="caret-accent"></main></body>')), 'unthemed-browser-surfaces')).toEqual([]);
+ expect(only(run(page('', '<main></main>').replace('--color-accent: oklch(50% 0.16 30); ', '')), 'unthemed-browser-surfaces')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: the document (F21, F22, F23)', () => {
+ test('skipped-heading prints at polish when a level is skipped; stepped levels are clean', () => {
+ const slop = page('', '<main>\n<h1>October</h1>\n<h3>Where the days went</h3>\n</main>');
+ const hits = only(run(slop), 'skipped-heading');
+ polishAt(hits, 'skipped-heading', lineOf(slop, '<h3>'));
+ expect(hits[0].evidence).toBe('h1 is followed by h3 ("Where the days went")');
+ expect(only(run(page('', '<main><h1>October</h1><h2>Where the days went</h2><h3>Matching</h3></main>')), 'skipped-heading')).toEqual([]);
+ });
+
+ test('justified-text prints at polish without hyphens: auto, in CSS or as text-justify; hyphenated justification is clean', () => {
+ const slop = page('p {\n text-align: justify;\n}', '<main><p>Three days were matching receipts.</p></main>');
+ const hits = only(run(slop), 'justified-text');
+ polishAt(hits, 'justified-text', lineOf(slop, 'text-align: justify'));
+ expect(hits[0].evidence).toBe('justified text without hyphenation on p');
+ const tw = page('', '<main>\n<p class="text-justify">Three days were matching receipts.</p>\n</main>');
+ expect(only(run(tw), 'justified-text').map((f) => f.line)).toEqual([lineOf(tw, 'text-justify')]);
+ expect(only(run(page('p { text-align: justify; hyphens: auto; }', '<main><p>Three days were matching receipts.</p></main>')), 'justified-text')).toEqual([]);
+ });
+
+ test('missing-lang prints at polish for <html> without lang; the title and description halves belong to the copy tier', () => {
+ const slop = page('', '<main></main>', '');
+ const hits = only(run(slop), 'missing-lang');
+ polishAt(hits, 'missing-lang', lineOf(slop, '<html>'));
+ expect(hits[0].evidence).toBe('<html> names no lang');
+ expect(only(run(page('', '<main></main>')), 'missing-lang')).toEqual([]);
+ });
+});
+
+describe('design-lint finish: fixtures', () => {
+ test('the clean page raises nothing from this family; slopped.html plants the unbalanced head and the straight quotes; the waiver fixture waives balanced-display-head', async () => {
+ const finish = new Set(['straight-quotes', 'three-dot-ellipsis', 'balanced-display-head', 'two-primary-buttons', 'icon-coin', 'display-figures-tabular', 'stamped-recipe', 'scroll-choreography-mix', 'fake-avatar', 'stock-person-photo', 'page-invariants', 'unthemed-browser-surfaces', 'skipped-heading', 'justified-text', 'missing-lang', 'hairline-under-shadow']);
+ const clean = await lint([path.join(FIXTURES, 'clean')], { cwd: ROOT });
+ expect(show(clean.findings.filter((f) => finish.has(f.rule)))).toEqual([]);
+ const slopped = await lint([path.join(FIXTURES, 'slopped.html')], { cwd: ROOT });
+ expect(only(slopped.findings, 'balanced-display-head').map((f) => [f.grade, f.line])).toEqual([['polish', 63]]);
+ expect(only(slopped.findings, 'straight-quotes').map((f) => [f.grade, f.line])).toEqual([['polish', 141]]);
+ const waiver = await lint([path.join(FIXTURES, 'waiver')], { cwd: ROOT });
+ expect(only(waiver.findings, 'balanced-display-head').map((f) => f.grade)).toEqual(['waived']);
+ });
+});
diff --git a/test/design-lint-fourth-cycle.test.ts b/test/design-lint-fourth-cycle.test.ts
new file mode 100644
index 000000000..b1309e79a
--- /dev/null
+++ b/test/design-lint-fourth-cycle.test.ts
@@ -0,0 +1,302 @@
+/**
+ * The fourth review cycle's regressions: commented-out markup dead for every rule, the shared tree pairing behind
+ * Tailwind frames and wireframe slots, a parser that cannot be driven exponential or recursive by hostile CSS, lint
+ * roots and cwd reached through a symlink, files the lint could not read reported instead of passing silently, and
+ * the render tier keeping its measured findings when a page answers in the wrong shape.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import type { RenderResult, RenderSpec } from '../lib/aside-render';
+import { parseCss, pxOf, resolveVars } from '../lib/design-lint/css';
+import { parseDoc, scriptSites } from '../lib/design-lint/html';
+import { lintRender, type Runner } from '../lib/design-lint/render';
+import { Reporter, type Finding } from '../lib/design-lint/report';
+import { lintStatic, MAX_FILE_BYTES } from '../lib/design-lint/static';
+import { FLOOR_REFUSAL, OWN_RULE_REFUSAL, applyWaivers, resolveWaivers, suspectedRules } from '../lib/design-lint/waivers';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif; }';
+const HEAD = '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n';
+
+function page(css: string, body: string): string {
+ return HEAD + '<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+}
+
+function tree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-cycle4-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+
+const quiet = { warn: () => {} };
+const run = (html: string, files: Record<string, string> = {}): Finding[] => {
+ const dir = tree({ 'index.html': html, ...files });
+ return lintStatic([dir], { cwd: dir, ...quiet }).findings;
+};
+const only = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+const rules = (f: Finding[]) => [...new Set(f.map((x) => x.rule))].sort();
+
+describe('design-lint fourth cycle: commented-out markup is dead for every rule', () => {
+ test('tells inside an HTML comment report nothing: inline literal, italic word, broken image, fake avatar, emoji, craft copy', () => {
+ const live = page('', '<main><h1>The harbour office</h1><p>Rows close in order.</p></main>');
+ const dead = page('', '<main><h1>The harbour office</h1><p>Rows close in order.</p></main>\n<!--\n<img alt="x"> <div style="color:#ff0000">x</div> <h2>a <em>b</em> word here</h2>\n<img src="https://thispersondoesnotexist.com/a.jpg" alt="face">\n<p>🚀 Unlock the power of seamless, cutting-edge solutions.</p>\n<section class="hero"><h2>Meet Sarah.</h2></section>\n-->');
+ const before = rules(run(live));
+ const after = run(dead);
+ expect(rules(after)).toEqual(before);
+ expect(only(after, 'literal-outside-tokens').concat(only(after, 'italic-word-in-heading'), only(after, 'broken-image'), only(after, 'fake-avatar'), only(after, 'generic-hero-copy'))).toEqual([]);
+ });
+
+ test('a commented-out module script does not make the page a build-only shell, so its page rules still run', () => {
+ const body = '<main><h1>Harbour</h1><p>Rows.</p></main>';
+ const shell = HEAD + '<script type="module" src="/src/main.tsx"></script></head><body>' + body + '</body></html>';
+ const commented = HEAD + '<!-- <script type="module" src="/src/main.tsx"></script> --></head><body>' + body + '</body></html>';
+ expect(only(run(shell), 'overflow-x-unclipped')).toEqual([]);
+ expect(only(run(commented), 'overflow-x-unclipped').length).toBe(1);
+ });
+});
+
+describe('design-lint fourth cycle: one pairing for every tree reader', () => {
+ test('an unclosed <li> list before an eyebrow does not hide kicker-above-heading from the Tailwind frames', () => {
+ const body = (li: string) => '<main><h1>Hi there</h1><ol><li>one' + li + '<li>two' + li + '</ol><section><p class="text-xs uppercase tracking-wider">Our depots</p><h2>Bergen and Stavanger</h2></section></main>';
+ const closed = run(page('', body('</li>')));
+ const open = run(page('', body('')));
+ expect(only(closed, 'kicker-above-heading').length).toBeGreaterThan(0);
+ expect(only(open, 'kicker-above-heading').map((f) => f.line)).toEqual(only(closed, 'kicker-above-heading').map((f) => f.line));
+ });
+
+ test('wireframe-slots groups a row of unclosed <li data-slot> items under their list', () => {
+ const items = (close: string) => Array.from({ length: 6 }, (_, i) => '<li data-slot="s' + i + '"><span>x</span>' + close).join('\n');
+ const f = run(page('', '<main><h1>Hi there</h1><ul class="row">' + items('') + '</ul></main>'));
+ const closed = run(page('', '<main><h1>Hi there</h1><ul class="row">' + items('</li>') + '</ul></main>'));
+ expect(only(f, 'wireframe-slots').map((x) => x.evidence)).toEqual(only(closed, 'wireframe-slots').map((x) => x.evidence));
+ expect(only(f, 'wireframe-slots').some((x) => /in one row or grid/.test(x.evidence))).toBe(true);
+ });
+
+ test('a heading start tag closes an open heading and a block start closes an open <p>, so an unclosed run costs its length', () => {
+ const doc = parseDoc('x.html', '<body>' + '<h2>Title <em>x</em>\n'.repeat(3000) + '<p>a<div>b</div>' + '</body>');
+ const heads = doc.tags.filter((t) => !t.close && t.name === 'h2');
+ expect(heads.length).toBe(3000);
+ for (const frag of ['<h2>x ', '<button>x ', '<h2>a <em>x ', '<span class="a">x ']) {
+ const dir = tree({ 'index.html': '<!doctype html><html lang="en"><head><title>t</title></head><body>' + frag.repeat(10000) + '</body></html>' });
+ const t = performance.now();
+ lintStatic([dir], { cwd: dir, ...quiet });
+ expect(performance.now() - t, frag).toBeLessThan(8000);
+ }
+ }, 40_000);
+
+ test('a component file of unclosed <script> openers parses in linear time', () => {
+ for (const ext of ['vue', 'svelte', 'astro']) {
+ const t = performance.now();
+ parseDoc('x.' + ext, '<script>'.repeat(48000));
+ expect(performance.now() - t, ext).toBeLessThan(2000);
+ }
+ const t = performance.now();
+ scriptSites('<template>' + '<script setup>\nconst a = 1;\n'.repeat(8000) + '</template>', 'vue');
+ expect(performance.now() - t).toBeLessThan(2000);
+ });
+});
+
+describe('design-lint fourth cycle: hostile CSS', () => {
+ test('a self-referential token resolves in bounded time and a chain resolves fully', () => {
+ const t = performance.now();
+ expect(resolveVars('var(--a)', { '--a': 'var(--a) ' + 'x'.repeat(40) })).toContain('x');
+ expect(resolveVars('var(--a)', { '--a': 'var(--b)', '--b': 'var(--a)' })).toMatch(/var\(--[ab]\)/);
+ expect(resolveVars('var(--a)', { '--a': 'var(--b) 1px', '--b': 'red' })).toBe('red 1px');
+ expect(performance.now() - t).toBeLessThan(2000);
+ const grown = resolveVars('var(--a)', { '--a': 'var(--b) var(--b)', '--b': 'var(--c) var(--c)', '--c': 'var(--d) var(--d)', '--d': 'var(--e) var(--e)', '--e': 'y'.repeat(2048) });
+ expect(grown.length).toBeLessThan(40000);
+ });
+
+ test('parseCss bounds @media nesting the way it bounds rule nesting, inline or linked', () => {
+ const depth = 20_000;
+ const css = '@media (min-width:1px){'.repeat(depth) + 'a{color:red}' + '}'.repeat(depth);
+ const t = performance.now();
+ expect(() => parseCss(css, 'deep.css')).not.toThrow();
+ expect(performance.now() - t).toBeLessThan(3000);
+ const dir = tree({ 'index.html': HEAD + '<style>' + css + '</style></head><body><main><h1>Hi</h1><p>Body.</p></main></body></html>' });
+ expect(() => lintStatic([dir], { cwd: dir, ...quiet })).not.toThrow();
+ });
+
+ test('pxOf reads leading-dot lengths', () => {
+ expect(pxOf('.875rem')).toBe(14);
+ expect(pxOf('-.5em')).toBe(-8);
+ const f = run(page('.meta { font-size: .75rem; text-transform: uppercase; letter-spacing: .08em; }', '<main><h1>Hi there</h1><p class="meta">Our depots</p><p>Body copy here.</p></main>'));
+ expect(only(f, 'wide-tracking').map((x) => x.evidence)).toEqual(['.meta: uppercase tracked 0.08em at 12px in a label role']);
+ });
+});
+
+describe('design-lint fourth cycle: roots, cwd and files the lint could not read', () => {
+ test('a lint root reached through a symlink prints cwd-relative paths and still attaches a root-relative stylesheet', () => {
+ const real = tree({ 'css/a.css': TOKENS + '\nhtml, body { overflow-x: clip; }', 'index.html': HEAD + '<link rel="stylesheet" href="/css/a.css"></head><body><main><h1>Hi</h1><p>Body.</p></main></body></html>' });
+ const link = real + '-link';
+ fs.symlinkSync(real, link);
+ tmpDirs.push(link);
+ const r = lintStatic([link], { cwd: link, ...quiet });
+ expect(r.findings.every((f) => !path.isAbsolute(f.file))).toBe(true);
+ expect(only(r.findings, 'overflow-x-unclipped')).toEqual([]);
+ expect(r.contexts.length).toBe(1);
+ expect(r.contexts[0].cssFiles.map((c) => path.basename(c.file))).toEqual(['a.css']);
+ });
+
+ test('an oversize page is one internal-error finding, not a silent pass, and an oversize linked stylesheet is skipped with a warning', () => {
+ const big = 'x'.repeat(MAX_FILE_BYTES + 1);
+ const dir = tree({ 'index.html': page('', '<main><h1>Hi</h1><p>Body.</p></main>'), 'huge.html': '<!doctype html>' + big, 'huge.css': '/* ' + big + ' */', 'linked.html': HEAD + '<link rel="stylesheet" href="huge.css"></head><body><main><h1>Hi</h1><p>Body.</p></main></body></html>' });
+ const warnings: string[] = [];
+ const r = lintStatic([dir], { cwd: dir, warn: (l) => warnings.push(l) });
+ expect(only(r.findings, 'internal-error').map((f) => [f.grade, f.file, /over the 2 MB limit/.test(f.evidence)]).sort()).toEqual([['ask', 'huge.css', true], ['ask', 'huge.html', true]]);
+ expect(warnings.some((w) => /huge\.css.*over the 2 MB limit/.test(w))).toBe(true);
+ expect(r.files.map((f) => path.basename(f)).sort()).toEqual(['index.html', 'linked.html']);
+ });
+
+ test('a stylesheet with a whitespace run in its name still waives its own finding', () => {
+ const dir = tree({
+ 'index.html': HEAD + '<link rel="stylesheet" href="my theme.css"></head><body><main><h1>The ledger</h1><p>The ledger keeps its grey rows grey.</p></main></body></html>',
+ 'my theme.css': '/* gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey */\n' + TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }',
+ });
+ const f = lintStatic([dir], { cwd: dir, ...quiet }).findings;
+ expect(only(f, 'waiver')).toEqual([]);
+ expect(only(f, 'zero-chroma-neutrals').map((x) => [x.grade, x.file])).toEqual([['waived', 'my theme.css']]);
+ });
+});
+
+describe('design-lint fourth cycle: rule judgement', () => {
+ test('overused-font catches the full family names of catalog stems and leaves a longer word alone', () => {
+ for (const face of ['Cormorant Garamond', 'Crimson Pro', 'DM Serif Display', 'Geist Sans']) {
+ const f = run(page(':root { --font-display: "' + face + '", serif; }', '<main><h1>Hi there</h1><p>Body.</p></main>'));
+ expect(only(f, 'overused-font').length, face).toBeGreaterThan(0);
+ }
+ const inter = run(page(':root { --font-display: "Interstate", sans-serif; }', '<main><h1>Hi there</h1><p>Body.</p></main>'));
+ expect(only(inter, 'overused-font')).toEqual([]);
+ });
+
+ test('a container capped with width: min() is not a wide-container finding', () => {
+ const f = run(page('.wrap { width: min(100% - 2rem, 72rem); margin-inline: auto; }\n.hero__visual { width: 40vw; height: 300px; }', '<div class="wrap"><section class="hero"><h1>Hi there</h1><div class="hero__visual"></div></section></div>'));
+ expect(only(f, 'wide-container')).toEqual([]);
+ const bare = run(page('.wrap { width: 100%; }\n.hero__visual { width: 40vw; height: 300px; }', '<div class="wrap"><section class="hero"><h1>Hi there</h1><div class="hero__visual"></div></section></div>'));
+ expect(only(bare, 'wide-container').length).toBeGreaterThan(0);
+ });
+
+ test('a box-shadow focus ring beside a border-colour change is not input-state-shift; a border-only focus state still is', () => {
+ const body = '<main><h1>Hi there</h1><form><label for="e">Email</label><input id="e" type="text"><button>Go</button></form></main>';
+ const ring = run(page('input { border: 1px solid var(--color-ink); }\ninput:focus { border-color: var(--color-accent); box-shadow: 0 0 0 3px var(--color-accent); }', body));
+ expect(only(ring, 'input-state-shift')).toEqual([]);
+ const border = run(page('input { border: 1px solid var(--color-ink); }\ninput:focus { border-color: var(--color-accent); }', body));
+ expect(only(border, 'input-state-shift').length).toBe(1);
+ });
+
+ test('a Meet heading below the hero is suspected, not the Floor; inside the hero it blocks', () => {
+ const below = run(page('', '<section class="hero"><h1>Hi there</h1><p>Lead.</p></section><section><h2>Meet Sarah.</h2><p>Sarah runs the depot.</p></section>'));
+ expect(only(below, 'generic-hero-copy').map((x) => x.grade)).toEqual(['ask']);
+ const inside = run(page('', '<section class="hero"><h1>Hi there</h1><h2>Meet Sarah.</h2></section>'));
+ expect(only(inside, 'generic-hero-copy').map((x) => x.grade)).toEqual(['blocks']);
+ });
+});
+
+describe('design-lint fourth cycle: render answers of the wrong shape', () => {
+ const PAGE = HEAD + '</head><body><main><h1>t</h1><p>Body.</p></main></body></html>';
+ const SETUP = 1, FIRST = 2, FOCUS = 13;
+ const runner = (patch: (evals: Record<number, string>, spec: RenderSpec) => void): Runner => async (spec: RenderSpec): Promise<RenderResult> => {
+ const evals: Record<number, string> = { [SETUP]: '{"lost":[]}' };
+ for (let i = FIRST; i <= FOCUS; i++) evals[i] = '[]';
+ patch(evals, spec);
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout: '' };
+ };
+
+ test('a non-array measure, a null entry, a bad grade and an at without a tag each name their probe and keep the other measured findings', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ for (const bad of ['5', '{}', '[null]', '{"error":5}']) {
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'fail', evidence: 'the hero overflows' }]); ev[FIRST + 2] = bad; }) });
+ expect(only(r.findings, 'horizontal-scroll').map((f) => f.evidence), bad).toEqual(['[320px] the hero overflows']);
+ expect(only(r.findings, 'render').map((f) => f.evidence), bad).toEqual([expect.stringMatching(/^the \w+ measurement at \d+px failed: /)]);
+ }
+ const odd = await lintRender([file], { cwd: dir, run: runner((ev) => {
+ ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'fail', evidence: 'the hero overflows' }, { rule: 'nested-cards', grade: 'fail', evidence: 'x', at: {} }, { rule: 'nested-cards', grade: 'maybe', evidence: 'y' }, { rule: 7, evidence: 'z' }]);
+ ev[FOCUS] = JSON.stringify([{ bare: true }, { key: 'a.skip', bare: false, ratio: 5 }]);
+ }) });
+ expect(only(odd.findings, 'horizontal-scroll').map((f) => f.evidence)).toEqual(['[320px] the hero overflows']);
+ expect(only(odd.findings, 'nested-cards').map((f) => [f.grade, f.line])).toEqual([['blocks', 1]]);
+ expect(only(odd.findings, 'render').map((f) => /\((.*?)\)/.exec(f.evidence)![1])).toEqual(['nested-cards', '7', 'focus']);
+ expect(only(odd.findings, 'missing-focus-visible')).toEqual([]);
+ });
+
+ test('a setup answer without a list of lost assets blocks as unprepared and the measures are still read', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[SETUP] = '{}'; ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'fail', evidence: 'the hero overflows' }]); }) });
+ expect(only(r.findings, 'render').map((f) => f.evidence)).toEqual(['the page could not be prepared for measurement: the setup answer has no list of lost assets']);
+ expect(only(r.findings, 'horizontal-scroll').length).toBe(1);
+ });
+
+ test('merging horizontal-scroll widths never repeats the kept width', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => {
+ ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'may' }, { rule: 'horizontal-scroll', grade: 'fail', evidence: 'does' }]);
+ ev[FIRST + 1] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'also' }]);
+ }) });
+ expect(only(r.findings, 'horizontal-scroll').map((f) => [f.grade, f.evidence])).toEqual([['blocks', '[320px] does (also at 375px)']]);
+ });
+});
+
+describe('design-lint fourth cycle: never-waivable classes refuse by class before the reason is weighed', () => {
+ test('a short reason on an own rule, a measured Floor rule and a Floor rule nobody found is refused by class, never for its length', () => {
+ const measured = new Reporter('page', '/x');
+ measured.report('nested-cards', '/x/a.html', 4, 'div.card > div.card');
+ const claims = ['render', 'nested-cards', 'horizontal-scroll'].map((rule) => ({ rule, reason: 'fine here', file: '/x/a.html', line: 1 }));
+ const set = resolveWaivers(claims, 'the ledger closes the month', '/x', suspectedRules(measured.findings));
+ expect(set.refused.map((f) => f.evidence)).toEqual([
+ `waiver on render refused: ${OWN_RULE_REFUSAL}`,
+ `waiver on nested-cards refused: ${FLOOR_REFUSAL}`,
+ `waiver on horizontal-scroll refused: ${FLOOR_REFUSAL}`,
+ ]);
+ expect(applyWaivers(measured.findings, set).map((f) => [f.rule, f.grade])).toEqual([['nested-cards', 'blocks'], ['waiver', 'ask'], ['waiver', 'ask'], ['waiver', 'ask']]);
+ });
+});
+
+describe('design-lint fourth cycle: the pixel pass with a readable screenshot', () => {
+ const PAGE = HEAD + '</head><body><main><h1>t</h1><p class="faint">Body.</p><a href="#">Go</a></main></body></html>';
+ const SWATCH = path.join(path.resolve(import.meta.dir, '..'), 'test', 'fixtures', 'design-lint', 'render', 'swatch.png');
+ const SETUP = 1, FIRST = 2, FOCUS = 13;
+
+ test('a contrast claim is dropped when the pixels behind it clear the threshold, rewritten when they confirm it, and a weak ring that clears on the pixels around it is dropped', async () => {
+ // swatch.png is 8x8, red on the left half and blue on the right; the page rects are in CSS pixels, scaled to the screenshot by its width
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const white = { rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast 2.50:1 under the 4.5:1 threshold on h1 (2.50:1)', probe: { path: 'main>h1', fg: [1, 1, 1], threshold: 4.5 } };
+ const grey = { rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)', probe: { path: 'main>p', fg: [120 / 255, 120 / 255, 120 / 255], threshold: 4.5 } };
+ const ring = { key: 'a', path: 'main>a', at: { tag: 'a', text: 'Go' }, bare: false, ratio: 1.2, ring: [1, 1, 1], pad: 2 };
+ const shots: string[] = [];
+ const run: Runner = async (spec: RenderSpec): Promise<RenderResult> => {
+ const evals: Record<number, string> = {};
+ const shot = spec.steps.findIndex((s) => s.kind === 'screenshot');
+ if (shot < 0) {
+ evals[SETUP] = '{"lost":[]}';
+ for (let i = FIRST; i <= FOCUS; i++) evals[i] = '[]';
+ evals[FIRST + 5] = JSON.stringify([white, grey]);
+ evals[FOCUS] = JSON.stringify([ring]);
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout: '' };
+ }
+ spec.steps.forEach((s, i) => {
+ if (s.kind !== 'screenshot') return;
+ fs.copyFileSync(SWATCH, s.out);
+ shots.push(path.basename(s.out));
+ const width = s.width ?? 0, half = width / 2;
+ evals[i - 1] = s.out.endsWith('text.png') ? JSON.stringify([{ x: 0, y: 0, w: half, h: width }, { x: half, y: 0, w: half, h: width }]) : JSON.stringify([{ x: 0, y: 0, w: half, h: width }]);
+ });
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout: '' };
+ };
+ const r = await lintRender([file], { cwd: dir, run });
+ expect(shots.sort()).toEqual(['ring.png', 'text.png']);
+ expect(only(r.findings, 'low-contrast').map((f) => f.evidence)).toEqual(['[1280px] contrast 2.29:1 against the pixels behind, under the 4.5:1 threshold on p.faint (2.29:1)']);
+ expect(only(r.findings, 'missing-focus-visible')).toEqual([]);
+ });
+});
diff --git a/test/design-lint-motion.test.ts b/test/design-lint-motion.test.ts
new file mode 100644
index 000000000..018ffca41
--- /dev/null
+++ b/test/design-lint-motion.test.ts
@@ -0,0 +1,270 @@
+/**
+ * The motion and interaction rule family of the design lint (lib/design-lint/rules/motion.ts): for every rule id, a
+ * planted positive with its line and grade, and a negative control at the edge of the threshold. The shared fixtures
+ * (slopped.html, clean/) are checked for this family's rules too.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { formatFinding, lint, type Finding } from '../lib/design-lint/index';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+const FAMILY = ['layout-transition', 'spacing-transition', 'hover-tells', 'bounce-easing', 'focus-ring-fade', 'tooltip-focus-delay', 'autorotate-no-pause', 'missing-focus-visible', 'missing-states', 'missing-reduced-motion', 'autoplay-unmuted', 'lazy-lcp', 'video-without-poster', 'input-state-shift', 'control-height', 'content-hidden-at-rest'];
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --font-display: "Fraunces", serif; --font-body: "Source Serif 4", serif; }\nhtml, body { overflow-x: clip; }';
+const STATES = 'a:focus-visible, .button:focus-visible { outline: 2px solid var(--color-ink); }\n.button:active { transform: translateY(1px); }\n.button:disabled { opacity: 0.5; cursor: not-allowed; }';
+const REDUCE = '@media (prefers-reduced-motion: reduce) { * { animation: none; transition: none; } }';
+
+function page(css: string, body: string, opts: { states?: boolean; reduce?: boolean } = {}): string {
+ const base = [TOKENS, opts.states === false ? '' : STATES, opts.reduce ? REDUCE : ''].filter(Boolean).join('\n');
+ return `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Fixture</title>\n<style>\n${base}\n${css}\n</style>\n</head>\n<body>\n<main>\n${body}\n</main>\n</body>\n</html>\n`;
+}
+
+async function lintPage(html: string, opts: { scope?: 'page' | 'component' } = {}): Promise<Finding[]> {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-motion-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, 'index.html');
+ fs.writeFileSync(file, html);
+ return (await lint([file], { cwd: dir, scope: opts.scope, warn: (l: string) => { throw new Error(l); } })).findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const lineOf = (html: string, needle: string): number => html.split('\n').findIndex((l) => l.includes(needle)) + 1;
+const hits = (findings: Finding[], rule: string) => only(findings, rule).map((f) => [f.grade, f.line]);
+const none = (findings: Finding[], rule: string) => expect(only(findings, rule).map(formatFinding)).toEqual([]);
+const BUTTON = '<a class="button" href="/book">Book the walkthrough</a>';
+
+describe('design-lint motion: layout-transition (gate 10a)', () => {
+ test('transition: all, a transitioned width, and a keyframe animating height each block', async () => {
+ const html = page('.card { transition: all 0.3s ease; }\n.drawer { transition: width 200ms; }\n@keyframes grow {\n from { height: 0; }\n to { height: 10rem; }\n}', BUTTON, { reduce: true });
+ const f = await lintPage(html);
+ expect(hits(f, 'layout-transition')).toEqual([['blocks', lineOf(html, 'all 0.3s')], ['blocks', lineOf(html, 'width 200ms')], ['blocks', lineOf(html, 'height: 0')], ['blocks', lineOf(html, 'height: 10rem')]]);
+ expect(only(f, 'layout-transition').map((x) => x.evidence)).toEqual(['transition: all on .card', 'transitioning width on .drawer', '@keyframes grow animates height', '@keyframes grow animates height']);
+ });
+ test('transform and opacity transitions, and a max-height keyframe, are not layout transitions', async () => {
+ const html = page('.card { transition: transform 200ms, opacity 200ms; }\n@keyframes open { from { max-height: 0; opacity: 0; } to { max-height: 20rem; opacity: 1; } }', BUTTON, { reduce: true });
+ none(await lintPage(html), 'layout-transition');
+ });
+});
+
+describe('design-lint motion: spacing-transition (gate 10b)', () => {
+ test('transitioning padding or animating margin reports at ask', async () => {
+ const html = page('.card { transition: padding 200ms; }\n@keyframes nudge { to { margin-left: 1rem; } }', BUTTON, { reduce: true });
+ const f = await lintPage(html);
+ expect(hits(f, 'spacing-transition')).toEqual([['ask', lineOf(html, 'padding 200ms')], ['ask', lineOf(html, 'margin-left: 1rem')]]);
+ });
+ test('a transform transition is clean', async () => {
+ none(await lintPage(page('.card { transition: transform 200ms; }', BUTTON, { reduce: true })), 'spacing-transition');
+ });
+});
+
+describe('design-lint motion: hover-tells (gate 11)', () => {
+ test('one hover scale stamped on two selectors, an image scaling on hover, and the lift on three cards each report at ask', async () => {
+ const html = page([
+ '.a:hover { transform: scale(1.05); }',
+ '.b:hover { transform: scale(1.05); }',
+ '.card__img:hover { transform: scale(1.1); }',
+ '.c1:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0 0 0 / 0.1); }',
+ '.c2:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0 0 0 / 0.1); }',
+ '.c3:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0 0 0 / 0.1); }',
+ ].join('\n'), BUTTON, { reduce: true });
+ const f = await lintPage(html);
+ expect(hits(f, 'hover-tells')).toEqual([['ask', lineOf(html, '.a:hover')], ['ask', lineOf(html, '.card__img:hover')], ['ask', lineOf(html, '.c3:hover')]]);
+ expect(only(f, 'hover-tells').map((x) => x.evidence)).toEqual([
+ 'the same hover scale(1.05) on 2 selectors',
+ 'an image transforms on hover (.card__img:hover)',
+ 'the hover lift (translateY plus shadow) on 3 selectors (.c1, .c2, .c3)',
+ ]);
+ });
+ test('one hover scale on one selector, a colour change on an image, and a lift on two cards are within bounds', async () => {
+ const html = page('.a:hover { transform: scale(1.02); }\n.card__img:hover { opacity: 0.9; }\n.c1:hover, .c2:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0 0 0 / 0.1); }', BUTTON, { reduce: true });
+ none(await lintPage(html), 'hover-tells');
+ });
+});
+
+describe('design-lint motion: bounce-easing (gate 12)', () => {
+ test('an overshooting cubic-bezier on a UI state reports at ask, through a token too', async () => {
+ const html = page(':root { --ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1); }\n.button:hover { transition: transform 300ms var(--ease-spring); }\n.modal { animation: pop 300ms cubic-bezier(0.2, -0.3, 0.4, 1); }', BUTTON, { reduce: true });
+ const f = await lintPage(html);
+ expect(hits(f, 'bounce-easing')).toEqual([['ask', lineOf(html, '.button:hover')], ['ask', lineOf(html, '.modal')]]);
+ expect(only(f, 'bounce-easing')[0].evidence).toBe('overshoot easing cubic-bezier(0.34, 1.56, 0.64, 1) on .button:hover');
+ });
+ test('an exponential ease-out is clean', async () => {
+ none(await lintPage(page('.button:hover { transition: transform 300ms cubic-bezier(0.2, 0.8, 0.2, 1); }', BUTTON, { reduce: true })), 'bounce-easing');
+ });
+});
+
+describe('design-lint motion: focus-ring-fade (gate 15)', () => {
+ test('a transition on the focus rule, and a resting transition of the property the ring is drawn with, both block', async () => {
+ const html = page('.cta:focus-visible { outline: 2px solid var(--color-ink); transition: outline 200ms ease; }\n.pill { transition: box-shadow 200ms; }\n.pill:focus-visible { box-shadow: 0 0 0 3px var(--color-ink); }', '<button class="cta">Go</button><button class="pill">Go</button>');
+ const f = await lintPage(html);
+ expect(hits(f, 'focus-ring-fade')).toEqual([['blocks', lineOf(html, 'transition: outline')], ['blocks', lineOf(html, 'transition: box-shadow')]]);
+ expect(only(f, 'focus-ring-fade').map((x) => x.evidence)).toEqual(['the focus ring transitions in on .cta:focus-visible', '.pill transitions box-shadow while :focus-visible sets it, so the ring fades in']);
+ });
+ test('a ring drawn with outline while only background transitions is instant', async () => {
+ none(await lintPage(page('.cta { transition: background 200ms; }\n.cta:focus-visible { outline: 2px solid var(--color-ink); }', '<button class="cta">Go</button>')), 'focus-ring-fade');
+ });
+});
+
+describe('design-lint motion: tooltip-focus-delay (gate 17)', () => {
+ test('a tooltip delayed as long on focus as on hover reports as a suspected tell, at ask', async () => {
+ const html = page('.tooltip:hover .tip { transition-delay: 800ms; opacity: 1; }\n.tooltip:focus-within .tip { transition-delay: 800ms; opacity: 1; }', '<span class="tooltip" tabindex="0">?<span class="tip">Help</span></span>');
+ const f = await lintPage(html);
+ expect(only(f, 'tooltip-focus-delay').map((x) => [x.grade, x.tier, x.line])).toEqual([['ask', 'ask', lineOf(html, ':focus-within')]]);
+ });
+ test('an instant focus tooltip is clean', async () => {
+ none(await lintPage(page('.tooltip:hover .tip { transition-delay: 800ms; opacity: 1; }\n.tooltip:focus-within .tip { transition-delay: 0ms; opacity: 1; }', '<span class="tooltip" tabindex="0">?<span class="tip">Help</span></span>')), 'tooltip-focus-delay');
+ });
+});
+
+describe('design-lint motion: autorotate-no-pause (gate 18)', () => {
+ test('an infinite animation on a marquee with no paused state reports as a suspected tell, at ask', async () => {
+ const html = page('.marquee { animation: slide 20s linear infinite; }\n@keyframes slide { to { transform: translateX(-50%); } }', '<div class="marquee">Logos</div>', { reduce: true });
+ const f = await lintPage(html);
+ expect(only(f, 'autorotate-no-pause').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'infinite'), 'an infinite animation on .marquee with no paused state on hover or focus']]);
+ });
+ test('a marquee that pauses on hover is clean', async () => {
+ none(await lintPage(page('.marquee { animation: slide 20s linear infinite; }\n.marquee:hover, .marquee:focus-within { animation-play-state: paused; }\n@keyframes slide { to { transform: translateX(-50%); } }', '<div class="marquee">Logos</div>', { reduce: true })), 'autorotate-no-pause');
+ });
+});
+
+describe('design-lint motion: missing-focus-visible and missing-states (gates 26a, 26b)', () => {
+ test('a page with a button and no :focus-visible, :active or :disabled style reports all three at the stylesheet', async () => {
+ const html = page('.button { color: var(--color-ink); }', '<button class="button">Go</button>', { states: false });
+ const f = await lintPage(html);
+ expect(only(f, 'missing-focus-visible').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', 1, 'no :focus-visible style anywhere: keyboard users cannot see where they are']]);
+ expect(only(f, 'missing-states').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', 1, 'no :active style anywhere'], ['ask', 1, 'no :disabled style anywhere']]);
+ });
+ test('a ring, an active state and a disabled state satisfy both; a page with nothing interactive asks for none', async () => {
+ const f = await lintPage(page('', BUTTON));
+ none(f, 'missing-focus-visible');
+ none(f, 'missing-states');
+ const inert = await lintPage(page('', '<p>Only prose.</p>', { states: false }));
+ none(inert, 'missing-focus-visible');
+ none(inert, 'missing-states');
+ });
+ test('a link-only page needs no :disabled, and an aria-disabled selector counts as the disabled state', async () => {
+ none(await lintPage(page('a:focus-visible { outline: 2px solid; }\na:active { color: red; }', '<a href="/">Home</a>', { states: false })), 'missing-states');
+ none(await lintPage(page('.button:focus-visible { outline: 2px solid; }\n.button:active { color: red; }\n.button[aria-disabled="true"] { opacity: 0.5; cursor: not-allowed; }', '<button class="button">Go</button>', { states: false })), 'missing-states');
+ });
+});
+
+describe('design-lint motion: missing-reduced-motion (gate 27)', () => {
+ test('keyframes with no prefers-reduced-motion block anywhere block at the keyframes', async () => {
+ const html = page('.bar { animation: grow 2s ease infinite; }\n@keyframes grow { from { opacity: 0; } to { opacity: 1; } }', BUTTON);
+ const f = await lintPage(html);
+ expect(only(f, 'missing-reduced-motion').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(html, 'from { opacity: 0'), 'motion present and no prefers-reduced-motion block anywhere']]);
+ const transition = page('.card { transition: transform 200ms; }', BUTTON);
+ expect(only(await lintPage(transition), 'missing-reduced-motion').map((x) => x.line)).toEqual([1]);
+ });
+ test('a prefers-reduced-motion block answers it, and a page with no motion needs none', async () => {
+ none(await lintPage(page('.bar { animation: grow 2s ease infinite; }\n@keyframes grow { from { opacity: 0; } to { opacity: 1; } }', BUTTON, { reduce: true })), 'missing-reduced-motion');
+ none(await lintPage(page('.card { transition: background 200ms; }', BUTTON)), 'missing-reduced-motion');
+ });
+});
+
+describe('design-lint motion: autoplay-unmuted, lazy-lcp and video-without-poster (gates 28a, 28b)', () => {
+ test('an autoplaying video without muted blocks; a video without poster asks; a lazy first image or video is a suspected LCP tell at ask', async () => {
+ const html = page('', '<section class="hero">\n<h1>Two days to close</h1>\n<video autoplay loop playsinline src="a.mp4"></video>\n<img loading="lazy" src="a.png" alt="A">\n</section>');
+ const f = await lintPage(html);
+ expect(only(f, 'autoplay-unmuted').map((x) => [x.grade, x.line])).toEqual([['blocks', lineOf(html, '<video')]]);
+ expect(only(f, 'video-without-poster').map((x) => [x.grade, x.line])).toEqual([['ask', lineOf(html, '<video')]]);
+ none(f, 'lazy-lcp');
+ const lazyImg = page('', '<section class="hero">\n<h1>Two days to close</h1>\n<img loading="lazy" src="a.png" alt="A">\n</section>');
+ expect(only(await lintPage(lazyImg), 'lazy-lcp').map((x) => [x.grade, x.tier, x.line])).toEqual([['ask', 'ask', lineOf(lazyImg, '<img')]]);
+ const lazyVideo = page('', '<video muted loading="lazy" poster="p.jpg" src="a.mp4"></video>');
+ expect(only(await lintPage(lazyVideo), 'lazy-lcp').map((x) => x.evidence)).toEqual(['the first video loads lazily and is likely the largest paint']);
+ });
+ test('autoplay muted with a poster, an eager first image and a lazy second image are clean', async () => {
+ const f = await lintPage(page('', '<section class="hero"><h1>Two days to close</h1><video autoplay muted loop playsinline poster="p.jpg" src="a.mp4"></video><img src="a.png" alt="A"></section>\n<img loading="lazy" src="b.png" alt="B">'));
+ none(f, 'autoplay-unmuted');
+ none(f, 'video-without-poster');
+ none(f, 'lazy-lcp');
+ });
+});
+
+describe('design-lint motion: input-state-shift (gate 39a)', () => {
+ const field = '<form><label for="e">Email</label><input id="e" type="email"><button class="button" type="submit">Send</button></form>';
+ test('a border that changes width on focus, a focus state drawn with border, and disabled by opacity alone each block', async () => {
+ const html = page('input { border: 1px solid var(--color-ink); }\ninput:focus { border: 2px solid var(--color-ink); }\n.field:focus { border-color: var(--color-ink); }\n.button:disabled { opacity: 0.5; }', field, { states: false });
+ const f = await lintPage(html);
+ expect(only(f, 'input-state-shift').map((x) => [x.grade, x.line, x.evidence])).toEqual([
+ ['blocks', lineOf(html, 'input:focus'), 'the border goes from 1px to 2px on input:focus, so the field shifts'],
+ ['blocks', lineOf(html, 'input:focus'), 'the focus state is drawn with border on input:focus'],
+ ['blocks', lineOf(html, '.field:focus'), 'the focus state is drawn with border on .field:focus'],
+ ['blocks', lineOf(html, '.button:disabled'), 'disabled by opacity alone on .button:disabled'],
+ ]);
+ });
+ test('a constant border with the focus state on outline, and a disabled state with cursor: not-allowed, are clean', async () => {
+ none(await lintPage(page('input { border: 1px solid var(--color-ink); }\ninput:focus { border-color: var(--color-ink); outline: 2px solid var(--color-ink); outline-offset: 2px; }', field)), 'input-state-shift');
+ });
+});
+
+describe('design-lint motion: control-height (gate 39b, static half)', () => {
+ test('a control whose CSS fixes its height outside 44 to 52px reports at ask on a page', async () => {
+ const html = page('.button { height: 36px; }\ninput { min-height: 3.5rem; }', '<form><input type="text" aria-label="Name">' + BUTTON + '</form>');
+ const f = await lintPage(html);
+ expect(only(f, 'control-height').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'height: 36px'), 'height: 36px (36px) on .button: controls stand 44 to 52px'], ['ask', lineOf(html, '3.5rem'), 'min-height: 3.5rem (56px) on input: controls stand 44 to 52px']]);
+ none(await lintPage(html, { scope: 'component' }), 'control-height');
+ });
+ test('48px controls, a hidden radio, and an icon button are not reported', async () => {
+ none(await lintPage(page('.button { min-height: 48px; }\ninput[type="radio"] { height: 1px; }\n.icon-button { height: 32px; }', '<form><input type="radio" aria-label="A"><button class="icon-button" aria-label="Close"></button>' + BUTTON + '</form>')), 'control-height');
+ });
+});
+
+describe('design-lint motion: content-hidden-at-rest (gate 62)', () => {
+ test('a reveal class hidden at rest with a transform, waiting for a script, blocks at the hiding declaration', async () => {
+ const html = page('.reveal {\n opacity: 0;\n transform: translateY(20px);\n transition: opacity 400ms, transform 400ms;\n}\n.reveal.is-visible { opacity: 1; transform: none; }', '<p class="reveal">Hidden until observed.</p>', { reduce: true });
+ const f = await lintPage(html);
+ expect(only(f, 'content-hidden-at-rest').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(html, 'opacity: 0;'), '.reveal is hidden at rest (opacity: 0) and needs a script to appear']]);
+ });
+ test('hiding under a .js class, animating from hidden to visible, and a hidden tooltip are clean', async () => {
+ none(await lintPage(page('.js .reveal { opacity: 0; transform: translateY(20px); }', '<p class="reveal">Hidden until observed.</p>', { reduce: true })), 'content-hidden-at-rest');
+ none(await lintPage(page('.rise { opacity: 0; animation: rise 600ms ease-out forwards; }\n@keyframes rise { to { opacity: 1; } }', '<p class="rise">Rises.</p>', { reduce: true })), 'content-hidden-at-rest');
+ none(await lintPage(page('.tooltip { opacity: 0; transform: translateY(4px); }', '<span class="tooltip">Help</span>', { reduce: true })), 'content-hidden-at-rest');
+ });
+});
+
+describe('design-lint motion: the shared fixtures', () => {
+ test('slopped.html trips the planted motion tells at their lines', async () => {
+ const f = (await lint([path.join(FIXTURES, 'slopped.html')], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } })).findings;
+ const mine = f.filter((x) => FAMILY.includes(x.rule)).map((x) => [x.rule, x.grade, x.line]);
+ expect(mine).toEqual([
+ ['focus-ring-fade', 'blocks', 85],
+ ['layout-transition', 'blocks', 79],
+ ['layout-transition', 'blocks', 97],
+ ['layout-transition', 'blocks', 98],
+ ['missing-reduced-motion', 'blocks', 97],
+ ['missing-states', 'ask', 1],
+ ['missing-states', 'ask', 1],
+ ]);
+ });
+ test('the clean page raises no motion finding', async () => {
+ const f = (await lint([path.join(FIXTURES, 'clean')], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } })).findings;
+ expect(f.filter((x) => FAMILY.includes(x.rule)).map(formatFinding)).toEqual([]);
+ });
+});
+
+describe('design-lint motion: the removed-outline check (third review cycle)', () => {
+ test('a fractional outline on :focus-visible is a ring, so outline: none on :focus does not block', async () => {
+ const f = await lintPage(page('a:focus { outline: none; }\na:focus-visible { outline: 0.25rem solid var(--color-ink); }', '<a href="/x">Go</a>', { states: false }).replace('a:focus-visible, .button:focus-visible { outline: 2px solid var(--color-ink); }\n', ''));
+ none(f, 'missing-focus-visible');
+ });
+ test('the usual :focus:not(:focus-visible) reset with a ring, and a box-shadow ring beside outline: none, are clean; outline: 0 and outline-style: none with no ring block', async () => {
+ const base = (css: string) => page(css, '<a href="/x">Go</a>', { states: false });
+ none(await lintPage(base('a:focus:not(:focus-visible) { outline: none; }\na:focus-visible { outline: 2px solid var(--color-ink); }')), 'missing-focus-visible');
+ none(await lintPage(base('a:focus { outline: none; box-shadow: 0 0 0 3px var(--color-ink); }')), 'missing-focus-visible');
+ for (const removed of ['outline: 0', 'outline: 0px', 'outline-style: none']) {
+ const html = base(`a:focus { ${removed}; }`);
+ const f = await lintPage(html);
+ expect(only(f, 'missing-focus-visible').map((x) => [x.grade, x.evidence.split(' on ')[0]])).toEqual([['blocks', removed]]);
+ }
+ const hoverOnly = await lintPage(base('a:focus { outline: none; }\na:hover { outline: 2px solid var(--color-ink); }'));
+ expect(only(hoverOnly, 'missing-focus-visible').map((x) => x.grade)).toEqual(['blocks']);
+ });
+});
diff --git a/test/design-lint-recorded.test.ts b/test/design-lint-recorded.test.ts
new file mode 100644
index 000000000..bce66b328
--- /dev/null
+++ b/test/design-lint-recorded.test.ts
@@ -0,0 +1,60 @@
+/**
+ * The lint over the repository's recorded design slop page (the review eval's
+ * ground truth, test/fixtures/review-eval-design-slop.{html,css}): every issue
+ * the page annotates that the lint has a rule for is reported, the clean
+ * fixture is not, and both agree with hallmark's own sloplint on the same
+ * files (checked by hand at hallmark 7ec8682; the gate set is identical).
+ * Phase 1 of the hallmark absorption plan, item D7: the free regression that a
+ * recorded output keeps linting the same way.
+ */
+import { describe, expect, test } from 'bun:test';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { lint } from '../lib/design-lint';
+import { exitCodeOf, formatSummary } from '../lib/design-lint/report';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures');
+
+/** The recorded page as it was served: index.html beside the styles.css it links. */
+function recordedPage(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-recorded-'));
+ fs.copyFileSync(path.join(FIXTURES, 'review-eval-design-slop.html'), path.join(dir, 'index.html'));
+ fs.copyFileSync(path.join(FIXTURES, 'review-eval-design-slop.css'), path.join(dir, 'styles.css'));
+ return dir;
+}
+
+describe('design-lint over the recorded review slop page', () => {
+ test('each annotated issue the lint has a rule for is reported, with its line, and the page exits 2', async () => {
+ const dir = recordedPage();
+ try {
+ const r = await lint([dir], { cwd: dir });
+ const at = (rule: string) => r.findings.filter((f) => f.rule === rule).map((f) => [f.grade, path.basename(f.file), f.line]);
+ // Issue 1: the blacklisted face (Papyrus) is a banned face in any role
+ expect(at('banned-font')).toEqual([['ask', 'styles.css', 6]]);
+ // Issue 5: the indigo-to-violet gradient is the banned gradient
+ expect(at('purple-blue-gradient')).toEqual([['blocks', 'styles.css', 14]]);
+ // The page declares no --color-* or --font-* token, so its literals bypass nothing and literal-outside-tokens stays quiet
+ expect(at('literal-outside-tokens')).toEqual([]);
+ // Issue 3: outline: none with nothing in its place
+ expect(at('missing-focus-visible')).toEqual([['blocks', 'styles.css', 1]]);
+ // Issue 7: the three-column icon-tile grid and its coins
+ expect(at('template-cards')).toEqual([['ask', 'styles.css', 33]]);
+ expect(at('icon-coin')).toEqual([['polish', 'styles.css', 51]]);
+ // Issue 6: generic hero copy, the two lines the design catalog names for it and the buzzword behind them
+ expect(at('generic-hero-copy')).toEqual([['blocks', 'index.html', 12], ['blocks', 'index.html', 13]]);
+ expect(at('marketing-buzzword')).toEqual([['ask', 'index.html', 1]]);
+ // Tells the page does not annotate but hallmark's sloplint reports on the same files
+ expect(at('pure-black-white').map((f) => f[2])).toEqual([17, 63, 85]);
+ expect(at('overflow-x-unclipped')).toEqual([['ask', 'styles.css', 1]]);
+ expect(at('off-scale-spacing')).toEqual([['ask', 'styles.css', 78]]);
+ expect(at('skipped-heading')).toEqual([['polish', 'index.html', 21]]);
+ expect(r.findings.some((f) => f.grade === 'waived')).toBe(false);
+ expect(exitCodeOf(r.summary)).toBe(2);
+ expect(formatSummary(r.summary)).toMatch(/^LINT_SUMMARY: blocks=7 ask=\d+ waived=0 polish=4 render=skipped: not requested$/);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/design-lint-render.test.ts b/test/design-lint-render.test.ts
new file mode 100644
index 000000000..d5fadcde6
--- /dev/null
+++ b/test/design-lint-render.test.ts
@@ -0,0 +1,306 @@
+/**
+ * The design lint's render tier: every render rule id gets a page that passes
+ * it (the clean fixture) and a page with the tell planted, measured through
+ * whichever browser lib/aside-render picks (gstack's own browse daemon on the
+ * free lane). Skipped with a named reason when neither browser is available;
+ * the skipped and render-failure paths run everywhere.
+ */
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { lint } from '../lib/design-lint/index';
+import { lintRender, lineOf } from '../lib/design-lint/render';
+import { installScript } from '../lib/design-lint/render-probe';
+import { decodePng, medianRgb } from '../lib/design-lint/render-png';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { RULES } from '../lib/design-lint/rules/ids';
+import { NO_BROWSER, buildRenderScript, pickEngine, renderWithBrowse, resolveBrowseBin, type EngineChoice } from '../lib/aside-render';
+import { asideAvailable } from './helpers/aside-available';
+import { browserAvailable, NO_BROWSER_REASON } from './helpers/browser-available';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const CLEAN = fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'design-lint', 'clean', 'index.html'), 'utf8');
+const hasBrowser = browserAvailable();
+if (!hasBrowser) process.stderr.write(`design-lint-render: SKIPPED — ${NO_BROWSER_REASON}\n`);
+
+const RENDER_RULES = Object.entries(RULES).filter(([, m]) => m.render).map(([id]) => id);
+
+/** The engine for these pages, chosen here rather than read from lib/aside-render's per-process cache, which other test files prime with fakes. */
+const engine = (): EngineChoice => {
+ if (asideAvailable()) return pickEngine(true);
+ const bin = resolveBrowseBin();
+ return bin ? { engine: 'browse', bin } : { engine: null, probe: { ok: false, reason: 'NEEDS_ASIDE', detail: NO_BROWSER_REASON }, error: NO_BROWSER_REASON };
+};
+
+function tmpPage(html: string): { file: string; dir: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-render-'));
+ const file = path.join(dir, 'index.html');
+ fs.writeFileSync(file, html);
+ return { file, dir };
+}
+
+/** The clean fixture with extra CSS in its head and extra markup before </main>. */
+const pageWith = (css: string, body: string, swap: Array<[string, string]> = []): string => {
+ let html = CLEAN.replace('</style>', css + '\n</style>').replace('</main>', body + '\n</main>');
+ for (const [from, to] of swap) { if (!html.includes(from)) throw new Error('swap target missing: ' + from); html = html.replace(from, to); }
+ return html;
+};
+
+const lineIn = (html: string, needle: string): number => { const i = html.indexOf(needle); if (i < 0) throw new Error('needle missing: ' + needle); return html.slice(0, i).split('\n').length; };
+
+async function measure(html: string): Promise<{ html: string; findings: Finding[]; status: string; of: (rule: string) => Finding[]; lines: string }> {
+ const { file, dir } = tmpPage(html);
+ try {
+ const r = await lintRender([file], { cwd: dir, engine });
+ return { html, findings: r.findings, status: r.status, of: (rule) => r.findings.filter((f) => f.rule === rule), lines: r.findings.map(formatFinding).join('\n') };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+const SVG_IMG = (w: number, h: number, fill: string) => `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${w}' height='${h}'%3E%3Crect width='${w}' height='${h}' fill='%23${fill}'/%3E%3C/svg%3E`;
+const WORDS = (n: number) => Array.from({ length: n }, (_, i) => ['ledger', 'invoice', 'carrier', 'receipt', 'review', 'close', 'depot', 'month'][i % 8]).join(' ');
+
+describe('design-lint render: the pure parts', () => {
+ test('lineOf finds the element by tag, class and opening text; falls back to the tag, then line 1', () => {
+ const src = '<main>\n<p class="lede">First words here</p>\n<p class="lede">Second words here</p>\n<button class="button">Go</button>\n</main>';
+ expect(lineOf(src, { tag: 'p', cls: 'lede', text: 'Second words here' })).toBe(3);
+ expect(lineOf(src, { tag: 'p', cls: 'lede', text: 'no such text' })).toBe(2);
+ expect(lineOf(src, { tag: 'button', cls: '', text: '' })).toBe(4);
+ expect(lineOf(src, { tag: 'h1', cls: '', text: '' })).toBe(1);
+ expect(lineOf(src + '\n<div data-slot="a"></div>\n<div data-slot="b"></div>', { tag: 'div', cls: '', text: '', attr: 'data-slot="b"' })).toBe(7);
+ expect(lineOf(null, { tag: 'p', cls: '', text: '' })).toBe(1);
+ });
+
+ test('the install script carries every probe and no module-scope reference', () => {
+ const js = installScript();
+ for (const name of ['setup', 'layout', 'contrast', 'accent', 'focus', 'occlusion', 'space', 'quality', 'hide', 'restore']) expect(js).toContain(name + ': (');
+ expect(js).not.toMatch(/\bimport\b|\bexport\b|require\(/);
+ });
+
+ test('decodePng reads an RGB PNG and medianRgb samples a rectangle, leaving out an inner one', () => {
+ const png = decodePng(fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'design-lint', 'render', 'swatch.png')))!;
+ expect([png.width, png.height, png.channels]).toEqual([8, 8, 3]);
+ expect(medianRgb(png, { x: 0, y: 0, w: 4, h: 8 })!.map((v) => Math.round(v * 255))).toEqual([200, 30, 30]);
+ expect(medianRgb(png, { x: 0, y: 0, w: 8, h: 8, inner: { l: 0, t: 0, r: 4, b: 8 } })!.map((v) => Math.round(v * 255))).toEqual([30, 30, 200]);
+ expect(decodePng(Buffer.from('not a png'))).toBeNull();
+ });
+
+ test('no browser: findings are empty and the status names the reason', async () => {
+ const r = await lintRender(['/nowhere/index.html'], { engine: () => ({ engine: null, probe: { ok: false, reason: 'NEEDS_ASIDE', detail: 'test' }, error: `${NO_BROWSER}: open Aside or run ./setup (NEEDS_ASIDE: test)` }) });
+ expect(r.findings).toEqual([]);
+ expect(r.status).toBe(`skipped: ${NO_BROWSER}: open Aside or run ./setup (NEEDS_ASIDE: test)`);
+ expect((await lintRender([])).status).toBe('skipped: no HTML page to render');
+ });
+});
+
+describe.skipIf(process.platform === 'win32')('design-lint render: the eval viewport and URL targets on both engines', () => {
+ test('the Aside script sets the device metrics before a sized eval and clears them after', () => {
+ const script = buildRenderScript('http://127.0.0.1:1/x.html', { file: '/x.html', steps: [{ kind: 'eval', expression: 'innerWidth', width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, { kind: 'eval', expression: 'document.title' }] });
+ const set = script.indexOf('Emulation.setDeviceMetricsOverride", {"width":1440,"height":900,"deviceScaleFactor":1,"mobile":false}');
+ const run = script.indexOf('pg.evaluate((src) => (0, eval)(src), "innerWidth")');
+ const clear = script.indexOf('Emulation.clearDeviceMetricsOverride');
+ expect(set).toBeGreaterThan(-1);
+ expect(set).toBeLessThan(run);
+ expect(run).toBeLessThan(clear);
+ expect(script.indexOf('"document.title"')).toBeGreaterThan(clear);
+ expect(script.match(/setDeviceMetricsOverride/g)).toHaveLength(1);
+ });
+
+ test('the browse path sets the viewport before a sized eval, restores the default after, and opens an http target without serving anything', async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-fake-browse-'));
+ try {
+ const log = path.join(tmp, 'argv.log');
+ const bin = path.join(tmp, 'browse');
+ fs.writeFileSync(bin, `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(log)}\ncase "$1" in newtab) echo '{"tabId":7}' ;; js) echo 42 ;; *) : ;; esac\n`, { mode: 0o755 });
+ const doc = path.join(tmp, 'doc.html');
+ fs.writeFileSync(doc, '<!doctype html><title>Doc</title>');
+ const r = await renderWithBrowse({ file: doc, steps: [{ kind: 'eval', expression: 'innerWidth', width: 1440, height: 900 }, { kind: 'eval', expression: '1' }] }, bin);
+ expect(r.error).toBeUndefined();
+ expect(r.evals).toEqual({ 0: '42', 1: '42' });
+ const lines = fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).filter((l) => !/^js \(\(\) => \{ window\.__gstackErrs|^js JSON\.stringify\(window\.__gstackErrs/.test(l));
+ expect(lines.slice(0, 6)).toEqual(['newtab --json', expect.stringMatching(/^goto http:\/\/127\.0\.0\.1:\d+\/[0-9a-f]{32}\/doc\.html --tab-id 7$/), 'viewport 1440x900 --tab-id 7', 'js innerWidth --tab-id 7', 'viewport 1280x720 --tab-id 7', 'js 1 --tab-id 7']);
+ fs.rmSync(log);
+ const u = await renderWithBrowse({ file: 'http://example.test/page', steps: [{ kind: 'eval', expression: '1' }] }, bin);
+ expect(u.error).toBeUndefined();
+ expect(fs.readFileSync(log, 'utf8')).toContain('goto http://example.test/page --tab-id 7');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});
+
+describe.skipIf(!hasBrowser)('design-lint render: the browser tier', () => {
+ test('the clean fixture passes every render rule; status is ran', async () => {
+ const r = await measure(CLEAN);
+ expect(r.status).toBe('ran');
+ expect(r.findings.filter((f) => RENDER_RULES.includes(f.rule) || f.rule === 'render').map(formatFinding)).toEqual([]);
+ }, 60_000);
+
+ test('a URL nobody answers and a file that is not there each report render; the status still says ran', async () => {
+ const r = await lintRender(['http://127.0.0.1:9/', '/nowhere/missing.html'], { engine });
+ expect(r.status).toBe('ran');
+ const render = r.findings.filter((f) => f.rule === 'render');
+ expect(render).toHaveLength(2);
+ expect(render[0].grade).toBe('blocks');
+ expect(render[0].evidence).toMatch(/^could not reach http:\/\/127\.0\.0\.1:9\//);
+ expect(render[1].evidence).toMatch(/^the page did not render: HTML file not found/);
+ }, 60_000);
+
+ test('layout tells: horizontal scroll, a wrapping button and link, the headline past the fold, a stylesheet that did not load', async () => {
+ const html = pageWith(
+ '.hero { padding-top: 760px; } .narrow { width: 120px; } .wide { width: 2400px; height: 8px; background: var(--color-line); }',
+ '<div class="wide"></div>\n<div class="narrow"><a class="button" href="/book">Book the complete walkthrough today</a></div>\n<footer><div class="narrow"><a class="quiet" href="/method">Read how the close works for you</a></div></footer>',
+ [['</head>', '<link rel="stylesheet" href="missing.css">\n</head>']],
+ );
+ const r = await measure(html);
+ expect(r.of('render').map((f) => [f.grade, f.evidence])).toEqual([['ask', 'fonts or stylesheets did not load (missing.css): the measurements show a fallback face']]);
+ expect(r.findings.every((f) => f.source === 'render')).toBe(true);
+ expect(r.of('horizontal-scroll').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', lineIn(html, 'class="wide"'), "[375px] div.wide runs 2057px past the 375px screen, hidden only by the page's clip"]]);
+ const unclipped = await measure(html.replace('html, body { overflow-x: clip; }', ''));
+ expect(unclipped.of('horizontal-scroll').map((f) => [f.grade, f.evidence])).toEqual([['blocks', '[320px] the page scrolls sideways: it is 2432px wide in a 320px viewport (also at 375, 414, 768, 1024, 1280, 1920px)']]);
+ const wraps = r.of('button-label-wraps');
+ expect(wraps.map((f) => [f.grade, f.line])).toEqual([['blocks', lineIn(html, 'Book the complete walkthrough today')]]);
+ expect(wraps[0].evidence).toMatch(/^\[320px\] control "Book the complete walkthrough to" wraps to \d lines \(a\.button\)$/);
+ expect(r.of('link-wraps').map((f) => [f.grade, f.line])).toEqual([['ask', lineIn(html, 'Read how the close works for you')]]);
+ expect(r.of('hero-fold').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', lineIn(html, '<h1>'), expect.stringMatching(/^\[1280px\] the headline crosses the 1280x800 fold/)]]);
+ }, 60_000);
+
+ test('contrast and focus: low contrast confirmed against the pixels, button text on its fill, a weak field edge, a bare focus state and a faint ring; white text over a dark picture is not a finding', async () => {
+ const html = pageWith(
+ '.faint { color: #b8b8b8; } .flat { background: #777; color: #808080; border-color: #777; } .edge { border: 1px solid #f2f2f2; background: #fff; height: 44px; } .bare:focus-visible { outline: none; } .weak:focus-visible { outline: 3px solid #e4e4e4; outline-offset: 2px; } .over { position: relative; width: 600px; } .over p { position: absolute; left: 24px; top: 24px; color: #fff; margin: 0; }',
+ '<section class="extra">\n<p class="faint">The faint paragraph nobody can read on the paper.</p>\n<a class="button flat" href="/buy">Buy the ledger</a>\n<label>Email <input class="edge" type="email" name="email"></label>\n<button class="button bare">Bare of focus</button>\n<button class="button weak">Weak ring</button>\n<div class="over"><img src="' + SVG_IMG(600, 200, '222222') + '" width="600" height="200" alt="A dark depot at night"><p>White on the night photograph</p></div>\n</section>',
+ );
+ const r = await measure(html);
+ const low = r.of('low-contrast');
+ expect(low.find((f) => f.line === lineIn(html, 'class="faint"'))?.evidence).toMatch(/^\[1280px\] contrast 1\.\d\d:1 against the pixels behind, under 4\.5:1 on p\.faint "The faint paragraph nobo"$/);
+ expect(low.find((f) => /field's edge/.test(f.evidence))?.evidence).toMatch(/^\[1440px\] a field's edge is under 3:1 against what surrounds it: input\.edge 1\.\d\d:1$/);
+ expect(low.some((f) => /White on the night/.test(f.evidence))).toBe(false);
+ expect(r.of('gray-on-color').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', lineIn(html, 'class="button flat"'), expect.stringMatching(/^\[1280px\] button text within a step of its fill on a\.button\.flat \(1\.\d\d:1\)$/)]]);
+ const focus = r.of('missing-focus-visible');
+ expect(focus.map((f) => f.grade)).toEqual(['blocks', 'blocks']);
+ expect(focus.find((f) => /nothing shows/.test(f.evidence))).toMatchObject({ line: lineIn(html, 'class="button bare"'), evidence: '[1440px] nothing shows keyboard focus on button.button "Bare of focus"' });
+ expect(focus.find((f) => /focus ring/.test(f.evidence))).toMatchObject({ line: lineIn(html, 'class="button weak"'), evidence: expect.stringMatching(/^\[1440px\] focus ring 1\.\d\d:1 against what is behind it on button\.button "Weak ring"$/) });
+ }, 90_000);
+
+ test('type and space tells at 1440: the word budget, a drawn SVG, an empty slot, counting marks, a tiny slot, a sliver, a lonely grid item, five weights, tiny text, long lines, crowded heads and a cramped box', async () => {
+ const html = pageWith(
+ '.marks { display: flex; gap: 4px; } .marks i { display: block; width: 8px; height: 8px; background: var(--color-ink); border-radius: 50%; } .tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; } .tiles div { min-height: 120px; background: var(--color-line); } .sliver { width: 60px; } .w3 { font-weight: 300; } .w6 { font-weight: 600; } .w9 { font-weight: 900; } .tiny { font-size: 10px; } .long { max-width: none; font-size: 15px; } .crowd h3 { margin: 2px 0 48px; } .box { background: var(--color-line); padding: 1px; width: 320px; }',
+ '<section class="extra">\n<h2>Everything the close touches</h2>\n<p class="budget">' + WORDS(120) + '</p>\n<svg class="plant" width="200" height="200" viewBox="0 0 200 200" aria-hidden="true"><path d="M20 180 C 60 20, 140 20, 180 180" fill="#8a6"/><path d="M40 160 Q 100 40 160 160" fill="#6a8"/><path d="M60 140 S 100 60 140 140" fill="#a86"/></svg>\n<div data-slot="product-shot" style="width: 420px; height: 300px; background: var(--color-line);"></div>\n<div class="marks" aria-hidden="true">' + '<i></i>'.repeat(30) + '</div>\n<div data-slot="mark" style="width: 20px; height: 20px; background: var(--color-line);"></div>\n<p class="sliver">A paragraph squeezed into a sliver of a column that runs for many lines.</p>\n<div class="tiles"><div></div><div></div><div></div><div></div></div>\n<p class="w3">Light weight runs across thirty characters.</p><p class="w6">Semibold weight runs across thirty characters.</p><p class="w9">Black weight runs across thirty characters here.</p>\n<p class="tiny">Ten pixel text that strains the eye across a whole paragraph of running prose.</p>\n<p class="long">' + WORDS(160) + '</p>\n<div class="crowd"><p>A paragraph above.</p><h3>Crowded head one</h3><p>The text it heads.</p><p>Another paragraph above.</p><h3>Crowded head two</h3><p>The text it heads.</p></div>\n<div class="box">Text pressed against the edge of its filled box.</div>\n</section>',
+ );
+ const r = await measure(html);
+ const one = (rule: string) => { const f = r.of(rule); expect(f.length, rule + '\n' + r.lines).toBeGreaterThan(0); return f[0]; };
+ expect(one('screen-word-budget')).toMatchObject({ grade: 'ask', evidence: expect.stringMatching(/^\[1440px\] \d+ words on one 900px screen/) });
+ expect(one('hand-drawn-svg')).toMatchObject({ grade: 'ask', line: lineIn(html, '<svg class="plant"'), evidence: '[1440px] drawn illustration: section.extra (200x200, 3 shapes)' });
+ expect(one('empty-picture')).toMatchObject({ grade: 'ask', line: lineIn(html, 'data-slot="product-shot"'), evidence: '[1440px] 1 empty picture: div[data-slot=product-shot] 420x300' });
+ expect(one('counting-marks')).toMatchObject({ grade: 'ask', line: lineIn(html, 'class="marks"'), evidence: '[1440px] counting device: div.marks holds 30 identical marks' });
+ expect(r.of('tiny-slot').map((f) => [f.grade, f.line, f.evidence])).toEqual([
+ ['polish', lineIn(html, 'data-slot="mark"'), '[375px] slot "mark" renders at 20 x 20px on a phone'],
+ ['polish', lineIn(html, 'data-slot="mark"'), '[1440px] slot "mark" renders at 20 x 20px'],
+ ]);
+ expect(one('text-sliver')).toMatchObject({ grade: 'polish', line: lineIn(html, 'class="sliver"'), evidence: expect.stringMatching(/^\[1440px\] "A paragraph squeezed into a " squeezed to 60px wide over \d+ lines \(p\.sliver\)$/) });
+ expect(one('lonely-grid-item')).toMatchObject({ grade: 'polish', line: lineIn(html, 'class="tiles"'), evidence: '[1440px] div.tiles leaves one item alone on its last row (3 + 1)' });
+ expect(one('font-weight-count')).toMatchObject({ grade: 'polish', evidence: '[1440px] 5 font weights in running use (300, 400, 600, 700, 900)' });
+ expect(one('tiny-text')).toMatchObject({ grade: 'ask', line: lineIn(html, 'class="tiny"'), evidence: '[1440px] text that strains the eye: p.tiny at 10px' });
+ expect(one('line-length')).toMatchObject({ grade: 'ask', line: lineIn(html, 'class="long"'), evidence: expect.stringMatching(/^\[1440px\] running prose set too wide: p\.long about \d{2,3} characters a line$/) });
+ expect(one('heading-rhythm')).toMatchObject({ grade: 'ask', line: lineIn(html, 'Crowded head one'), evidence: expect.stringMatching(/^\[1440px\] heads nearer what precedes them than what they head: h3 "Crowded head one" 24px over, 48px under; h3 "Crowded/) });
+ expect(one('cramped-padding')).toMatchObject({ grade: 'ask', line: lineIn(html, 'class="box"'), evidence: expect.stringMatching(/^\[1440px\] text crowds the edge of its box: div\.box left \dpx/) });
+ }, 90_000);
+
+ test('the hero and its sections: a dead band, small section heads, thin sections, text under a cover, and the 1920 container', async () => {
+ const html = pageWith(
+ '.hero { align-items: start; justify-content: start; } .hero figure { display: none; } .wrap { max-width: none; padding: 0; } h2 { font-size: 24px; } p { max-width: none; } .cover { position: absolute; left: 0; width: 300px; height: 80px; margin-top: -80px; background: var(--color-ink); }',
+ '<section class="thin"><h2>A thin section</h2><p style="max-width: 30ch">A short body on a wide canvas with nothing else in it.</p></section>\n<section class="under"><p class="hidden-run" style="max-width: 20ch">This paragraph is painted under the cover.</p><div class="cover" aria-hidden="true"></div><p class="wide-run">' + WORDS(60) + '.</p></section>',
+ [['<section class="story">', '<section class="story" style="display: none">'], ['<section class="ledger">', '<section class="ledger" style="display: none">'], ['<section class="close">', '<section class="close" style="display: none">']],
+ );
+ const r = await measure(html);
+ expect(r.of('dead-band').map((f) => [f.grade, f.line, f.evidence])).toEqual([['ask', lineIn(html, '<section class="hero">'), expect.stringMatching(/^\[1440px\] \d{3}px of nothing between the hero's last content \(y \d+\) and the fold$/)]]);
+ expect(r.of('small-section-heads').map((f) => [f.grade, f.evidence])).toEqual([['ask', expect.stringMatching(/^\[1440px\] section heads render at 24px under a \d+px hero head$/)]]);
+ expect(r.of('thin-section').map((f) => [f.grade, f.line])).toEqual([['ask', lineIn(html, '<section class="thin">')]]);
+ expect(r.of('thin-section')[0].evidence).toMatch(/^\[1440px\] \d thin sections?: "A thin section" \(\d+% wide, no mass\)/);
+ expect(r.of('text-occlusion').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', lineIn(html, 'class="hidden-run"'), expect.stringMatching(/^\[1440px\] text painted under another element: div\.cover over "This paragraph i"/)]]);
+ const wide = r.of('wide-container');
+ expect(wide.map((f) => f.grade)).toEqual(wide.map(() => 'blocks'));
+ expect(wide.map((f) => f.evidence)).toEqual(expect.arrayContaining([expect.stringMatching(/^\[1920px\] the hero text starts \d+px from the edge at 1920$/), expect.stringMatching(/^\[1920px\] \d text blocks? runs? wider than 1600px at 1920/)]));
+ }, 90_000);
+
+ test('the photo wall, the accent footprint and hero content sitting low', async () => {
+ const photo = (fill: string) => '<section class="shot"><img src="' + SVG_IMG(1200, 520, fill) + '" width="1200" height="520" alt="A depot"></section>';
+ const html = pageWith(
+ '.band { background: var(--color-accent); height: 220px; } .shot img { width: 100%; height: auto; display: block; }',
+ '<div class="band"></div>\n' + photo('778866') + '\n' + photo('667788') + '\n' + photo('886677'),
+ [['<section class="hero">', '<div class="band"></div>\n <section class="hero">'], ['<section class="story">', '<section class="story" style="display: none">'], ['<section class="ledger">', '<section class="ledger" style="display: none">'], ['align-items: center;', 'align-items: end;'], ['<figure>', '<figure style="display: none">']],
+ );
+ const r = await measure(html);
+ const balance = r.of('hero-balance');
+ expect(balance.map((f) => f.grade)).toEqual(balance.map(() => 'ask'));
+ expect(balance.map((f) => f.evidence)).toContainEqual(expect.stringMatching(/^\[1440px\] the hero content sits low: \d+px above it, \d+px below$/));
+ expect(r.of('photo-wall').map((f) => [f.grade, f.evidence])).toEqual([['ask', expect.stringMatching(/^\[1440px\] photographs cover \d\d% of the page below the hero \(3 pictures\)$/)]]);
+ expect(r.of('accent-footprint').map((f) => [f.grade, f.evidence])).toEqual([['ask', expect.stringMatching(/^\[1280px\] the accent paints about \d+\.\d% of the 1280x800 viewport \(over 8%\)$/)]]);
+ }, 60_000);
+
+ test('a hero with more than two actions reports the count under screen-word-budget; the clean two do not', async () => {
+ const html = pageWith('', '', [['<a class="quiet" href="/method">Read how the close works</a>', '<a class="quiet" href="/method">Read how the close works</a>\n <a class="quiet" href="/pricing">See the pricing</a>\n <a class="quiet" href="/tour">Take the tour</a>']]);
+ const r = await measure(html);
+ expect(r.of('screen-word-budget').map((f) => [f.grade, f.line, f.evidence])).toEqual([['ask', lineIn(html, 'href="/pricing"'), '[1440px] the hero offers 4 actions']]);
+ }, 60_000);
+
+ test('section gaps: sections crowded together, every gap the same, and more than nine sections', async () => {
+ const block = (n: number) => '<section class="gap' + n + '"><h2>Section ' + n + ' of the close</h2><p>' + WORDS(24) + '.</p></section>';
+ const crowded = await measure(pageWith('.gap1, .gap2, .gap3 { padding: 0; margin: 4px 0; }', block(1) + '\n' + block(2) + '\n' + block(3)));
+ expect(crowded.of('section-gap').map((f) => [f.grade, f.evidence])).toEqual([['ask', expect.stringMatching(/^\[1440px\] the smallest gap between sections is \d+px \(gaps: [-\d, ]+\)$/)]]);
+ const same = await measure(pageWith(
+ '.wrap > section { padding: 0; margin: 0 0 140px; } .wrap > section:last-child { margin-bottom: 0; } .hero { min-height: 0; } .hero figure { display: none; }',
+ block(1) + '\n' + block(2) + '\n' + block(3),
+ [['<section class="story">', '<section class="story" style="display: none">'], ['<section class="ledger">', '<section class="ledger" style="display: none">'], ['<section class="close">', '<section class="close" style="display: none">']],
+ ));
+ expect(same.of('section-gap').map((f) => [f.grade, f.evidence])).toEqual([['ask', expect.stringMatching(/^\[1440px\] every section gap is \d+px$/)]]);
+ const many = await measure(pageWith('.wrap > section { padding: 0; margin: 0 0 160px; }', Array.from({ length: 7 }, (_, i) => block(i + 1)).join('\n')));
+ expect(many.of('section-gap').map((f) => [f.grade, f.evidence])).toContainEqual(['ask', '[1440px] 11 sections on one page']);
+ expect(many.of('section-gap').find((f) => f.evidence.endsWith('sections on one page'))!.line).toBe(lineIn(many.html, 'class="gap6"'));
+ }, 90_000);
+});
+
+describe('design-lint render: hardening (ship review)', () => {
+ test('lineOf tolerates regex metacharacters in a tag name the page reports', () => {
+ expect(() => lineOf('<x>\n<a(b class="c">hi</a(b>', { tag: 'a(b', cls: 'c', text: 'hi' })).not.toThrow();
+ expect(lineOf('<x>\n<a(b class="c">hi</a(b>', { tag: 'a(b', cls: 'c', text: 'hi' })).toBe(2);
+ });
+
+ test.skipIf(!hasBrowser)('a waiver on low-contrast is refused once the render tier measures it: the measured finding blocks, nothing is waived', async () => {
+ const html = '<!-- gstack-lint-disable low-contrast: the faint paragraph is the ledger watermark for the paper -->\n' + pageWith('.faint { color: #b8b8b8; background: #fff; }', '<p class="faint">The faint paragraph nobody can read on the paper ledger.</p>');
+ const { dir } = tmpPage(html);
+ try {
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, engine });
+ expect(r.findings.filter((f) => f.rule === 'low-contrast' && f.source === 'render').map((f) => f.grade)).toEqual(['blocks']);
+ expect(r.findings.filter((f) => f.rule === 'waiver').map((f) => f.evidence)).toEqual(['waiver on low-contrast refused: it blocks; the Floor is never waivable']);
+ expect(r.summary.waived).toBe(0);
+ expect(r.exitCode).toBe(2);
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test.skipIf(!hasBrowser)('a page whose script redefines the probes gets a blocking render finding, not a quiet pass', async () => {
+ const html = pageWith('', '<script>Object.defineProperty(window, "__gstackLint", { configurable: false, get() { return { setup: () => ({ lost: [] }), layout: () => [{ rule: "nope", grade: "fail", evidence: "x" }], contrast: () => [], accent: () => [], space: () => [], quality: () => [], occlusion: () => [], focus: () => [], hide: () => [], restore: () => 0 }; }, set() {} });</script>');
+ const { dir } = tmpPage(html);
+ try {
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, engine });
+ expect(r.findings.filter((f) => f.rule === 'render').map((f) => [f.grade, /does not know|could not be prepared|did not render|measurement/.test(f.evidence)])).toContainEqual(['blocks', true]);
+ expect(r.exitCode).toBe(2);
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test.skipIf(!hasBrowser)('a page waiving section-gap sees its render section-gap finding at waived, not ask', async () => {
+ const block = (n: number) => `<section class="gap${n}"><h2>Section ${n} of the close</h2><p>${WORDS(24)}.</p></section>`;
+ const html = '<!-- gstack-lint-disable section-gap: the ledger separates its close sections with hairline rules, not air -->\n'
+ + pageWith('.gap1,.gap2,.gap3{padding:0;margin:4px 0}', block(1) + block(2) + block(3));
+ const { file, dir } = tmpPage(html);
+ try {
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, engine });
+ expect(r.findings.filter((f) => f.rule === 'waiver')).toEqual([]);
+ expect(r.findings.filter((f) => f.rule === 'section-gap').map((f) => [f.grade, f.file, f.source])).toEqual([['waived', 'index.html', 'render']]);
+ expect(r.summary.waived).toBe(1);
+ void file;
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+ }, 90_000);
+});
diff --git a/test/design-lint-settle.test.ts b/test/design-lint-settle.test.ts
new file mode 100644
index 000000000..2ea773746
--- /dev/null
+++ b/test/design-lint-settle.test.ts
@@ -0,0 +1,184 @@
+/**
+ * The render tier settled without a browser: a fake page runner hands lintRender every answer a browser could give
+ * (nothing, null, malformed JSON, a probe error, a warn on a blocking rule, a polish tell, a thrown page script,
+ * a pixel pass that cannot be read) and lint() settles the result against the page's waivers. Every cell of the
+ * state matrix the browser tests only reach with Chromium installed is pinned here on every lane.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import type { RenderResult, RenderSpec } from '../lib/aside-render';
+import { lint } from '../lib/design-lint/index';
+import { lintRender, type Runner } from '../lib/design-lint/render';
+import type { Finding } from '../lib/design-lint/report';
+import { FLOOR_REFUSAL, OWN_RULE_REFUSAL } from '../lib/design-lint/waivers';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const PAGE = (lead = '') => lead + '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Ledger</title><meta name="description" content="The ledger closes the month."><link rel="icon" href="data:,"><style>\n:root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --font-display: "Literata", serif; --font-body: "Source Serif 4", serif; }\nhtml, body { overflow-x: clip; }\na:focus-visible { outline: 2px solid var(--color-ink); }\na:active { opacity: .9; }\n</style></head><body><a href="#main">Skip to content</a><main id="main"><h1>The ledger</h1><p>The ledger closes the month with a hairline rule under every total.</p></main></body></html>';
+
+function tmpPage(html: string): { dir: string; file: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-settle-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, 'index.html');
+ fs.writeFileSync(file, html);
+ return { dir, file };
+}
+
+/** Step indices of one measuring pass: 0 installs the probes, 1 is setup, 2..13 the twelve measures (13 is the focus walk). */
+const SETUP = 1, FIRST = 2, FOCUS = 13;
+
+type Patch = (evals: Record<number, string>, spec: RenderSpec) => void;
+
+/** A runner whose page answers every measure with nothing to report, then lets a test rewrite the answers; a pixel pass (the spec with a screenshot step) answers through the same patch. */
+function runner(patch: Patch = () => {}, stdout = ''): Runner & { specs: RenderSpec[] } {
+ const specs: RenderSpec[] = [];
+ const run = (async (spec: RenderSpec): Promise<RenderResult> => {
+ specs.push(spec);
+ const evals: Record<number, string> = { [SETUP]: '{"lost":[]}' };
+ for (let i = FIRST; i <= FOCUS; i++) evals[i] = '[]';
+ patch(evals, spec);
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout };
+ }) as Runner & { specs: RenderSpec[] };
+ run.specs = specs;
+ return run;
+}
+
+const renders = (f: Finding[]) => f.filter((x) => x.rule === 'render').map((x) => [x.grade, x.evidence]);
+const byRule = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+
+describe('design-lint render settled without a browser: what the page hands back', () => {
+ test('a clean page measured by a quiet runner has no finding and status ran', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const r = await lintRender([file], { cwd: dir, run: runner() });
+ expect(r.status).toBe('ran');
+ expect(r.findings).toEqual([]);
+ });
+
+ test('a measure that came back missing, null, malformed or as a probe error is one blocking render finding naming the probe and the width', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const cases: Array<[string | undefined, RegExp]> = [
+ [undefined, /^the layout measurement at 320px failed: no result came back$/],
+ ['null', /^the layout measurement at 320px failed: empty result$/],
+ ['abc', /^the layout measurement at 320px failed: .*JSON/],
+ ['{"error":"probe lost the document"}', /^the layout measurement at 320px failed: probe lost the document$/],
+ ];
+ for (const [answer, want] of cases) {
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => { if (answer === undefined) delete ev[FIRST]; else ev[FIRST] = answer; }) });
+ expect(renders(r.findings)).toHaveLength(1);
+ expect(renders(r.findings)[0][0]).toBe('blocks');
+ expect(renders(r.findings)[0][1]).toMatch(want);
+ }
+ });
+
+ test('a setup that failed blocks; fonts that did not load are suspected, so the finding sits at ask', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const failed = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[SETUP] = '{"error":"no document"}'; }) });
+ expect(renders(failed.findings)).toEqual([['blocks', 'the page could not be prepared for measurement: no document']]);
+ const lost = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[SETUP] = '{"lost":["Literata","/css/site.css"]}'; }) });
+ expect(renders(lost.findings)).toEqual([['ask', 'fonts or stylesheets did not load (Literata, /css/site.css): the measurements show a fallback face']]);
+ });
+
+ test('a page script that threw on load is a blocking render finding carrying the first 90 characters of its message', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const r = await lintRender([file], { cwd: dir, run: runner(() => {}, 'PAGE_ERRORS=["uncaught: Error: boom at line 3"]\n') });
+ expect(renders(r.findings)).toEqual([['blocks', 'a script threw on load: Error: boom at line 3']]);
+ const long = await lintRender([file], { cwd: dir, run: runner(() => {}, 'PAGE_ERRORS=' + JSON.stringify(['uncaught: ' + 'x'.repeat(200)]) + '\n') });
+ expect(renders(long.findings)[0][1]).toBe('a script threw on load: ' + 'x'.repeat(90));
+ });
+
+ test('a page that did not render, and a runner that threw, each land as one blocking render finding', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const dead = await lintRender([file], { cwd: dir, run: async () => ({ ok: false, outputs: [], evals: {}, stdout: '', error: 'browser gone' }) });
+ expect(renders(dead.findings)).toEqual([['blocks', 'the page did not render: browser gone']]);
+ const threw = await lintRender([file], { cwd: dir, run: async () => { throw new Error('socket closed'); } });
+ expect(renders(threw.findings)).toEqual([['blocks', 'the page could not be measured: socket closed']]);
+ });
+
+ test('a warn on a blocking rule lands at ask with source render; a fail lands at blocks; a rule the lint does not know is tampering', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => {
+ ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'the hero may overflow' }, { rule: 'horizontal-scroll', grade: 'fail', evidence: 'the hero overflows' }]);
+ ev[FIRST + 1] = JSON.stringify([{ rule: 'nope', grade: 'fail', evidence: 'x' }, { rule: 'horizontal-scroll', grade: 'maybe', evidence: 'y' }]);
+ }) });
+ expect(byRule(r.findings, 'horizontal-scroll').map((f) => [f.grade, f.source, f.evidence])).toEqual([['blocks', 'render', '[320px] the hero overflows']]);
+ const warns = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'the hero may overflow' }]); }) });
+ expect(byRule(warns.findings, 'horizontal-scroll').map((f) => [f.grade, f.source, f.evidence])).toEqual([['ask', 'render', '[320px] the hero may overflow']]);
+ expect(renders(r.findings).map(([g, e]) => [g, e.replace(/\(.*?\)/, '(…)').replace(/with the pr.*$/, 'with the probes')])).toEqual([
+ ['blocks', 'the page handed back a measurement the lint does not know (…); its scripts may be tampering with the probes'],
+ ['blocks', 'the page handed back a measurement the lint does not know (…); its scripts may be tampering with the probes'],
+ ]);
+ expect(renders(r.findings).map(([, e]) => /\((.*?)\)/.exec(e)![1])).toEqual(['nope', 'horizontal-scroll']);
+ });
+
+ test('a contrast claim whose pixel pass cannot be read keeps its computed ratio', async () => {
+ const { dir, file } = tmpPage(PAGE());
+ const claim = { rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)', probe: { path: 'main>p', fg: [180, 180, 180], threshold: 4.5 } };
+ for (const hide of ['{"error":"hide failed"}', 'null', undefined]) {
+ const run = runner((ev, spec) => {
+ if (spec.steps.some((s) => s.kind === 'screenshot')) { if (hide === undefined) delete ev[FIRST]; else ev[FIRST] = hide; return; }
+ ev[FIRST + 5] = JSON.stringify([claim]);
+ });
+ const r = await lintRender([file], { cwd: dir, run });
+ expect(run.specs).toHaveLength(2);
+ expect(byRule(r.findings, 'low-contrast').map((f) => [f.grade, f.evidence])).toEqual([['blocks', '[1280px] computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)']]);
+ }
+ });
+});
+
+describe('design-lint render settled without a browser: waivers through lint()', () => {
+ test('a render warn on a blocking rule is suspected, so the page claim answers it: waived, no refusal', async () => {
+ const { dir } = tmpPage(PAGE('<!-- gstack-lint-disable horizontal-scroll: the ledger table scrolls sideways on purpose under its month headers -->\n'));
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'the table may overflow' }]); }) });
+ expect(byRule(r.findings, 'waiver')).toEqual([]);
+ expect(byRule(r.findings, 'horizontal-scroll').map((f) => [f.grade, f.file, f.source])).toEqual([['waived', 'index.html', 'render']]);
+ expect(r.summary.waived).toBe(1);
+ expect(r.exitCode).toBe(0);
+ });
+
+ test('without the render tier nothing suspects the rule, so the same claim is refused as the Floor', async () => {
+ const { dir } = tmpPage(PAGE('<!-- gstack-lint-disable horizontal-scroll: the ledger table scrolls sideways on purpose under its month headers -->\n'));
+ const r = await lint([dir], { cwd: dir, warn: () => {} });
+ expect(byRule(r.findings, 'waiver').map((f) => f.evidence)).toEqual([`waiver on horizontal-scroll refused: ${FLOOR_REFUSAL}`]);
+ expect(byRule(r.findings, 'horizontal-scroll')).toEqual([]);
+ });
+
+ test('a short claim on a suspected rule is refused for its length, not as the Floor, and the render warn stays at ask', async () => {
+ const { dir } = tmpPage(PAGE('<!-- gstack-lint-disable horizontal-scroll: table scrolls -->\n'));
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'the table may overflow' }]); }) });
+ expect(byRule(r.findings, 'waiver').map((f) => f.evidence)).toEqual(['waiver on horizontal-scroll refused: reason under 24 characters']);
+ expect(byRule(r.findings, 'horizontal-scroll').map((f) => f.grade)).toEqual(['ask']);
+ expect(r.exitCode).toBe(1);
+ });
+
+ test('a measured blocking render finding stays at blocks and a claim on the lint\'s own render rule is refused by name', async () => {
+ const { dir } = tmpPage(PAGE('<!-- gstack-lint-disable render: the ledger page is measured by hand each month end -->\n<!-- gstack-lint-disable horizontal-scroll: the ledger table scrolls sideways on purpose under its month headers -->\n'));
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'fail', evidence: 'the table overflows' }]); ev[FIRST + 1] = JSON.stringify([{ rule: 'nope', grade: 'fail', evidence: 'x' }]); }) });
+ expect(byRule(r.findings, 'waiver').map((f) => f.evidence).sort()).toEqual([`waiver on horizontal-scroll refused: ${FLOOR_REFUSAL}`, `waiver on render refused: ${OWN_RULE_REFUSAL}`]);
+ expect(byRule(r.findings, 'horizontal-scroll').map((f) => f.grade)).toEqual(['blocks']);
+ expect(renders(r.findings).map(([g]) => g)).toEqual(['blocks']);
+ expect(r.summary.waived).toBe(0);
+ expect(r.exitCode).toBe(2);
+ });
+
+ test('a polish render tell is settled by the page claim at waived', async () => {
+ const { dir } = tmpPage(PAGE('<!-- gstack-lint-disable text-sliver: the ledger margin column is a sliver by design of the paper form -->\n'));
+ const r = await lint([dir], { cwd: dir, render: true, warn: () => {}, run: runner((ev) => { ev[FIRST + 7] = JSON.stringify([{ rule: 'text-sliver', grade: 'fail', evidence: 'a 90px column' }]); }) });
+ expect(byRule(r.findings, 'waiver')).toEqual([]);
+ expect(byRule(r.findings, 'text-sliver').map((f) => [f.grade, f.source])).toEqual([['waived', 'render']]);
+ expect(r.summary.polish).toBe(0);
+ expect(r.summary.waived).toBe(1);
+ });
+
+ test('render findings of a URL target pass through unsettled, and a page with a whitespace run in its name still meets its own findings', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-settle-'));
+ tmpDirs.push(dir);
+ fs.writeFileSync(path.join(dir, 'my page.html'), PAGE('<!-- gstack-lint-disable horizontal-scroll: the ledger table scrolls sideways on purpose under its month headers -->\n'));
+ const r = await lint([dir], { cwd: dir, render: true, urls: ['http://127.0.0.1:1/x'], warn: () => {}, run: runner((ev) => { ev[FIRST] = JSON.stringify([{ rule: 'horizontal-scroll', grade: 'warn', evidence: 'the table may overflow' }]); }) });
+ expect(byRule(r.findings, 'horizontal-scroll').map((f) => [f.grade, f.file])).toEqual([['waived', 'my page.html']]);
+ expect(renders(r.findings).map(([g, e]) => [g, e.startsWith('could not reach http://127.0.0.1:1/x')])).toEqual([['blocks', true]]);
+ expect(byRule(r.findings, 'render')[0].file).toBe('http://127.0.0.1:1/x');
+ });
+});
diff --git a/test/design-lint-seventh-cycle.test.ts b/test/design-lint-seventh-cycle.test.ts
new file mode 100644
index 000000000..bbf4acb71
--- /dev/null
+++ b/test/design-lint-seventh-cycle.test.ts
@@ -0,0 +1,146 @@
+/**
+ * The seventh review cycle's regressions: the stray-`<` tail that made every `[^>]*>` scan quadratic, the JSX scanner's
+ * mismatched-closer cascade, the token table read in one colour mode, a theme class block as tokens, the component
+ * directory's per-file claims under either scope with their own suspected rules, the Reporter's own file key in the
+ * Tailwind dedupe, and the rule judgements the design pass asked for (outline: none is not a ring, a sign-in form is
+ * not a mailing-list band, a token finding points at the declaration that won, one control-tracking ceiling).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { jsxPseudo, parseDoc } from '../lib/design-lint/html';
+import { lintStatic } from '../lib/design-lint/static';
+import type { Finding } from '../lib/design-lint/report';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif; }';
+const HEAD = '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n';
+const page = (css: string, body: string): string => HEAD + '<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+const sheet = (css: string, body: string): string => HEAD + '<style>\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+
+function tree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-cycle7-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+const quiet = { warn: () => {} };
+const run = (html: string, files: Record<string, string> = {}): Finding[] => { const dir = tree({ 'index.html': html, ...files }); return lintStatic([dir], { cwd: dir, ...quiet }).findings; };
+const only = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+const timed = (fn: () => void): number => { const t = performance.now(); fn(); return performance.now() - t; };
+const DASHES = 'The ledger \u2014 the month \u2014 the close \u2014 the depot \u2014 the review \u2014 the rule \u2014 the row \u2014 the sum';
+const CARD = 'export function Card() { return <p>' + DASHES + '</p>; }';
+
+describe('design-lint seventh cycle: a file costs its length', () => {
+ test('a page whose tail is thousands of unclosed <img starts lints in linear time, and its tags are still read', () => {
+ const dir = tree({ 'index.html': HEAD + '</head><body><main><h1>Hello there</h1><p>Some prose about a thing.</p></main>' + '<img '.repeat(80_000) });
+ let f: Finding[] = [];
+ expect(timed(() => { f = lintStatic([dir], { cwd: dir, ...quiet }).findings; })).toBeLessThan(5000);
+ expect(only(f, 'broken-image')).toEqual([]);
+ const doc = parseDoc('/tmp/t.html', '<main><h1>Hi</h1><img <img src="a.png"></main>');
+ expect(doc.tags.filter((t) => t.name === 'img').length).toBe(1);
+ expect(doc.src.indexOf('<img')).toBe(doc.src.lastIndexOf('<img'));
+ });
+
+ test('a box-shadow of many paren-free layers costs its length', () => {
+ const dir = tree({ 's.css': ':root{--x:1}\n.card{border:1px solid #ccc;box-shadow:' + Array.from({ length: 32000 }, () => '0 1px 2px red').join(', ') + '}\n' });
+ expect(timed(() => lintStatic([dir], { cwd: dir, ...quiet }))).toBeLessThan(2000);
+ });
+
+ test('a generic element and a stray or ancestor-closing tag cost a JSX file its length, not its depth', () => {
+ const build = (depth: number) => 'export default function A() { return (' + '<div className="a">'.repeat(depth) + '<Table<Row> rows={rows}>' + '<p className="x">hello <b>b</b></p>'.repeat(4000) + '</Table>' + '</div>'.repeat(depth) + '); }';
+ expect(timed(() => jsxPseudo(build(60)))).toBeLessThan(500);
+ expect(jsxPseudo(build(2)).classAt.size).toBe(4002);
+ const stray = 'export default function A() { return (' + '<div className="a">'.repeat(150) + '</span>' + '<p className="x">hello</p>'.repeat(8000) + '</div>'.repeat(150) + '); }';
+ expect(timed(() => jsxPseudo(stray))).toBeLessThan(500);
+ expect(parseDoc('/tmp/A.tsx', stray).tags.filter((t) => !t.close && t.name === 'p').length).toBe(8000);
+ expect(parseDoc('/tmp/B.tsx', 'export default function B() { return (<div><span>text</div>); }').tags.map((t) => (t.close ? '/' : '') + t.name)).toEqual(['div', 'span', '/div']);
+ });
+});
+
+describe('design-lint seventh cycle: the token table in one mode', () => {
+ test('a class-scoped theme block and a component-local custom property are token definitions, not literals', () => {
+ const f = run(page('.dark { --color-paper: oklch(15% 0.01 80); --color-ink: oklch(95% 0.01 80); } .card { --accent: #f00; }', '<main><h1>Ledger of the dark</h1><p>Read it in either mode.</p></main>'));
+ expect(only(f, 'literal-outside-tokens')).toEqual([]);
+ });
+
+ test('a prefers-color-scheme override does not mix modes in the token table', () => {
+ const css = ':root { --color-paper: oklch(98% 0.01 80); --color-ink: oklch(20% 0.02 80); --color-muted: oklch(45% 0.02 80); }\n@media (prefers-color-scheme: dark) { :root { --color-paper: oklch(15% 0.01 80); --color-ink: oklch(95% 0.01 80); } }\n.note { color: var(--color-muted); background: var(--color-paper); }';
+ expect(only(run(sheet(css, '<main><h1>Ledger</h1><p class="note">A note in the muted ink.</p></main>')), 'low-contrast')).toEqual([]);
+ });
+
+ test('a token finding points at the declaration whose value won', () => {
+ const last = run(sheet(':root{--font-display:Georgia}\n:root{--font-display:Papyrus}', '<main><h1>Hello there</h1><p>Body.</p></main>'));
+ expect(only(last, 'banned-font').map((x) => [x.line, x.evidence])).toEqual([[6, '"papyrus" (--font-display)']]);
+ const dark = run(sheet(':root{--font-display:Georgia}\n[data-theme=dark]{--font-display:Papyrus}', '<main><h1>Hello there</h1><p>Body.</p></main>'));
+ expect(only(dark, 'banned-font')).toEqual([]);
+ });
+});
+
+describe('design-lint seventh cycle: waivers in a directory of components', () => {
+ test('a component claim never covers a sibling file, whatever the scope, and a short one is refused at its line', () => {
+ const dir = tree({ 'Card.tsx': CARD, 'Hero.tsx': '// gstack-lint-disable em-dash-overuse: the ledger sets its dashes as the month closes on the depot\nexport function Hero() { return <h1>The ledger closes the month on the depot</h1>; }' });
+ const f = lintStatic([dir], { cwd: dir, ...quiet }).findings;
+ expect(only(f, 'em-dash-overuse').map((x) => [x.file, x.grade])).toEqual([['Card.tsx', 'ask']]);
+ expect(only(f, 'waiver')).toEqual([]);
+ const short = tree({ 'Card.tsx': '// gstack-lint-disable em-dash-overuse: short\n' + CARD, 'Hero.tsx': 'export function Hero() { return <h1>The ledger</h1>; }' });
+ const g = lintStatic([short], { cwd: short, ...quiet }).findings;
+ expect(only(g, 'em-dash-overuse').map((x) => x.grade)).toEqual(['ask']);
+ expect(only(g, 'waiver').map((x) => [x.file, x.line, x.evidence])).toEqual([['Card.tsx', 1, 'waiver on em-dash-overuse refused: reason under 24 characters']]);
+ });
+
+ test("a sibling that measures a blocking rule does not turn another file's suspected finding into the Floor", () => {
+ const files = { 'Hero.tsx': 'export function Hero() { return <section className="hero"><h1>Welcome to the depot</h1></section>; }', 'Card.tsx': '// gstack-lint-disable generic-hero-copy: the card quotes the printed welcome sign that hangs over the depot door\nexport function Card() { return <p>Welcome to the depot, the sign over the door says.</p>; }' };
+ for (const scope of ['component', 'page'] as const) {
+ const dir = tree(files);
+ const f = lintStatic([dir], { cwd: dir, ...quiet, scope }).findings;
+ expect(only(f, 'generic-hero-copy').map((x) => [x.file, x.grade]).sort()).toEqual([['Card.tsx', 'waived'], ['Hero.tsx', 'blocks']]);
+ expect(only(f, 'waiver')).toEqual([]);
+ }
+ });
+
+ test('a stylesheet beside the components answers for itself: accepted without a shared word, refused at its line', () => {
+ const comps = (reason: string) => { const dir = tree({ 'Card.tsx': 'export function Card() { return <p className="row">The ledger.</p>; }', 'theme.css': '/* gstack-lint-disable zero-chroma-neutrals: ' + reason + ' */\n' + TOKENS + '\n:root { --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }' }); return lintStatic([dir], { cwd: dir, ...quiet, scope: 'component' }).findings; };
+ const ok = comps('the ledger keeps its grey rows grey in the theme sheet');
+ expect(only(ok, 'waiver')).toEqual([]);
+ expect(only(ok, 'zero-chroma-neutrals').map((x) => [x.file, x.grade])).toEqual([['theme.css', 'waived']]);
+ const bad = comps('short');
+ expect(only(bad, 'zero-chroma-neutrals').map((x) => [x.file, x.grade])).toEqual([['theme.css', 'ask']]);
+ expect(only(bad, 'waiver').map((x) => [x.file, x.line])).toEqual([['theme.css', 1]]);
+ });
+});
+
+describe('design-lint seventh cycle: rule judgements', () => {
+ test('a Tailwind tell on a line the stylesheet families reported prints once, whatever the page is named', () => {
+ const html = page('.eyebrow{font-size:12px;text-transform:uppercase;letter-spacing:.08em}', '<main><h1>Hi there</h1><section><p class="eyebrow text-xs uppercase tracking-wider">Our depots</p><h2>Bergen and Stavanger</h2></section></main>');
+ const counts = ['plain.html', 'two spaces.html'].map((name) => { const dir = tree({ [name]: html }); const f = lintStatic([dir], { cwd: dir, ...quiet }).findings; return [only(f, 'wide-tracking').length, only(f, 'kicker-above-heading').length]; });
+ expect(counts[1]).toEqual(counts[0]);
+ expect(counts[0][1]).toBe(1);
+ });
+
+ test('outline: none beside a focus border change is input-state-shift; a sign-in form closing the page is not an email band', () => {
+ const focus = run(page('input { border: 1px solid var(--color-ink) }\ninput:focus { outline: none; border-color: var(--color-accent) }\nbutton:focus-visible { outline: 2px solid var(--color-accent) }', '<main><h1>Sign in</h1><form><label for="e">Email</label><input id="e" type="email"><button>Send</button></form></main>'));
+ expect(only(focus, 'input-state-shift').map((x) => x.evidence)).toEqual(['the focus state is drawn with border on input:focus']);
+ const signin = run(page('input { height: 48px }', '<main><h1>Sign in to the ledger</h1><section><p>Your ledger waits behind the door.</p></section><section><form action="/session" method="post"><label for="e">Email</label><input id="e" type="email"><label for="p">Password</label><input id="p" type="password"><button>Sign in</button></form></section></main>'));
+ expect(only(signin, 'email-band-close')).toEqual([]);
+ });
+
+ test('an uppercase control under an uppercase display may carry 0.04em in a stylesheet as in a class string, no more', () => {
+ const f = run(page('h1 { text-transform: uppercase; } .btn{text-transform:uppercase;letter-spacing:0.045em;font-size:14px} .cta{text-transform:uppercase;letter-spacing:0.04em;font-size:14px}', '<main><h1>HELLO THERE</h1><a class="btn" href="#">Go now</a><a class="cta" href="#">Stay</a></main>'));
+ expect(only(f, 'wide-tracking').map((x) => x.evidence)).toEqual(['.btn: an uppercase control tracked 0.045em']);
+ });
+
+ test('a linked stylesheet that does not exist is warned about and otherwise ignored', () => {
+ const warned: string[] = [];
+ const dir = tree({ 'index.html': HEAD + '<link rel="stylesheet" href="missing.css"></head><body><main><h1>Hello</h1><p>Body.</p></main></body></html>' });
+ const r = lintStatic([dir], { cwd: dir, warn: (l) => warned.push(l) });
+ expect(warned).toEqual([expect.stringMatching(/skipped .*missing\.css, not found$/)]);
+ expect(only(r.findings, 'internal-error')).toEqual([]);
+ });
+});
diff --git a/test/design-lint-sixth-cycle.test.ts b/test/design-lint-sixth-cycle.test.ts
new file mode 100644
index 000000000..3b7954b8b
--- /dev/null
+++ b/test/design-lint-sixth-cycle.test.ts
@@ -0,0 +1,214 @@
+/**
+ * The sixth review cycle's regressions: the line-length and tracking rules that walked the page or the sheet once per
+ * rule, the JSX scanner's unclosed cascade, a stylesheet reached through a symlink, the LINT line's own separator in
+ * page text, the untested waiver and render cells the state matrix named, and the rule judgements the design pass asked
+ * for (a meta label in mono, a leading-dot length, a percentage leading, an icon before the italic word, digit ranges).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import type { RenderResult, RenderSpec } from '../lib/aside-render';
+import { parseDoc } from '../lib/design-lint/html';
+import { lintRender, type Runner } from '../lib/design-lint/render';
+import { exitCodeOf, summarize, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+import { applyWaivers, resolveWaivers } from '../lib/design-lint/waivers';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --color-accent: oklch(50% 0.16 30); --color-accent-ink: oklch(98% 0.01 30); --color-muted: oklch(50% 0.02 250); --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif; --font-mono: "JetBrains Mono", monospace; }';
+const HEAD = '<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Harbour office</title><meta name="description" content="A test page."><link rel="icon" href="data:,">\n';
+const page = (css: string, body: string): string => HEAD + '<style>\n' + TOKENS + '\n' + css + '\n</style>\n</head>\n<body>\n' + body + '\n</body>\n</html>\n';
+
+function tree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-cycle6-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+const quiet = { warn: () => {} };
+const run = (html: string, files: Record<string, string> = {}): Finding[] => { const dir = tree({ 'index.html': html, ...files }); return lintStatic([dir], { cwd: dir, ...quiet }).findings; };
+const components = (files: Record<string, string>): Finding[] => { const dir = tree(files); return lintStatic([dir], { cwd: dir, ...quiet, scope: 'component' }).findings; };
+const only = (f: Finding[], rule: string) => f.filter((x) => x.rule === rule);
+const timed = (fn: () => void): number => { const t = performance.now(); fn(); return performance.now() - t; };
+const DASHES = 'The ledger \u2014 the month \u2014 the close \u2014 the depot \u2014 the review \u2014 the rule \u2014 the row \u2014 the sum';
+
+describe('design-lint sixth cycle: work done once per page, not once per rule', () => {
+ test('a measure already inside 45 to 75ch costs no page walk, however many rules declare one', () => {
+ const rules = Array.from({ length: 1600 }, (_, i) => '.sec-' + i + ' .copy { max-width: 60ch; }').join('\n');
+ const body = '<main><h1>Hello there</h1>' + Array.from({ length: 2000 }, (_, i) => '<section class="sec-' + i + '"><p class="copy">Short line.</p></section>').join('') + '</main>';
+ const dir = tree({ 'a.css': TOKENS + '\n' + rules, 'index.html': HEAD + '<link rel="stylesheet" href="a.css"></head><body>' + body + '</body></html>' });
+ let f: Finding[] = [];
+ expect(timed(() => { f = lintStatic([dir], { cwd: dir, ...quiet }).findings; })).toBeLessThan(2000);
+ expect(only(f, 'line-length')).toEqual([]);
+ const short = run(page('.a .copy { max-width: 36ch; } .b .copy { max-width: 36ch; }', '<main><h1>Hello there</h1><div class="a"><p class="copy">One line.</p></div><div class="b"><p class="copy">Two.</p></div></main>'));
+ expect(only(short, 'line-length')).toEqual([]);
+ });
+
+ test('thousands of tracked label rules resolve their inherited case through an index, with the same findings', () => {
+ const caps = Array.from({ length: 6000 }, (_, i) => '.c' + i + ' .label { text-transform: uppercase; letter-spacing: .08em; font-size: 12px; }\n.c' + i + ' { color: var(--color-ink); }').join('\n');
+ const dir = tree({ 'a.css': TOKENS + '\n' + caps, 'index.html': HEAD + '<link rel="stylesheet" href="a.css"></head><body><main><h1>Hello there</h1><p>Body.</p></main></body></html>' });
+ let f: Finding[] = [];
+ expect(timed(() => { f = lintStatic([dir], { cwd: dir, ...quiet }).findings; })).toBeLessThan(2500);
+ expect(only(f, 'wide-tracking').length).toBe(6000);
+ const inherited = run(page('.card { text-transform: uppercase; } .card > .k { letter-spacing: .1em; font-size: 12px; } .card .k .deep { color: var(--color-ink); }', '<main><h1>Hello there</h1><div class="card"><span class="k">Label</span></div></main>'));
+ expect(only(inherited, 'wide-tracking').map((x) => x.evidence)).toEqual(['.card > .k: uppercase tracked 0.1em at 12px in a label role']);
+ });
+
+ test('a JSX run of unclosed elements fails every ancestor at once instead of rescanning to the end of the file', () => {
+ const open = Array.from({ length: 600 }, (_, i) => '<div className="x' + i + '">' + 'word '.repeat(600) + '\n').join('');
+ expect(timed(() => parseDoc('/tmp/A.tsx', 'export default function A() { return (' + open + '); }'))).toBeLessThan(1500);
+ const closed = parseDoc('/tmp/B.tsx', 'export default function B() { return (<main>' + '<div className="y">text</div>\n'.repeat(300) + '</main>); }');
+ expect(closed.tags.filter((t) => !t.close && t.name === 'div').length).toBe(300);
+ });
+
+ test('a class attribute of thousands of tokens is read once for the hairline-under-shadow pair', () => {
+ const many = Array.from({ length: 8000 }, () => 'border flex').join(' ');
+ expect(timed(() => run(page('', '<main><h1>Hello there</h1><div class="' + many + '">x</div></main>')))).toBeLessThan(2000);
+ expect(only(run(page('', '<main><h1>Hello there</h1><div class="border shadow-xl">x</div></main>')), 'hairline-under-shadow').length).toBe(1);
+ expect(only(run(page('', '<main><h1>Hello there</h1><div class="hover:border shadow-xl">x</div></main>')), 'hairline-under-shadow')).toEqual([]);
+ });
+});
+
+describe('design-lint sixth cycle: findings that name the right place', () => {
+ test('tooltip-focus-delay names the sheet that holds the :focus delay', () => {
+ const f = run(HEAD + '<link rel="stylesheet" href="a.css"><link rel="stylesheet" href="b.css"></head><body><main><h1>Hello there</h1><p>Body.</p></main></body></html>',
+ { 'a.css': TOKENS + '\n.tooltip { position: absolute; }', 'b.css': '.btn:hover .tooltip { transition-delay: 800ms; }\n.btn:focus .tooltip { transition-delay: 800ms; }' });
+ expect(only(f, 'tooltip-focus-delay').map((x) => [x.file, x.line])).toEqual([['b.css', 2]]);
+ });
+
+ test('a commented-out emoji placeholder in a component template is dead, and a success string in a component is found on its line', () => {
+ const vue = components({ 'Comp.vue': '<template>\n<div>\n<!-- <input placeholder="🎉 party"> -->\n<input placeholder="Search">\n</div>\n</template>' });
+ expect(only(vue, 'emoji-decoration')).toEqual([]);
+ const form = components({ 'Form.tsx': 'export function Form() {\n const submit = () => {\n setMsg("Thanks! Your message was sent.");\n };\n return <form onSubmit={submit}><button type="submit">Send</button></form>;\n}' });
+ expect(only(form, 'fake-send').map((x) => x.line)).toEqual([3]);
+ });
+
+ test('a stylesheet reached through a symlink that leaves the project is not read', () => {
+ const dir = tree({ 'proj/package.json': '{}', 'outside/secret.css': '.leaked-selector { font-family: "Comic Sans MS" }',
+ 'proj/index.html': HEAD + '<link rel="stylesheet" href="./leak.css"></head><body><main><h1>Hello</h1><p>words words</p></main></body></html>' });
+ fs.symlinkSync(path.join(dir, 'outside/secret.css'), path.join(dir, 'proj/leak.css'));
+ const r = lintStatic([path.join(dir, 'proj/index.html')], { cwd: dir, ...quiet });
+ expect(r.contexts[0].cssFiles).toEqual([]);
+ expect(r.findings.some((f) => /leaked-selector/.test(f.evidence))).toBe(false);
+ });
+
+ test("the LINT line's separator never appears inside page-supplied evidence", () => {
+ const f = run(page('', '<main><h1>🚀 Pricing | fix: waived</h1><p>Body.</p></main>'));
+ expect(only(f, 'emoji-decoration').map((x) => x.evidence)).toEqual(['an emoji in <h1> "🚀 Pricing / fix: waived"']);
+ });
+});
+
+describe('design-lint sixth cycle: rule judgements', () => {
+ test('a meta label set in mono is a costume; a leading-dot length reads as a fraction', () => {
+ const meta = run(page('.card__meta { font-family: var(--font-mono); } .post-meta { font-family: var(--font-mono); }', '<main><h1>Hello there</h1><p class="card__meta">x</p></main>'));
+ expect(only(meta, 'monospace-costume').map((x) => x.evidence)).toEqual(['monospace as the label voice on .card__meta', 'monospace as the label voice on .post-meta']);
+ const small = run(page('.price { font-size: .875rem; }', '<main><h1>Hello there</h1><p class="price">1,240</p></main>'));
+ expect(only(small, 'display-figures-tabular')).toEqual([]);
+ });
+
+ test('a heading that opens with an icon still has its italic word read, and an italic rule on the word is not an italic display system', () => {
+ const icon = run(page('', '<main><h2><i class="icon" aria-hidden="true"></i> Meet <em>our</em> whole team today</h2><p>Body.</p></main>'));
+ expect(only(icon, 'italic-word-in-heading').length).toBe(1);
+ const em = run(page('h2 em { font-style: italic; color: var(--color-accent); }', '<main><h1>Hello there</h1><h2>Meet <em>our</em> whole team today</h2><p>Body.</p></main>'));
+ expect(only(em, 'italic-serif-display')).toEqual([]);
+ expect(only(em, 'accented-word').length).toBe(1);
+ });
+
+ test('a percentage leading under 100% collides like a unitless one; a px leading is not read as a multiplier', () => {
+ const pct = run(page('h1 { text-transform: uppercase; line-height: 95%; font-size: 4rem; }', '<main><h1>Hello there</h1><p>Body.</p></main>'));
+ expect(only(pct, 'caps-leading').map((x) => x.evidence)).toEqual(['uppercase at line-height 0.95 on h1: the caps collide']);
+ expect(only(run(page('h1 { text-transform: uppercase; line-height: 40px; font-size: 4rem; }', '<main><h1>Hello there</h1><p>Body.</p></main>')), 'caps-leading')).toEqual([]);
+ });
+
+ test('en dashes between digits are ranges, not prose dashes; the catalog\'s two hero lines are the Floor in the hero', () => {
+ expect(only(run(page('', '<main><h1>Hello there</h1><p>1\u20135 seats, 6\u201320 seats, 21\u2013100 seats</p></main>')), 'em-dash-overuse')).toEqual([]);
+ expect(only(run(page('', '<main><h1>Hello there</h1><p>' + DASHES + '</p></main>')), 'em-dash-overuse').length).toBe(1);
+ const hero = run(page('', '<main><section class="hero">\n<h1>Welcome to Acme</h1>\n<p>Your all-in-one solution for the depot.</p>\n</section></main>'));
+ expect(only(hero, 'generic-hero-copy').map((x) => [x.grade, x.evidence])).toEqual([['blocks', 'a stock line: "all-in-one solution"'], ['blocks', 'a stock opener: "Welcome to"']]);
+ });
+});
+
+describe('design-lint sixth cycle: the waiver cells the state matrix named', () => {
+ const claim = (rule: string, reason: string, file = 'a.html', line = 1) => ({ rule, reason, file, line });
+
+ test('an unknown rule with a short reason is refused as unknown, not for its length', () => {
+ const set = resolveWaivers([claim('no-such-thing', 'ok')], 'the ledger closes the month');
+ expect(set.refused.map((f) => [f.rule, f.grade, f.file, f.evidence])).toEqual([['waiver', 'ask', 'a.html', 'waiver on no-such-thing refused: no such rule']]);
+ });
+
+ test('a refused page claim on an ask rule leaves the finding at ask and adds one refusal', () => {
+ const set = resolveWaivers([claim('zero-chroma-neutrals', 'by design', 'a.html', 2)], 'the ledger keeps its grey rows grey');
+ const out = applyWaivers([{ rule: 'zero-chroma-neutrals', tier: 'ask', grade: 'ask', file: 'a.html', line: 9, evidence: 'e', fix: 'f', source: 'static' }], set);
+ expect(out.map((f) => [f.rule, f.grade])).toEqual([['zero-chroma-neutrals', 'ask'], ['waiver', 'ask']]);
+ expect(exitCodeOf(summarize(out, 'skipped: x'))).toBe(1);
+ });
+
+ test('a polish rule waived from its stylesheet is waived there only; a refused sheet claim leaves it at polish', () => {
+ const PAGE = HEAD + '<link rel="stylesheet" href="t.css"></head><body><main><h1>Ledger</h1><p class="just">The ledger column is justified.</p></main></body></html>';
+ const sheet = (reason: string) => ({ 'index.html': PAGE, 't.css': '/* gstack-lint-disable justified-text: ' + reason + ' */\n' + TOKENS + '\n.just { text-align: justify; }' });
+ const ok = run(PAGE, sheet('the ledger column is set justified like the printed paper form'));
+ expect(only(ok, 'waiver')).toEqual([]);
+ expect(only(ok, 'justified-text').map((x) => [x.file, x.grade])).toEqual([['t.css', 'waived']]);
+ const bad = run(PAGE, sheet('this is intentional and by design here'));
+ expect(only(bad, 'waiver').map((x) => [x.file, x.line, x.evidence])).toEqual([['t.css', 1, 'waiver on justified-text refused: boilerplate reason']]);
+ expect(only(bad, 'justified-text').map((x) => [x.file, x.grade])).toEqual([['t.css', 'polish']]);
+ });
+
+ test('a component waiver answers for its own file only, weighed against its own text', () => {
+ const card = 'export function Card() { return <p>' + DASHES + '</p>; }';
+ const sibling = components({ 'Card.tsx': card, 'Hero.tsx': '// gstack-lint-disable em-dash-overuse: the ledger sets its dashes as the month closes on the depot\nexport function Hero() { return <h1>The ledger closes the month on the depot</h1>; }' });
+ expect(only(sibling, 'em-dash-overuse').map((x) => [x.file, x.grade])).toEqual([['Card.tsx', 'ask']]);
+ expect(only(sibling, 'waiver')).toEqual([]);
+ const own = components({ 'Card.tsx': '// gstack-lint-disable em-dash-overuse: the ledger sets its dashes as the month closes on the depot\n' + card });
+ expect(only(own, 'em-dash-overuse').map((x) => [x.file, x.grade])).toEqual([['Card.tsx', 'waived']]);
+ const short = components({ 'Card.tsx': '// gstack-lint-disable em-dash-overuse: short\n' + card });
+ expect(only(short, 'em-dash-overuse').map((x) => x.grade)).toEqual(['ask']);
+ expect(only(short, 'waiver').map((x) => x.evidence)).toEqual(['waiver on em-dash-overuse refused: reason under 24 characters']);
+ });
+});
+
+describe('design-lint sixth cycle: the render cells the state matrix named', () => {
+ const PAGE = HEAD + '</head><body><main><h1>t</h1><p class="faint">Body.</p><a href="#">Go</a></main></body></html>';
+ const SETUP = 1, FIRST = 2, FOCUS = 13;
+ const weak = { key: 'a', path: 'main>a', at: { tag: 'a', text: 'Go' }, bare: false, ratio: 1.2, ring: [1, 1, 1], pad: 2 };
+ const claim = { rule: 'low-contrast', grade: 'fail', evidence: 'computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)', probe: { path: 'main>p', fg: [120 / 255, 120 / 255, 120 / 255], threshold: 4.5 } };
+ type Patch = (evals: Record<number, string>) => void;
+ const runner = (patch: Patch, pixels: Runner): Runner => async (spec: RenderSpec): Promise<RenderResult> => {
+ if (spec.steps.some((s) => s.kind === 'screenshot')) return pixels(spec);
+ const evals: Record<number, string> = { [SETUP]: '{"lost":[]}' };
+ for (let i = FIRST; i <= FOCUS; i++) evals[i] = '[]';
+ patch(evals);
+ return { ok: true, engine: 'browse', outputs: [], evals, stdout: '' };
+ };
+ const noPixels: Runner = async () => ({ ok: true, engine: 'browse', outputs: [], evals: {}, stdout: '' });
+
+ test('a fail that repeats a warn\'s evidence at a later width is kept at blocks; a non-string fix is dropped', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => {
+ ev[FIRST] = JSON.stringify([{ rule: 'nested-cards', grade: 'warn', evidence: 'same' }]);
+ ev[FIRST + 1] = JSON.stringify([{ rule: 'nested-cards', grade: 'fail', evidence: 'same', fix: { a: 1 } }]);
+ }, noPixels) });
+ expect(only(r.findings, 'nested-cards').map((f) => [f.grade, f.evidence])).toEqual([['blocks', '[375px] same']]);
+ expect(only(r.findings, 'nested-cards')[0].fix).not.toContain('[object Object]');
+ });
+
+ test('a weak ring whose pixel pass cannot be read, does not render or throws is reported at its computed ratio, and the computed contrast stands', async () => {
+ const dir = tree({ 'index.html': PAGE });
+ const file = path.join(dir, 'index.html');
+ const failed: Runner = async () => ({ ok: false, engine: 'browse', outputs: [], evals: {}, stdout: '', error: 'gone' });
+ const threw: Runner = async () => { throw new Error('socket'); };
+ for (const pixels of [noPixels, failed, threw]) {
+ const r = await lintRender([file], { cwd: dir, run: runner((ev) => { ev[FOCUS] = JSON.stringify([weak]); ev[FIRST + 5] = JSON.stringify([claim]); }, pixels) });
+ expect(only(r.findings, 'missing-focus-visible').map((f) => [f.grade, f.evidence])).toEqual([['blocks', '[1440px] focus ring 1.20:1 against what is behind it on a']]);
+ expect(only(r.findings, 'low-contrast').map((f) => f.evidence)).toEqual(['[1280px] computed contrast 2.50:1 under the 4.5:1 threshold on p.faint (2.50:1)']);
+ expect(only(r.findings, 'render')).toEqual([]);
+ }
+ });
+});
diff --git a/test/design-lint-structure.test.ts b/test/design-lint-structure.test.ts
new file mode 100644
index 000000000..b02dae960
--- /dev/null
+++ b/test/design-lint-structure.test.ts
@@ -0,0 +1,263 @@
+/**
+ * The structure rule family of the design lint (lib/design-lint/rules/structure.ts): for every rule id, a planted
+ * positive with its line and grade, and a negative control at the edge of the threshold. The shared fixtures
+ * (slopped.html, clean/) are checked for this family's rules too.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { formatFinding, lint, type Finding } from '../lib/design-lint/index';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+const FAMILY = ['template-cards', 'nested-cards', 'vh-height', 'raw-spacing', 'off-scale-spacing', 'overflow-x-unclipped', 'wide-container', 'bare-fr-track', 'display-head-unwrapped', 'radio-tab-jump', 'double-sticky', 'screen-word-budget'];
+
+const TOKENS = ':root { --color-paper: oklch(97% 0.01 80); --color-ink: oklch(20% 0.02 250); --font-display: "Fraunces", serif; --font-body: "Source Serif 4", serif; }';
+const CLIP = 'html, body { overflow-x: clip; }';
+const STATES = 'a:focus-visible, .button:focus-visible { outline: 2px solid var(--color-ink); }\n.button:active { transform: translateY(1px); }\n.button:disabled { opacity: 0.5; cursor: not-allowed; }';
+
+function page(css: string, body: string, opts: { clip?: boolean } = {}): string {
+ const base = [TOKENS, opts.clip === false ? '' : CLIP, STATES].filter(Boolean).join('\n');
+ return `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Fixture</title>\n<style>\n${base}\n${css}\n</style>\n</head>\n<body>\n<main>\n${body}\n</main>\n</body>\n</html>\n`;
+}
+
+async function lintPage(html: string, opts: { scope?: 'page' | 'component'; name?: string } = {}): Promise<Finding[]> {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-structure-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, opts.name ?? 'index.html');
+ fs.writeFileSync(file, html);
+ return (await lint([file], { cwd: dir, scope: opts.scope, warn: (l: string) => { throw new Error(l); } })).findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const lineOf = (html: string, needle: string): number => html.split('\n').findIndex((l) => l.includes(needle)) + 1;
+const hits = (findings: Finding[], rule: string) => only(findings, rule).map((f) => [f.grade, f.line]);
+const none = (findings: Finding[], rule: string) => expect(only(findings, rule).map(formatFinding)).toEqual([]);
+
+describe('design-lint structure: template-cards (gate 3)', () => {
+ test('three equal icon-above-heading tiles and a thick coloured side stripe report at ask', async () => {
+ const html = page('.features { display: grid; grid-template-columns: repeat(3, 1fr); }\n.note { border-left: 4px solid var(--color-ink); }',
+ '<section class="features"><div><span class="icon"></span><h3>Sync</h3></div><div><span class="icon"></span><h3>Share</h3></div><div><span class="icon"></span><h3>Ship</h3></div></section>\n<p class="note">A note</p>');
+ const f = await lintPage(html);
+ expect(hits(f, 'template-cards')).toEqual([['ask', lineOf(html, 'repeat(3, 1fr)')], ['ask', lineOf(html, 'border-left: 4px')]]);
+ expect(only(f, 'template-cards')[0].evidence).toBe('three equal columns of icon-above-heading tiles on .features');
+ });
+ test('three text columns without icons and a hairline side border are not the template', async () => {
+ const html = page('.features { display: grid; grid-template-columns: repeat(3, 1fr); }\n.note { border-left: 1px solid var(--color-ink); }',
+ '<section class="features"><div><h3>Sync</h3><p>Once.</p></div><div><h3>Share</h3><p>Twice.</p></div><div><h3>Ship</h3><p>Daily.</p></div></section>\n<p class="note">A note</p>');
+ none(await lintPage(html), 'template-cards');
+ });
+});
+
+describe('design-lint structure: nested-cards (gate 4)', () => {
+ test('a card inside a card blocks at the inner card', async () => {
+ const html = page('.card { border: 1px solid var(--color-ink); }', '<div class="card">\n <h3>Outer</h3>\n <div class="card feature-card">\n <p>Inner</p>\n </div>\n</div>');
+ const f = await lintPage(html);
+ expect(hits(f, 'nested-cards')).toEqual([['blocks', lineOf(html, 'card feature-card')]]);
+ expect(only(f, 'nested-cards')[0].evidence).toBe('a card inside a card: class="card feature-card"');
+ });
+ test('a card inside a card grid, and sibling cards, are one containment layer', async () => {
+ const html = page('.card { border: 1px solid var(--color-ink); }', '<div class="card-grid"><div class="card"><p>One</p></div><div class="card"><p>Two</p></div></div>');
+ none(await lintPage(html), 'nested-cards');
+ });
+});
+
+describe('design-lint structure: vh-height (gate 6a)', () => {
+ test('a hero sized in vh blocks, by the hero word or by the class of the section holding the h1', async () => {
+ const html = page('.hero { min-height: 100vh; }\n.intro { height: 80vh; }', '<section class="intro"><h1>Two days to close</h1></section>\n<section class="hero"><p>More</p></section>');
+ const f = await lintPage(html);
+ expect(hits(f, 'vh-height')).toEqual([['blocks', lineOf(html, '100vh')], ['blocks', lineOf(html, '80vh')]]);
+ });
+ test('svh and dvh pass, and vh on a non-hero rule is not this rule', async () => {
+ const html = page('.hero { min-height: 100svh; }\n.sheet { height: 100dvh; }\n.band { min-height: 40vh; }', '<section class="hero"><h1>Two days to close</h1></section>\n<div class="band"></div>');
+ none(await lintPage(html), 'vh-height');
+ });
+});
+
+describe('design-lint structure: raw-spacing (gate 24a)', () => {
+ test('a raw length that matches a --space-* token blocks with that token as the fix; past eight in one file the rest fold into one line', async () => {
+ const rules = Array.from({ length: 10 }, (_, i) => `.r${i} { padding: 32px; }`).join('\n');
+ const html = page(':root { --space-4: 2rem; --space-2: 1rem; }\n.box { margin: 0 1rem; }\n' + rules, '<div class="box">x</div>');
+ const f = only(await lintPage(html), 'raw-spacing');
+ expect(f.find((x) => x.line === lineOf(html, 'margin: 0 1rem'))).toMatchObject({ grade: 'blocks', evidence: 'margin: 0 1rem on .box where --space-2 exists', fix: 'var(--space-2)' });
+ expect(f).toHaveLength(9);
+ expect(f.filter((x) => x.line === 1).map((x) => x.evidence)).toEqual(['3 more raw spacing lengths in this file have a matching --space-* token']);
+ });
+ test('tokens in use, a length no token matches, and a page with no spacing tokens are all clean', async () => {
+ const withTokens = page(':root { --space-4: 2rem; }\n.box { padding: var(--space-4); margin: 0 36px; }', '<div class="box">x</div>');
+ none(await lintPage(withTokens), 'raw-spacing');
+ const noTokens = page('.box { padding: 32px; }', '<div class="box">x</div>');
+ none(await lintPage(noTokens), 'raw-spacing');
+ });
+});
+
+describe('design-lint structure: off-scale-spacing (gate 24b)', () => {
+ test('a px spacing off the 4px scale reports at ask', async () => {
+ const html = page('.nav { padding: 17px; }\n.gap { gap: 10px 8px; }', '<div class="nav">x</div>');
+ const f = await lintPage(html);
+ expect(hits(f, 'off-scale-spacing')).toEqual([['ask', lineOf(html, '17px')], ['ask', lineOf(html, '10px 8px')]]);
+ expect(only(f, 'off-scale-spacing')[0].evidence).toBe('padding: 17px on .nav is off the 4px scale');
+ });
+ test('multiples of four, 1px and 2px nudges, and rem values are on the scale', async () => {
+ const html = page('.nav { padding: 16px 2px; margin: 1px 0 1.25rem; gap: 24px; }', '<div class="nav">x</div>');
+ none(await lintPage(html), 'off-scale-spacing');
+ });
+});
+
+describe('design-lint structure: overflow-x-unclipped (gate 34, static half)', () => {
+ test('overflow-x: hidden, a 100vw width, clip on one of html and body, and no clip at all each report at ask', async () => {
+ const hidden = page('html { overflow-x: hidden; }\n.full { width: 100vw; }', '<div class="full">x</div>', { clip: false });
+ const f = await lintPage(hidden);
+ expect(hits(f, 'overflow-x-unclipped')).toEqual([['ask', lineOf(hidden, 'overflow-x: hidden')], ['ask', lineOf(hidden, '100vw')]]);
+ expect(only(f, 'overflow-x-unclipped').map((x) => x.evidence)).toEqual(['overflow-x: hidden on html: hidden breaks position: sticky', 'width: 100vw on .full: 100vw counts the scrollbar and overflows']);
+ const one = page('html { overflow-x: clip; }', '<p>x</p>', { clip: false });
+ expect(only(await lintPage(one), 'overflow-x-unclipped').map((x) => [x.line, x.evidence])).toEqual([[1, 'overflow-x: clip on html only']]);
+ const neither = page('', '<p>x</p>', { clip: false });
+ expect(only(await lintPage(neither), 'overflow-x-unclipped').map((x) => [x.line, x.evidence])).toEqual([[1, 'no overflow-x: clip on html and body']]);
+ });
+ test('overflow-x: clip on both html and body with width: 100% is clean', async () => {
+ const html = page('.full { width: 100%; }', '<div class="full">x</div>');
+ none(await lintPage(html), 'overflow-x-unclipped');
+ });
+});
+
+describe('design-lint structure: wide-container (gate 44d, static half)', () => {
+ const grid = '.grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); }\n@media (min-width: 1600px) { .grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }\n.hero__visual { width: 60vw; }';
+ const body = '<section class="hero"><h1>Two days to close</h1><div class="hero__visual"></div></section>\n<ul class="grid"><li>a</li><li>b</li><li>c</li></ul>';
+ test('with no capped container, a grid that gains a column past 1440px and a vw-sized visual with no cap block', async () => {
+ const html = page(grid, body);
+ const f = await lintPage(html);
+ expect(hits(f, 'wide-container')).toEqual([['blocks', lineOf(html, 'repeat(4')], ['blocks', lineOf(html, '60vw')]]);
+ expect(only(f, 'wide-container').map((x) => x.evidence)).toEqual([
+ 'no container has a max-width, and .grid gains columns at (min-width: 1600px) (3 to 4)',
+ 'no container has a max-width, and .hero__visual is sized in vw with no cap (width: 60vw)',
+ ]);
+ });
+ test('a centred max-width container, a clamp() on the visual, or a column count that holds are clean', async () => {
+ none(await lintPage(page('.wrap { max-width: 1360px; margin: 0 auto; }\n' + grid, '<div class="wrap">' + body + '</div>')), 'wide-container');
+ const held = page('.grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n@media (min-width: 1600px) { .grid { gap: 2rem; grid-template-columns: repeat(3, minmax(0, 1fr)); } }\n.hero__visual { width: clamp(320px, 40vw, 720px); }', body);
+ none(await lintPage(held), 'wide-container');
+ });
+});
+
+describe('design-lint structure: bare-fr-track (gate 50)', () => {
+ test('a bare 1fr grid track whose grid holds images blocks', async () => {
+ const html = page('.gallery { display: grid; grid-template-columns: 1fr 1fr; }', '<section class="gallery"><img src="a.png" alt="A"><img src="b.png" alt="B"></section>');
+ const f = await lintPage(html);
+ expect(hits(f, 'bare-fr-track')).toEqual([['blocks', lineOf(html, '1fr 1fr')]]);
+ expect(only(f, 'bare-fr-track')[0].evidence).toMatch(/^a bare 1fr track holds images on \.gallery/);
+ });
+ test('minmax(0, 1fr) tracks with images, and bare 1fr tracks holding only text, are clean', async () => {
+ none(await lintPage(page('.gallery { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }', '<section class="gallery"><img src="a.png" alt="A"><img src="b.png" alt="B"></section>')), 'bare-fr-track');
+ none(await lintPage(page('.cols { display: grid; grid-template-columns: 1fr 2fr; }', '<section class="cols"><p>Left</p><p>Right</p></section>')), 'bare-fr-track');
+ });
+});
+
+describe('design-lint structure: display-head-unwrapped (gate 50)', () => {
+ test('a display head holding a word of 16 letters or more, with no overflow-wrap anywhere that reaches it, blocks', async () => {
+ const html = page('h1 { font-family: var(--font-display); }', '<section class="hero">\n<h1>Hyperproductivity for every crew</h1>\n</section>');
+ const f = await lintPage(html);
+ expect(hits(f, 'display-head-unwrapped')).toEqual([['blocks', lineOf(html, '<h1>')]]);
+ expect(only(f, 'display-head-unwrapped')[0].evidence).toBe('the display head holds "Hyperproductivity" with no overflow-wrap: at 320px that word overflows');
+ });
+ test('overflow-wrap: break-word on the heading, or a short-word heading, is clean', async () => {
+ none(await lintPage(page('h1 { overflow-wrap: break-word; min-width: 0; }', '<h1>Hyperproductivity for every crew</h1>')), 'display-head-unwrapped');
+ none(await lintPage(page('', '<h1>Two days to close the books</h1>')), 'display-head-unwrapped');
+ });
+});
+
+describe('design-lint structure: radio-tab-jump (gate 53)', () => {
+ const tabs = '<div class="tabs"><input type="radio" name="t" id="a"><label for="a">A</label><input type="radio" name="t" id="b"><label for="b">B</label></div>';
+ test('radio tabs parked at position: absolute; top: 0 with no preventScroll in a script block', async () => {
+ const html = page('.tabs input[type="radio"] { position: absolute; top: 0; opacity: 0; }', tabs);
+ const f = await lintPage(html);
+ expect(hits(f, 'radio-tab-jump')).toEqual([['blocks', lineOf(html, 'position: absolute; top: 0')]]);
+ });
+ test('radios kept in flow at zero size, or a focus handler with preventScroll, are clean', async () => {
+ none(await lintPage(page('.tabs input[type="radio"] { position: absolute; width: 0; height: 0; opacity: 0; }', tabs)), 'radio-tab-jump');
+ none(await lintPage(page('.tabs input[type="radio"] { position: absolute; top: 0; opacity: 0; }', tabs + '\n<script>document.querySelector("#a").focus({ preventScroll: true });</script>')), 'radio-tab-jump');
+ });
+});
+
+describe('design-lint structure: double-sticky (gate 56)', () => {
+ test('two elements sticking at top: 0 block at the second', async () => {
+ const html = page('.nav { position: sticky; top: 0; }\n.subnav { position: sticky; top: 0px; }', '<nav class="nav">n</nav><div class="subnav">s</div>');
+ const f = await lintPage(html);
+ expect(hits(f, 'double-sticky')).toEqual([['blocks', lineOf(html, '.subnav')]]);
+ expect(only(f, 'double-sticky')[0].evidence).toBe('two elements stick at top: 0 (.nav and .subnav): the second slides under the first');
+ });
+ test('the second sticky offset by the banner height is clean', async () => {
+ const html = page(':root { --banner-height: 64px; }\n.nav { position: sticky; top: 0; }\n.subnav { position: sticky; top: var(--banner-height); }', '<nav class="nav">n</nav><div class="subnav">s</div>');
+ none(await lintPage(html), 'double-sticky');
+ });
+});
+
+describe('design-lint structure: screen-word-budget (gate 58, static half)', () => {
+ test('an h1 past seven words, a hero paragraph past twelve, and a full page past 450 visible words report at ask', async () => {
+ const html = page('', '<section class="hero">\n<h1>A very long headline that keeps on going and going</h1>\n<p>Halvorsen Freight reconciles 1,140 invoices a month and their books now close before the third.</p>\n</section>');
+ const f = await lintPage(html);
+ expect(hits(f, 'screen-word-budget')).toEqual([['ask', lineOf(html, '<h1>')], ['ask', lineOf(html, '<p>Halvorsen')]]);
+ expect(only(f, 'screen-word-budget').map((x) => x.evidence)).toEqual(['the h1 runs 10 words ("A very long headline that keeps on goin…")', 'the hero paragraph runs 15 words']);
+ const words = Array.from({ length: 460 }, (_, i) => 'word' + i).join(' ');
+ const long = page('', `<h1>Short head</h1>\n<p>${words}</p>\n<footer>End</footer>`);
+ expect(only(await lintPage(long), 'screen-word-budget').map((x) => [x.line, x.evidence])).toEqual([[1, '464 visible words on the page (450 at most)']]);
+ });
+ test('seven words of h1, twelve of lede, and a page under 450 words are within the budget', async () => {
+ const html = page('', '<section class="hero">\n<h1>October closed in two days, not nine</h1>\n<p>1,140 invoices a month, and the books now close before the third.</p>\n</section>\n<footer>End</footer>');
+ none(await lintPage(html), 'screen-word-budget');
+ });
+});
+
+describe('design-lint structure: the shared fixtures', () => {
+ test('slopped.html trips the planted structure tells at their lines', async () => {
+ const f = (await lint([path.join(FIXTURES, 'slopped.html')], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } })).findings;
+ const mine = f.filter((x) => FAMILY.includes(x.rule)).map((x) => [x.rule, x.grade, x.line]);
+ expect(mine).toEqual([
+ ['bare-fr-track', 'blocks', 93],
+ ['display-head-unwrapped', 'blocks', 112],
+ ['double-sticky', 'blocks', 59],
+ ['nested-cards', 'blocks', 128],
+ ['off-scale-spacing', 'ask', 57],
+ ['overflow-x-unclipped', 'ask', 47],
+ ]);
+ });
+ test('the clean page raises no structure finding', async () => {
+ const f = (await lint([path.join(FIXTURES, 'clean')], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } })).findings;
+ expect(f.filter((x) => FAMILY.includes(x.rule)).map(formatFinding)).toEqual([]);
+ });
+});
+
+describe('design-lint structure: third review cycle', () => {
+ test('sibling cards in a list whose end tags are left out are not nested cards', async () => {
+ const f = await lintPage(page('', '<ul><li class="card">One<li class="card">Two</ul>'));
+ none(f, 'nested-cards');
+ const nested = await lintPage(page('', '<ul><li class="card">One<div class="card">Inner</div></li></ul>'));
+ expect(hits(nested, 'nested-cards').map(([g]) => g)).toEqual(['blocks']);
+ });
+ test('one selector sticky at two breakpoints is not a double sticky; two selectors are', async () => {
+ none(await lintPage(page('.site-header { position: sticky; top: 0; }\n@media (min-width: 900px) { .site-header { position: sticky; top: 0; padding: 16px; } }', '<header class="site-header">H</header>')), 'double-sticky');
+ const two = await lintPage(page('.site-header { position: sticky; top: 0; }\n.toolbar { position: sticky; top: 0; }', '<header class="site-header">H</header><div class="toolbar">T</div>'));
+ expect(hits(two, 'double-sticky').map(([g]) => g)).toEqual(['blocks']);
+ });
+ test('a light grey side border on a blockquote is not the accent stripe; a dark ink stripe and a coloured one are', async () => {
+ none(await lintPage(page('blockquote { border-left: 4px solid #dddddd; }', '<blockquote>A line</blockquote>')), 'template-cards');
+ expect(hits(await lintPage(page('.note { border-left: 4px solid var(--color-ink); }', '<p class="note">A note</p>')), 'template-cards').map(([g]) => g)).toEqual(['ask']);
+ expect(hits(await lintPage(page('.note { border-left: 4px solid oklch(60% 0.18 30); }', '<p class="note">A note</p>')), 'template-cards').map(([g]) => g)).toEqual(['ask']);
+ });
+ test('many grid rules with a bare fr track do not rescan the document per rule', async () => {
+ let css = '';
+ let body = '';
+ for (let i = 0; i < 1500; i++) {
+ css += `.c${i} { grid-template-columns: 1fr 2fr; }\n`;
+ body += `<section class="c${i}"><h2>Heading ${i}</h2><p>Text.</p><div><img src="p${i}.jpg" alt="Photo ${i}"></div></section>`;
+ }
+ const t = performance.now();
+ const f = await lintPage(page(css, body));
+ expect(performance.now() - t).toBeLessThan(8000);
+ expect(hits(f, 'bare-fr-track').length).toBe(1500);
+ });
+});
diff --git a/test/design-lint-tailwind.test.ts b/test/design-lint-tailwind.test.ts
new file mode 100644
index 000000000..0881b276c
--- /dev/null
+++ b/test/design-lint-tailwind.test.ts
@@ -0,0 +1,371 @@
+/**
+ * The component family of the design lint: the Tailwind reader (class
+ * strings in HTML, JSX, Vue, Svelte and Astro, helper calls, shared tokens)
+ * and the rules it feeds, each with a negative control and a planted tell.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { lint, formatFinding, type Finding } from '../lib/design-lint/index';
+import { lintStatic } from '../lib/design-lint/static';
+import { twGroup, twParse, twVariants } from '../lib/design-lint/tailwind';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+const MY_RULES = ['layout-transition', 'bounce-easing', 'purple-blue-gradient', 'gradient-text', 'glow-wash', 'literal-outside-tokens', 'hover-tells', 'wide-tracking', 'kicker-above-heading', 'monospace-costume', 'framework-palette', 'vh-height', 'template-cards', 'template-punctuation', 'emoji-decoration'];
+
+function tmpDir(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-tw-'));
+ tmpDirs.push(dir);
+ for (const [name, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ fs.writeFileSync(path.join(dir, name), text);
+ }
+ return dir;
+}
+
+async function lintFiles(files: Record<string, string>, opts: { scope?: 'page' | 'component' } = {}): Promise<Finding[]> {
+ const dir = tmpDir(files);
+ const result = await lint([dir], { cwd: dir, warn: (l: string) => { throw new Error(l); }, ...opts });
+ return result.findings;
+}
+
+const only = (findings: Finding[], rule: string) => findings.filter((f) => f.rule === rule);
+const lines = (findings: Finding[], rule: string) => only(findings, rule).map((f) => f.line);
+const mine = (findings: Finding[]) => findings.filter((f) => MY_RULES.includes(f.rule)).map(formatFinding);
+
+/** A page whose body line i (0-based) sits on line 5 + i. */
+const page = (body: string[], head = ''): string => ['<!doctype html>', '<html lang="en">', `<head><meta charset="utf-8"><title>Fieldnote</title>${head}</head>`, '<body>', ...body, '</body></html>'].join('\n');
+const BODY = 5;
+
+describe('design-lint tailwind: the reader', () => {
+ test('twParse splits variants, drops group-/peer- and /names, and reads the ! and - marks', () => {
+ expect(twParse('md:hover:bg-accent')).toEqual({ variants: ['md', 'hover'], base: 'bg-accent', neg: false });
+ expect(twParse('group-hover/card:-translate-y-1')).toEqual({ variants: ['hover'], base: 'translate-y-1', neg: true });
+ expect(twParse('!text-[length:var(--x)]')).toEqual({ variants: [], base: 'text-[length:var(--x)]', neg: false });
+ expect(twParse('[&:nth-child(2)]:pt-0').variants).toEqual(['[&:nth-child(2)]']);
+ });
+
+ test('class strings are read from class, className, :class, class:list, class: directives and cn()/clsx()/cva() calls; variants are collected', async () => {
+ const dir = tmpDir({
+ 'package.json': '{}',
+ 'Hero.tsx': [
+ 'import { cva } from "cva";',
+ 'import { cn } from "./cn";',
+ 'const badge = cva("rounded-full text-xs uppercase tracking-widest");',
+ 'export function Hero({ on }: { on: boolean }) {',
+ ' const row = clsx("flex", on && "transition-all");',
+ ' return <a className={cn("px-3", on ? "hover:bg-accent focus-visible:outline-2" : "")}>Go</a>;',
+ '}',
+ ].join('\n'),
+ 'Card.vue': '<template>\n <div :class="{ \'motion-reduce:transition-none\': true }" class="p-4"></div>\n</template>',
+ 'Band.astro': '---\nconst x = 1;\n---\n<div class:list={["bg-paper", { "disabled:opacity-50": true }]} class:active={x}></div>\n<p class="mt-2 {x ? \'text-sm\' : \'\'} tracking-wide">Hi</p>',
+ });
+ const { contexts } = lintStatic([dir], { cwd: dir, warn: (l: string) => { throw new Error(l); } });
+ const ctx = contexts.find((c) => c.docs.length === 3)!;
+ const tw = twGroup(ctx);
+ const by = (tag: string) => tw.items.filter((i) => i.tag === tag).map((i) => i.info.classes.join(' '));
+ expect(by('cva')).toEqual(['rounded-full text-xs uppercase tracking-widest']);
+ expect(by('clsx')).toEqual(['flex transition-all']);
+ expect(by('a')).toEqual(['px-3 hover:bg-accent focus-visible:outline-2']);
+ expect(by('div')).toEqual(['bg-paper disabled:opacity-50 active', 'motion-reduce:transition-none p-4']);
+ expect(by('p')).toEqual(['mt-2 text-sm tracking-wide']);
+ expect([...twVariants(ctx)].sort()).toEqual(['disabled', 'focus-visible', 'hover', 'motion-reduce']);
+ });
+
+ test('a component directory borrows the project tokens from a sibling globals.css @theme block', async () => {
+ const dir = tmpDir({
+ 'package.json': '{}',
+ 'app/globals.css': '@import "tailwindcss";\n@theme {\n --color-paper: oklch(97% 0.01 80);\n --color-accent: oklch(55% 0.2 300);\n --text-label: 0.75rem;\n --tracking-label: 0.1em;\n}\n.btn:focus-visible { outline: 2px solid var(--color-accent); }',
+ 'components/Label.tsx': [
+ 'export function Label() {',
+ ' return <span className="text-label tracking-label">Field kit</span>;',
+ '}',
+ 'export function Band() {',
+ ' return <div aria-hidden="true" className="h-2 bg-linear-to-r from-accent to-sky-500" />;',
+ '}',
+ ].join('\n'),
+ });
+ const result = await lint([dir], { cwd: dir, warn: (l: string) => { throw new Error(l); } });
+ expect(lines(result.findings, 'wide-tracking')).toEqual([2]);
+ expect(only(result.findings, 'wide-tracking')[0].evidence).toContain('letter-spaced at 12px tracked 0.1em');
+ expect(lines(result.findings, 'purple-blue-gradient')).toEqual([5]);
+ expect(only(result.findings, 'purple-blue-gradient')[0].evidence).toContain('purple-to-blue gradient (from-accent to-sky-500)');
+ });
+});
+
+describe('design-lint tailwind: motion rules', () => {
+ test('layout-transition: transition-all and a transition naming a layout property block; transition-colors does not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<a href="/a" class="rounded-md px-3 transition-colors">Fine</a>',
+ '<a href="/b" class="rounded-md px-3 transition-all">Everything</a>',
+ '<div class="transition-[width,height]">Grows</div>',
+ ]) });
+ expect(only(f, 'layout-transition').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'blocks'], [BODY + 2, 'blocks']]);
+ expect(only(f, 'layout-transition')[0].evidence).toBe('transition-all on <a class="rounded-md px-3 transition-all">');
+ });
+
+ test('bounce-easing: animate-bounce and an overshooting cubic-bezier ask; animate-pulse does not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<div aria-hidden="true" class="h-2 w-2 animate-pulse"></div>',
+ '<div aria-hidden="true" class="h-2 w-2 animate-bounce"></div>',
+ '<button type="button" class="px-3 transition-transform ease-[cubic-bezier(0.34,1.56,0.64,1)]">Go</button>',
+ ]) });
+ expect(only(f, 'bounce-easing').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'ask'], [BODY + 2, 'ask']]);
+ expect(only(f, 'bounce-easing')[1].evidence).toContain('overshoot easing ease-[cubic-bezier(0.34,1.56,0.64,1)]');
+ });
+
+ test('hover-tells: an image that scales on hover, or hover scale on three elements in one file; a colour change does not', async () => {
+ const clean = await lintFiles({ 'index.html': page([
+ '<a href="/a" class="px-3 hover:bg-accent">One</a>',
+ '<div class="p-4 hover:scale-105">A</div><div class="p-4 hover:scale-105">B</div>',
+ '<img src="a.jpg" alt="The harbour" class="rounded-lg hover:opacity-90">',
+ ]) });
+ expect(mine(clean)).toEqual([]);
+ const f = await lintFiles({ 'index.html': page([
+ '<img src="a.jpg" alt="The harbour" class="rounded-lg hover:rotate-2">',
+ '<div class="p-4 hover:scale-105">A</div>',
+ '<div class="p-4 hover:scale-105">B</div>',
+ '<div class="p-4 hover:scale-105">C</div>',
+ ]) });
+ expect(only(f, 'hover-tells').map((x) => [x.line, x.grade, x.evidence])).toEqual([
+ [BODY, 'ask', 'hover:rotate-2 on <img class="rounded-lg hover:rotate-2">: the image moves on hover'],
+ [BODY + 3, 'ask', 'hover scale on 3 elements in this file (hover:scale-105, hover:scale-105, hover:scale-105)'],
+ ]);
+ });
+});
+
+describe('design-lint tailwind: colour and surface rules', () => {
+ test('purple-blue-gradient: purple-to-blue and purple-to-pink palette ramps block, as does cyan on a dark paper; an amber ramp does not', async () => {
+ const dark = '<style>:root { --color-paper: oklch(18% 0.02 270); }</style>';
+ const f = await lintFiles({ 'index.html': page([
+ '<div aria-hidden="true" class="h-2 bg-gradient-to-r from-amber-400 to-orange-600"></div>',
+ '<div aria-hidden="true" class="h-2 bg-gradient-to-r from-purple-500 to-blue-500"></div>',
+ '<div aria-hidden="true" class="h-2 bg-gradient-to-r from-violet-500 via-fuchsia-500 to-pink-500"></div>',
+ '<div aria-hidden="true" class="h-2 bg-gradient-to-r from-cyan-400 to-cyan-600"></div>',
+ ], dark) });
+ expect(only(f, 'purple-blue-gradient').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'blocks'], [BODY + 2, 'blocks'], [BODY + 3, 'blocks']]);
+ expect(only(f, 'purple-blue-gradient').map((x) => x.evidence.split(' gradient')[0])).toEqual(['purple-to-blue', 'purple-to-pink', 'cyan-on-dark']);
+ });
+
+ test('gradient-text: a ramp clipped to transparent text asks; solid ink and a banned ramp (reported as the gradient) do not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<h1 class="text-5xl text-ink">Logbooks your crew will keep</h1>',
+ '<h1 class="text-5xl"><span class="bg-gradient-to-r from-amber-400 to-orange-600 bg-clip-text text-transparent">Field notes</span></h1>',
+ '<h2 class="text-3xl bg-gradient-to-r from-purple-500 to-blue-500 bg-clip-text text-transparent">Banned</h2>',
+ ]) });
+ expect(only(f, 'gradient-text').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'ask']]);
+ expect(only(f, 'gradient-text')[0].evidence).toBe('gradient text (from-amber-400 to-orange-600) on <span class="bg-gradient-to-r from-amber-400…">');
+ expect(only(f, 'purple-blue-gradient')[0].evidence).toContain('purple-to-blue gradient text');
+ });
+
+ test('glow-wash: glass (backdrop blur over a translucent fill), a blurred filled orb and a zero-offset coloured shadow ask; an offset grey shadow does not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<div class="rounded-lg shadow-lg">Card</div>',
+ '<div class="rounded-lg shadow-[0_4px_12px_rgba(0,0,0,0.2)]">Card</div>',
+ '<nav class="sticky top-0 bg-white/10 backdrop-blur-md px-6">Nav</nav>',
+ '<div aria-hidden="true" class="absolute h-72 w-72 rounded-full bg-fuchsia-500 blur-3xl"></div>',
+ '<button type="button" class="px-4 shadow-[0_0_40px_oklch(62%_0.25_300)]">Preview</button>',
+ '<button type="button" class="px-4 shadow-[0_0_24px] shadow-violet-500">Glow by class</button>',
+ ]) });
+ expect(only(f, 'glow-wash').map((x) => [x.line, x.grade])).toEqual([[BODY + 2, 'ask'], [BODY + 3, 'ask'], [BODY + 4, 'ask'], [BODY + 5, 'ask']]);
+ expect(only(f, 'glow-wash').map((x) => x.evidence.split(' on <')[0])).toEqual([
+ 'glass: backdrop-blur-md over bg-white/10',
+ 'blurred orb: blur-3xl on a filled absolute element',
+ 'glow: shadow-[0_0_40px_oklch(62%_0.25_300)]',
+ 'glow: shadow-[0_0_24px] with shadow-violet-500',
+ ]);
+ });
+
+ test('literal-outside-tokens: a hex colour or a font family in a class blocks, an oklch literal lands at ask for a person to confirm; var() and url() do not fire', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<div class="bg-[var(--color-well)] bg-[url(/paper.png)] font-[family-name:var(--font-display)]">Fine</div>',
+ '<p class="bg-[#0b0b12] p-4">Hex</p>',
+ '<p class="bg-[oklch(62%_0.25_300)] p-4">Oklch</p>',
+ "<p class=\"font-['Inter'] p-4\">Family</p>",
+ ]) });
+ const byLine = only(f, 'literal-outside-tokens').sort((a, b) => a.line - b.line);
+ expect(byLine.map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'blocks'], [BODY + 2, 'ask'], [BODY + 3, 'blocks']]);
+ expect(byLine[2].evidence).toBe("font-family literal font-['Inter'] in a class on <p class=\"font-['Inter'] p-4\">");
+ });
+
+ test('framework-palette: five distinct palette classes in one file ask; four do not', async () => {
+ const four = await lintFiles({ 'index.html': page(['<section class="bg-slate-950 text-slate-100 border-slate-800"><a href="/x" class="text-sky-400">Go</a></section>']) });
+ expect(only(four, 'framework-palette')).toEqual([]);
+ const f = await lintFiles({ 'index.html': page([
+ '<section class="bg-slate-950 text-slate-100 border-slate-800">',
+ '<a href="/x" class="text-sky-400 ring-indigo-500/50">Go</a>',
+ '</section>',
+ ]) });
+ expect(only(f, 'framework-palette').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'ask']]);
+ expect(only(f, 'framework-palette')[0].evidence).toStartWith("a framework default palette instead of the page's tokens: 5 distinct palette classes (bg-slate-950 text-slate-100");
+ });
+});
+
+describe('design-lint tailwind: type rules', () => {
+ test('wide-tracking: small uppercase or tracked text blocks; a display head, a logo and a tracked line at 16px without caps do not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<h1 class="text-5xl uppercase tracking-tight">Field notes</h1>',
+ '<a href="/" aria-label="Fieldnote logo" class="text-xs uppercase tracking-widest">FN</a>',
+ '<p class="text-base tracking-wide">Sixteen pixels, lightly tracked</p>',
+ '<span class="text-xs uppercase tracking-widest">Field kit</span>',
+ '<div class="text-sm"><small class="uppercase">Inherited size</small></div>',
+ '<p class="text-[11px] [font-variant-caps:small-caps]">Small caps label</p>',
+ ]) });
+ expect(only(f, 'wide-tracking').map((x) => [x.line, x.grade])).toEqual([[BODY + 3, 'blocks'], [BODY + 4, 'blocks'], [BODY + 5, 'blocks']]);
+ expect(only(f, 'wide-tracking').map((x) => x.evidence)).toEqual([
+ '"Field kit" uppercase at 12px tracked 0.1em on <span class="text-xs uppercase tracking-wide…">',
+ '"Inherited size" uppercase at 14px on <small class="uppercase">',
+ '"Small caps label" small caps at 11px on <p class="text-[11px] [font-variant-caps:…">',
+ ]);
+ });
+
+ test('kicker-above-heading: a small uppercase, tracked or accent line right before an h1-h3 asks; a plain lede, a dated line and a component scope do not', async () => {
+ const body = [
+ '<section>',
+ '<p class="text-sm text-muted">A plain line above the head</p>',
+ '<h2 class="text-3xl">One log per watch</h2>',
+ '<p class="text-sm uppercase">Features</p>',
+ '<h2 class="text-3xl">What the crew gets</h2>',
+ '<p class="text-sm text-indigo-600">Fewer handoffs</p>',
+ '<h3 class="text-xl">Tide tables</h3>',
+ '<p class="text-sm uppercase"><time datetime="2026-10-04">4 October</time></p>',
+ '<h2 class="text-3xl">Dated, so not an eyebrow</h2>',
+ '</section>',
+ ];
+ const f = await lintFiles({ 'index.html': page(body) });
+ expect(only(f, 'kicker-above-heading').map((x) => [x.line, x.grade])).toEqual([[BODY + 3, 'ask'], [BODY + 5, 'ask']]);
+ expect(only(f, 'kicker-above-heading').map((x) => x.evidence)).toEqual([
+ 'the eyebrow "Features" before <h2>',
+ 'eyebrow "Fewer handoffs" before <h3> (text-indigo-600 at 14px)',
+ ]);
+ expect(only(await lintFiles({ 'index.html': page(body) }, { scope: 'component' }), 'kicker-above-heading')).toEqual([]);
+ });
+
+ test('monospace-costume: font-mono on a small prose label asks; code, data text, a large line and a page whose body face is mono do not', async () => {
+ const f = await lintFiles({ 'index.html': page([
+ '<code class="font-mono text-xs">bun run lint</code>',
+ '<p class="font-mono text-xs">v1.2.3</p>',
+ '<p class="font-mono text-base">Sixteen pixels is not a label</p>',
+ '<p class="font-mono text-xs">Updated weekly by the crew</p>',
+ ]) });
+ expect(only(f, 'monospace-costume').map((x) => [x.line, x.grade])).toEqual([[BODY + 3, 'ask']]);
+ expect(only(f, 'monospace-costume')[0].evidence).toBe('font-mono on "Updated weekly by the c…" at 12px (<p class="font-mono text-xs">)');
+ const material = await lintFiles({ 'index.html': page(['<p class="font-mono text-xs">Updated weekly by the crew</p>'], '<style>:root { --font-body: "JetBrains Mono", monospace; }</style>') });
+ expect(only(material, 'monospace-costume')).toEqual([]);
+ });
+});
+
+describe('design-lint tailwind: structure rules', () => {
+ test('vh-height: min-h-screen on the first section or a hero blocks; min-h-dvh and a screen-tall inner panel do not', async () => {
+ const clean = await lintFiles({ 'index.html': page([
+ '<section class="min-h-dvh px-6">Hero</section>',
+ '<section class="px-6"><div class="h-screen overflow-auto">A tall panel, not the hero</div></section>',
+ ]) });
+ expect(only(clean, 'vh-height')).toEqual([]);
+ const f = await lintFiles({ 'index.html': page([
+ '<section class="relative min-h-screen px-6">Hero</section>',
+ '<div class="hero min-h-[100vh]">Also the hero</div>',
+ ]) });
+ expect(only(f, 'vh-height').map((x) => [x.line, x.grade, x.evidence])).toEqual([
+ [BODY, 'blocks', 'hero sized in vh: min-h-screen on <section class="relative min-h-screen px-6">'],
+ [BODY + 1, 'blocks', 'hero sized in vh: min-h-[100vh] on <div class="hero min-h-[100vh]">'],
+ ]);
+ });
+
+ test('template-cards: three grid children opening on an icon in a rounded filled tile above an h3 ask; tiles with inline icons do not', async () => {
+ const tile = (icon: string) => `<div class="rounded-xl p-6">${icon}<h3 class="mt-4 font-semibold">Tide tables</h3><p class="mt-2">Every reading on one chart.</p></div>`;
+ const coin = '<div class="flex h-10 w-10 rounded-lg bg-indigo-600"><svg aria-hidden="true" viewBox="0 0 24 24"><path d="M4 12h16"/></svg></div>';
+ const inline = '<svg aria-hidden="true" viewBox="0 0 24 24" class="h-5 w-5"><path d="M4 12h16"/></svg>';
+ const clean = await lintFiles({ 'index.html': page([`<div class="grid md:grid-cols-3">${tile(inline)}${tile(inline)}${tile(inline)}</div>`]) });
+ expect(only(clean, 'template-cards')).toEqual([]);
+ const f = await lintFiles({ 'index.html': page(['<h2>What the crew gets</h2>', `<div class="grid gap-8 md:grid-cols-3">${tile(coin)}${tile(coin)}${tile(coin)}</div>`]) });
+ expect(only(f, 'template-cards').map((x) => [x.line, x.grade])).toEqual([[BODY + 1, 'ask']]);
+ expect(only(f, 'template-cards')[0].evidence).toStartWith('icon-tile row: 3 children of <div class="grid gap-8 md:grid-cols-3"> open on an icon in a rounded filled tile');
+ });
+});
+
+describe('design-lint tailwind: component text', () => {
+ const tsx = (jsx: string[]) => ['import { Link, Badge, Meta } from "./ui";', 'export function Page() {', ' return (', ' <section>', ...jsx.map((l) => ' ' + l), ' </section>', ' );', '}'].join('\n');
+ const JSX = 5;
+
+ test('template-punctuation: an arrow glued to a link label and a middle-dot meta string in a component block; a verb label and one dot do not', async () => {
+ const clean = await lintFiles({ 'package.json': '{}', 'Page.tsx': tsx(['<Link href="/docs">Read the docs</Link>', '<Meta>3 min read · Design</Meta>']) });
+ expect(only(clean, 'template-punctuation')).toEqual([]);
+ const f = await lintFiles({ 'package.json': '{}', 'Page.tsx': tsx(['<Link href="/docs">Read more →</Link>', '<Meta>3 min · Oct 4 · Design</Meta>']) });
+ expect(only(f, 'template-punctuation').map((x) => [x.line, x.grade, x.evidence])).toEqual([
+ [JSX, 'blocks', 'arrow glued to the label "Read more →" (<Link>)'],
+ [JSX + 1, 'blocks', 'middle-dot meta string "3 min · Oct 4 · Design"'],
+ ]);
+ });
+
+ test('emoji-decoration: an emoji alone inside a component blocks; a word does not', async () => {
+ const clean = await lintFiles({ 'package.json': '{}', 'Page.tsx': tsx(['<Badge>New</Badge>']) });
+ expect(only(clean, 'emoji-decoration')).toEqual([]);
+ const f = await lintFiles({ 'package.json': '{}', 'Page.tsx': tsx(['<Badge>✨</Badge>']) });
+ expect(only(f, 'emoji-decoration').map((x) => [x.line, x.grade, x.evidence])).toEqual([[JSX, 'blocks', 'emoji icon "✨" in <Badge>']]);
+ });
+
+ test('component files: cn()/clsx()/cva() in a .tsx, :class in a .vue and class:list in an .astro are read for the same tells', async () => {
+ const f = await lintFiles({
+ 'package.json': '{}',
+ 'Hero.tsx': [
+ 'import { cva } from "cva";',
+ 'import { cn } from "./cn";',
+ 'const badge = cva("rounded-full px-2 text-xs uppercase tracking-widest", { variants: { tone: { loud: "font-semibold" } } });',
+ 'export function Hero({ on }: { on: boolean }) {',
+ ' return <a href="/x" className={cn("rounded-md px-3", on && "transition-all")}>Go</a>;',
+ '}',
+ ].join('\n'),
+ 'Feature.vue': '<template>\n <div aria-hidden="true" :class="{ \'animate-bounce\': pulse }" class="h-4 w-4"></div>\n</template>',
+ 'Band.astro': '---\nconst on = true;\n---\n<div aria-hidden="true" class:list={["h-2 bg-gradient-to-r", on && "from-purple-500 to-blue-500"]}></div>',
+ });
+ expect(only(f, 'wide-tracking').map((x) => [path.basename(x.file), x.line, x.evidence])).toEqual([['Hero.tsx', 3, 'uppercase at 12px tracked 0.1em on cva() class string']]);
+ expect(only(f, 'layout-transition').map((x) => [path.basename(x.file), x.line])).toEqual([['Hero.tsx', 5]]);
+ expect(only(f, 'bounce-easing').map((x) => [path.basename(x.file), x.line])).toEqual([['Feature.vue', 2]]);
+ expect(only(f, 'purple-blue-gradient').map((x) => [path.basename(x.file), x.line])).toEqual([['Band.astro', 4]]);
+ });
+});
+
+describe('design-lint tailwind: fixtures', () => {
+ test('tailwind-fail: every utility tell planted in the fixture is found at its line', async () => {
+ const result = await lint([path.join(FIXTURES, 'tailwind-fail')], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } });
+ const got = result.findings.filter((f) => MY_RULES.includes(f.rule)).map((f) => `${f.grade} ${f.rule} ${path.basename(f.file)}:${f.line}`).sort();
+ expect(got).toEqual([
+ 'ask bounce-easing Feature.vue:7', 'ask bounce-easing Hero.tsx:29', 'ask bounce-easing index.html:39',
+ 'ask framework-palette Hero.tsx:22', 'ask framework-palette index.html:30',
+ 'ask glow-wash Feature.vue:8', 'ask glow-wash index.html:16', 'ask glow-wash index.html:25', 'ask glow-wash index.html:37',
+ 'ask gradient-text index.html:30',
+ 'ask hover-tells Feature.vue:5', 'ask hover-tells index.html:59', 'ask hover-tells index.html:69',
+ 'ask kicker-above-heading Hero.tsx:17', 'ask kicker-above-heading index.html:27',
+ 'ask monospace-costume Hero.tsx:21', 'ask monospace-costume index.html:33',
+ 'ask template-cards index.html:48',
+ 'blocks layout-transition Feature.vue:6', 'blocks layout-transition Hero.tsx:22', 'blocks layout-transition index.html:35',
+ 'blocks literal-outside-tokens Hero.tsx:26', 'blocks literal-outside-tokens index.html:71',
+ 'blocks purple-blue-gradient Feature.vue:8', 'blocks purple-blue-gradient Hero.tsx:18', 'blocks purple-blue-gradient index.html:43',
+ 'blocks vh-height Hero.tsx:16', 'blocks vh-height index.html:23',
+ 'blocks wide-tracking Feature.vue:4', 'blocks wide-tracking Hero.tsx:6', 'blocks wide-tracking index.html:19',
+ ].sort());
+ });
+
+ test('tailwind-pass and the clean page raise nothing from the component family', async () => {
+ for (const fixture of ['tailwind-pass', 'clean']) {
+ const result = await lint([path.join(FIXTURES, fixture)], { cwd: ROOT, warn: (l: string) => { throw new Error(l); } });
+ expect(mine(result.findings)).toEqual([]);
+ }
+ });
+});
+
+describe('design-lint tailwind: one gradient classifier for both tiers (third review cycle)', () => {
+ test('arbitrary indigo-to-violet stops report the same purple-blue-gradient the stylesheet form does', async () => {
+ const tw = await lintFiles({ 'A.tsx': 'export const A = () => <div className="bg-gradient-to-r from-[#6366f1] to-[#8b5cf6] p-4">hello there</div>;' });
+ expect(only(tw, 'purple-blue-gradient').map((f) => [f.grade, f.evidence])).toEqual([['blocks', expect.stringContaining('indigo-to-violet')]]);
+ const css = await lintFiles({ 'a.css': '.g { background: linear-gradient(90deg, #6366f1, #8b5cf6); }' });
+ expect(only(css, 'purple-blue-gradient').map((f) => [f.grade, f.evidence])).toEqual([['blocks', expect.stringContaining('indigo-to-violet')]]);
+ });
+});
diff --git a/test/design-lint-type.test.ts b/test/design-lint-type.test.ts
new file mode 100644
index 000000000..b506db442
--- /dev/null
+++ b/test/design-lint-type.test.ts
@@ -0,0 +1,213 @@
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { formatFinding, type Finding } from '../lib/design-lint/report';
+import { lintStatic } from '../lib/design-lint/static';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+/** 1-based line of the first line holding the needle. */
+const lineOf = (text: string, needle: string, nth = 1): number => {
+ let i = -1;
+ for (let n = 0; n < nth; n++) {
+ i = text.indexOf(needle, i + 1);
+ if (i < 0) throw new Error(`needle not in page: ${needle}`);
+ }
+ return text.slice(0, i).split('\n').length;
+};
+
+const TOKENS = `:root {
+ --color-paper: oklch(97% 0.01 250);
+ --color-ink: oklch(20% 0.02 250);
+ --color-muted: oklch(45% 0.02 250);
+ --color-accent: oklch(55% 0.15 250);
+ --color-accent-ink: oklch(98% 0.01 250);
+ --font-display: "Literata", Georgia, serif;
+ --font-body: "Public Sans", sans-serif;
+}`;
+
+/** A page whose <style> holds the tokens and the css, and whose <body> holds the markup. */
+const page = (css: string, body = '<h1>Ledger</h1><p>The books close on the first.</p>', tokens = TOKENS): string =>
+ `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Ledger</title>\n<style>\n${tokens}\n${css}\n</style>\n</head>\n<body>\n${body}\n</body>\n</html>\n`;
+
+function lintPage(html: string, name = 'index.html'): { html: string; findings: Finding[]; dir: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-type-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, name);
+ fs.writeFileSync(file, html);
+ return { html, dir, findings: lintStatic([file], { cwd: dir, warn: (l) => { throw new Error(l); } }).findings };
+}
+
+const byRule = (findings: Finding[], rule: string): Finding[] => findings.filter((f) => f.rule === rule);
+const lines = (findings: Finding[]): string[] => findings.map(formatFinding);
+describe('design-lint type: overused-font (1, ask)', () => {
+ test('a chosen display face, and Inter as the body face only, are clean', () => {
+ const { findings } = lintPage(page('h1 { font-family: var(--font-display); }', undefined, TOKENS.replace('"Public Sans", sans-serif', '"Inter", sans-serif')));
+ expect(byRule(findings, 'overused-font')).toEqual([]);
+ });
+ test('Poppins as --font-display and Inter on an h2 each ask at their line, once per place', () => {
+ const { html, findings } = lintPage(page('h1 { font-family: var(--font-display); }\nh2 { font-family: "Inter", sans-serif; }\nh2.alt { font-family: "Inter", sans-serif; }', undefined, TOKENS.replace('"Literata", Georgia, serif', '"Poppins", sans-serif')));
+ expect(byRule(findings, 'overused-font').map((x) => [x.grade, x.line, x.evidence])).toEqual([
+ ['ask', lineOf(html, '--font-display:'), '"poppins" as the display face (--font-display)'],
+ ['ask', lineOf(html, 'h1 {'), '"poppins" as the display face (h1)'],
+ ['ask', lineOf(html, 'h2 {'), '"inter" as the display face (h2)'],
+ ['ask', lineOf(html, 'h2.alt {'), '"inter" as the display face (h2.alt)'],
+ ]);
+ });
+});
+
+describe('design-lint type: line-length (25, ask)', () => {
+ test('a 62ch paragraph, a 30ch lede and a 32ch class whose paragraphs are one short sentence are clean', () => {
+ const { findings } = lintPage(page('p { max-width: 62ch; }\n.lede { max-width: 30ch; }\n.copy { max-width: 32ch; }', '<p class="copy">One short sentence.</p>'));
+ expect(byRule(findings, 'line-length')).toEqual([]);
+ });
+ test('a 90ch paragraph and a 40ch prose block ask with the range in the evidence', () => {
+ const { html, findings } = lintPage(page('p { max-width: 90ch; }\n.prose { max-width: 40ch; }', '<div class="prose"><p>The first sentence runs on. The second does too. The third as well, so this is prose and not a lede.</p></div>'));
+ expect(byRule(findings, 'line-length').map((x) => [x.grade, x.line, x.evidence, x.fix])).toEqual([
+ ['ask', lineOf(html, 'p { max-width: 90ch'), 'a measure of 90ch on p (45 to 75ch reads well)', 'max-width between 45 and 75ch'],
+ ['ask', lineOf(html, '.prose {'), 'a measure of 40ch on .prose (45 to 75ch reads well)', 'max-width between 45 and 75ch'],
+ ]);
+ });
+});
+
+describe('design-lint type: font-family-count (37, ask)', () => {
+ test('three families plus generic names are clean', () => {
+ const { findings } = lintPage(page('code { font-family: "JetBrains Mono", monospace; }\n.aside { font-family: monospace; }'));
+ expect(byRule(findings, 'font-family-count')).toEqual([]);
+ });
+ test('a fourth family asks at the fourth declaration and lists them', () => {
+ const { html, findings } = lintPage(page('code { font-family: "JetBrains Mono", monospace; }\nblockquote { font-family: var(--font-quote); }', undefined, TOKENS + '\n:root { --font-quote: "Playfair Display", serif; }'));
+ expect(byRule(findings, 'font-family-count').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'code {'), '4 font families: literata, public sans, playfair display, jetbrains mono']]);
+ });
+});
+
+describe('design-lint type: italic-word-in-heading (38i, blocks) and italic-serif-display (38ii, ask)', () => {
+ test('a roman heading, and an <em> the stylesheet sets upright, are clean', () => {
+ const { findings } = lintPage(page('h2 em { font-style: normal; font-weight: 600; }', '<h2>Fast <em>and</em> safe</h2>'));
+ expect(lines([...byRule(findings, 'italic-word-in-heading'), ...byRule(findings, 'italic-serif-display')])).toEqual([]);
+ });
+ test('an <em> inside an h2 blocks at the heading line; an italic h1 asks at the font-style line', () => {
+ const { html, findings } = lintPage(page('h1 {\n font-style: italic;\n}', '<h2>Fast <em>and</em> safe</h2>'));
+ expect(byRule(findings, 'italic-word-in-heading').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(html, '<h2>Fast'), 'an <em> inside an otherwise roman <h2>']]);
+ expect(byRule(findings, 'italic-serif-display').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'font-style: italic'), 'italic display type on h1']]);
+ });
+});
+
+describe('design-lint type: accented-word (38iii, ask)', () => {
+ test('a span that repeats the head\'s own colour, or covers most of the head, is clean', () => {
+ const { findings } = lintPage(page('h1 { color: var(--color-ink); }\n.same { color: var(--color-ink); }\n.most { color: var(--color-accent); }', '<h1>Ship <span class="same">faster</span></h1><h2><span class="most">Everything the crew needs</span> now</h2>'));
+ expect(byRule(findings, 'accented-word')).toEqual([]);
+ });
+ test('a coloured child selector of a heading, and a classed span coloured apart from its h1, each ask at the rule', () => {
+ const { html, findings } = lintPage(page('h2 span { color: var(--color-accent); }\n.hi { color: var(--color-accent); }', '<h1>Ship <span class="hi">faster</span> every week</h1>'));
+ expect(byRule(findings, 'accented-word').map((x) => [x.grade, x.line, x.evidence])).toEqual([
+ ['ask', lineOf(html, 'h2 span {'), 'one word of a heading set apart (h2 span)'],
+ ['ask', lineOf(html, '.hi {'), 'one word of a heading set apart (.hi)'],
+ ]);
+ });
+});
+
+describe('design-lint type: caps-leading (55a, blocks) and caps-lockup-leading (55b, ask)', () => {
+ test('uppercase at 1.05, uppercase at 1.0 that can wrap, and uppercase small type are clean', () => {
+ const { findings } = lintPage(page('h2 { text-transform: uppercase; line-height: 1.05; }\n.display { text-transform: uppercase; line-height: 1; }\n.tag { text-transform: uppercase; line-height: 0.9; font-size: 12px; }'));
+ expect(lines([...byRule(findings, 'caps-leading'), ...byRule(findings, 'caps-lockup-leading')])).toEqual([]);
+ });
+ test('an uppercase h2 at 0.94 blocks at the line-height; a nowrap caps lockup at 1.0 asks', () => {
+ const { html, findings } = lintPage(page('h2 {\n text-transform: uppercase;\n line-height: 0.94;\n}\n.lockup {\n text-transform: uppercase;\n white-space: nowrap;\n font-size: 2rem;\n line-height: 1;\n}'));
+ expect(byRule(findings, 'caps-leading').map((x) => [x.grade, x.line, x.evidence])).toEqual([['blocks', lineOf(html, 'line-height: 0.94'), 'uppercase at line-height 0.94 on h2: the caps collide']]);
+ expect(byRule(findings, 'caps-lockup-leading').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'line-height: 1;'), 'uppercase at line-height 1 on .lockup: the caps collide']]);
+ });
+});
+
+describe('design-lint type: monospace-costume (64, ask)', () => {
+ const mono = TOKENS + '\n:root { --font-mono: "JetBrains Mono", monospace; }';
+ test('mono on a price, and mono as the body material, are clean', () => {
+ const { findings } = lintPage(page('.price { font-family: var(--font-mono); }\n.caption { font-family: var(--font-body); }', undefined, mono));
+ expect(byRule(findings, 'monospace-costume')).toEqual([]);
+ const material = lintPage(page('.caption { font-family: var(--font-mono); }', undefined, mono.replace('--font-body: "Public Sans", sans-serif', '--font-body: "Geist Mono", monospace')));
+ expect(byRule(material.findings, 'monospace-costume')).toEqual([]);
+ });
+ test('mono on a label asks at the font-family line, once per selector', () => {
+ const { html, findings } = lintPage(page('.label {\n font-family: var(--font-mono);\n}\n.label:hover { font-family: var(--font-mono); }', undefined, mono));
+ expect(byRule(findings, 'monospace-costume').map((x) => [x.grade, x.line, x.evidence])).toEqual([['ask', lineOf(html, 'font-family: var(--font-mono)'), 'monospace as the label voice on .label']]);
+ });
+});
+
+describe('design-lint type: wide-tracking (67, blocks)', () => {
+ test('an uppercase heading, a wordmark, a tracked display line and sentence-case labels are clean', () => {
+ const { findings } = lintPage(page('h2 { text-transform: uppercase; }\n.wordmark { text-transform: uppercase; letter-spacing: 0.1em; font-size: 12px; }\n.display { letter-spacing: 0.05em; font-size: 3rem; }\n.label { font-size: 13px; }', '<span class="label">Shipping weekly</span><span class="wordmark">LEDGERLINE</span>'));
+ expect(byRule(findings, 'wide-tracking')).toEqual([]);
+ });
+ test('a tracked caps eyebrow, an uppercase control and markup typed in capitals each block at their line', () => {
+ const { html, findings } = lintPage(page('.eyebrow { text-transform: uppercase; letter-spacing: 0.12em; font-size: 12px; }\n.button { text-transform: uppercase; font-size: 14px; }\n.tag { font-size: 12px; }', '<span class="tag">LIMITED TIME OFFER</span>'));
+ expect(byRule(findings, 'wide-tracking').map((x) => [x.grade, x.line, x.evidence, x.fix])).toEqual([
+ ['blocks', lineOf(html, '.eyebrow {'), '.eyebrow: uppercase tracked 0.12em at 12px in a label role', 'the body face, a step smaller, sentence case, untracked'],
+ ['blocks', lineOf(html, '.button {'), '.button: an uppercase control on a page whose display is not uppercase', 'controls follow the display voice: sentence case here, or tracking 0.04em at most where the display itself is uppercase'],
+ ['blocks', lineOf(html, '<span class="tag">'), '"LIMITED TIME OFFER" typed in capitals at 12px (<span class="tag">)', 'sentence case in the body face; capitals survive only as a wordmark or as the display voice'],
+ ]);
+ });
+ test('where the display itself is uppercase, a control tracked past 0.045em blocks and one at 0.04em does not', () => {
+ const base = 'h1 { text-transform: uppercase; }\n';
+ const tight = lintPage(page(base + '.button { text-transform: uppercase; letter-spacing: 0.04em; font-size: 14px; }'));
+ expect(byRule(tight.findings, 'wide-tracking')).toEqual([]);
+ const loose = lintPage(page(base + '.button { text-transform: uppercase; letter-spacing: 0.08em; font-size: 14px; }'));
+ expect(byRule(loose.findings, 'wide-tracking').map((x) => x.evidence)).toEqual(['.button: an uppercase control tracked 0.08em']);
+ });
+});
+
+describe('design-lint type: fixtures', () => {
+ const MINE = new Set(['overused-font', 'line-length', 'font-family-count', 'italic-word-in-heading', 'italic-serif-display', 'accented-word', 'caps-leading', 'caps-lockup-leading', 'monospace-costume', 'wide-tracking']);
+ test('the clean page and the eyebrow carve-outs have no type finding', () => {
+ for (const dir of ['clean', 'eyebrow-pass']) {
+ const { findings } = lintStatic([path.join(FIXTURES, dir)], { cwd: ROOT });
+ expect(lines(findings.filter((f) => MINE.has(f.rule)))).toEqual([]);
+ }
+ });
+ test('slopped.html: the caps h2 blocks; Poppins, the fourth family, the italic h2 and the mono label ask', () => {
+ const file = path.join(FIXTURES, 'slopped.html');
+ const html = fs.readFileSync(file, 'utf8');
+ const { findings } = lintStatic([file], { cwd: ROOT });
+ expect(findings.filter((f) => MINE.has(f.rule)).map((f) => [f.rule, f.grade, f.line]).sort()).toEqual([
+ ['caps-leading', 'blocks', lineOf(html, 'line-height: 0.94')],
+ ['font-family-count', 'ask', lineOf(html, '--font-quote:')],
+ ['italic-serif-display', 'ask', lineOf(html, 'font-style: italic')],
+ ['monospace-costume', 'ask', lineOf(html, '.mono-label {')],
+ ['overused-font', 'ask', lineOf(html, '--font-display:')],
+ ['overused-font', 'ask', lineOf(html, 'font-family: var(--font-display);')],
+ ['overused-font', 'ask', lineOf(html, 'font-family: var(--font-display);', 2)],
+ ].sort());
+ });
+ test('eyebrow-fail: the four tracked caps labels block and the mono eyebrow asks', () => {
+ const file = path.join(FIXTURES, 'eyebrow-fail', 'index.html');
+ const html = fs.readFileSync(file, 'utf8');
+ const { findings } = lintStatic([file], { cwd: ROOT });
+ expect(byRule(findings, 'wide-tracking').map((f) => [f.grade, f.line])).toEqual(['.a__eyebrow {', '.b__strand {', '.e__mark {', '.overline {'].map((s) => ['blocks', lineOf(html, s)]));
+ expect(byRule(findings, 'monospace-costume').map((f) => [f.grade, f.line])).toEqual([['ask', lineOf(html, '.a__eyebrow {')]]);
+ });
+});
+
+describe('design-lint type: third review cycle', () => {
+ test('banned-font: a banned face as the first family on a heading or in a --font-* token asks once; a fallback position, a var() and a near name are clean', () => {
+ const { html, findings } = lintPage(page('h1 { font-family: "Comic Sans MS", cursive; }\nh2 { font-family: Impact, sans-serif; }\n.quote { font-family: var(--font-body); }\n.note { font-family: "Papyrus Variable Text", serif; }\n.last { font-family: Georgia, Papyrus, serif; }', '<h1>Ledger</h1><h2>Notes</h2><p class="quote">Q</p><p class="note">N</p><p class="last">L</p>', TOKENS.replace('--font-body: "Public Sans", sans-serif;', '--font-body: Papyrus, serif;')));
+ const hits = byRule(findings, 'banned-font').map((f) => [f.grade, f.line, f.evidence]);
+ expect(hits).toEqual([
+ ['ask', lineOf(html, '--font-body: Papyrus'), '"papyrus" (--font-body)'],
+ ['ask', lineOf(html, '"Comic Sans MS"'), '"comic sans ms" (h1)'],
+ ['ask', lineOf(html, 'Impact'), '"impact" (h2)'],
+ ['ask', lineOf(html, '"Papyrus Variable Text"'), '"papyrus variable text" (.note)'],
+ ]);
+ });
+ test('an empty <i> icon glyph in a heading, and an <em> that is the whole heading, are not an italic word', () => {
+ const icon = lintPage(page('', '<h2><i class="fa fa-star" aria-hidden="true"></i> Features</h2>'));
+ expect(lines(byRule(icon.findings, 'italic-word-in-heading'))).toEqual([]);
+ const whole = lintPage(page('', '<h3><em>Whole heading italic</em></h3>'));
+ expect(lines(byRule(whole.findings, 'italic-word-in-heading'))).toEqual([]);
+ const word = lintPage(page('', '<h2>Fast <em>and</em> safe</h2>'));
+ expect(byRule(word.findings, 'italic-word-in-heading').map((f) => f.grade)).toEqual(['blocks']);
+ });
+});
diff --git a/test/design-lint.test.ts b/test/design-lint.test.ts
new file mode 100644
index 000000000..d53e730cb
--- /dev/null
+++ b/test/design-lint.test.ts
@@ -0,0 +1,645 @@
+/**
+ * The design lint's core contract: parsers, the rule table, the output lines,
+ * exit codes and waivers. Rule families have their own files
+ * (test/design-lint-<family>.test.ts); the render tier is
+ * test/design-lint-render.test.ts.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { buildStyleIndex, buildTokens, parseCss, pxOf, resolveVars, stylesFor, type StyleIndex } from '../lib/design-lint/css';
+import { contrastRatio, parseColor, srgbToOklch } from '../lib/design-lint/color';
+import { ancestorsOf, directChildren, getAttr, innerOf, jsxPseudo, parseDoc, plainText, treeOf } from '../lib/design-lint/html';
+import { lint, formatResult } from '../lib/design-lint/index';
+import { Reporter, exitCodeOf, finalize, formatFinding, formatSummary, summarize } from '../lib/design-lint/report';
+import { collectFiles, contextWaivers, lintStatic, MAX_FILE_BYTES } from '../lib/design-lint/static';
+import type { LintContext } from '../lib/design-lint/context';
+import { browserAvailable } from './helpers/browser-available';
+import { RULES } from '../lib/design-lint/rules/ids';
+import { FAMILIES } from '../lib/design-lint/rules';
+import { findWaivers, reasonIsBoilerplate, resolveWaivers, applyWaivers, suspectedRules } from '../lib/design-lint/waivers';
+
+const tmpDirs: string[] = [];
+afterAll(() => { for (const d of tmpDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const BIN = path.join(ROOT, 'bin', 'gstack-design-lint');
+const FIXTURES = path.join(ROOT, 'test', 'fixtures', 'design-lint');
+
+function runBin(args: string[], cwd = ROOT) {
+ const r = Bun.spawnSync([BIN, ...args], { cwd, stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });
+ return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() };
+}
+
+function tmpPage(html: string, name = 'index.html'): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-'));
+ tmpDirs.push(dir);
+ const file = path.join(dir, name);
+ fs.writeFileSync(file, html);
+ return file;
+}
+
+/** A temporary tree: each key is a relative path (parent directories are created), each value the file's text. */
+function tmpTree(files: Record<string, string>): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-lint-tree-'));
+ tmpDirs.push(dir);
+ for (const [rel, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
+ fs.writeFileSync(path.join(dir, rel), text);
+ }
+ return dir;
+}
+
+describe('design-lint: CSS reading', () => {
+ test('nested rules, media blocks and keyframes flatten with line numbers; tokens resolve through var() with fallbacks', () => {
+ const css = `:root { --color-ink: oklch(20% 0.02 250); --space-4: 1rem; }
+.card {
+ padding: var(--space-4);
+ &:hover { color: var(--color-ink); }
+ @media (min-width: 60em) { padding: 2rem; }
+}
+@keyframes rise { from { opacity: 0 } to { opacity: 1 } }`;
+ const rules = parseCss(css, 'a.css');
+ const sel = (s: string) => rules.filter((r) => r.selector === s);
+ expect(sel('.card')[0].decls).toEqual([{ prop: 'padding', value: 'var(--space-4)', line: 3 }]);
+ expect(sel('.card:hover')[0].decls[0]).toEqual({ prop: 'color', value: 'var(--color-ink)', line: 4 });
+ expect(sel('.card').find((r) => r.media === '(min-width: 60em)')?.decls[0].value).toBe('2rem');
+ expect(rules.filter((r) => r.keyframes === 'rise')).toHaveLength(2);
+ const tokens = buildTokens(rules);
+ expect(tokens['--space-4']).toBe('1rem');
+ expect(resolveVars('var(--space-4) var(--missing, 8px)', tokens)).toBe('1rem 8px');
+ expect(pxOf('1.5rem')).toBe(24);
+ expect(pxOf('50%')).toBeNull();
+ });
+});
+
+describe('design-lint: colour', () => {
+ test('hex, rgb, hsl and oklch parse; contrast and OKLCH round-trip hold', () => {
+ expect(parseColor('#fff')).toEqual({ r: 1, g: 1, b: 1, alpha: 1 });
+ expect(parseColor('rgb(0 0 0 / 50%)')?.alpha).toBe(0.5);
+ expect(parseColor('hsl(0 100% 50%)')?.r).toBeCloseTo(1, 5);
+ const ok = parseColor('oklch(50% 0.1 250)')!;
+ expect(ok.okl).toEqual({ L: 0.5, C: 0.1, H: 250 });
+ const back = srgbToOklch(ok);
+ expect(back.L).toBeCloseTo(0.5, 1);
+ expect(back.H).toBeCloseTo(250, 0);
+ expect(contrastRatio(parseColor('black')!, parseColor('white')!)).toBeCloseTo(21, 1);
+ expect(parseColor('var(--x)')).toBeNull();
+ });
+});
+
+describe('design-lint: markup reading', () => {
+ test('tags keep positions and lines; styles and scripts are lifted; component files become pseudo-HTML with their class strings', () => {
+ const doc = parseDoc('p.html', '<html><head><style>h1{color:red}</style></head>\n<body>\n<h1 class="t">Hi &amp; bye</h1><img src="a.png" alt="">\n<script>alert(1)</script></body></html>');
+ expect(doc.tags.find((t) => t.name === 'h1')?.line).toBe(3);
+ expect(doc.styles[0].css).toBe('h1{color:red}');
+ expect(doc.scripts.trim()).toBe('alert(1)');
+ expect(doc.text).toContain('Hi & bye');
+ expect(getAttr(doc.tags.find((t) => t.name === 'img')!.attrs, 'alt')).toBe('');
+ expect(plainText('<p>A &middot; B &rarr;</p>')).toBe('A · B →');
+ const tsx = parseDoc('Hero.tsx', 'export const Hero = () => (<section className={cn("bg-indigo-500", open && "p-4")}><h1 className="text-4xl">Hi</h1></section>);');
+ expect(tsx.kind).toBe('jsx');
+ expect(tsx.tags.map((t) => t.name).filter((n) => n === 'section' || n === 'h1')).toEqual(['section', 'h1', 'h1', 'section']);
+ expect(tsx.classAt.get(tsx.tags.find((t) => t.name === 'section')!.pos)).toEqual(['bg-indigo-500', 'p-4']);
+ });
+});
+
+describe('design-lint: the rule table', () => {
+ test('every id is kebab-case with a tier, a source gate, a title and a fix; docs/design-lint.md names each one', () => {
+ const docs = fs.readFileSync(path.join(ROOT, 'docs', 'design-lint.md'), 'utf8');
+ for (const [id, m] of Object.entries(RULES)) {
+ expect(id).toMatch(/^[a-z][a-z0-9-]*$/);
+ expect(['blocks', 'ask', 'polish']).toContain(m.tier);
+ expect(m.gate.length).toBeGreaterThan(0);
+ expect(m.title.length).toBeGreaterThan(8);
+ expect(m.fix.length).toBeGreaterThan(3);
+ expect(docs).toContain('`' + id + '`');
+ }
+ expect(Object.keys(RULES).length).toBeGreaterThan(100);
+ expect(FAMILIES.map((f) => f.name)).toEqual(['color', 'type', 'structure', 'chrome', 'motion', 'assets', 'finish', 'component', 'copy']);
+ });
+
+ test('the three house rules gstack keeps at ask stay at ask, and the Floor rules the plan names block', () => {
+ expect(RULES['kicker-above-heading'].tier).toBe('ask');
+ expect(RULES['screen-word-budget'].tier).toBe('ask');
+ expect(RULES['em-dash-overuse'].tier).toBe('ask');
+ expect(RULES['overflow-x-unclipped'].tier).toBe('ask');
+ for (const id of ['purple-blue-gradient', 'nested-cards', 'wide-tracking', 'template-punctuation', 'missing-focus-visible', 'low-contrast', 'content-hidden-at-rest', 'hero-fold']) expect(RULES[id].tier).toBe('blocks');
+ });
+});
+
+describe('design-lint: the output contract', () => {
+ test('a finding prints as LINT: <grade> <rule> <file>:<line> <evidence> | fix: <fix>; a suspected blocking tell lands at ask; unknown ids throw', () => {
+ const r = new Reporter('page', '/cwd');
+ r.report('nested-cards', '/cwd/site/index.html', 12, 'div.card > div.card', {});
+ r.report('invented-proof', '/cwd/site/index.html', 30, '"Trusted by 500+ teams"', { suspected: true });
+ r.report('section-gap', '/cwd/site/index.html', 1, 'x');
+ expect(formatFinding(r.findings[0])).toBe('LINT: blocks nested-cards site/index.html:12 div.card > div.card | fix: one containment layer');
+ expect(r.findings[1].tier).toBe('ask');
+ expect(() => r.report('no-such-rule', 'f', 1, 'x')).toThrow(/unknown rule id/);
+ const component = new Reporter('component', '/cwd');
+ component.report('section-gap', '/cwd/a.tsx', 1, 'page-only rule under component scope');
+ expect(component.findings).toEqual([]);
+ });
+
+ test('blocks exit 2, an unanswered ask exits 1, polish alone exits 0; waived is counted apart from ask and never summed into blocks', () => {
+ const base = { file: 'a.html', line: 1, evidence: 'e', fix: 'f', source: 'static' as const };
+ const blocks = { rule: 'nested-cards', tier: 'blocks' as const, grade: 'blocks' as const, ...base };
+ const ask = { rule: 'section-gap', tier: 'ask' as const, grade: 'ask' as const, ...base };
+ const waived = { ...ask, grade: 'waived' as const, waiver: 'because the ledger separates rows with rules' };
+ const polish = { rule: 'straight-quotes', tier: 'polish' as const, grade: 'polish' as const, ...base };
+ expect(exitCodeOf(summarize([blocks, ask, polish], 'skipped: x'))).toBe(2);
+ expect(exitCodeOf(summarize([ask, polish], 'ran'))).toBe(1);
+ expect(exitCodeOf(summarize([polish, waived], 'ran'))).toBe(0);
+ expect(formatSummary(summarize([blocks, waived, waived, polish], 'ran'))).toBe('LINT_SUMMARY: blocks=1 ask=0 waived=2 polish=1 render=ran');
+ expect(finalize([polish, ask, blocks, blocks]).map((f) => f.grade)).toEqual(['blocks', 'ask', 'polish']);
+ expect(formatFinding(waived)).toContain('| fix: waived (because the ledger');
+ });
+
+ test('the bin prints the contract and exits by it; --rules lists the table; a usage error exits 3', () => {
+ const slopped = runBin(['test/fixtures/design-lint/slopped.html']);
+ expect(slopped.code).toBe(2);
+ const lines = slopped.out.trim().split('\n');
+ for (const l of lines.slice(0, -1)) expect(l).toMatch(/^LINT: (blocks|ask|polish|waived) [a-z][a-z0-9-]* \S+:\d+ .+ \| fix: .+$/);
+ expect(lines.at(-1)).toMatch(/^LINT_SUMMARY: blocks=\d+ ask=\d+ waived=\d+ polish=\d+ render=skipped: not requested$/);
+ expect(runBin(['--rules']).out).toContain('nested-cards');
+ expect(runBin([]).code).toBe(3);
+ expect(runBin(['--scope', 'app', 'x.html']).code).toBe(3);
+ const json = JSON.parse(runBin(['--json', 'test/fixtures/design-lint/slopped.html']).out);
+ expect(json.summary.blocks).toBeGreaterThan(0);
+ expect(Array.isArray(json.findings)).toBe(true);
+ });
+
+ test('a clean page passes: exit 0 and LINT_SUMMARY blocks=0 ask=0', async () => {
+ const file = tmpPage(fs.readFileSync(path.join(FIXTURES, 'clean', 'index.html'), 'utf8'));
+ const result = await lint([file], { cwd: path.dirname(file) });
+ const unexpected = result.findings.filter((f) => f.grade === 'blocks' || f.grade === 'ask');
+ expect(unexpected.map(formatFinding)).toEqual([]);
+ expect(result.exitCode).toBe(0);
+ expect(formatResult(result)).toContain('LINT_SUMMARY: blocks=0 ask=0');
+ });
+
+ // Value: protects=every usage exit (3) the bin promises and --help's 0; fails_when=a flag check is dropped or a usage error falls through to lint() and exits 0; why_new=the bin test only covers no-args and --scope; seam=none; no_claim=stderr wording beyond the key phrase
+ test('the bin exits 3 for a non-http --url, an unknown flag, a flag without its value, a path it cannot read and a tree with nothing to lint; --help exits 0', () => {
+ const url = runBin(['--url', 'ftp://example.test/page']);
+ expect([url.code, url.err]).toEqual([3, expect.stringContaining('http or https')]);
+ const flag = runBin(['--bogus', 'x.html']);
+ expect([flag.code, flag.err]).toEqual([3, expect.stringContaining('unknown flag --bogus')]);
+ const value = runBin(['x.html', '--job']);
+ expect([value.code, value.err]).toEqual([3, expect.stringContaining('--job needs a value')]);
+ const missing = runBin(['/nowhere/design-lint/none.html']);
+ expect([missing.code, missing.err]).toEqual([3, expect.stringContaining('cannot read /nowhere/design-lint/none.html')]);
+ expect(missing.err).toContain('no .html, .css, .jsx, .tsx, .vue, .svelte or .astro files found');
+ const nothing = runBin([tmpTree({ 'notes.txt': 'not a page', 'data.json': '{}' })]);
+ expect([nothing.code, nothing.out]).toEqual([3, '']);
+ const help = runBin(['--help']);
+ expect([help.code, help.out.trim(), help.err]).toEqual([0, expect.stringMatching(/^usage: gstack-design-lint </), '']);
+ });
+
+ // Value: protects=lint() wires --render/--url to the render tier: only HTML pages render, a URL is a target of its own; fails_when=render is requested but never reaches lintRender, or a URL target is dropped; why_new=lintRender is tested alone, the glue in lint() and the bin is not; seam=none; no_claim=the no-browser summary wording beyond its prefix
+ test('render requested on a tree without a page says so in the summary; --url with no file is a render target of its own', async () => {
+ const cssOnly = tmpTree({ 'tokens.css': ':root { --color-ink: oklch(22% 0.03 250); }', 'Hero.tsx': 'export const Hero = () => <h1 className="text-xl">Ledger</h1>;' });
+ const result = await lint([cssOnly], { cwd: cssOnly, render: true, warn: () => {} });
+ expect(result.files.map((f) => path.basename(f))).toEqual(['Hero.tsx', 'tokens.css']);
+ expect(result.summary.render).toBe('skipped: no HTML page to render');
+ expect(formatResult(result)).toMatch(/render=skipped: no HTML page to render$/);
+ const nothing = await lint([cssOnly], { cwd: cssOnly, warn: () => {} });
+ expect(nothing.summary.render).toBe('skipped: not requested');
+
+ const r = runBin(['--url', 'http://127.0.0.1:9/']);
+ if (browserAvailable()) {
+ expect(r.code).toBe(2);
+ expect(r.out).toMatch(/^LINT: blocks render http:\/\/127\.0\.0\.1:9\/:1 could not reach http:\/\/127\.0\.0\.1:9\/: .+ \| fix: .+$/m);
+ expect(r.out).toMatch(/^LINT_SUMMARY: blocks=1 ask=0 waived=0 polish=0 render=ran$/m);
+ } else {
+ expect(r.code).toBe(0);
+ expect(r.out).toMatch(/^LINT_SUMMARY: blocks=0 ask=0 waived=0 polish=0 render=skipped: /m);
+ }
+ });
+});
+
+describe('design-lint: the static tier\'s files and contexts', () => {
+ // Value: protects=which files the walk reads and which stylesheet may carry a page's waiver; fails_when=vendored or built CSS is linted, or a linked stylesheet from elsewhere waives a page's finding; why_new=no test walks a tree with node_modules, dot or build directories, or a waiver in CSS; seam=none; no_claim=ordering inside one directory beyond sorted names
+ test('the walk skips node_modules, dot folders and build output below the top, warns on an unreadable path; a waiver in any stylesheet the page reads answers for that stylesheet', () => {
+ const dir = tmpTree({
+ 'site/index.html': '<!doctype html><html lang="en"><head><title>Ledger</title><link rel="stylesheet" href="local.css"><link rel="stylesheet" href="../shared/theme.css"></head><body><main><h1>The ledger</h1><p>The ledger separates its rows with hairline rules.</p></main></body></html>',
+ 'site/local.css': '/* gstack-lint-disable section-gap: the ledger separates its rows with rules */\n.row { border-top: 1px solid var(--color-line); }',
+ 'shared/theme.css': '/* gstack-lint-disable template-nav: the ledger keeps three links for its three modes */\n:root { --color-line: oklch(85% 0.015 80); }',
+ 'site/node_modules/lib/vendor.css': '.v { color: #123456; }',
+ 'site/.cache/stale.html': '<h1>stale</h1>',
+ 'site/dist/built.css': '.b { color: #654321; }',
+ 'dist/top.css': '.t { color: var(--color-line); }',
+ });
+ const warned: string[] = [];
+ const files = collectFiles([path.join(dir, 'site'), path.join(dir, 'dist'), path.join(dir, 'site', 'index.html'), path.join(dir, 'gone')], (l) => warned.push(l));
+ expect(files.map((f) => path.relative(dir, f))).toEqual(['site/index.html', 'site/local.css', 'dist/top.css']);
+ expect(warned).toEqual([`design-lint: cannot read ${path.join(dir, 'gone')}`]);
+
+ const { contexts } = lintStatic([path.join(dir, 'site')], { cwd: dir, warn: (l) => { throw new Error(l); } });
+ expect(contexts).toHaveLength(1);
+ expect(contexts[0].cssFiles.map((c) => path.relative(dir, c.file))).toEqual(['site/local.css', 'shared/theme.css']);
+ const set = contextWaivers(contexts[0], dir);
+ expect([...set.accepted.entries()]).toEqual([['section-gap@site/local.css', 'the ledger separates its rows with rules'], ['template-nav@shared/theme.css', 'the ledger keeps three links for its three modes']]);
+ expect(set.refused).toEqual([]);
+ });
+
+ // Value: protects=two pages in one directory each own only the stylesheets they link; fails_when=grouping hands every stylesheet to every page, so one page's waiver answers the other's finding and the finding prints twice; why_new=every fixture directory holds one page; seam=none; no_claim=which page a stylesheet linked by neither belongs to
+ test('two pages in one directory: a finding in one page\'s stylesheet is reported once and is not waived by the other page', () => {
+ const dir = tmpTree({
+ 'a.html': '<!doctype html><html lang="en"><head><title>Ledger</title><link rel="stylesheet" href="a.css"></head><body><main><h1>The ledger</h1><p>The ledger closes the month on the first day.</p></main></body></html>',
+ 'a.css': ':root { --color-gray: oklch(55% 0 0); --color-ink: oklch(22% 0.03 250); }\n.rule { border-color: var(--color-gray); }',
+ 'b.html': '<!-- gstack-lint-disable zero-chroma-neutrals: the archive keeps its grey plates grey -->\n<!doctype html><html lang="en"><head><title>Archive</title><link rel="stylesheet" href="b.css"></head><body><main><h1>The archive</h1><p>The archive keeps its grey plates on the shelf.</p></main></body></html>',
+ 'b.css': ':root { --color-ink: oklch(22% 0.03 250); }\n.shelf { color: var(--color-ink); }',
+ });
+ const result = lintStatic([dir], { cwd: dir, warn: (l) => { throw new Error(l); } });
+ expect(result.contexts.map((c) => [path.basename(c.key), c.cssFiles.map((f) => path.basename(f.file))])).toEqual([['a.html', ['a.css']], ['b.html', ['b.css']]]);
+ const grey = finalize(result.findings).filter((f) => f.rule === 'zero-chroma-neutrals');
+ expect(grey.map((f) => [f.grade, f.file, f.line])).toEqual([['ask', 'a.css', 1]]);
+ expect(result.findings.filter((f) => f.rule === 'waiver')).toEqual([]);
+ });
+});
+
+describe('design-lint: the copy tier', () => {
+ // Value: protects=design-craft tells reach the lint as findings at line 1 with their count, source copy, under the craft ids; fails_when=the craft bridge drops ids, loses the count suffix, or re-reports the static tier's 100vh and transition: all tells; why_new=no test asserts a single copy-tier finding (the fixtures only check line format); seam=none; no_claim=the craft patterns themselves, which lib/design-craft owns
+ test('lorem, missing alt and alert() report with their counts at line 1 as copy findings; 100vh and transition: all stay with the static tier; a component file gets none', () => {
+ const dir = tmpTree({
+ 'index.html': '<!doctype html>\n<html lang="en">\n<head><title>Ledger</title><meta name="description" content="The ledger closes the month."><link rel="icon" href="/icon.svg"><style>.hero { min-height: 100vh; transition: all 0.2s; }</style></head>\n<body><a class="skip" href="#main">Skip to content</a><main id="main"><h1>Lorem ipsum dolor</h1><img src="a.png"><img src="b.png"><p>Lorem ipsum again on the ledger.</p></main>\n<script>alert("saved")</script></body></html>',
+ 'Card.tsx': 'export const Card = () => <article className="p-4"><p>Lorem ipsum in a component</p><img src="c.png" /></article>;',
+ });
+ const { findings } = lintStatic([dir], { cwd: dir, warn: (l) => { throw new Error(l); } });
+ const copy = findings.filter((f) => f.source === 'copy');
+ expect(copy.map((f) => [f.grade, f.rule, f.file, f.line, f.evidence])).toEqual([
+ ['blocks', 'lorem', 'index.html', 1, 'lorem ipsum placeholder text, 2 times'],
+ ['ask', 'alert', 'index.html', 1, 'alert() for a message'],
+ ['blocks', 'img-no-alt', 'index.html', 1, 'an <img> without alt, 2 times'],
+ ]);
+ expect(copy.find((f) => f.rule === 'img-no-alt')?.fix).toBe('add alt text (alt="" when decorative)');
+ expect(findings.filter((f) => f.rule === 'vh-height').map((f) => [f.source, f.grade])).toEqual([['static', 'blocks']]);
+ expect(findings.filter((f) => f.rule === 'layout-transition').map((f) => f.source)).toEqual(['static']);
+ expect(findings.some((f) => f.file === 'Card.tsx' && f.source === 'copy')).toBe(false);
+ });
+});
+
+describe('design-lint: waivers', () => {
+ const page = 'The manifesto sets long declarative lines on black paper for the ledger.';
+ const claim = (rule: string, reason: string) => ({ rule, reason, file: 'a.html', line: 3 });
+
+ test('an ask or polish rule is waived with the rule id and a reason about the page; the Floor is refused', () => {
+ const set = resolveWaivers([claim('line-length', 'the manifesto sets long declarative lines'), claim('nested-cards', 'the manifesto nests its ledger on purpose for the paper')], page);
+ expect([...set.accepted.keys()]).toEqual(['line-length']);
+ expect(set.refused.map((f) => f.evidence)).toEqual(['waiver on nested-cards refused: it blocks; the Floor is never waivable']);
+ const findings = applyWaivers([
+ { rule: 'line-length', tier: 'ask', grade: 'ask', file: 'a.html', line: 9, evidence: 'e', fix: 'f', source: 'static' },
+ { rule: 'nested-cards', tier: 'blocks', grade: 'blocks', file: 'a.html', line: 9, evidence: 'e', fix: 'f', source: 'static' },
+ ], set);
+ expect(findings.map((f) => [f.rule, f.grade])).toEqual([['line-length', 'waived'], ['nested-cards', 'blocks'], ['waiver', 'ask']]);
+ });
+
+ test('short, boilerplate, reused, self-vouching and duplicate reasons are refused, each naming why', () => {
+ const set = resolveWaivers([
+ claim('line-length', 'looks better this way'),
+ claim('section-gap', 'intentional design choice by design'),
+ claim('template-nav', 'the manifesto sets long declarative lines'),
+ claim('template-footer', 'the manifesto sets long declarative lines'),
+ claim('overused-font', 'quartz pelican umbrella semaphore'),
+ claim('gradient-text', 'the ledger separates its rows with rules'),
+ claim('gradient-text', 'the ledger separates its rows with hairline rules'),
+ claim('not-a-rule', 'the manifesto sets long declarative lines'),
+ ], page);
+ expect([...set.accepted.keys()]).toEqual(['gradient-text']);
+ expect(set.refused.map((f) => f.evidence.replace(/^waiver on \S+ refused: /, ''))).toEqual([
+ 'reason under 24 characters', 'boilerplate reason', 'reason reused on another waiver', 'reason reused on another waiver',
+ 'reason shares no word with the page', 'one waiver per rule', 'no such rule',
+ ]);
+ expect(reasonIsBoilerplate('deliberately, it works')).toBe(true);
+ expect(reasonIsBoilerplate('the ledger separates its rows with rules')).toBe(false);
+ });
+
+ test('both comment forms are read, including impeccable-disable, from HTML, CSS and component sources', () => {
+ const claims = findWaivers('a.html', '<!-- gstack-lint-disable section-gap: the ledger separates its rows with rules -->\n<style>/* impeccable-disable line-length: the manifesto sets long lines */</style>\n// gstack-lint-disable template-nav: three links are the three modes');
+ expect(claims.map((c) => [c.rule, c.line, c.reason])).toEqual([
+ ['section-gap', 1, 'the ledger separates its rows with rules'],
+ ['line-length', 2, 'the manifesto sets long lines'],
+ ['template-nav', 3, 'three links are the three modes'],
+ ]);
+ });
+
+ test('the waiver fixture: five honoured (a house-style polish note), two refused (Floor, short reason), nothing blocks', async () => {
+ const result = await lint([path.join(FIXTURES, 'waiver')], { cwd: ROOT });
+ expect(result.summary.blocks).toBe(0);
+ const refused = result.findings.filter((f) => f.rule === 'waiver').map((f) => f.evidence);
+ expect(refused).toEqual([
+ 'waiver on low-contrast refused: it blocks; the Floor is never waivable',
+ 'waiver on template-footer refused: reason under 24 characters',
+ ]);
+ expect(result.findings.filter((f) => f.rule === 'house-style')).toHaveLength(1);
+ expect(result.findings.some((f) => f.rule === 'low-contrast' && f.grade === 'waived')).toBe(false);
+ });
+});
+
+describe('design-lint: third review cycle', () => {
+ test('two waiver comments on one line are both read, and a stylesheet claim answers only for that stylesheet', () => {
+ const claims = findWaivers('a.html', '<!-- gstack-lint-disable section-gap: the ledger separates rows --> <!-- gstack-lint-disable line-length: the manifesto sets long lines -->\n/* impeccable-disable overused-font: the masthead face is the paper */ .x{}');
+ expect(claims.map((c) => [c.rule, c.reason])).toEqual([['section-gap', 'the ledger separates rows'], ['line-length', 'the manifesto sets long lines'], ['overused-font', 'the masthead face is the paper']]);
+ const dir = tmpTree({
+ 'index.html': '<!doctype html><html lang="en"><head><title>Ledger</title><link rel="stylesheet" href="t.css"><style>.row { border-color: oklch(55% 0 0); }</style></head><body><main><h1>The ledger</h1><p>The ledger closes the month.</p></main></body></html>',
+ 't.css': '/* gstack-lint-disable zero-chroma-neutrals: quartz pelican umbrella semaphore xylophone */\n:root { --color-ink: oklch(22% 0.03 250); --color-gray: oklch(55% 0 0); }\n.cell { color: var(--color-gray); }',
+ });
+ const f = finalize(lintStatic([dir], { cwd: dir, warn: () => {} }).findings);
+ expect(f.filter((x) => x.rule === 'waiver')).toEqual([]);
+ expect(f.filter((x) => x.rule === 'zero-chroma-neutrals').map((x) => [x.file, x.grade]).sort()).toEqual([['index.html', 'ask'], ['t.css', 'waived']]);
+ });
+
+ test('the indexed stylesFor answers exactly as the linear scan', () => {
+ const rules = parseCss('a{color:red}\n.x{margin:0}\n.x.y{padding:1px}\na.x:hover{color:blue}\n@media (max-width:600px){.x{top:0}}\nbutton.y{gap:2px}\n.y a{left:0}\ndiv{right:0}', 'a.css');
+ const idx = buildStyleIndex(rules);
+ const plain = [...idx] as StyleIndex;
+ let compared = 0;
+ for (const cls of ['', 'x', 'y', 'x y', 'z']) for (const tag of ['a', 'button', 'div', 'span']) for (const resting of [false, true]) {
+ expect(stylesFor(idx, cls, tag, resting)).toEqual(stylesFor(plain, cls, tag, resting));
+ compared++;
+ }
+ expect(compared).toBe(40);
+ expect(stylesFor(idx, 'x y', 'a', false).map((d) => d.prop + ':' + d.value)).toContain('padding:1px');
+ expect(stylesFor(idx, 'x', 'div', true).map((d) => d.prop + ':' + d.value)).toEqual(['margin:0', 'right:0']);
+ });
+
+ test('the bin forwards --job (case-folded) and --scope to the lint', () => {
+ const html = '<!doctype html><html lang="en"><head><title>t</title><style>:root{--color-ink:#222}</style></head><body><main><h1>Letters</h1><p>A monthly letter about the harbour.</p><section><form><input type="email" name="email"><button>Join</button></form></section></main></body></html>';
+ const file = tmpPage(html);
+ const plain = runBin([file], path.dirname(file));
+ expect(plain.out).toMatch(/^LINT: ask email-band-close index\.html:\d+ .*no job was named/m);
+ const subscribe = runBin(['--job', 'Subscribe', file], path.dirname(file));
+ expect(subscribe.out).not.toContain('email-band-close');
+ const component = runBin(['--scope', 'component', file], path.dirname(file));
+ expect(component.out).not.toContain('email-band-close');
+ expect(component.out).not.toMatch(/^LINT: \w+ (missing-skip-link|template-nav|section-gap) /m);
+ });
+
+ test('a comma-heavy nested selector and a long unclosed list each lint in linear time', async () => {
+ let t = performance.now();
+ parseCss('a{' + ','.repeat(80000) + '{color:red}}', 'x.css');
+ expect(performance.now() - t).toBeLessThan(3000);
+ const dir = tmpTree({ 'index.html': '<!doctype html><html lang="en"><head><title>t</title></head><body><ul>' + '<li>item text here'.repeat(8000) + '</ul></body></html>' });
+ t = performance.now();
+ await lint([dir], { warn: () => {} });
+ expect(performance.now() - t).toBeLessThan(8000);
+ });
+
+ test('a file over the size limit is skipped with a warning and a symlink cycle is walked once', () => {
+ const dir = tmpTree({ 'site/index.html': '<!doctype html><title>t</title>', 'site/big.css': 'a{}' });
+ fs.truncateSync(path.join(dir, 'site', 'big.css'), MAX_FILE_BYTES + 1);
+ fs.symlinkSync(path.join(dir, 'site'), path.join(dir, 'site', 'loop'));
+ const warned: string[] = [];
+ const files = collectFiles([dir], (l) => warned.push(l));
+ expect(files.map((f) => path.relative(dir, f))).toEqual(['site/index.html']);
+ expect(warned).toEqual([`design-lint: skipped ${path.join(dir, 'site', 'big.css')} (2 MB, over the 2 MB limit)`]);
+ });
+
+ test('every id gstack-design-craft can emit has a lint rule or belongs to the static tier', () => {
+ const src = fs.readFileSync(path.join(ROOT, 'lib', 'design-craft.ts'), 'utf8');
+ const ids = [...new Set([...src.matchAll(/id: '([a-z-]+)'/g)].map((m) => m[1]))];
+ expect(ids.length).toBeGreaterThan(15);
+ expect(ids.filter((id) => !(id in RULES) && id !== 'transition-all')).toEqual([]);
+ expect(ids.filter((id) => id in RULES && RULES[id].gate !== 'craft')).toEqual(['vh-height']);
+ });
+});
+
+describe('design-lint: hardening (ship review)', () => {
+ test('a stylesheet one page links from another directory is linted once, with that page, and its waiver is weighed against the page', () => {
+ const dir = tmpTree({
+ 'site/pages/index.html': '<!doctype html><html lang="en"><head><title>Ledger</title><link rel="stylesheet" href="../css/theme.css"></head><body><main><h1>The ledger</h1><p>The ledger keeps its grey rows grey on purpose.</p></main></body></html>',
+ 'site/css/theme.css': '/* gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey */\n:root { --color-ink: oklch(22% 0.03 250); --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }',
+ });
+ const whole = lintStatic([path.join(dir, 'site')], { cwd: dir, warn: () => {} });
+ const pagesOnly = lintStatic([path.join(dir, 'site', 'pages')], { cwd: dir, warn: () => {} });
+ expect(whole.contexts.filter((c) => c.cssFiles.some((f) => f.file.endsWith('theme.css')))).toHaveLength(1);
+ expect(whole.findings.filter((f) => f.rule === 'waiver')).toEqual([]);
+ expect(whole.findings.map((f) => [f.rule, f.grade, f.file]).sort()).toEqual(pagesOnly.findings.map((f) => [f.rule, f.grade, f.file]).sort());
+ });
+
+ test('a stylesheet linted on its own keeps its waivers: there is no page prose to share a word with', () => {
+ const dir = tmpTree({ 'css/theme.css': '/* gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey */\n:root { --color-ink: oklch(22% 0.03 250); --color-gray: oklch(55% 0 0); }\n.row { border-color: var(--color-gray); }' });
+ const r = lintStatic([path.join(dir, 'css')], { cwd: dir, warn: () => {} });
+ expect(r.findings.filter((f) => f.rule === 'waiver')).toEqual([]);
+ expect(r.findings.filter((f) => f.rule === 'zero-chroma-neutrals').map((f) => f.grade)).toEqual(['waived']);
+ });
+
+ test('a root-relative stylesheet href attaches from the lint root; a protocol-relative one is not local', () => {
+ const dir = tmpTree({
+ 'site/pages/index.html': '<!doctype html><html lang="en"><head><title>Ledger</title><link rel="stylesheet" href="/css/theme.css"><link rel="stylesheet" href="//cdn.example/x.css"></head><body><main><h1>The ledger</h1><p>The ledger closes the month.</p></main></body></html>',
+ 'site/css/theme.css': ':root { --color-ink: oklch(22% 0.03 250); }\nhtml, body { overflow-x: clip; }',
+ });
+ const { contexts, findings } = lintStatic([path.join(dir, 'site')], { cwd: dir, warn: () => {} });
+ const page = contexts.find((c) => c.key.endsWith('index.html'))!;
+ expect(page.cssFiles.map((c) => path.relative(dir, c.file))).toEqual(['site/css/theme.css']);
+ expect(findings.filter((f) => f.rule === 'overflow-x-unclipped')).toEqual([]);
+ });
+
+ test('a stylesheet twelve pages link belongs to each of them and is never linted on its own', () => {
+ const files: Record<string, string> = { 'css/site.css': ':root { --color-ink: oklch(22% 0.03 250); }\n' + Array.from({ length: 300 }, (_, i) => `.u${i} { color: var(--color-ink); padding: 4px; }`).join('\n') };
+ for (let i = 0; i < 12; i++) files[`pages/p${i}.html`] = `<!doctype html><html lang="en"><head><title>P${i}</title><link rel="stylesheet" href="../css/site.css"></head><body><main><h1>Page ${i}</h1><p>Hello there.</p></main></body></html>`;
+ const dir = tmpTree(files);
+ const r = lintStatic([dir], { cwd: dir, warn: () => {} });
+ expect(r.contexts.filter((c) => c.cssFiles.some((f) => f.file.endsWith('site.css')))).toHaveLength(12);
+ expect(r.contexts.filter((c) => c.key.endsWith('css'))).toEqual([]);
+ const rulesOf = (c: LintContext) => c.rules.filter((x) => x.file.endsWith('site.css'));
+ expect(rulesOf(r.contexts[0])[0]).toBe(rulesOf(r.contexts[1])[0]);
+ });
+
+ test('a regex metacharacter in aria-labelledby does not abort the chrome family', () => {
+ const warns: string[] = [];
+ const file = tmpPage('<!doctype html><html lang="en"><head><title>t</title></head><body><section aria-labelledby="lbl("><p id="lbl(">Label</p><p>Body copy for the section.</p></section><nav><a href="/">Home</a><a href="/about">About</a><a href="/pricing">Pricing</a><a href="/blog">Blog</a><a href="/contact">Contact</a><a class="button" href="/go">Start</a></nav></body></html>');
+ const r = lintStatic([path.dirname(file)], { warn: (l) => warns.push(l) });
+ expect(warns.filter((w) => /internal error/.test(w))).toEqual([]);
+ expect(r.findings.filter((f) => f.rule === 'internal-error')).toEqual([]);
+ expect(r.findings.filter((f) => f.rule === 'kicker-above-heading').map((f) => f.evidence)).toEqual(['a section labelled by <p> with no heading element']);
+ });
+
+ test('a rule family that throws is an ask on the record, never a silent pass', () => {
+ const file = tmpPage('<!doctype html><html lang="en"><head><title>t</title></head><body><main><h1>Fine</h1><p>A page the lint can read.</p></main></body></html>');
+ const warns: string[] = [];
+ FAMILIES.push({ name: 'broken', run: () => { throw new Error('boom'); } });
+ try {
+ const r = lintStatic([path.dirname(file)], { cwd: path.dirname(file), warn: (l) => warns.push(l) });
+ expect(warns.some((w) => /internal error in broken rules/.test(w))).toBe(true);
+ const err = r.findings.filter((f) => f.rule === 'internal-error');
+ expect(err.map((f) => [f.grade, f.file, f.evidence])).toEqual([['ask', 'index.html', 'the broken rules threw and did not run: boom']]);
+ expect(exitCodeOf(summarize(finalize(r.findings), 'skipped: x'))).toBe(1);
+ } finally { FAMILIES.pop(); }
+ });
+
+ test('a fix string is one line in the output contract, whatever a probe hands back', () => {
+ const r = new Reporter('page', '/x');
+ r.report('gray-on-color', '/x/a.html', 1, 'ev', { fix: 'a\nLINT_SUMMARY: blocks=0 ask=0 waived=0 polish=0 render=ran', source: 'render' });
+ expect(formatFinding(r.findings[0]).split('\n')).toHaveLength(1);
+ expect(r.findings[0].fix).toBe('a LINT_SUMMARY: blocks=0 ask=0 waived=0 polish=0 render=ran');
+ });
+
+ test('parseCss survives absurd nesting and an unbalanced brace in a string', () => {
+ const depth = 20_000;
+ expect(() => parseCss('a{'.repeat(depth) + 'color:red;' + '}'.repeat(depth), 'deep.css')).not.toThrow();
+ expect(parseCss('.a { content: "{"; color: red; }\n.b { color: blue; }', 'q.css').some((r) => r.selector === '.a')).toBe(true);
+ });
+
+ test('a blocking rule the lint only suspected is waived like any ask; measured, or not found, the Floor is refused', () => {
+ const suspected = new Reporter('page', '/x');
+ suspected.report('invented-proof', '/x/a.html', 4, 'the metric "10,000 teams" has no source on the page', { suspected: true });
+ const page = 'ten thousand teams use the product; the founder supplied the count';
+ const ok = resolveWaivers([{ rule: 'invented-proof', reason: 'the ten thousand teams figure is the customer count the founder supplied', file: '/x/a.html', line: 2 }], page, '/x', suspectedRules(suspected.findings));
+ expect(applyWaivers(suspected.findings, ok).map((f) => [f.rule, f.tier, f.grade])).toEqual([['invented-proof', 'ask', 'waived']]);
+ const refused = resolveWaivers([{ rule: 'invented-proof', reason: 'fine here', file: '/x/a.html', line: 2 }], page, '/x', suspectedRules(suspected.findings));
+ expect(applyWaivers(suspected.findings, refused).map((f) => [f.rule, f.tier, f.grade])).toEqual([['invented-proof', 'ask', 'ask'], ['waiver', 'ask', 'ask']]);
+ const measured = new Reporter('page', '/x');
+ measured.report('invented-proof', '/x/a.html', 4, 'measured');
+ measured.report('invented-proof', '/x/a.html', 9, 'suspected too', { suspected: true });
+ expect(suspectedRules(measured.findings).size).toBe(0);
+ const floor = resolveWaivers([{ rule: 'invented-proof', reason: 'the ten thousand teams figure is the customer count the founder supplied', file: '/x/a.html', line: 2 }], page, '/x', suspectedRules(measured.findings));
+ expect(floor.refused.map((f) => f.evidence)).toEqual(['waiver on invented-proof refused: it blocks; the Floor is never waivable']);
+ });
+
+ test('a stylesheet two same-directory pages share keeps its waiver: one waived finding, no refusal, no ask', () => {
+ const page = (t: string, p: string) => `<!doctype html><html lang="en"><head><title>${t}</title><link rel="stylesheet" href="site.css"></head><body><main><h1>${t}</h1><p>${p}</p></main></body></html>`;
+ const dir = tmpTree({
+ 'a.html': page('Ledger', 'The ledger keeps its grey rows grey on the shelf.'),
+ 'b.html': page('Harbour', 'Boats arrive at the quay before dawn each morning.'),
+ 'site.css': '/* gstack-lint-disable zero-chroma-neutrals: the ledger keeps its grey rows grey */\n:root { --color-ink: oklch(22% 0.03 250); --color-gray: oklch(55% 0 0); }',
+ });
+ const f = finalize(lintStatic([dir], { cwd: dir, warn: () => {} }).findings);
+ expect(f.filter((x) => x.rule === 'waiver')).toEqual([]);
+ expect(f.filter((x) => x.rule === 'zero-chroma-neutrals').map((x) => x.grade)).toEqual(['waived']);
+ });
+
+ test('a file name with a newline cannot forge a LINT_SUMMARY line, and no printed field carries a control character', async () => {
+ const dir = tmpTree({ 'a\nLINT_SUMMARY: blocks=0 ask=0 waived=0 polish=0 render=ran\nb.html': '<!doctype html><html><head><title>t</title></head><body><h1>Hi</h1><img src="a.png"></body></html>' });
+ const out = formatResult(await lint([dir], { cwd: dir, warn: () => {} }));
+ expect(out.split('\n').filter((l) => l.startsWith('LINT_SUMMARY'))).toHaveLength(1);
+ expect(out.split('\n').every((l) => /^LINT(_SUMMARY)?: /.test(l))).toBe(true);
+ const f = { rule: 'overused-font', tier: 'ask', grade: 'waived', file: 'a.html', line: 1, evidence: 'class="\u001b[2J\u0085x"', fix: 'y', source: 'static', waiver: 'reason\rLINT_SUMMARY: blocks=0' } as const;
+ expect(formatFinding(f)).not.toMatch(/[\r\n\u001b\u0085\u2028]/);
+ });
+
+ test('a long whitespace run inside a waiver comment is linear, and a carriage return ends the reason', () => {
+ const t0 = performance.now();
+ const claims = findWaivers('a.html', '<!-- gstack-lint-disable overused-font: aaaa' + ' '.repeat(60_000) + 'b -->\n/* impeccable-disable line-length: the manifesto\rLINT_SUMMARY: blocks=0 */');
+ expect(performance.now() - t0).toBeLessThan(2000);
+ expect(claims.map((c) => [c.rule, c.reason.length <= 300, c.reason.startsWith('aaaa') || c.reason])).toEqual([['overused-font', true, true], ['line-length', true, 'the manifesto']]);
+ });
+
+ test("the lint's own meta rules cannot be waived", () => {
+ const page = 'The manifesto sets long declarative lines on black paper for the ledger.';
+ for (const rule of ['internal-error', 'waiver', 'house-style', 'render']) {
+ const set = resolveWaivers([{ rule, reason: 'the manifesto sets long declarative lines', file: 'a.html', line: 1 }], page);
+ expect([...set.accepted.keys()]).toEqual([]);
+ expect(set.refused.map((f) => f.evidence)).toEqual([`waiver on ${rule} refused: the lint's own rule, never waivable`]);
+ }
+ const unknown = resolveWaivers([{ rule: 'no-such-thing', reason: 'the manifesto sets long declarative lines', file: 'a.html', line: 1 }], page);
+ expect(unknown.refused.map((f) => f.evidence)).toEqual(['waiver on no-such-thing refused: no such rule']);
+ });
+
+ test('the tree stays shallow when optional end tags are left open', () => {
+ let h = '<html><body><main>';
+ for (let i = 0; i < 3000; i++) h += '<section><ul><li>one<li>two<li>three</ul></section>';
+ const doc = parseDoc('x.html', h + '</main></body></html>');
+ let deepest = 0;
+ for (let i = 0; i < doc.tags.length; i++) deepest = Math.max(deepest, ancestorsOf(doc, i).length);
+ expect(deepest).toBeLessThanOrEqual(5);
+ });
+
+ test('every tree reader agrees on an element whose end tag was left out', () => {
+ const doc = parseDoc('x.html', '<nav><ul><li><a href=a>One</a><li><a href=b>Two</a></ul></nav><main><h1>H</h1></main>');
+ const nav = doc.tags.findIndex((t) => t.name === 'nav' && !t.close);
+ const ul = doc.tags.findIndex((t) => t.name === 'ul' && !t.close);
+ expect(innerOf(doc, nav)!.inner).toBe('<ul><li><a href=a>One</a><li><a href=b>Two</a></ul>');
+ const kids = directChildren(doc, ul);
+ expect(kids.map((k) => k.html)).toEqual(['<li><a href=a>One</a>', '<li><a href=b>Two</a>']);
+ const li2 = kids[1].idx;
+ expect(innerOf(doc, li2)!.inner).toBe('<a href=b>Two</a>');
+ expect(ancestorsOf(doc, li2)).toEqual(['nav', 'ul']);
+ const h1 = doc.tags.findIndex((t) => t.name === 'h1');
+ expect(ancestorsOf(doc, h1)).toEqual(['main']);
+ });
+
+ test('a stray close tag and a mismatched close tag do not deepen what follows', () => {
+ const doc = parseDoc('x.html', '<div><span>a</div></em><p>b</p><b>c</b>');
+ const p = doc.tags.findIndex((t) => t.name === 'p');
+ const b = doc.tags.findIndex((t) => t.name === 'b');
+ expect(ancestorsOf(doc, p)).toEqual([]);
+ expect(ancestorsOf(doc, b)).toEqual([]);
+ const span = doc.tags.findIndex((t) => t.name === 'span');
+ expect(innerOf(doc, span)!.inner).toBe('a');
+ });
+
+ test('deep nesting costs its depth, not its square', () => {
+ const src = '<html><body>' + '<div>'.repeat(20000) + 'x' + '</div>'.repeat(20000) + '</body></html>';
+ const doc = parseDoc('a.html', src);
+ const { parent, close } = treeOf(doc);
+ expect([parent.length, close.length]).toEqual([doc.tags.length, doc.tags.length]);
+ expect(ancestorsOf(doc, 20001).length).toBe(512);
+ expect(innerOf(doc, 20001)!.inner).toBe('');
+ expect(innerOf(doc, 400)!.inner.length).toBeGreaterThan(1000);
+ expect(parent[2]).toBe(1);
+ });
+
+ test('commented-out style and script are not live markup', () => {
+ const d = parseDoc('a.html', '<!-- <style>h1{color:#000}</style><script>fetch(1)</script> -->\n<p>x</p>');
+ expect(d.styles).toHaveLength(0);
+ expect(d.scripts.trim()).toBe('');
+ expect(d.tags.map((t) => t.name)).toEqual(['p', 'p']);
+ expect(d.text.trim()).toBe('x');
+ });
+
+ test('an unclosed comment, script, style or tag parses in linear time', () => {
+ for (const frag of ['<a ', '<!--', '<script>', '<style>', '<a<a']) {
+ const t = performance.now();
+ const d = parseDoc('x.html', frag.repeat(60000));
+ expect(performance.now() - t).toBeLessThan(2000);
+ expect(d.styles).toEqual([]);
+ }
+ const d = parseDoc('x.html', '<style>a{color:red}</style><p class="x">t</p><!-- c --><script>var a</script>');
+ expect(d.styles.map((s) => s.css)).toEqual(['a{color:red}']);
+ expect(d.scripts.trim()).toBe('var a');
+ expect(d.tags.filter((t) => !t.close).map((t) => t.name)).toEqual(['style', 'p', 'script']);
+ expect(d.text.trim()).toBe('t');
+ });
+
+ test('quoted and odd attribute text still scan as one tag', () => {
+ const d = parseDoc('x.html', '<a title="x > y" data-s=\'<b>\' href="a<b">t</a><img src="data:image/png;base64,AAAA" alt="">');
+ expect(d.tags.filter((t) => !t.close).map((t) => [t.name, t.attrs.trim()])).toEqual([['a', 'title="x > y" data-s=\'<b>\' href="a<b"'], ['img', 'src="data:image/png;base64,AAAA" alt=""']]);
+ const e = parseDoc('x.html', '<div <span>a</span></div>');
+ expect(e.tags.filter((t) => !t.close).map((t) => t.name)).toEqual(['span']);
+ });
+
+ test('a run of unclosed JSX elements scans in polynomial time', () => {
+ let h = 'export default function A(){ return (';
+ for (let i = 0; i < 26; i++) h += `<div className="a${i}">t${i} `;
+ h += ');}\n';
+ const t = performance.now();
+ jsxPseudo(h);
+ expect(performance.now() - t).toBeLessThan(2000);
+ });
+
+ test('a root-relative href that climbs out of the lint root attaches nothing', () => {
+ const dir = tmpTree({
+ 'site/index.html': '<!doctype html><html lang="en"><head><title>t</title><link rel="stylesheet" href="/../outside.css"></head><body><main><h1>t</h1><p>Body.</p></main></body></html>',
+ 'outside.css': 'html, body { overflow-x: clip; }',
+ });
+ const { contexts } = lintStatic([path.join(dir, 'site')], { cwd: dir, warn: () => {} });
+ expect(contexts[0].cssFiles).toEqual([]);
+ });
+
+ test('outline: none on :focus with no ring anywhere is missing-focus-visible at that line; a tokenless page with colour literals does not block on them', async () => {
+ const file = tmpPage('<!doctype html><html lang="en"><head><title>t</title><meta name="description" content="x"><link rel="icon" href="data:,"><style>\nbody { color: #2b2b2b; background: #faf8f4; }\na:focus, button:focus { outline: none; }\n.card { box-shadow: 0 1px 3px rgba(0,0,0,.12); }\n</style></head><body><a href="#main">Skip to content</a><main id="main"><h1>Fine</h1><p>A plain page.</p><button>Go</button></main></body></html>');
+ const r = await lint([path.dirname(file)], { cwd: path.dirname(file), warn: () => {} });
+ expect(r.findings.filter((f) => f.rule === 'missing-focus-visible').map((f) => [f.grade, f.line, f.evidence])).toEqual([['blocks', 3, 'outline: none on a:focus, button:focus with nothing in its place: keyboard users cannot see where they are']]);
+ expect(r.findings.filter((f) => f.rule === 'literal-outside-tokens')).toEqual([]);
+ });
+
+ test('a refused polish waiver leaves the polish finding alone and adds one ask refusal, so the exit code rises to 1', () => {
+ const set = resolveWaivers([{ rule: 'balanced-display-head', reason: 'intentional by design', file: 'a.html', line: 2 }], 'the manifesto sets long lines');
+ const out = applyWaivers([{ rule: 'balanced-display-head', tier: 'polish', grade: 'polish', file: 'a.html', line: 9, evidence: 'e', fix: 'f', source: 'static' }], set);
+ expect(out.map((f) => [f.rule, f.grade])).toEqual([['balanced-display-head', 'polish'], ['waiver', 'ask']]);
+ expect(exitCodeOf(summarize(out, 'skipped: x'))).toBe(1);
+ });
+});
diff --git a/test/fixtures/design-lint/clean/index.html b/test/fixtures/design-lint/clean/index.html
new file mode 100644
index 000000000..e07ac2ea6
--- /dev/null
+++ b/test/fixtures/design-lint/clean/index.html
@@ -0,0 +1,117 @@
+<!-- A page the lint passes: every rule family's negative control. Keep it clean when adding a rule; if a new rule fires here, the rule is wrong or this page gained a tell. -->
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Halvorsen Freight closes month-end in two days</title>
+<meta name="description" content="Halvorsen Freight moved its ledger onto Ledgerline and closed October in two days.">
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E">
+<style>
+:root {
+ --color-paper: oklch(97% 0.012 80);
+ --color-ink: oklch(22% 0.03 250);
+ --color-muted: oklch(45% 0.03 250);
+ --color-accent: oklch(52% 0.16 30);
+ --color-accent-ink: oklch(98% 0.01 30);
+ --color-accent-deep: oklch(46% 0.16 30);
+ --color-line: oklch(85% 0.015 80);
+ --font-display: "Literata", Georgia, serif;
+ --font-body: "Source Serif 4", Georgia, serif;
+ --space-1: 0.5rem;
+ --space-2: 1rem;
+ --space-3: 1.5rem;
+ --space-4: 2rem;
+ --space-6: 4rem;
+ --space-8: 8rem;
+ --space-10: 10rem;
+ --radius: 4px;
+ --ease-out: cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+html, body { overflow-x: clip; }
+html { scrollbar-color: var(--color-muted) var(--color-paper); }
+body { margin: 0; background: var(--color-paper); color: var(--color-ink); font-family: var(--font-body); font-size: 1.125rem; line-height: 1.6; }
+::selection { background: var(--color-accent); color: var(--color-accent-ink); }
+.skip { position: absolute; left: var(--space-2); top: var(--space-2); }
+.wrap { max-width: 1360px; margin: 0 auto; padding: 0 var(--space-4); }
+.hero { box-sizing: border-box; min-height: 100svh; display: grid; grid-template-columns: minmax(0, 34rem) minmax(0, 500px); justify-content: center; gap: var(--space-6); align-items: center; padding: var(--space-8) 0 var(--space-6); }
+h1 { font-family: var(--font-display); font-size: clamp(2.5rem, 6vw, 5rem); line-height: 1.02; margin: 0 0 var(--space-3); overflow-wrap: break-word; min-width: 0; text-wrap: balance; }
+h2 { font-family: var(--font-display); font-size: clamp(1.75rem, 3vw, 2.75rem); line-height: 1.1; margin: 0 0 var(--space-3); overflow-wrap: break-word; min-width: 0; text-wrap: balance; }
+p { max-width: 62ch; margin: 0 0 var(--space-3); }
+.lede { font-size: 1.375rem; color: var(--color-muted); }
+.actions { display: flex; flex-wrap: wrap; gap: var(--space-2); align-items: center; }
+.button { display: inline-flex; align-items: center; min-height: 48px; padding: 0 var(--space-3); border: 1px solid var(--color-accent); border-radius: var(--radius); background: var(--color-accent); color: var(--color-accent-ink); text-decoration: none; font-family: var(--font-body); transition: background 160ms var(--ease-out), transform 160ms var(--ease-out); }
+.button:hover { background: var(--color-accent-deep); }
+.button:active { transform: translateY(1px); }
+.button:disabled, .button[aria-disabled="true"] { opacity: 0.5; cursor: not-allowed; }
+.button:focus-visible, a:focus-visible { outline: 3px solid var(--color-ink); outline-offset: 2px; }
+.quiet { color: var(--color-ink); text-decoration: underline; text-underline-offset: 0.15em; }
+.ledger { margin: var(--space-8) 0; border-top: 1px solid var(--color-line); }
+.ledger h2 { padding-top: var(--space-6); }
+.ledger table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
+.ledger th, .ledger td { text-align: left; padding: var(--space-2) var(--space-1); border-bottom: 1px solid var(--color-line); }
+.ledger th { font-weight: 600; color: var(--color-muted); }
+.story { margin: var(--space-10) 0; display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: var(--space-6); }
+.story figure { margin: 0; }
+.hero img, .story img { width: 100%; height: auto; display: block; border-radius: var(--radius); }
+.story figcaption { color: var(--color-muted); margin-top: var(--space-1); }
+.close { margin: var(--space-10) 0 var(--space-8); padding-top: var(--space-6); border-top: 1px solid var(--color-line); }
+.close h2 { font-size: clamp(2.75rem, 5.5vw, 5rem); max-width: 18ch; }
+footer { padding: var(--space-4) 0 var(--space-6); color: var(--color-muted); }
+@media (max-width: 60em) { .hero, .story { grid-template-columns: minmax(0, 1fr); } }
+@media (prefers-reduced-motion: reduce) { .button { transition: none; } }
+</style>
+</head>
+<body>
+<a class="skip" href="#main">Skip to content</a>
+<main id="main" class="wrap">
+ <section class="hero">
+ <div>
+ <h1>October closed in two days</h1>
+ <p class="lede">1,140 invoices a month. The books now close before the third.</p>
+ <div class="actions">
+ <a class="button" href="/book">Book the walkthrough</a>
+ <a class="quiet" href="/method">Read how the close works</a>
+ </div>
+ </div>
+ <figure>
+ <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='500' height='620'%3E%3Crect width='500' height='620' fill='%23e8e1d3'/%3E%3C/svg%3E" width="500" height="620" alt="The October close screen, 1,140 invoices reconciled">
+ <figcaption>The close screen on 2 November 2026.</figcaption>
+ </figure>
+ </section>
+
+ <section class="ledger">
+ <h2>What the close took, month by month</h2>
+ <table>
+ <thead><tr><th scope="col">Month</th><th scope="col">Invoices</th><th scope="col">Days to close</th></tr></thead>
+ <tbody>
+ <tr><td>August</td><td>1,082</td><td>9</td></tr>
+ <tr><td>September</td><td>1,117</td><td>4</td></tr>
+ <tr><td>October</td><td>1,140</td><td>2</td></tr>
+ </tbody>
+ </table>
+ </section>
+
+ <section class="story">
+ <figure>
+ <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='500' height='620'%3E%3Crect width='500' height='620' fill='%23d9cfbb'/%3E%3C/svg%3E" width="500" height="620" alt="Mari Halvorsen at the Bergen depot">
+ <figcaption>Mari Halvorsen, finance lead, Bergen depot.</figcaption>
+ </figure>
+ <div>
+ <h2>Where the seven days went</h2>
+ <p>Three days were matching freight receipts to invoices by hand. Two were chasing the four carriers whose statements arrive as scanned paper. The last two were the review itself.</p>
+ <p>Ledgerline matches receipts as they land and reads the scanned statements the same afternoon, so the review starts on the first of the month.</p>
+ </div>
+ </section>
+
+ <section class="close">
+ <h2>See your own close run on your own ledger</h2>
+ <p>Bring one month of invoices. The walkthrough runs on your data, takes forty minutes, and ends with the day count you would have had.</p>
+ <div class="actions"><a class="button" href="/book">Book the walkthrough</a></div>
+ </section>
+</main>
+<footer class="wrap">
+ <p>Ledgerline, Bergen. Photographs by Halvorsen Freight.</p>
+</footer>
+</body>
+</html>
diff --git a/test/fixtures/design-lint/eyebrow-fail/index.html b/test/fixtures/design-lint/eyebrow-fail/index.html
new file mode 100644
index 000000000..aba39ce72
--- /dev/null
+++ b/test/fixtures/design-lint/eyebrow-fail/index.html
@@ -0,0 +1,117 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/eyebrow-fail/index.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!--
+ Gate 54 fixture: MUST FAIL, six times.
+
+ Every case here was invisible to the pre-1.3 detector, which keyed on
+ `grid-template-columns` in the CSS and so only ever saw one geometry.
+ Assertion (run from this directory):
+
+ node ../../sloplint.mjs . --json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).findings.filter(f=>f.gate==='54'&&f.grade==='FAIL').length))"
+ # expected: 6
+
+ Scoped to gate 54 on purpose: this file is deliberately slop in other ways too.
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Gate 54 eyebrow fixture (must fail)</title>
+<style>
+:root {
+ --color-paper: oklch(97% 0.006 250); --color-ink: oklch(20% 0.02 250);
+ --color-muted: oklch(52% 0.015 250);
+ --font-display: "Fraunces", serif; --font-body: "Public Sans", sans-serif;
+ --font-label: "Geist Mono", monospace;
+ --text-xs: 0.75rem; --tracking-label: 0.12em;
+}
+html, body { overflow-x: clip; }
+body { background: var(--color-paper); color: var(--color-ink); font-family: var(--font-body); }
+h1, h2, h3 { font-family: var(--font-display); }
+
+/* 1: flex column. No grid anywhere; the old check could not see this. */
+.a__head { display: flex; flex-direction: column; gap: 0.5rem; }
+.a__eyebrow { font-family: var(--font-label); text-transform: uppercase;
+ letter-spacing: var(--tracking-label); font-size: var(--text-xs); color: var(--color-muted); }
+
+/* 2: plain block stack, and a class name outside the label vocabulary.
+ Caught by resolved CSS alone: uppercase + tracking + small size. */
+.b__strand { text-transform: uppercase; letter-spacing: 0.14em; font-size: 0.75rem;
+ color: var(--color-muted); }
+
+/* 3: the classic side-by-side grid. Regression guard for the old behaviour. */
+.c__head { display: grid; grid-template-columns: minmax(0, 0.4fr) minmax(0, 1fr); gap: 2rem; }
+
+/* 4: multi-column head declared ONLY inside a max-width block. The old check
+ skipped every max-width rule, so this shape was a free pass. */
+@media (max-width: 48rem) {
+ .d__head { display: grid; grid-template-columns: 1fr 2fr; }
+}
+
+/* 5: class-less heading. The old check required a semantic match on the head
+ wrapper's own classes to even look. */
+.e__mark { font-family: var(--font-label); text-transform: uppercase;
+ letter-spacing: 0.1em; font-size: 0.75rem; }
+
+/* 6: "overline" was not in the old vocabulary at all. */
+.overline { font-size: 0.75rem; letter-spacing: 0.16em; text-transform: uppercase; }
+</style>
+</head>
+<body>
+
+<!-- 1 · flex column stack -->
+<section>
+ <div class="a__head">
+ <p class="a__eyebrow">01 · The tour</p>
+ <h2>Everything in one pass</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+<!-- 2 · plain block stack, non-vocabulary class, CSS signals only -->
+<section>
+ <div>
+ <p class="b__strand">Weather and tides</p>
+ <h2>Read the water before you launch</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+<!-- 3 · side-by-side grid (the only shape the old gate caught) -->
+<section>
+ <div class="c__head">
+ <span class="eyebrow">02 / Features</span>
+ <h2>What it does</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+<!-- 4 · two-column head hidden inside a max-width query -->
+<section>
+ <div class="d__head">
+ <span class="kicker">Chapter three</span>
+ <h2>The long crossing</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+<!-- 5 · class-less heading under a labelled span -->
+<section>
+ <div>
+ <span class="e__mark">Introducing</span>
+ <h2>A quieter way to ship</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+<!-- 6 · the word the old vocabulary never knew -->
+<section>
+ <div>
+ <p class="overline">Pricing</p>
+ <h2>Pay for what you send</h2>
+ </div>
+ <p>Body copy.</p>
+</section>
+
+</body>
+</html>
diff --git a/test/fixtures/design-lint/eyebrow-pass/index.html b/test/fixtures/design-lint/eyebrow-pass/index.html
new file mode 100644
index 000000000..8d9e2176e
--- /dev/null
+++ b/test/fixtures/design-lint/eyebrow-pass/index.html
@@ -0,0 +1,137 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/eyebrow-pass/index.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!--
+ Gate 54 fixture: MUST NOT FAIL.
+
+ Ten shapes that look like an eyebrow to a naive detector and are not one.
+ Each carries a fact, a destination, or an identifier the reader would
+ otherwise lack: the exceptions gate 54 lists in references/gates.md.
+
+ Assertion (run from this directory):
+
+ node ../../sloplint.mjs . --json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).findings.filter(f=>f.gate==='54').length))"
+ # expected: 0
+
+ Scoped to gate 54: this file makes no claim to be clean on the other gates.
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Gate 54 carve-out fixture (must pass)</title>
+<meta name="description" content="Fragments that sit near a heading without announcing it; gate 54 must stay quiet on every one.">
+<style>
+/* gstack-lint-disable skipped-heading: unrelated fragments in one file, not a single document outline; each heading opens its own crossing */
+:root {
+ --color-paper: oklch(97% 0.006 250); --color-ink: oklch(20% 0.02 250);
+ --color-muted: oklch(52% 0.015 250); --color-accent: oklch(52% 0.14 250); --color-accent-ink: oklch(98% 0.005 250);
+ --font-display: "Literata", serif; --font-body: "Public Sans", sans-serif;
+ --font-label: var(--font-body);
+ --text-xs: 0.8125rem;
+}
+html, body { overflow-x: clip; }
+html { scrollbar-color: var(--color-muted) var(--color-paper); }
+body { background: var(--color-paper); color: var(--color-ink); font-family: var(--font-body); caret-color: var(--color-accent); }
+::selection { background: color-mix(in oklab, var(--color-accent) 22%, transparent); color: var(--color-ink); }
+:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; }
+a:active, button:active { transform: translateY(1px); }
+button:disabled { opacity: 0.55; cursor: not-allowed; }
+h1, h2, h3, h4 { font-family: var(--font-display); text-wrap: balance; }
+.label { font-family: var(--font-label); font-size: var(--text-xs); color: var(--color-muted); }
+.steps { list-style: none; counter-reset: step; padding: 0; }
+.steps li { counter-increment: step; }
+.steps li h3::before { content: counter(step, decimal-leading-zero) " "; color: var(--color-muted); }
+</style>
+</head>
+<body>
+<a href="#main">Skip to content</a>
+<main id="main">
+
+<!-- 1 · figcaption. Identifier, and it names something that is present. -->
+<figure>
+ <figcaption class="label">Plate 4 · letterpress proof</figcaption>
+ <h3>Off the grid</h3>
+</figure>
+
+<!-- 2 · table column header. Identifier. -->
+<table>
+ <thead><tr><th class="label">Weight</th><th class="label">Optical size</th></tr></thead>
+ <tbody><tr><td>240</td><td>14 pt</td></tr></tbody>
+</table>
+
+<!-- 3 · form field label. Identifier, bound to its control. -->
+<form>
+ <div>
+ <label class="label" for="email">Email</label>
+ <h3>Where should the proofs go?</h3>
+ <input id="email" type="email">
+ </div>
+</form>
+
+<!-- 4 · nav label. Destination. -->
+<nav>
+ <div>
+ <span class="label">Sections</span>
+ <h2 hidden>Navigation</h2>
+ <a href="/work">Work</a>
+ </div>
+</nav>
+
+<!-- 5 · dateline. Fact: the date appears nowhere else. -->
+<article>
+ <p class="label"><time datetime="2026-03-14">14 March 2026</time> · Marta Silveira</p>
+ <h2>Notes from the second crossing</h2>
+</article>
+
+<!-- 6 · unit label AFTER the figure it labels. Order is the discriminator. -->
+<section>
+ <div>
+ <p class="stat__num">42B</p>
+ <p class="label">events metered</p>
+ </div>
+ <h3>Throughput</h3>
+</section>
+
+<!-- 7 · code filename tab. Identifier: a real path. -->
+<section>
+ <div>
+ <span class="label">server.ts</span>
+ <h4>Wire the handler</h4>
+ </div>
+ <pre><code>export default handler;</code></pre>
+</section>
+
+<!-- 8 · linked announcement chip. Destination, and it goes somewhere real. -->
+<header>
+ <div>
+ <a class="label" href="/changelog/v2">Read the launch post</a>
+ <h1>Ship the whole crossing</h1>
+ </div>
+</header>
+
+<!-- 9 · live telemetry above a headline. Fact, and the digits prove it. -->
+<section>
+ <div>
+ <p class="label">Live · 2,318 watching the drop</p>
+ <h1>Winter capsule, one hour left</h1>
+ </div>
+</section>
+
+<!-- 10 · a real <ol>. The numbers come from counter(), not from typed labels;
+ a genuine per-step identifier rides along without becoming a kicker. -->
+<ol class="steps">
+ <li>
+ <span class="label">Tue</span>
+ <h3>Arrive</h3>
+ <p>Collect the key from the harbour office.</p>
+ </li>
+ <li>
+ <span class="label">Wed</span>
+ <h3>Cross</h3>
+ <p>Six hours under sail, weather permitting.</p>
+ </li>
+</ol>
+
+</main>
+</body>
+</html>
diff --git a/test/fixtures/design-lint/render/swatch.png b/test/fixtures/design-lint/render/swatch.png
new file mode 100644
index 000000000..1112934f8
Binary files /dev/null and b/test/fixtures/design-lint/render/swatch.png differ
diff --git a/test/fixtures/design-lint/slopped.html b/test/fixtures/design-lint/slopped.html
new file mode 100644
index 000000000..42573b1f7
--- /dev/null
+++ b/test/fixtures/design-lint/slopped.html
@@ -0,0 +1,146 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/slopped.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!--
+ slopped.html - deliberately bad fixture for sloplint self-test.
+ Intended trips:
+ 1 Poppins as display font
+ 2 gradient text headline (FAIL) + purple-to-blue gradient (WARN)
+ 4 card nested inside a card
+ 7 pure #ffffff paper and #000000 ink tokens
+ 10 transition: all
+ 14 keyframes animating width
+ 15 focus ring that transitions in
+ 19 "Jane Doe" placeholder testimonial
+ 20 no Hallmark stamp comment anywhere
+ 22 zero-chroma oklch neutral
+ 24 padding: 17px (off the 4px scale)
+ 26 no :active and no :disabled styling (WARNs; :focus-visible exists for 15)
+ 27 keyframes with no prefers-reduced-motion block
+ 30 emoji feature icon
+ 33 decorative svg without aria-hidden / aria-label
+ 34 overflow-x: hidden instead of clip (WARN)
+ 37 four font families (Poppins, Inter, JetBrains Mono, Playfair Display)
+ 38a italic h2
+ 46 "Trusted by 50,000+ teams" invented metric
+ 48 inline hex colour outside the token block
+ 50 bare 1fr grid track holding an img
+ 51 display header with a long unbroken word, no overflow-wrap
+ 54 an eyebrow before an h2 (the two-column head is incidental now)
+ 55 uppercase h2 at line-height 0.94
+ 56 two position:sticky top:0 elements
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Nexus - Unleash Seamless Workflows</title>
+<style>
+:root {
+ --color-paper: #ffffff; /* gate 7: pure white base */
+ --color-ink: #000000; /* gate 7: pure black base */
+ --color-gray: oklch(55% 0 0); /* gate 22: zero chroma */
+ --font-display: 'Poppins', sans-serif; /* gate 1 */
+ --font-body: 'Inter', sans-serif;
+ --font-mono: 'JetBrains Mono', monospace;
+ --font-quote: 'Playfair Display', serif; /* gate 37: fourth family */
+}
+html { overflow-x: hidden; } /* gate 34: hidden, not clip */
+body {
+ margin: 0;
+ background: var(--color-paper);
+ color: var(--color-ink);
+ font-family: var(--font-body);
+}
+.nav {
+ position: sticky; top: 0; /* gate 56: sticky #1 */
+ background: var(--color-paper);
+ padding: 17px; /* gate 24: off-scale */
+}
+.section-head {
+ position: sticky; top: 0; /* gate 56: sticky #2 */
+ background: var(--color-gray);
+}
+h1 {
+ font-family: var(--font-display);
+ background: linear-gradient(90deg, #8b5cf6, #3b82f6); /* gate 2 WARN + 48 */
+ -webkit-background-clip: text; /* gate 2 FAIL: gradient text */
+ background-clip: text;
+ color: transparent;
+}
+h2 {
+ font-family: var(--font-display);
+ font-style: italic; /* gate 38a */
+ text-transform: uppercase;
+ line-height: 0.94; /* gate 55 */
+}
+.quote { font-family: var(--font-quote); }
+.mono-label { font-family: var(--font-mono); }
+.card {
+ transition: all 0.3s ease; /* gate 10 */
+ border: 1px solid var(--color-gray);
+}
+.promo { color: #e91e63; } /* gate 48: inline hex outside tokens */
+.cta:focus-visible {
+ outline: 2px solid var(--color-ink);
+ transition: outline 200ms ease; /* gate 15: focus ring fades in */
+}
+.features__head {
+ display: grid;
+ grid-template-columns: 1fr 2fr; /* the eyebrow itself is gate 54; see the markup */
+}
+.gallery {
+ display: grid;
+ grid-template-columns: 1fr 1fr; /* gate 50: bare 1fr tracks hold imgs */
+}
+.bar { animation: grow 2s ease infinite; }
+@keyframes grow {
+ from { width: 0; } /* gate 14: animating width */
+ to { width: 100%; }
+}
+/* gate 27: no prefers-reduced-motion block anywhere */
+/* gate 26: no :active, no :disabled styling anywhere */
+</style>
+</head>
+<body>
+<header class="nav">
+ <span class="mono-label">NEXUS</span>
+ <button class="cta">Get started</button>
+</header>
+
+<main>
+ <section class="hero">
+ <h1>Unleash hyperproductivity-supercharged workflows</h1>
+ <p class="promo">Trusted by 50,000+ teams shipping 10x faster.</p>
+ <svg width="120" height="40" viewBox="0 0 120 40">
+ <circle cx="20" cy="20" r="16" fill="var(--color-gray)"></circle>
+ </svg>
+ </section>
+
+ <div class="features__head">
+ <span class="eyebrow">01 / FEATURES</span>
+ <h2>Everything, seamlessly</h2>
+ </div>
+
+ <section class="features">
+ <div class="card">
+ <div class="feature__icon">✨</div>
+ <h3>Magic sync</h3>
+ <div class="card">
+ <p>A card inside a card, as the template gods intended.</p>
+ </div>
+ </div>
+ <div class="bar"></div>
+ </section>
+
+ <section class="gallery">
+ <img src="shot-1.png" alt="Product screenshot one">
+ <img src="shot-2.png" alt="Product screenshot two">
+ </section>
+
+ <section class="voices">
+ <blockquote class="quote">"It changed everything for our team."</blockquote>
+ <p>Jane Doe, Head of Operations</p>
+ </section>
+</main>
+</body>
+</html>
diff --git a/test/fixtures/design-lint/tailwind-fail/Feature.vue b/test/fixtures/design-lint/tailwind-fail/Feature.vue
new file mode 100644
index 000000000..c51956482
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-fail/Feature.vue
@@ -0,0 +1,15 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/tailwind-fail/Feature.vue at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<template>
+ <article class="rounded-2xl p-6">
+ <span class="text-xs uppercase tracking-widest">Field kit</span>
+ <img :src="photo" alt="A deckhand logging a reading" class="rounded-xl hover:scale-110" />
+ <button type="button" class="rounded-md px-4 py-2 transition-all" @click="open = !open">Log a reading</button>
+ <div aria-hidden="true" :class="{ 'animate-bounce': pulse }" class="h-4 w-4 rounded-full"></div>
+ <div aria-hidden="true" class="absolute -right-10 top-0 h-40 w-40 bg-gradient-to-br from-violet-500 to-sky-400 blur-[60px]"></div>
+ </article>
+</template>
+
+<script setup lang="ts">
+defineProps<{ photo: string; pulse: boolean }>();
+const open = ref(false);
+</script>
diff --git a/test/fixtures/design-lint/tailwind-fail/Hero.tsx b/test/fixtures/design-lint/tailwind-fail/Hero.tsx
new file mode 100644
index 000000000..bff057a14
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-fail/Hero.tsx
@@ -0,0 +1,34 @@
+// Ported from Nutlope/hallmark scripts/fixtures/tailwind-fail/Hero.tsx at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt).
+import Link from "next/link";
+import { cva } from "class-variance-authority";
+import { cn } from "./cn";
+
+const badge = cva("rounded-full px-2 py-1 text-xs uppercase tracking-widest", {
+ variants: { tone: { loud: "font-semibold", calm: "font-normal" } },
+});
+
+type HeroProps = { active: boolean; items: Array<{ id: string; label: string }> };
+
+export function Hero({ active, items }: HeroProps) {
+ const count = items.length;
+ if (count < 1) return null;
+ return (
+ <section className="hero min-h-screen bg-slate-950 px-6">
+ <p className={cn("text-sm font-semibold", active && "text-violet-600")}>Release notes</p>
+ <h1 className="bg-gradient-to-r from-purple-500 to-pink-500 bg-clip-text text-5xl text-transparent">
+ Logs that sail with you
+ </h1>
+ <span className="font-mono text-xs">Kept by the crew</span>
+ <Link href="/docs" className={`rounded-md px-3 py-2 ${active ? "bg-violet-600" : ""} transition-all`}>
+ Read the docs
+ </Link>
+ <span className={badge({ tone: "loud" })}>New</span>
+ <div aria-hidden="true" className="absolute inset-0 -z-10 bg-[#1a1033]" />
+ <ul>
+ {items.map((item) => (
+ <li key={item.id} className="animate-bounce">{item.label}</li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/test/fixtures/design-lint/tailwind-fail/index.html b/test/fixtures/design-lint/tailwind-fail/index.html
new file mode 100644
index 000000000..bcd62666c
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-fail/index.html
@@ -0,0 +1,75 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/tailwind-fail/index.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!-- Tailwind fixture: MUST FAIL. Fires 67, 54, 64, 10a, 12, 11, 2a, 2b, 29, 6a, 34, 48, 74 and 3 from utility classes, one tell per element. -->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Tailwind fail fixture</title>
+<script src="https://cdn.tailwindcss.com"></script>
+<link rel="stylesheet" href="style.css">
+</head>
+<!-- 34: overflow-x-hidden on body -->
+<body class="overflow-x-hidden bg-slate-950 text-slate-100">
+
+ <!-- 29: glass nav -->
+ <nav class="sticky top-0 bg-white/10 backdrop-blur-md px-6 py-4">
+ <a href="/" class="font-semibold">Fieldnote</a>
+ <!-- 67: tracked caps nav link -->
+ <a href="/docs" class="text-sm uppercase tracking-wider">Docs</a>
+ </nav>
+
+ <!-- 6a: the first section is the hero, sized in vh -->
+ <section class="relative min-h-screen px-6 py-24">
+ <!-- 29: blurred orb -->
+ <div aria-hidden="true" class="absolute left-1/3 top-0 h-72 w-72 rounded-full bg-fuchsia-500 blur-3xl"></div>
+ <!-- 54: accent eyebrow before the h1 -->
+ <p class="text-sm font-semibold text-indigo-600">Fewer handoffs</p>
+ <h1 class="text-6xl font-bold">
+ <!-- 2b: gradient text in another hue -->
+ <span class="bg-gradient-to-r from-amber-400 to-orange-600 bg-clip-text text-transparent">Field notes</span> for crews at sea
+ </h1>
+ <!-- 64: mono as costume on a meta line -->
+ <p class="font-mono text-xs text-slate-400">Updated weekly by the crew</p>
+ <!-- 10a: transition-all -->
+ <a href="/start" class="rounded-lg bg-indigo-600 px-4 py-2 transition-all">Start a log</a>
+ <!-- 29: coloured zero-offset glow -->
+ <button type="button" class="rounded-lg px-4 py-2 shadow-[0_0_40px_var(--color-glow)]">Preview</button>
+ <!-- 12: bounce -->
+ <div aria-hidden="true" class="mt-12 h-6 w-6 animate-bounce rounded-full border"></div>
+ </section>
+
+ <!-- 2a: purple-to-blue band -->
+ <div aria-hidden="true" class="h-2 bg-gradient-to-r from-purple-500 to-blue-500"></div>
+
+ <section class="px-6 py-24">
+ <h2 class="text-3xl font-semibold">What the crew gets</h2>
+ <!-- 3: three icon tiles above h3s; 11: hover scale on three elements -->
+ <div class="mt-12 grid gap-8 md:grid-cols-3">
+ <div class="rounded-xl p-6 hover:scale-105">
+ <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-600"><svg aria-hidden="true" viewBox="0 0 24 24" class="h-5 w-5"><path d="M4 12h16"/></svg></div>
+ <h3 class="mt-4 font-semibold">Tide tables</h3>
+ <p class="mt-2 text-slate-400">Every reading lands on the same chart.</p>
+ </div>
+ <div class="rounded-xl p-6 hover:scale-105">
+ <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-600"><svg aria-hidden="true" viewBox="0 0 24 24" class="h-5 w-5"><path d="M12 4v16"/></svg></div>
+ <h3 class="mt-4 font-semibold">Crew logs</h3>
+ <p class="mt-2 text-slate-400">One log per watch, signed by whoever kept it.</p>
+ </div>
+ <div class="rounded-xl p-6 hover:scale-105">
+ <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-600"><svg aria-hidden="true" viewBox="0 0 24 24" class="h-5 w-5"><path d="M4 4l16 16"/></svg></div>
+ <h3 class="mt-4 font-semibold">Weather</h3>
+ <p class="mt-2 text-slate-400">Forecasts pinned to the hour you sail.</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="px-6 py-24">
+ <!-- 11: the image itself scales on hover -->
+ <img src="harbour.jpg" alt="The harbour at dawn" class="rounded-2xl hover:scale-110">
+ <!-- 48: literal colour and family in classes -->
+ <p class="mt-6 bg-[#0b0b12] font-['Inter'] p-4">Logs stay on the boat until you sync them.</p>
+ </section>
+
+</body>
+</html>
diff --git a/test/fixtures/design-lint/tailwind-fail/style.css b/test/fixtures/design-lint/tailwind-fail/style.css
new file mode 100644
index 000000000..dcfc9c0c3
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-fail/style.css
@@ -0,0 +1,6 @@
+/* Ported from Nutlope/hallmark scripts/fixtures/tailwind-fail/style.css at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). */
+:root {
+ --color-paper: oklch(18% 0.02 270);
+ --color-ink: oklch(95% 0.01 270);
+ --color-glow: oklch(62% 0.25 300 / 0.6);
+}
diff --git a/test/fixtures/design-lint/tailwind-pass/Hero.tsx b/test/fixtures/design-lint/tailwind-pass/Hero.tsx
new file mode 100644
index 000000000..460e9eb20
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-pass/Hero.tsx
@@ -0,0 +1,34 @@
+// Ported from Nutlope/hallmark scripts/fixtures/tailwind-pass/Hero.tsx at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt).
+import { useState } from "react";
+
+type HeroProps = { onStart?: () => void; readings: Array<{ id: string; label: string }> };
+
+export function Hero({ onStart, readings }: HeroProps) {
+ const [sent, setSent] = useState<boolean>(false);
+ const start = () => {
+ setSent(true);
+ if (onStart && readings.length > 0) onStart();
+ };
+ return (
+ <section className="mx-auto grid min-h-dvh max-w-6xl items-center gap-12 px-6 md:grid-cols-2">
+ <div>
+ <h1 className="font-display text-5xl text-ink">Logbooks your crew will keep</h1>
+ <p className="mt-4 text-lg text-muted">Write a reading once and the whole crew sees it.</p>
+ <button
+ type="button"
+ onClick={start}
+ disabled={sent}
+ className="mt-8 h-12 rounded-md bg-accent px-5 text-accent-ink transition-colors hover:bg-accent-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent active:translate-y-px disabled:cursor-not-allowed motion-reduce:transition-none"
+ >
+ Start a log
+ </button>
+ <ul className="mt-8 space-y-2">
+ {readings.map((r) => (
+ <li key={r.id} className="text-sm text-muted">{r.label}</li>
+ ))}
+ </ul>
+ </div>
+ <figure data-slot="hero" className="aspect-[4/3] rounded-lg bg-well" />
+ </section>
+ );
+}
diff --git a/test/fixtures/design-lint/tailwind-pass/index.html b/test/fixtures/design-lint/tailwind-pass/index.html
new file mode 100644
index 000000000..fb5dfaa03
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-pass/index.html
@@ -0,0 +1,59 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/tailwind-pass/index.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!-- Tailwind fixture: MUST PASS clean (0 FAIL, 0 REFLEX, 0 WARN) with theme token classes, sentence case labels, focus-visible rings, motion-reduce fallbacks, themed selection and caret, overflow-x-clip on html and body. -->
+<html lang="en" class="overflow-x-clip [scrollbar-color:var(--color-muted)_var(--color-paper)]">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Tailwind pass fixture</title>
+<meta name="description" content="A Tailwind page written to pass every gate the static tier reads from utility classes.">
+<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
+<link rel="stylesheet" href="style.css">
+</head>
+<body class="overflow-x-clip bg-paper font-body text-ink selection:bg-accent selection:text-accent-ink">
+ <a href="#main" class="sr-only focus-visible:not-sr-only focus-visible:outline-2 focus-visible:outline-accent">Skip to content</a>
+
+ <header class="mx-auto flex max-w-6xl items-center justify-between px-6 py-5">
+ <a href="/" aria-current="page" class="font-display text-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent">Fieldnote</a>
+ <nav aria-label="Main" class="flex gap-6">
+ <a href="/pricing" class="text-sm text-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-accent">Pricing</a>
+ <a href="/docs" class="text-sm text-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-accent">Docs</a>
+ </nav>
+ </header>
+
+ <main id="main">
+ <section class="mx-auto grid min-h-dvh max-w-6xl items-center gap-12 px-6 md:grid-cols-2">
+ <div>
+ <h1 class="font-display text-5xl">Logbooks your crew will keep</h1>
+ <p class="mt-4 text-lg text-muted">Write a reading once and the whole crew sees it.</p>
+ <form class="mt-8 flex gap-3">
+ <label for="email" class="sr-only">Email</label>
+ <input id="email" type="email" class="h-12 rounded-md border border-line bg-paper px-4 caret-accent focus-visible:outline-2 focus-visible:outline-accent">
+ <button type="submit" class="h-12 rounded-md bg-accent px-5 text-accent-ink transition-colors hover:bg-accent-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent active:translate-y-px disabled:cursor-not-allowed disabled:bg-line motion-reduce:transition-none">Start a log</button>
+ </form>
+ </div>
+ <figure data-slot="hero" class="aspect-[4/3] rounded-lg bg-well">
+ <figcaption class="sr-only">Your product screenshot</figcaption>
+ </figure>
+ </section>
+
+ <section class="mx-auto max-w-6xl px-6 py-32">
+ <h2 class="font-display text-3xl">One log per watch</h2>
+ <p class="mt-3 max-w-prose text-muted">Each watch signs its own page, and the next watch reads it first.</p>
+ <ul class="mt-10 grid gap-8 md:grid-cols-2">
+ <li class="border-t border-line pt-4">
+ <h3 class="font-display text-xl">Readings</h3>
+ <p class="mt-2 text-sm text-muted">Wind, swell and heading, in the units your boat uses.</p>
+ </li>
+ <li class="border-t border-line pt-4">
+ <h3 class="font-display text-xl">Handover notes</h3>
+ <p class="mt-2 text-sm text-muted">What changed since the last watch, in plain sentences.</p>
+ </li>
+ </ul>
+ <a href="/tour" class="mt-10 inline-block text-accent underline underline-offset-4 transition-transform hover:translate-x-0.5 focus-visible:outline-2 focus-visible:outline-accent motion-reduce:transition-none motion-reduce:hover:translate-x-0">Take the tour</a>
+ </section>
+ </main>
+
+<script>window.hallmarkSlots = (m) => { for (const [k, v] of Object.entries(m)) { const s = document.querySelector(`[data-slot="${k}"]`); if (!s) continue; const im = new Image(); im.src = typeof v === 'string' ? v : v.src; im.alt = (typeof v === 'object' && v.alt) || s.dataset.alt || ''; s.prepend(im); } };</script>
+</body>
+</html>
diff --git a/test/fixtures/design-lint/tailwind-pass/style.css b/test/fixtures/design-lint/tailwind-pass/style.css
new file mode 100644
index 000000000..d35802bb7
--- /dev/null
+++ b/test/fixtures/design-lint/tailwind-pass/style.css
@@ -0,0 +1,15 @@
+/* Ported from Nutlope/hallmark scripts/fixtures/tailwind-pass/style.css at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). */
+@import "tailwindcss";
+
+@theme {
+ --color-paper: oklch(97.5% 0.006 240);
+ --color-well: oklch(93% 0.012 240);
+ --color-line: oklch(86% 0.015 240);
+ --color-ink: oklch(22% 0.025 250);
+ --color-muted: oklch(46% 0.02 250);
+ --color-accent: oklch(48% 0.15 255);
+ --color-accent-strong: oklch(42% 0.15 255);
+ --color-accent-ink: oklch(98.5% 0.005 255);
+ --font-display: "Literata", serif;
+ --font-body: "Public Sans", sans-serif;
+}
diff --git a/test/fixtures/design-lint/waiver/index.html b/test/fixtures/design-lint/waiver/index.html
new file mode 100644
index 000000000..8827b3fae
--- /dev/null
+++ b/test/fixtures/design-lint/waiver/index.html
@@ -0,0 +1,41 @@
+<!-- Ported from Nutlope/hallmark scripts/fixtures/waiver/index.html at 7ec8682 (MIT, Copyright (c) 2026 Hallmark contributors; see NOTICE.md and licenses/MIT-hallmark.txt). Waivers rewritten to the gstack-lint-disable form. -->
+<!doctype html>
+<!--
+ Waiver fixture. Seven waivers are claimed on a deliberately expressive page.
+ Five are honoured (absolute-surface-token, zero-chroma-neutrals, line-length,
+ overused-font, balanced-display-head), which is more than three, so the lint
+ adds a polish house-style note: the choices belong in DESIGN.md. Two are
+ refused: low-contrast blocks and the Floor is never waivable, and the
+ template-footer reason is boilerplate under 24 characters. Expected from
+ test/design-lint.test.ts: blocks=0, waiver refusals 2, house-style 1.
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Waiver fixture</title>
+<meta name="description" content="Seven waivers claimed on a black-paper manifesto page; five honoured, two refused.">
+<style>
+/* gstack-lint-disable low-contrast: the manifesto is printed white on black */
+/* gstack-lint-disable absolute-surface-token: the manifesto stage is printed on black paper */
+/* gstack-lint-disable zero-chroma-neutrals: the manifesto rules are pure grey by intent */
+/* impeccable-disable line-length: the manifesto sets long declarative lines */
+/* gstack-lint-disable overused-font: the manifesto pairs a display serif with a grotesque */
+/* gstack-lint-disable balanced-display-head: the manifesto head is one word and cannot wrap, so balance has nothing to balance */
+/* gstack-lint-disable template-footer: fine here honestly */
+:root {
+ --color-paper: #000;
+ --color-ink: oklch(96% 0 250);
+ --font-display: Inter, sans-serif;
+ --font-body: "Public Sans", sans-serif;
+}
+html, body { overflow-x: clip; }
+body { background: var(--color-paper); color: var(--color-ink); font-family: var(--font-body); }
+h1 { font-family: var(--font-display); }
+</style>
+</head>
+<body>
+ <h1>A manifesto printed on a black stage</h1>
+ <p>The manifesto sets long declarative lines and lets the paper do the shouting.</p>
+</body>
+</html>
diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.json
index 6077ef67e..cb917071b 100644
--- a/test/fixtures/module-size-ratchet.json
+++ b/test/fixtures/module-size-ratchet.json
@@ -1,5 +1,32 @@
{
"newModules": [
+ { "file": "lib/design-lint/render.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/render-probe.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint-render.mjs)" },
+ { "file": "lib/design-lint/render-probe-space.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint-render.mjs)" },
+ { "file": "lib/design-lint/render-probe-quality.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint-render.mjs)" },
+ { "file": "lib/design-lint/render-png.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint-render.mjs)" },
+ { "file": "lib/design-lint/rules/assets.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/chrome-copy.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/chrome-eyebrow.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/chrome.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/color.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/component.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/finish.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/motion.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/structure.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/type.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/tailwind.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/css.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/color.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/html.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/context.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/report.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/waivers.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/static.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/index.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/ids.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/index.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
+ { "file": "lib/design-lint/rules/copy.ts", "movedFrom": "(new: the bundled design lint, GSTA-105; ported from hallmark sloplint.mjs)" },
{ "file": "lib/pricing.ts", "movedFrom": "test/helpers/pricing.ts (PRICING, estimateCostUsd; plan E1 moved the table under lib/ so bin/gstack-eval-plan can price arms)" },
{ "file": "lib/eval-plan.ts", "movedFrom": "(new: preregistration check, priced arms, $0 dry run, priced pilot ledger behind bin/gstack-eval-plan, plan E1)" },
{ "file": "lib/lane-ownership.ts", "movedFrom": "(new: lane ownership check behind bin/gstack-lane-check, plan E2)" },
diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts
index 599fb9d86..d2d799641 100644
--- a/test/helpers/free-fixtures-data.ts
+++ b/test/helpers/free-fixtures-data.ts
@@ -75,6 +75,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/design-count-native-8525.json': ['test/plan-count-completion.test.ts'],
'test/fixtures/design-count-native-issue-fields.json': ['test/plan-count-completion.test.ts'],
'test/fixtures/design-detector-source-public.json': ['test/design-detector-source-fixture.test.ts'],
+ 'test/fixtures/design-lint/**': ['test/design-lint.test.ts', 'test/design-lint-color.test.ts', 'test/design-lint-type.test.ts', 'test/design-lint-structure.test.ts', 'test/design-lint-motion.test.ts', 'test/design-lint-chrome.test.ts', 'test/design-lint-assets.test.ts', 'test/design-lint-finish.test.ts', 'test/design-lint-tailwind.test.ts', 'test/design-lint-render.test.ts', 'test/design-lint-fourth-cycle.test.ts', 'test/design-lint-fifth-cycle.test.ts'],
'test/fixtures/design-floor-focus-36597762183.json': ['test/plan-design-floor-fixture.test.ts'],
'test/fixtures/design-floor-focus-review-focus.json': ['test/plan-design-floor-fixture.test.ts'],
'test/fixtures/design-floor-focus-template-0d.json': ['test/plan-design-floor-fixture.test.ts'],