maddox-engine 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # maddox
2
2
 
3
- Scans source code for design-token, motion, and component-state drift against your own design system.
3
+ Scans source code — or a live deployed page — for design-token, motion, and component-state drift against your own design system.
4
4
 
5
5
  This is the open-source scanning engine behind [Maddox Engine](https://www.maddoxengine.com) — the same code the hosted dashboard and GitHub Action run, extracted so you can run it locally or in CI with no account required.
6
6
 
7
7
  ## What it checks
8
8
 
9
- - **Colors** — every hex literal in your source, matched against your `@theme` tokens by exact value, then by RGB distance for near-misses.
10
- - **Motion** — durations and easings used in code, checked against your real motion tokens (duration against duration, ease against ease — never cross-compared).
11
- - **Component states** — an explicit contract you write yourself (a JSON file naming which states each kind of component must cover: `disabled`, `loading`, `error`, and so on). Confirms the state is referenced in the file; it doesn't verify it renders correctly — that's a static source check, not a visual one.
9
+ - **Colors** — every hex literal in your source (or a live page's rendered HTML/CSS), matched against your `@theme` tokens by exact value, then by RGB distance for near-misses.
10
+ - **Motion** — durations and easings used in code, checked against your real motion tokens (duration against duration, ease against ease — never cross-compared). Source-scan only; see `--url` below.
11
+ - **Component states** — an explicit contract you write yourself (a JSON file naming which states each kind of component must cover: `disabled`, `loading`, `error`, and so on). Confirms the state is referenced in the file; it doesn't verify it renders correctly — that's a static source check, not a visual one. Source-scan only.
12
12
 
13
- This is a static source-code scanner, not a pixel/DOM visual-regression tool. It checks the values developers actually wrote against the tokens that are supposed to govern them, so it catches drift that renders identically to a real token (and so produces zero visual diff) but was never written as one.
13
+ This is a source-code and rendered-output scanner, not a pixel/DOM visual-regression tool. It checks the values a page actually ships against the tokens that are supposed to govern them, so it catches drift that renders identically to a real token (and so produces zero visual diff) but was never written as one.
14
14
 
15
15
  ## Usage
16
16
 
@@ -20,10 +20,11 @@ npx maddox-engine <target-source-dir> <path-to-globals.css-with-@theme-block> [o
20
20
 
21
21
  Options:
22
22
 
23
- - `--project <name>` — project name (defaults to the target directory's basename)
23
+ - `--project <name>` — project name (defaults to the target directory's basename, or the URL's hostname in `--url` mode)
24
24
  - `--motion <path>` — path to a JSON file of motion tokens (e.g. a vendored copy of your motion-tokens export)
25
- - `--states <path>` — path to a state-contract JSON file (see below)
25
+ - `--states <path>` — path to a state-contract JSON file (see below). No effect in `--url` mode.
26
26
  - `--tokens-studio <path>` — path to a Tokens Studio / W3C Design Tokens JSON export (see below); merged with, and taking precedence over, `@theme` on any path both define
27
+ - `--url <page-url>` — scan a deployed page instead of local source (see below); pass a placeholder like `-` for `<target-source-dir>` when using this alone
27
28
  - `--format text|json|markdown` — output format (default: `text`)
28
29
  - `--fail-below <0-100>` — exit non-zero if the drift health score falls below this threshold; omit to never fail
29
30
 
@@ -50,6 +51,21 @@ Ground truth is explicit — nothing is inferred about which states a component
50
51
 
51
52
  If your tokens live in Figma via the Tokens Studio plugin rather than (or alongside) a Tailwind `@theme` block, export them to JSON and point `--tokens-studio` at the file. A single-set export (the whole file is one token tree) and a multi-set export (top-level keys are set names, e.g. `global`, `dark`) are both supported — for a multi-set export, every set is merged, later sets overriding earlier ones by path. `{alias}` references are resolved automatically. Only token types that resolve to a single comparable value (`color`, `spacing`, `sizing`, `fontSizes`, `borderRadius`, `dimension`) are used — composite types like `typography` or `boxShadow` describe a bundle of properties, not one value to diff against, and are skipped rather than misclassified.
52
53
 
54
+ ### Scanning a live page
55
+
56
+ ```bash
57
+ npx maddox-engine - ./src/app/globals.css --url https://example.com --format text
58
+ ```
59
+
60
+ `--url` fetches the page's rendered HTML plus every same-origin `<link rel="stylesheet">` it links to, and runs the same color/font-size extraction against what's actually shipped — not what's in the repo at scan time. This is the difference between a source-linter and a production check: a stale CDN cache, a build step that silently drops a token, or a config typo can all make the deployed page diverge from what the source says, and only a live-URL scan catches that.
61
+
62
+ Two things don't carry over to `--url` mode:
63
+
64
+ - **Motion** — durations/eases only ever appear in rendered HTML/CSS as static literals if a component hardcodes them there, which real motion libraries don't do (they animate via the JS runtime). Motion findings are dropped from every `--url` scan rather than surfaced as noise from unrelated CSS.
65
+ - **Component states** — state-completeness is a "is this identifier referenced in this file's source" check; a fetched, already-rendered page has no source to check. `--states` is accepted but has no effect in `--url` mode.
66
+
67
+ Third-party stylesheets (a different origin than the page itself, e.g. a font CDN) are never fetched — only same-origin CSS, so findings only ever point at code the project actually owns.
68
+
53
69
  ### Suggested fixes
54
70
 
55
71
  Every `near-miss` finding with a resolved nearest token gets a `suggestion` — the concrete replacement text (`var(--token-name)` for a CSS value, or `motionTokens.path.to.value` for a motion token). It's advisory text for a human to apply, not an automatic edit: nothing in this package rewrites your source files. An `unrecognized` value with no close match, and a `missing`-state finding, never get one — there's no safe mechanical fix for either.
@@ -74,11 +90,12 @@ This repo is also a GitHub Action — `omrdev1/maddox-cli` — that runs a scan,
74
90
 
75
91
  Inputs:
76
92
 
77
- - `target-dir` *(required)* — directory to scan
93
+ - `target-dir` *(required unless `url` is set)* — directory to scan
78
94
  - `theme-css` *(required)* — path to the CSS file containing the `@theme` block
79
95
  - `motion-tokens` — path to a motion-tokens JSON file
80
- - `states` — path to a state-contract JSON file
96
+ - `states` — path to a state-contract JSON file. No effect when `url` is set.
81
97
  - `tokens-studio` — path to a Tokens Studio / W3C Design Tokens JSON export
98
+ - `url` — a deployed page URL to scan instead of local source
82
99
  - `github-token` *(required)* — for posting the PR comment, usually `${{ secrets.GITHUB_TOKEN }}`
83
100
  - `fail-below` — fail the build below this health score; omit for comment-only
84
101
  - `api-key` / `api-url` — optional, upload results to a [Maddox Engine](https://www.maddoxengine.com) dashboard account for scan history and drift trends across projects (a separate hosted product, not required to use the Action itself)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "maddox-engine",
3
- "version": "0.2.0",
4
- "description": "Scans source code for design-token, motion, and component-state drift against your own design system — the same engine behind Maddox Engine's CI checks.",
3
+ "version": "0.3.0",
4
+ "description": "Scans source code or a live deployed page for design-token, motion, and component-state drift against your own design system — the same engine behind Maddox Engine's CI checks.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
package/src/cli.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env -S npx tsx
2
2
 
3
3
  import { readFileSync } from "node:fs";
4
- import { audit, healthScore, loadGroundTruth, loadStateContract } from "./core.js";
4
+ import { audit, auditUrl, healthScore, loadGroundTruth, loadStateContract } from "./core.js";
5
5
  import { summarize, toJson, toMarkdown, toText, type ScanSummary } from "./format.js";
6
6
 
7
7
  async function uploadResult(apiUrl: string, apiKey: string, projectName: string, summary: ScanSummary) {
@@ -36,18 +36,23 @@ function flagValue(name: string): string | undefined {
36
36
  async function main() {
37
37
  const targetDir = process.argv[2];
38
38
  const themeCssPath = process.argv[3];
39
+ const url = flagValue("--url");
39
40
 
40
- if (!targetDir || !themeCssPath) {
41
+ if (!themeCssPath || (!targetDir && !url)) {
41
42
  console.error(
42
43
  "Usage: pnpm scan <target-source-dir> <path-to-globals.css-with-@theme-block> " +
43
44
  "[--project <name>] [--motion <path-to-motion-tokens.json>] " +
44
45
  "[--states <path-to-state-contract.json>] [--format text|json|markdown] " +
45
- "[--fail-below <0-100>] [--tokens-studio <path-to-tokens-studio-export.json>]"
46
+ "[--fail-below <0-100>] [--tokens-studio <path-to-tokens-studio-export.json>] " +
47
+ "[--url <live-page-url>]\n" +
48
+ " --url scans a deployed page's rendered HTML/CSS instead of local source " +
49
+ "(pass a placeholder for <target-source-dir>, e.g. '-', when using --url alone). " +
50
+ "--states has no effect in --url mode: state-completeness is a source-code check."
46
51
  );
47
52
  process.exit(1);
48
53
  }
49
54
 
50
- const projectName = flagValue("--project") ?? targetDir.split("/").pop() ?? "unnamed-project";
55
+ const projectName = flagValue("--project") ?? (url ? new URL(url).hostname : targetDir.split("/").pop()) ?? "unnamed-project";
51
56
  const format = flagValue("--format") ?? "text";
52
57
 
53
58
  // Motion tokens are an optional external JSON file (a plain object like
@@ -64,7 +69,8 @@ async function main() {
64
69
 
65
70
  const tokensStudioPath = flagValue("--tokens-studio");
66
71
  const groundTruth = loadGroundTruth(themeCssPath, motionTokens, tokensStudioPath);
67
- const result = await audit(targetDir, groundTruth, stateContract);
72
+
73
+ const result = url ? await auditUrl(url, groundTruth) : await audit(targetDir, groundTruth, stateContract);
68
74
  const summary = summarize(result.findings, result.filesScanned);
69
75
 
70
76
  if (format === "json") {
package/src/core.ts CHANGED
@@ -2,12 +2,14 @@ export * from "./types.js";
2
2
  export * from "./groundTruth.js";
3
3
  export * from "./tokensStudio.js";
4
4
  export * from "./scan.js";
5
+ export * from "./crawl.js";
5
6
  export * from "./diff.js";
6
7
  export * from "./stateCheck.js";
7
8
  export * from "./healthScore.js";
8
9
  export * from "./suggestFix.js";
9
10
 
10
11
  import { scanSource, scanFiles } from "./scan.js";
12
+ import { crawlUrl } from "./crawl.js";
11
13
  import { diffUsages } from "./diff.js";
12
14
  import { checkStates } from "./stateCheck.js";
13
15
  import { attachSuggestions } from "./suggestFix.js";
@@ -32,3 +34,18 @@ export async function audit(
32
34
 
33
35
  return { findings, filesScanned: scannedFiles.size };
34
36
  }
37
+
38
+ /**
39
+ * The production-aware counterpart to audit(): fetches a live page (plus
40
+ * its same-origin stylesheets) instead of walking local source files, and
41
+ * diffs what's actually shipped against the same ground truth. No state
42
+ * contract here — component-state completeness is a source-code question
43
+ * (is the state referenced anywhere in this file's source), which has no
44
+ * equivalent for a fetched, already-rendered page.
45
+ */
46
+ export async function auditUrl(pageUrl: string, groundTruth: GroundTruth): Promise<ScanResult> {
47
+ const { usages, sourcesScanned } = await crawlUrl(pageUrl);
48
+ const findings = diffUsages(usages, groundTruth);
49
+ attachSuggestions(findings);
50
+ return { findings, filesScanned: sourcesScanned.length };
51
+ }
package/src/crawl.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { extractFromContent, type RawUsage } from "./scan.js";
2
+
3
+ // Only ever follow relative/absolute-path stylesheet links resolved
4
+ // against the page's own origin — never a third-party CDN's CSS, since
5
+ // that's not the project's own design system and would only add noise
6
+ // (and, worse, false "unrecognized" findings for code the project never
7
+ // wrote).
8
+ function isSameOrigin(href: string, pageUrl: URL): boolean {
9
+ try {
10
+ const resolved = new URL(href, pageUrl);
11
+ return resolved.origin === pageUrl.origin;
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+
17
+ // Matches <link ... rel="stylesheet" ... href="..."> and the reverse
18
+ // attribute order, case-insensitively, without a full HTML parser —
19
+ // good enough for the handful of <link> tags a real page head has.
20
+ const STYLESHEET_LINK_RE =
21
+ /<link\b[^>]*\brel=["']stylesheet["'][^>]*\bhref=["']([^"']+)["'][^>]*>|<link\b[^>]*\bhref=["']([^"']+)["'][^>]*\brel=["']stylesheet["'][^>]*>/gi;
22
+
23
+ function findStylesheetHrefs(html: string): string[] {
24
+ const hrefs: string[] = [];
25
+ STYLESHEET_LINK_RE.lastIndex = 0;
26
+ let m: RegExpExecArray | null;
27
+ while ((m = STYLESHEET_LINK_RE.exec(html)) !== null) {
28
+ hrefs.push(m[1] ?? m[2]);
29
+ }
30
+ return hrefs;
31
+ }
32
+
33
+ export interface CrawlResult {
34
+ usages: RawUsage[];
35
+ // The page URL plus every stylesheet URL actually fetched — reported
36
+ // back so a caller (or the CLI's own output) can show what was scanned,
37
+ // the live-URL equivalent of scanSource's file count.
38
+ sourcesScanned: string[];
39
+ }
40
+
41
+ /**
42
+ * Fetches a live page's rendered HTML plus every same-origin linked
43
+ * stylesheet, and runs the same color/font-size/motion literal
44
+ * extraction scanSource runs over local source files. This is what makes
45
+ * Maddox "production-aware" rather than local-source-only: it checks
46
+ * what a real deployed page actually ships, not just what's in the repo
47
+ * at scan time (a config typo, a stale CDN cache, or a build step that
48
+ * silently drops a token could all cause the two to diverge).
49
+ *
50
+ * Framer Motion / GSAP usage is deliberately dropped from the result.
51
+ * Real motion libraries set durations/eases via the JS animation runtime,
52
+ * not static markup, so they never legitimately appear in rendered
53
+ * HTML/CSS — but framework-compiled CSS reliably DOES contain unrelated
54
+ * matches for the same shared regex (confirmed against a real deploy:
55
+ * Tailwind's own `--default-transition-duration:.15s` custom property
56
+ * matches the duration pattern, `transition-timing-function` matches the
57
+ * ease pattern). Rather than surface those as noisy false "unrecognized"
58
+ * findings, motion usages are filtered out of every crawl result before
59
+ * it's returned — motion checking stays a source-scan-only capability.
60
+ */
61
+ export async function crawlUrl(pageUrl: string): Promise<CrawlResult> {
62
+ const url = new URL(pageUrl);
63
+ const usages: RawUsage[] = [];
64
+ const sourcesScanned: string[] = [];
65
+
66
+ const pageResponse = await fetch(url, { redirect: "follow" });
67
+ if (!pageResponse.ok) {
68
+ throw new Error(`Failed to fetch ${url}: ${pageResponse.status} ${pageResponse.statusText}`);
69
+ }
70
+ const html = await pageResponse.text();
71
+ usages.push(...extractFromContent(url.toString(), html));
72
+ sourcesScanned.push(url.toString());
73
+
74
+ const stylesheetHrefs = findStylesheetHrefs(html).filter((href) => isSameOrigin(href, url));
75
+
76
+ for (const href of stylesheetHrefs) {
77
+ const cssUrl = new URL(href, url).toString();
78
+ try {
79
+ const cssResponse = await fetch(cssUrl);
80
+ if (!cssResponse.ok) continue;
81
+ const css = await cssResponse.text();
82
+ usages.push(...extractFromContent(cssUrl, css));
83
+ sourcesScanned.push(cssUrl);
84
+ } catch {
85
+ // A single unreachable stylesheet shouldn't fail the whole crawl —
86
+ // same tolerance readScannedFiles already has for an unreadable
87
+ // local file.
88
+ }
89
+ }
90
+
91
+ return { usages: usages.filter((u) => u.kind !== "motion"), sourcesScanned };
92
+ }