mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 06:06:37 +03:00
Sync generated provider output
This commit is contained in:
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
@@ -2681,12 +2681,12 @@
|
||||
});
|
||||
const check = el('span', {
|
||||
fontSize: '15px', lineHeight: '1', flexShrink: '0',
|
||||
color: 'oklch(45% 0.15 145)',
|
||||
color: 'oklch(45% 0.18 145)',
|
||||
});
|
||||
check.textContent = '\u2713';
|
||||
row.appendChild(check);
|
||||
const label = el('span', {
|
||||
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
|
||||
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
|
||||
});
|
||||
label.textContent = 'Variant applied';
|
||||
row.appendChild(label);
|
||||
@@ -8192,7 +8192,7 @@ void main() {
|
||||
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
|
||||
const STEER_AWAIT_TIMEOUT_MS = 120000;
|
||||
const AGENT_STATUS_POLL_MS = 5000;
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
|
||||
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
|
||||
const GLOBAL_BAR_SECTION_GAP = 8;
|
||||
const GLOBAL_BAR_INNER_GAP = 2;
|
||||
@@ -8259,8 +8259,8 @@ void main() {
|
||||
// Neutral hairline for internal control borders / dividers (was a warm
|
||||
// gold rule that read as muddy champagne edges on the pill / input / count).
|
||||
hairline: 'oklch(92% 0 0 / 0.12)',
|
||||
text: 'oklch(84% 0.035 82)',
|
||||
textDim: 'oklch(63% 0.024 82)',
|
||||
text: 'oklch(91% 0 0)',
|
||||
textDim: 'oklch(72% 0 0)',
|
||||
accent: C.brand,
|
||||
accentSoft: C.brandSoft,
|
||||
exitHover: 'oklch(58% 0.15 35 / 0.18)',
|
||||
@@ -9064,9 +9064,9 @@ void main() {
|
||||
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
|
||||
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
|
||||
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
|
||||
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
|
||||
uiAppendStyle(s);
|
||||
}
|
||||
@@ -9306,7 +9306,7 @@ void main() {
|
||||
const agentDot = el('span', {
|
||||
position: 'absolute', right: '-1px', bottom: '7px',
|
||||
width: '6px', height: '6px', borderRadius: '50%',
|
||||
background: 'oklch(78% 0.14 75)',
|
||||
background: 'oklch(77% 0.13 82)',
|
||||
boxShadow: '0 0 0 2px ' + P.surface,
|
||||
display: 'none', pointerEvents: 'none',
|
||||
});
|
||||
@@ -9408,11 +9408,11 @@ void main() {
|
||||
// DESIGN.md panel toggle - quartet of color squares as the mark.
|
||||
const designBtn = makeIconBtn({
|
||||
id: PREFIX + '-design-toggle',
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
|
||||
<span style="background:oklch(84% 0.19 80.46)"></span>
|
||||
<span style="background:oklch(70% 0.12 188)"></span>
|
||||
<span style="background:oklch(84% 0.035 82)"></span>
|
||||
<span style="background:oklch(34% 0.014 82)"></span>
|
||||
<span style="background:oklch(91% 0 0)"></span>
|
||||
<span style="background:oklch(34% 0 0)"></span>
|
||||
</span>`,
|
||||
label: 'DESIGN.md',
|
||||
ariaLabel: 'Toggle DESIGN.md panel',
|
||||
@@ -9996,8 +9996,8 @@ void main() {
|
||||
meta: 'oklch(55% 0 0)',
|
||||
hairline: 'oklch(88% 0 0)',
|
||||
hairlineSoft: 'oklch(92% 0 0)',
|
||||
amber: 'oklch(70% 0.13 65)', // stale-hint accent
|
||||
amberBg: 'oklch(95% 0.05 80)',
|
||||
amber: 'oklch(77% 0.13 82)', // stale-hint accent
|
||||
amberBg: 'oklch(89% 0.055 84)',
|
||||
};
|
||||
|
||||
function designPanelCss(BP) {
|
||||
@@ -10088,7 +10088,7 @@ void main() {
|
||||
}
|
||||
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
|
||||
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
|
||||
.error { color: oklch(45% 0.15 25); }
|
||||
.error { color: oklch(58% 0.15 35); }
|
||||
|
||||
/* Stale hint */
|
||||
.stale {
|
||||
@@ -10240,8 +10240,8 @@ void main() {
|
||||
content: ''; position: absolute; left: 4px; top: 13px;
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
}
|
||||
.coll .do::before { background: oklch(62% 0.16 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.22 25); }
|
||||
.coll .do::before { background: oklch(45% 0.18 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.15 35); }
|
||||
|
||||
.coll .overview-body {
|
||||
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.6.0
|
||||
version: 3.7.0
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
|
||||
license: Apache 2.0
|
||||
|
||||
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
@@ -2681,12 +2681,12 @@
|
||||
});
|
||||
const check = el('span', {
|
||||
fontSize: '15px', lineHeight: '1', flexShrink: '0',
|
||||
color: 'oklch(45% 0.15 145)',
|
||||
color: 'oklch(45% 0.18 145)',
|
||||
});
|
||||
check.textContent = '\u2713';
|
||||
row.appendChild(check);
|
||||
const label = el('span', {
|
||||
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
|
||||
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
|
||||
});
|
||||
label.textContent = 'Variant applied';
|
||||
row.appendChild(label);
|
||||
@@ -8192,7 +8192,7 @@ void main() {
|
||||
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
|
||||
const STEER_AWAIT_TIMEOUT_MS = 120000;
|
||||
const AGENT_STATUS_POLL_MS = 5000;
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
|
||||
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
|
||||
const GLOBAL_BAR_SECTION_GAP = 8;
|
||||
const GLOBAL_BAR_INNER_GAP = 2;
|
||||
@@ -8259,8 +8259,8 @@ void main() {
|
||||
// Neutral hairline for internal control borders / dividers (was a warm
|
||||
// gold rule that read as muddy champagne edges on the pill / input / count).
|
||||
hairline: 'oklch(92% 0 0 / 0.12)',
|
||||
text: 'oklch(84% 0.035 82)',
|
||||
textDim: 'oklch(63% 0.024 82)',
|
||||
text: 'oklch(91% 0 0)',
|
||||
textDim: 'oklch(72% 0 0)',
|
||||
accent: C.brand,
|
||||
accentSoft: C.brandSoft,
|
||||
exitHover: 'oklch(58% 0.15 35 / 0.18)',
|
||||
@@ -9064,9 +9064,9 @@ void main() {
|
||||
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
|
||||
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
|
||||
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
|
||||
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
|
||||
uiAppendStyle(s);
|
||||
}
|
||||
@@ -9306,7 +9306,7 @@ void main() {
|
||||
const agentDot = el('span', {
|
||||
position: 'absolute', right: '-1px', bottom: '7px',
|
||||
width: '6px', height: '6px', borderRadius: '50%',
|
||||
background: 'oklch(78% 0.14 75)',
|
||||
background: 'oklch(77% 0.13 82)',
|
||||
boxShadow: '0 0 0 2px ' + P.surface,
|
||||
display: 'none', pointerEvents: 'none',
|
||||
});
|
||||
@@ -9408,11 +9408,11 @@ void main() {
|
||||
// DESIGN.md panel toggle - quartet of color squares as the mark.
|
||||
const designBtn = makeIconBtn({
|
||||
id: PREFIX + '-design-toggle',
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
|
||||
<span style="background:oklch(84% 0.19 80.46)"></span>
|
||||
<span style="background:oklch(70% 0.12 188)"></span>
|
||||
<span style="background:oklch(84% 0.035 82)"></span>
|
||||
<span style="background:oklch(34% 0.014 82)"></span>
|
||||
<span style="background:oklch(91% 0 0)"></span>
|
||||
<span style="background:oklch(34% 0 0)"></span>
|
||||
</span>`,
|
||||
label: 'DESIGN.md',
|
||||
ariaLabel: 'Toggle DESIGN.md panel',
|
||||
@@ -9996,8 +9996,8 @@ void main() {
|
||||
meta: 'oklch(55% 0 0)',
|
||||
hairline: 'oklch(88% 0 0)',
|
||||
hairlineSoft: 'oklch(92% 0 0)',
|
||||
amber: 'oklch(70% 0.13 65)', // stale-hint accent
|
||||
amberBg: 'oklch(95% 0.05 80)',
|
||||
amber: 'oklch(77% 0.13 82)', // stale-hint accent
|
||||
amberBg: 'oklch(89% 0.055 84)',
|
||||
};
|
||||
|
||||
function designPanelCss(BP) {
|
||||
@@ -10088,7 +10088,7 @@ void main() {
|
||||
}
|
||||
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
|
||||
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
|
||||
.error { color: oklch(45% 0.15 25); }
|
||||
.error { color: oklch(58% 0.15 35); }
|
||||
|
||||
/* Stale hint */
|
||||
.stale {
|
||||
@@ -10240,8 +10240,8 @@ void main() {
|
||||
content: ''; position: absolute; left: 4px; top: 13px;
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
}
|
||||
.coll .do::before { background: oklch(62% 0.16 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.22 25); }
|
||||
.coll .do::before { background: oklch(45% 0.18 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.15 35); }
|
||||
|
||||
.coll .overview-body {
|
||||
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.6.0
|
||||
version: 3.7.0
|
||||
license: Apache 2.0
|
||||
---
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
@@ -2681,12 +2681,12 @@
|
||||
});
|
||||
const check = el('span', {
|
||||
fontSize: '15px', lineHeight: '1', flexShrink: '0',
|
||||
color: 'oklch(45% 0.15 145)',
|
||||
color: 'oklch(45% 0.18 145)',
|
||||
});
|
||||
check.textContent = '\u2713';
|
||||
row.appendChild(check);
|
||||
const label = el('span', {
|
||||
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
|
||||
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
|
||||
});
|
||||
label.textContent = 'Variant applied';
|
||||
row.appendChild(label);
|
||||
@@ -8192,7 +8192,7 @@ void main() {
|
||||
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
|
||||
const STEER_AWAIT_TIMEOUT_MS = 120000;
|
||||
const AGENT_STATUS_POLL_MS = 5000;
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
|
||||
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
|
||||
const GLOBAL_BAR_SECTION_GAP = 8;
|
||||
const GLOBAL_BAR_INNER_GAP = 2;
|
||||
@@ -8259,8 +8259,8 @@ void main() {
|
||||
// Neutral hairline for internal control borders / dividers (was a warm
|
||||
// gold rule that read as muddy champagne edges on the pill / input / count).
|
||||
hairline: 'oklch(92% 0 0 / 0.12)',
|
||||
text: 'oklch(84% 0.035 82)',
|
||||
textDim: 'oklch(63% 0.024 82)',
|
||||
text: 'oklch(91% 0 0)',
|
||||
textDim: 'oklch(72% 0 0)',
|
||||
accent: C.brand,
|
||||
accentSoft: C.brandSoft,
|
||||
exitHover: 'oklch(58% 0.15 35 / 0.18)',
|
||||
@@ -9064,9 +9064,9 @@ void main() {
|
||||
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
|
||||
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
|
||||
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
|
||||
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
|
||||
uiAppendStyle(s);
|
||||
}
|
||||
@@ -9306,7 +9306,7 @@ void main() {
|
||||
const agentDot = el('span', {
|
||||
position: 'absolute', right: '-1px', bottom: '7px',
|
||||
width: '6px', height: '6px', borderRadius: '50%',
|
||||
background: 'oklch(78% 0.14 75)',
|
||||
background: 'oklch(77% 0.13 82)',
|
||||
boxShadow: '0 0 0 2px ' + P.surface,
|
||||
display: 'none', pointerEvents: 'none',
|
||||
});
|
||||
@@ -9408,11 +9408,11 @@ void main() {
|
||||
// DESIGN.md panel toggle - quartet of color squares as the mark.
|
||||
const designBtn = makeIconBtn({
|
||||
id: PREFIX + '-design-toggle',
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
|
||||
<span style="background:oklch(84% 0.19 80.46)"></span>
|
||||
<span style="background:oklch(70% 0.12 188)"></span>
|
||||
<span style="background:oklch(84% 0.035 82)"></span>
|
||||
<span style="background:oklch(34% 0.014 82)"></span>
|
||||
<span style="background:oklch(91% 0 0)"></span>
|
||||
<span style="background:oklch(34% 0 0)"></span>
|
||||
</span>`,
|
||||
label: 'DESIGN.md',
|
||||
ariaLabel: 'Toggle DESIGN.md panel',
|
||||
@@ -9996,8 +9996,8 @@ void main() {
|
||||
meta: 'oklch(55% 0 0)',
|
||||
hairline: 'oklch(88% 0 0)',
|
||||
hairlineSoft: 'oklch(92% 0 0)',
|
||||
amber: 'oklch(70% 0.13 65)', // stale-hint accent
|
||||
amberBg: 'oklch(95% 0.05 80)',
|
||||
amber: 'oklch(77% 0.13 82)', // stale-hint accent
|
||||
amberBg: 'oklch(89% 0.055 84)',
|
||||
};
|
||||
|
||||
function designPanelCss(BP) {
|
||||
@@ -10088,7 +10088,7 @@ void main() {
|
||||
}
|
||||
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
|
||||
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
|
||||
.error { color: oklch(45% 0.15 25); }
|
||||
.error { color: oklch(58% 0.15 35); }
|
||||
|
||||
/* Stale hint */
|
||||
.stale {
|
||||
@@ -10240,8 +10240,8 @@ void main() {
|
||||
content: ''; position: absolute; left: 4px; top: 13px;
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
}
|
||||
.coll .do::before { background: oklch(62% 0.16 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.22 25); }
|
||||
.coll .do::before { background: oklch(45% 0.18 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.15 35); }
|
||||
|
||||
.coll .overview-body {
|
||||
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.6.0
|
||||
version: 3.7.0
|
||||
---
|
||||
|
||||
Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
|
||||
|
||||
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
@@ -2681,12 +2681,12 @@
|
||||
});
|
||||
const check = el('span', {
|
||||
fontSize: '15px', lineHeight: '1', flexShrink: '0',
|
||||
color: 'oklch(45% 0.15 145)',
|
||||
color: 'oklch(45% 0.18 145)',
|
||||
});
|
||||
check.textContent = '\u2713';
|
||||
row.appendChild(check);
|
||||
const label = el('span', {
|
||||
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
|
||||
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
|
||||
});
|
||||
label.textContent = 'Variant applied';
|
||||
row.appendChild(label);
|
||||
@@ -8192,7 +8192,7 @@ void main() {
|
||||
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
|
||||
const STEER_AWAIT_TIMEOUT_MS = 120000;
|
||||
const AGENT_STATUS_POLL_MS = 5000;
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
|
||||
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
|
||||
const GLOBAL_BAR_SECTION_GAP = 8;
|
||||
const GLOBAL_BAR_INNER_GAP = 2;
|
||||
@@ -8259,8 +8259,8 @@ void main() {
|
||||
// Neutral hairline for internal control borders / dividers (was a warm
|
||||
// gold rule that read as muddy champagne edges on the pill / input / count).
|
||||
hairline: 'oklch(92% 0 0 / 0.12)',
|
||||
text: 'oklch(84% 0.035 82)',
|
||||
textDim: 'oklch(63% 0.024 82)',
|
||||
text: 'oklch(91% 0 0)',
|
||||
textDim: 'oklch(72% 0 0)',
|
||||
accent: C.brand,
|
||||
accentSoft: C.brandSoft,
|
||||
exitHover: 'oklch(58% 0.15 35 / 0.18)',
|
||||
@@ -9064,9 +9064,9 @@ void main() {
|
||||
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
|
||||
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
|
||||
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
|
||||
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
|
||||
uiAppendStyle(s);
|
||||
}
|
||||
@@ -9306,7 +9306,7 @@ void main() {
|
||||
const agentDot = el('span', {
|
||||
position: 'absolute', right: '-1px', bottom: '7px',
|
||||
width: '6px', height: '6px', borderRadius: '50%',
|
||||
background: 'oklch(78% 0.14 75)',
|
||||
background: 'oklch(77% 0.13 82)',
|
||||
boxShadow: '0 0 0 2px ' + P.surface,
|
||||
display: 'none', pointerEvents: 'none',
|
||||
});
|
||||
@@ -9408,11 +9408,11 @@ void main() {
|
||||
// DESIGN.md panel toggle - quartet of color squares as the mark.
|
||||
const designBtn = makeIconBtn({
|
||||
id: PREFIX + '-design-toggle',
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
|
||||
<span style="background:oklch(84% 0.19 80.46)"></span>
|
||||
<span style="background:oklch(70% 0.12 188)"></span>
|
||||
<span style="background:oklch(84% 0.035 82)"></span>
|
||||
<span style="background:oklch(34% 0.014 82)"></span>
|
||||
<span style="background:oklch(91% 0 0)"></span>
|
||||
<span style="background:oklch(34% 0 0)"></span>
|
||||
</span>`,
|
||||
label: 'DESIGN.md',
|
||||
ariaLabel: 'Toggle DESIGN.md panel',
|
||||
@@ -9996,8 +9996,8 @@ void main() {
|
||||
meta: 'oklch(55% 0 0)',
|
||||
hairline: 'oklch(88% 0 0)',
|
||||
hairlineSoft: 'oklch(92% 0 0)',
|
||||
amber: 'oklch(70% 0.13 65)', // stale-hint accent
|
||||
amberBg: 'oklch(95% 0.05 80)',
|
||||
amber: 'oklch(77% 0.13 82)', // stale-hint accent
|
||||
amberBg: 'oklch(89% 0.055 84)',
|
||||
};
|
||||
|
||||
function designPanelCss(BP) {
|
||||
@@ -10088,7 +10088,7 @@ void main() {
|
||||
}
|
||||
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
|
||||
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
|
||||
.error { color: oklch(45% 0.15 25); }
|
||||
.error { color: oklch(58% 0.15 35); }
|
||||
|
||||
/* Stale hint */
|
||||
.stale {
|
||||
@@ -10240,8 +10240,8 @@ void main() {
|
||||
content: ''; position: absolute; left: 4px; top: 13px;
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
}
|
||||
.coll .do::before { background: oklch(62% 0.16 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.22 25); }
|
||||
.coll .do::before { background: oklch(45% 0.18 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.15 35); }
|
||||
|
||||
.coll .overview-body {
|
||||
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.6.0
|
||||
version: 3.7.0
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
|
||||
license: Apache 2.0
|
||||
|
||||
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
@@ -2681,12 +2681,12 @@
|
||||
});
|
||||
const check = el('span', {
|
||||
fontSize: '15px', lineHeight: '1', flexShrink: '0',
|
||||
color: 'oklch(45% 0.15 145)',
|
||||
color: 'oklch(45% 0.18 145)',
|
||||
});
|
||||
check.textContent = '\u2713';
|
||||
row.appendChild(check);
|
||||
const label = el('span', {
|
||||
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
|
||||
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
|
||||
});
|
||||
label.textContent = 'Variant applied';
|
||||
row.appendChild(label);
|
||||
@@ -8192,7 +8192,7 @@ void main() {
|
||||
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
|
||||
const STEER_AWAIT_TIMEOUT_MS = 120000;
|
||||
const AGENT_STATUS_POLL_MS = 5000;
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
|
||||
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
|
||||
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
|
||||
const GLOBAL_BAR_SECTION_GAP = 8;
|
||||
const GLOBAL_BAR_INNER_GAP = 2;
|
||||
@@ -8259,8 +8259,8 @@ void main() {
|
||||
// Neutral hairline for internal control borders / dividers (was a warm
|
||||
// gold rule that read as muddy champagne edges on the pill / input / count).
|
||||
hairline: 'oklch(92% 0 0 / 0.12)',
|
||||
text: 'oklch(84% 0.035 82)',
|
||||
textDim: 'oklch(63% 0.024 82)',
|
||||
text: 'oklch(91% 0 0)',
|
||||
textDim: 'oklch(72% 0 0)',
|
||||
accent: C.brand,
|
||||
accentSoft: C.brandSoft,
|
||||
exitHover: 'oklch(58% 0.15 35 / 0.18)',
|
||||
@@ -9064,9 +9064,9 @@ void main() {
|
||||
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
|
||||
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
|
||||
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
|
||||
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
|
||||
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
|
||||
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
|
||||
uiAppendStyle(s);
|
||||
}
|
||||
@@ -9306,7 +9306,7 @@ void main() {
|
||||
const agentDot = el('span', {
|
||||
position: 'absolute', right: '-1px', bottom: '7px',
|
||||
width: '6px', height: '6px', borderRadius: '50%',
|
||||
background: 'oklch(78% 0.14 75)',
|
||||
background: 'oklch(77% 0.13 82)',
|
||||
boxShadow: '0 0 0 2px ' + P.surface,
|
||||
display: 'none', pointerEvents: 'none',
|
||||
});
|
||||
@@ -9408,11 +9408,11 @@ void main() {
|
||||
// DESIGN.md panel toggle - quartet of color squares as the mark.
|
||||
const designBtn = makeIconBtn({
|
||||
id: PREFIX + '-design-toggle',
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
|
||||
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
|
||||
<span style="background:oklch(84% 0.19 80.46)"></span>
|
||||
<span style="background:oklch(70% 0.12 188)"></span>
|
||||
<span style="background:oklch(84% 0.035 82)"></span>
|
||||
<span style="background:oklch(34% 0.014 82)"></span>
|
||||
<span style="background:oklch(91% 0 0)"></span>
|
||||
<span style="background:oklch(34% 0 0)"></span>
|
||||
</span>`,
|
||||
label: 'DESIGN.md',
|
||||
ariaLabel: 'Toggle DESIGN.md panel',
|
||||
@@ -9996,8 +9996,8 @@ void main() {
|
||||
meta: 'oklch(55% 0 0)',
|
||||
hairline: 'oklch(88% 0 0)',
|
||||
hairlineSoft: 'oklch(92% 0 0)',
|
||||
amber: 'oklch(70% 0.13 65)', // stale-hint accent
|
||||
amberBg: 'oklch(95% 0.05 80)',
|
||||
amber: 'oklch(77% 0.13 82)', // stale-hint accent
|
||||
amberBg: 'oklch(89% 0.055 84)',
|
||||
};
|
||||
|
||||
function designPanelCss(BP) {
|
||||
@@ -10088,7 +10088,7 @@ void main() {
|
||||
}
|
||||
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
|
||||
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
|
||||
.error { color: oklch(45% 0.15 25); }
|
||||
.error { color: oklch(58% 0.15 35); }
|
||||
|
||||
/* Stale hint */
|
||||
.stale {
|
||||
@@ -10240,8 +10240,8 @@ void main() {
|
||||
content: ''; position: absolute; left: 4px; top: 13px;
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
}
|
||||
.coll .do::before { background: oklch(62% 0.16 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.22 25); }
|
||||
.coll .do::before { background: oklch(45% 0.18 145); }
|
||||
.coll .dont::before { background: oklch(58% 0.15 35); }
|
||||
|
||||
.coll .overview-body {
|
||||
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.6.0
|
||||
version: 3.7.0
|
||||
license: Apache 2.0
|
||||
---
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
|
||||
|
||||
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
|
||||
|
||||
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
|
||||
|
||||
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
|
||||
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
|
||||
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
|
||||
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
|
||||
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
|
||||
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
|
||||
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
|
||||
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
|
||||
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
|
||||
|
||||
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { loadDesignSystemForCwd } from '../design-system.mjs';
|
||||
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
|
||||
import { detectHtml } from '../engines/static-html/detect-html.mjs';
|
||||
import { detectText } from '../engines/regex/detect-text.mjs';
|
||||
import {
|
||||
filterDetectionFindings,
|
||||
readDetectionConfig,
|
||||
shouldIgnoreDetectionFile,
|
||||
} from '../../lib/impeccable-config.mjs';
|
||||
import {
|
||||
HTML_EXTENSIONS,
|
||||
buildImportGraph,
|
||||
@@ -79,10 +85,17 @@ function printUsage() {
|
||||
Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
|
||||
Options:
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--no-config Do not apply project config, detector ignores, or DESIGN.md
|
||||
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
|
||||
--help Show this help message
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
and detector.designSystem.enabled.
|
||||
|
||||
Detection modes:
|
||||
HTML files Static HTML/CSS analysis (default, catches linked CSS)
|
||||
@@ -93,7 +106,8 @@ Examples:
|
||||
impeccable detect src/
|
||||
impeccable detect index.html
|
||||
impeccable detect https://example.com
|
||||
impeccable detect --json .`);
|
||||
impeccable detect --json .
|
||||
impeccable detect --no-config src/`);
|
||||
}
|
||||
|
||||
async function detectCli() {
|
||||
@@ -114,10 +128,16 @@ async function detectCli() {
|
||||
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
|
||||
);
|
||||
}
|
||||
const configEnabled = !args.includes('--no-config');
|
||||
const detectionConfig = configEnabled
|
||||
? readDetectionConfig(process.cwd())
|
||||
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
|
||||
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
|
||||
const scanOptions = designSystem ? { providers, designSystem } : { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -175,7 +195,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved);
|
||||
const files = walkDir(resolved)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
|
||||
@@ -219,6 +240,7 @@ async function detectCli() {
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
@@ -232,6 +254,8 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
allFindings = filterDetectionFindings(allFindings, detectionConfig);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { finding } from './findings.mjs';
|
||||
import { GENERIC_FONTS } from './shared/constants.mjs';
|
||||
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
|
||||
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
const COLOR_CHANNEL_TOLERANCE = 6;
|
||||
const RADIUS_TOLERANCE_PX = 0.5;
|
||||
|
||||
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
|
||||
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
|
||||
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
|
||||
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
|
||||
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
|
||||
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignMdPath(cwd = process.cwd()) {
|
||||
const root = firstExisting(cwd, DESIGN_NAMES);
|
||||
if (root) return { path: root, contextDir: cwd };
|
||||
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const dir = path.resolve(cwd, rel);
|
||||
const found = firstExisting(dir, DESIGN_NAMES);
|
||||
if (found) return { path: found, contextDir: dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
|
||||
const candidates = [
|
||||
path.join(cwd, '.impeccable', 'design.json'),
|
||||
path.join(cwd, 'DESIGN.json'),
|
||||
path.join(contextDir, 'DESIGN.json'),
|
||||
];
|
||||
return candidates.find((candidate, index) =>
|
||||
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
|
||||
) || null;
|
||||
}
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = String(md || '').split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return null;
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return null;
|
||||
try {
|
||||
return parseYamlSubset(lines.slice(1, end).join('\n'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseYamlSubset(yaml) {
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of String(yaml || '').split(/\r?\n/)) {
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
if (!filePath) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function splitFontStack(stack) {
|
||||
return String(stack || '')
|
||||
.replace(/\s*!important\s*$/i, '')
|
||||
.split(',')
|
||||
.map(normalizeFontName)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function primaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
|
||||
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function isLiteralFontStack(stack) {
|
||||
const text = String(stack || '');
|
||||
return !/[$`{}]|\s\+\s|\|\|/.test(text);
|
||||
}
|
||||
|
||||
function cssColorLabel(raw) {
|
||||
return String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function colorKey(color) {
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b}`;
|
||||
}
|
||||
|
||||
function colorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= COLOR_CHANNEL_TOLERANCE;
|
||||
}
|
||||
|
||||
function hslToRgb(H, S, L, alpha = 1) {
|
||||
const h = (((H % 360) + 360) % 360) / 360;
|
||||
const s = Math.max(0, Math.min(1, S));
|
||||
const l = Math.max(0, Math.min(1, L));
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return {
|
||||
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
|
||||
g: Math.round(hue2rgb(p, q, h) * 255),
|
||||
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDesignColor(value) {
|
||||
const text = String(value || '').trim();
|
||||
const parsed = parseAnyColor(text);
|
||||
if (parsed) return parsed;
|
||||
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
|
||||
if (hsl) {
|
||||
return hslToRgb(
|
||||
parseFloat(hsl[1]),
|
||||
parseFloat(hsl[2]) / 100,
|
||||
parseFloat(hsl[3]) / 100,
|
||||
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addDesignColor(out, value, label) {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (!parsed) return;
|
||||
const key = colorKey(parsed);
|
||||
if (!out.allowedColorKeys.has(key)) {
|
||||
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
|
||||
}
|
||||
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
|
||||
}
|
||||
|
||||
function addColorObject(out, colors, prefix = 'colors') {
|
||||
if (!colors || typeof colors !== 'object') return;
|
||||
for (const [name, value] of Object.entries(colors)) {
|
||||
if (typeof value === 'string') {
|
||||
addDesignColor(out, value, `${prefix}.${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addSidecarColors(out, sidecar) {
|
||||
const colorMeta = sidecar?.extensions?.colorMeta;
|
||||
if (!colorMeta || typeof colorMeta !== 'object') return;
|
||||
|
||||
for (const [name, meta] of Object.entries(colorMeta)) {
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
|
||||
if (Array.isArray(meta.tonalRamp)) {
|
||||
for (const [index, value] of meta.tonalRamp.entries()) {
|
||||
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addTypographyFonts(out, typography) {
|
||||
if (!typography || typeof typography !== 'object') return;
|
||||
for (const role of Object.values(typography)) {
|
||||
if (!role || typeof role !== 'object') continue;
|
||||
if (typeof role.fontFamily !== 'string') continue;
|
||||
for (const font of splitFontStack(role.fontFamily)) {
|
||||
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedScale(out, rounded) {
|
||||
if (!rounded || typeof rounded !== 'object') return;
|
||||
for (const [rawName, value] of Object.entries(rounded)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
addRoundedToken(out, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundedToken(out, name, value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return;
|
||||
const raw = String(value).trim();
|
||||
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
|
||||
const px = resolveLengthPx(raw, 16);
|
||||
if (px == null || !Number.isFinite(px)) return;
|
||||
out.allowedRadii.push({ name, value: raw, px });
|
||||
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
|
||||
}
|
||||
|
||||
function addSidecarRadii(out, sidecar) {
|
||||
const roundedMeta = sidecar?.extensions?.roundedMeta;
|
||||
if (!roundedMeta || typeof roundedMeta !== 'object') return;
|
||||
|
||||
for (const [rawName, meta] of Object.entries(roundedMeta)) {
|
||||
const name = unquoteYamlKey(rawName).toLowerCase();
|
||||
if (typeof meta === 'string' || typeof meta === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}`, meta);
|
||||
continue;
|
||||
}
|
||||
if (!meta || typeof meta !== 'object') continue;
|
||||
for (const key of ['canonical', 'value']) {
|
||||
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
|
||||
}
|
||||
}
|
||||
for (const key of ['values', 'aliases']) {
|
||||
if (!Array.isArray(meta[key])) continue;
|
||||
for (const [index, value] of meta[key].entries()) {
|
||||
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
|
||||
}
|
||||
}
|
||||
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
|
||||
out.hasPillRadius = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDesignSystem(input = {}) {
|
||||
const frontmatter = input.frontmatter || {};
|
||||
const sidecar = input.sidecar || null;
|
||||
const out = {
|
||||
present: true,
|
||||
sourcePath: input.sourcePath || null,
|
||||
sidecarPath: input.sidecarPath || null,
|
||||
mdNewerThanJson: input.mdNewerThanJson === true,
|
||||
allowedFonts: new Set(),
|
||||
allowedColorKeys: new Map(),
|
||||
allowedRadii: [],
|
||||
hasPillRadius: false,
|
||||
};
|
||||
|
||||
addTypographyFonts(out, frontmatter.typography);
|
||||
addColorObject(out, frontmatter.colors);
|
||||
addSidecarColors(out, sidecar);
|
||||
addRoundedScale(out, frontmatter.rounded);
|
||||
addSidecarRadii(out, sidecar);
|
||||
|
||||
out.hasFonts = out.allowedFonts.size > 0;
|
||||
out.hasColors = out.allowedColorKeys.size > 0;
|
||||
out.hasRadii = out.allowedRadii.length > 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadDesignSystemForCwd(cwd = process.cwd()) {
|
||||
const md = resolveDesignMdPath(cwd);
|
||||
if (!md) return null;
|
||||
|
||||
let frontmatter = null;
|
||||
let mdStat = null;
|
||||
try {
|
||||
mdStat = fs.statSync(md.path);
|
||||
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!frontmatter || typeof frontmatter !== 'object') return null;
|
||||
|
||||
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
|
||||
const sidecar = safeReadJson(sidecarPath);
|
||||
let sidecarStat = null;
|
||||
try {
|
||||
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
|
||||
} catch {
|
||||
sidecarStat = null;
|
||||
}
|
||||
|
||||
return normalizeDesignSystem({
|
||||
frontmatter,
|
||||
sidecar,
|
||||
sourcePath: md.path,
|
||||
sidecarPath,
|
||||
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function isAllowedFont(font, designSystem) {
|
||||
if (!font || GENERIC_FONTS.has(font)) return true;
|
||||
if (!designSystem?.hasFonts) return true;
|
||||
return designSystem.allowedFonts.has(font);
|
||||
}
|
||||
|
||||
function isAllowedColorRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
for (const entry of designSystem.allowedColorKeys.values()) {
|
||||
if (colorsClose(parsed, entry.color)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedRadiusRaw(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function lineLooksCommented(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
|
||||
}
|
||||
|
||||
function isProbablyColorLiteral(line, match) {
|
||||
const raw = match?.[0] || '';
|
||||
const index = match.index ?? -1;
|
||||
if (index < 0) return false;
|
||||
if (isInsideCssAttributeSelector(line, index)) return false;
|
||||
|
||||
const before = line.slice(0, index);
|
||||
const after = line.slice(index + raw.length);
|
||||
|
||||
if (raw.startsWith('#')) {
|
||||
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. ↔
|
||||
|
||||
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
|
||||
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
|
||||
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
|
||||
}
|
||||
|
||||
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
|
||||
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
|
||||
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
|
||||
|
||||
return styleContext || cssFunctionContext || jsColorKeyContext;
|
||||
}
|
||||
|
||||
function isInsideCssAttributeSelector(line, index) {
|
||||
if (index < 0) return false;
|
||||
const before = line.slice(0, index);
|
||||
const lastOpen = before.lastIndexOf('[');
|
||||
if (lastOpen === -1) return false;
|
||||
const lastClose = before.lastIndexOf(']');
|
||||
if (lastClose > lastOpen) return false;
|
||||
const after = line.slice(index);
|
||||
const close = after.indexOf(']');
|
||||
const block = after.indexOf('{');
|
||||
return close !== -1 && (block === -1 || close < block);
|
||||
}
|
||||
|
||||
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
|
||||
return { ...finding(id, filePath, snippet, line), ...extras };
|
||||
}
|
||||
|
||||
function decodeGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkFontStack(stack, filePath, line, designSystem, context) {
|
||||
const primary = primaryFont(stack);
|
||||
if (!primary || isAllowedFont(primary, designSystem)) return [];
|
||||
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
|
||||
return [makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${context}: ${display} is not declared in DESIGN.md typography`,
|
||||
line,
|
||||
{ ignoreValue: display },
|
||||
)];
|
||||
}
|
||||
|
||||
function extractRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function checkRadiusValue(value, filePath, line, designSystem, context) {
|
||||
const findings = [];
|
||||
for (const token of extractRadiusTokens(value)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`${context}: ${token} is outside the DESIGN.md rounded scale`,
|
||||
line,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkSourceDesignSystem(content, filePath, options = {}) {
|
||||
const designSystem = options.designSystem;
|
||||
if (!designSystem?.present) return [];
|
||||
|
||||
const findings = [];
|
||||
const lines = String(content || '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNum = i + 1;
|
||||
if (lineLooksCommented(line)) continue;
|
||||
|
||||
if (designSystem.hasFonts) {
|
||||
for (const match of line.matchAll(FONT_DECL_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
|
||||
}
|
||||
for (const match of line.matchAll(FONT_JS_RE)) {
|
||||
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
|
||||
}
|
||||
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
|
||||
const url = match[0];
|
||||
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
|
||||
if (!font || isAllowedFont(font, designSystem)) continue;
|
||||
const display = decodeGoogleFamily(familyMatch[1]);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
lineNum,
|
||||
{ ignoreValue: display },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
for (const match of line.matchAll(CSS_COLOR_RE)) {
|
||||
if (!isProbablyColorLiteral(line, match)) continue;
|
||||
const raw = cssColorLabel(match[0]);
|
||||
if (isAllowedColorRaw(raw, designSystem)) continue;
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`Undocumented color ${raw} is outside DESIGN.md colors`,
|
||||
lineNum,
|
||||
{ ignoreValue: raw },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
|
||||
}
|
||||
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
|
||||
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeDesignFindings(findings);
|
||||
}
|
||||
|
||||
function hasDirectText(el) {
|
||||
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function sampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
|
||||
if (!designSystem?.present) return [];
|
||||
const findings = [];
|
||||
const seenFonts = new Set();
|
||||
const seenColors = new Set();
|
||||
const seenRadii = new Set();
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
if (shouldSkipStaticDesignElement(el, window)) continue;
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = window.getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && hasDirectText(el)) {
|
||||
const font = primaryFont(style.fontFamily || '');
|
||||
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
|
||||
seenFonts.add(font);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-font',
|
||||
filePath,
|
||||
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
0,
|
||||
{ ignoreValue: font },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = cssColorLabel(raw);
|
||||
if (isAllowedColorRaw(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seenColors.has(key)) continue;
|
||||
seenColors.add(key);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-color',
|
||||
filePath,
|
||||
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
|
||||
0,
|
||||
{ ignoreValue: label },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
const rawRadius = String(style.borderRadius || '').trim();
|
||||
if (!rawRadius) continue;
|
||||
for (const token of extractRadiusTokens(rawRadius)) {
|
||||
if (isAllowedRadiusRaw(token, designSystem)) continue;
|
||||
if (seenRadii.has(token)) continue;
|
||||
seenRadii.add(token);
|
||||
findings.push(makeDesignFinding(
|
||||
'design-system-radius',
|
||||
filePath,
|
||||
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
0,
|
||||
{ ignoreValue: token },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function shouldSkipStaticDesignElement(el, window) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
|
||||
|
||||
let current = el;
|
||||
while (current) {
|
||||
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
const style = window.getComputedStyle(current);
|
||||
const display = String(style.display || '').toLowerCase();
|
||||
const visibility = String(style.visibility || '').toLowerCase();
|
||||
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseDesignColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function canonicalDesignFindingKey(item) {
|
||||
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
|
||||
const value = item.ignoreValue || item.value || '';
|
||||
if (item.antipattern === 'design-system-font') {
|
||||
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
|
||||
const font = normalizeFontName(value);
|
||||
return font ? `${item.antipattern}:${context}:${font}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-color') {
|
||||
const parsed = parseDesignColor(value);
|
||||
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
|
||||
const label = cssColorLabel(value).toLowerCase();
|
||||
return label ? `${item.antipattern}:color:${label}` : null;
|
||||
}
|
||||
if (item.antipattern === 'design-system-radius') {
|
||||
const px = resolveLengthPx(String(value || '').trim(), 16);
|
||||
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
|
||||
const label = String(value || '').trim().toLowerCase();
|
||||
return label ? `${item.antipattern}:radius:${label}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mergeDesignSystemFindings(...groups) {
|
||||
const out = [];
|
||||
const seen = new Map();
|
||||
for (const group of groups) {
|
||||
for (const item of group || []) {
|
||||
const key = canonicalDesignFindingKey(item);
|
||||
if (key) {
|
||||
if (seen.has(key)) {
|
||||
const existing = out[seen.get(key)];
|
||||
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
|
||||
continue;
|
||||
}
|
||||
seen.set(key, out.length);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dedupeDesignFindings(findings) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const item of findings) {
|
||||
const key = [
|
||||
item.antipattern,
|
||||
item.line || 0,
|
||||
normalizeFontName(item.ignoreValue || item.snippet || ''),
|
||||
].join('\0');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export {
|
||||
parseFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
isAllowedFont,
|
||||
isAllowedColorRaw,
|
||||
isAllowedRadiusRaw,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
};
|
||||
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
@@ -4394,6 +4423,7 @@ if (IS_BROWSER) {
|
||||
category: ap ? ap.category : 'quality',
|
||||
severity: ap?.severity || 'warning',
|
||||
detail: f.detail || f.snippet,
|
||||
ignoreValue: f.ignoreValue || f.value || '',
|
||||
name: ap ? ap.name : (f.type || f.id),
|
||||
description: ap ? ap.description : '',
|
||||
};
|
||||
@@ -4430,10 +4460,203 @@ if (IS_BROWSER) {
|
||||
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
|
||||
}
|
||||
|
||||
const DESIGN_COLOR_TOLERANCE = 6;
|
||||
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
|
||||
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
|
||||
|
||||
function normalizeBrowserFontName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function browserPrimaryFont(stack) {
|
||||
if (!stack || /var\(/i.test(stack)) return '';
|
||||
return String(stack || '')
|
||||
.split(',')
|
||||
.map(normalizeBrowserFontName)
|
||||
.find(font => font && !GENERIC_FONTS.has(font)) || '';
|
||||
}
|
||||
|
||||
function browserDesignSystemConfig() {
|
||||
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
|
||||
if (!raw?.present) return null;
|
||||
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
|
||||
const allowedColors = (raw.allowedColors || [])
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b }));
|
||||
const allowedRadii = (raw.allowedRadii || [])
|
||||
.map(Number)
|
||||
.filter(px => Number.isFinite(px));
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
|
||||
allowedFonts,
|
||||
hasColors: raw.hasColors === true && allowedColors.length > 0,
|
||||
allowedColors,
|
||||
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
|
||||
allowedRadii,
|
||||
hasPillRadius: raw.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
function browserColorsClose(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return Math.max(
|
||||
Math.abs(a.r - b.r),
|
||||
Math.abs(a.g - b.g),
|
||||
Math.abs(a.b - b.b),
|
||||
) <= DESIGN_COLOR_TOLERANCE;
|
||||
}
|
||||
|
||||
function isBrowserDesignColorAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasColors) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
|
||||
if (text.includes('var(')) return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
if (!parsed) return true;
|
||||
if ((parsed.a ?? 1) <= 0.05) return true;
|
||||
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
|
||||
}
|
||||
|
||||
function isBrowserTransparentCss(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text || text === 'transparent') return true;
|
||||
const parsed = parseAnyColor(text);
|
||||
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
|
||||
}
|
||||
|
||||
function isBrowserDesignRadiusAllowed(raw, designSystem) {
|
||||
if (!designSystem?.hasRadii) return true;
|
||||
const text = String(raw || '').trim().toLowerCase();
|
||||
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
|
||||
if (text.includes('var(') || text.includes('%')) return true;
|
||||
const px = resolveLengthPx(text, 16);
|
||||
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
|
||||
if (designSystem.hasPillRadius && px >= 99) return true;
|
||||
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
|
||||
}
|
||||
|
||||
function browserRadiusTokens(value) {
|
||||
return String(value || '')
|
||||
.replace(/\s*\/\s*/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map(token => token.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function browserHasDirectText(el) {
|
||||
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
|
||||
}
|
||||
|
||||
function browserSampleText(el) {
|
||||
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
return text ? ` "${text.slice(0, 40)}"` : '';
|
||||
}
|
||||
|
||||
function shouldSkipDesignElement(el) {
|
||||
const tag = el.tagName?.toLowerCase?.() || '';
|
||||
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
|
||||
}
|
||||
|
||||
function checkElementDesignSystemDOM(el, designSystem, seen) {
|
||||
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
|
||||
const findings = [];
|
||||
const tag = el.tagName?.toLowerCase?.() || 'unknown';
|
||||
const style = getComputedStyle(el);
|
||||
|
||||
if (designSystem.hasFonts && browserHasDirectText(el)) {
|
||||
const font = browserPrimaryFont(style.fontFamily || '');
|
||||
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
|
||||
ignoreValue: font,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasColors) {
|
||||
const colorChecks = [];
|
||||
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
|
||||
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
|
||||
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
|
||||
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
|
||||
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
|
||||
}
|
||||
}
|
||||
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
|
||||
|
||||
for (const [kind, raw] of colorChecks) {
|
||||
const label = String(raw || '').trim().replace(/\s+/g, ' ');
|
||||
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
|
||||
const key = `${kind}:${label}`;
|
||||
if (seen.colors.has(key)) continue;
|
||||
seen.colors.add(key);
|
||||
findings.push({
|
||||
type: 'design-system-color',
|
||||
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
|
||||
ignoreValue: label,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (designSystem.hasRadii) {
|
||||
for (const token of browserRadiusTokens(style.borderRadius || '')) {
|
||||
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
|
||||
if (seen.radii.has(token)) continue;
|
||||
seen.radii.add(token);
|
||||
findings.push({
|
||||
type: 'design-system-radius',
|
||||
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
|
||||
ignoreValue: token,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function decodeBrowserGoogleFamily(value) {
|
||||
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
|
||||
try {
|
||||
return decodeURIComponent(family);
|
||||
} catch {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
|
||||
function checkBrowserDesignSystemSources(designSystem, seen) {
|
||||
if (!designSystem?.hasFonts) return [];
|
||||
const findings = [];
|
||||
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
|
||||
const href = link.getAttribute('href') || '';
|
||||
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
|
||||
const display = decodeBrowserGoogleFamily(match[1]);
|
||||
const font = normalizeBrowserFontName(display);
|
||||
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
|
||||
seen.fonts.add(font);
|
||||
findings.push({
|
||||
type: 'design-system-font',
|
||||
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
|
||||
ignoreValue: display,
|
||||
});
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
const designSystem = browserDesignSystemConfig();
|
||||
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
@@ -4464,6 +4687,7 @@ if (IS_BROWSER) {
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementDesignSystemDOM(el, designSystem, designSeen),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
@@ -4480,6 +4704,13 @@ if (IS_BROWSER) {
|
||||
|
||||
const pageLevelFindings = [];
|
||||
|
||||
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (designSourceFindings.length > 0) {
|
||||
pageLevelFindings.push(...designSourceFindings);
|
||||
addBrowserFindings(groupMap, document.body, designSourceFindings);
|
||||
}
|
||||
|
||||
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
|
||||
if (typoFindings.length > 0) {
|
||||
pageLevelFindings.push(...typoFindings);
|
||||
|
||||
@@ -23,6 +23,13 @@ export {
|
||||
checkHtmlPatterns,
|
||||
} from './rules/checks.mjs';
|
||||
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
|
||||
export {
|
||||
parseFrontmatter as parseDesignFrontmatter,
|
||||
normalizeDesignSystem,
|
||||
loadDesignSystemForCwd,
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
} from './design-system.mjs';
|
||||
export { detectHtml } from './engines/static-html/detect-html.mjs';
|
||||
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
|
||||
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
|
||||
|
||||
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
function serializeDesignSystemForBrowser(designSystem) {
|
||||
if (!designSystem?.present) return null;
|
||||
return {
|
||||
present: true,
|
||||
hasFonts: designSystem.hasFonts === true,
|
||||
allowedFonts: Array.from(designSystem.allowedFonts || []),
|
||||
hasColors: designSystem.hasColors === true,
|
||||
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
|
||||
.map(entry => entry?.color)
|
||||
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
|
||||
.map(color => ({ r: color.r, g: color.g, b: color.b })),
|
||||
hasRadii: designSystem.hasRadii === true,
|
||||
allowedRadii: (designSystem.allowedRadii || [])
|
||||
.map(entry => Number(entry?.px))
|
||||
.filter(px => Number.isFinite(px)),
|
||||
hasPillRadius: designSystem.hasPillRadius === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
|
||||
if (options?.visualContrast === false) return [];
|
||||
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
|
||||
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
|
||||
}
|
||||
|
||||
// Inject the browser detection script and collect results
|
||||
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
ruleId: 'configure-pure-detect',
|
||||
target: url,
|
||||
}, () => page.evaluate(() => {
|
||||
}, () => page.evaluate((designSystem) => {
|
||||
window.__IMPECCABLE_CONFIG__ = {
|
||||
...(window.__IMPECCABLE_CONFIG__ || {}),
|
||||
autoScan: false,
|
||||
...(designSystem ? { designSystem } : {}),
|
||||
};
|
||||
}));
|
||||
}, browserDesignSystem));
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'scan',
|
||||
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
return window.impeccableDetect({ decorate: false, serialize: true });
|
||||
});
|
||||
return serializedGroups.flatMap(({ findings }) =>
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail }))
|
||||
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
|
||||
);
|
||||
});
|
||||
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
|
||||
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
return filterByProviders(results.map(f => {
|
||||
const item = finding(f.id, url, f.snippet);
|
||||
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
|
||||
return item;
|
||||
}), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { checkSourceDesignSystem } from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
@@ -503,6 +504,15 @@ function detectText(content, filePath, options = {}) {
|
||||
}));
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
|
||||
}
|
||||
|
||||
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
|
||||
const deduped = [];
|
||||
for (const f of findings) {
|
||||
|
||||
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
|
||||
marginBottom: '0px',
|
||||
marginLeft: '0px',
|
||||
position: 'static',
|
||||
visibility: 'visible',
|
||||
top: 'auto',
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
|
||||
'margin-bottom': 'marginBottom',
|
||||
'margin-left': 'marginLeft',
|
||||
'position': 'position',
|
||||
'visibility': 'visibility',
|
||||
'top': 'top',
|
||||
'right': 'right',
|
||||
'bottom': 'bottom',
|
||||
|
||||
@@ -2,6 +2,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
|
||||
import {
|
||||
checkSourceDesignSystem,
|
||||
collectStaticDesignSystemFindings,
|
||||
mergeDesignSystemFindings,
|
||||
} from '../../design-system.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
@@ -168,6 +173,22 @@ async function detectHtml(filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.designSystem) {
|
||||
const sourceDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'source',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
|
||||
const staticDesignFindings = profileFindings(profile, {
|
||||
engine: 'static-html',
|
||||
phase: 'page',
|
||||
ruleId: 'design-system',
|
||||
target: filePath,
|
||||
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
|
||||
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
|
||||
}
|
||||
|
||||
if (isFullPage(html)) {
|
||||
const runPageCheck = (ruleId, callback) => profile
|
||||
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
|
||||
|
||||
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
{
|
||||
id: 'design-system-font',
|
||||
category: 'quality',
|
||||
name: 'Font outside DESIGN.md',
|
||||
description:
|
||||
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'font family outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-color',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Color outside DESIGN.md',
|
||||
description:
|
||||
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'literal color outside the project design system',
|
||||
},
|
||||
{
|
||||
id: 'design-system-radius',
|
||||
category: 'quality',
|
||||
severity: 'advisory',
|
||||
name: 'Radius outside DESIGN.md',
|
||||
description:
|
||||
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'border radius outside the project design system',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook
|
||||
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
|
||||
* in the current project.
|
||||
* `/impeccable hooks <on|off|status|reset>` — manage the design hook runtime
|
||||
* via the `hook` key and shared detector ignores via the `detector` key in
|
||||
* .impeccable/config.json / .impeccable/config.local.json.
|
||||
*
|
||||
* Usage:
|
||||
* node hook-admin.mjs status # print current state
|
||||
@@ -120,23 +120,48 @@ function readRawConfigFile(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hook settings to edit: the unified file's `hook` subtree.
|
||||
function readRawConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
|
||||
return unified.hook;
|
||||
}
|
||||
return null;
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
function hookSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
|
||||
? unified.hook
|
||||
: null;
|
||||
}
|
||||
|
||||
// Write the hook config back under the `hook` key of the unified file, leaving
|
||||
// any sibling keys (e.g. updateCheck) untouched.
|
||||
function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
function detectorSection(unified) {
|
||||
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
|
||||
? unified.detector
|
||||
: null;
|
||||
}
|
||||
|
||||
function readRawHookConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
return hookSection(unified);
|
||||
}
|
||||
|
||||
function readRawDetectorConfig(cwd, opts = {}) {
|
||||
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
|
||||
const merged = mergeDetectorConfig(hookSection(unified));
|
||||
return mergeDetectorConfig(detectorSection(unified), merged);
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Write hook runtime config under `hook`, leaving detector filters in
|
||||
// `detector` and preserving sibling keys such as updateCheck.
|
||||
function writeHookConfig(cwd, hookConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
|
||||
const existingHook = stripDetectorKeys(hookSection(existing));
|
||||
// Merge over the existing hook object so fields the merge helpers don't manage
|
||||
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
|
||||
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
|
||||
@@ -145,15 +170,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeConfig(existing) {
|
||||
// Persist the full shape so /impeccable hooks edits leave a complete file
|
||||
// for the user to see, not an unhelpful `{"enabled":false}`.
|
||||
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
|
||||
if (opts.local) ensureHookGitExcludes(cwd);
|
||||
const existingRaw = readRawConfigFile(filePath).raw;
|
||||
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
|
||||
const nextHook = stripDetectorKeys(hookSection(existing));
|
||||
const existingDetector = mergeDetectorConfig(detectorSection(existing));
|
||||
const next = {
|
||||
...existing,
|
||||
detector: mergeDetectorConfig(detectorConfig, existingDetector),
|
||||
};
|
||||
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
|
||||
else delete next.hook;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function mergeHookConfig(existing) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
return {
|
||||
enabled: base.enabled === false ? false : true,
|
||||
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
|
||||
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
|
||||
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
|
||||
limits: {
|
||||
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
|
||||
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
|
||||
@@ -161,28 +199,54 @@ function mergeConfig(existing) {
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLocalConfig(existing) {
|
||||
function mergeDetectorConfig(existing, seed = null) {
|
||||
const base = existing && typeof existing === 'object' ? existing : {};
|
||||
const out = {};
|
||||
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
|
||||
out.enabled = base.enabled === false ? false : true;
|
||||
const out = seed ? {
|
||||
ignoreRules: [...seed.ignoreRules],
|
||||
ignoreFiles: [...seed.ignoreFiles],
|
||||
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
|
||||
} : {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
|
||||
out.designSystem = { ...seed.designSystem };
|
||||
}
|
||||
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
|
||||
out.designSystem = {
|
||||
...(out.designSystem || {}),
|
||||
enabled: base.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(base.ignoreRules)) {
|
||||
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
|
||||
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
|
||||
}
|
||||
if (Array.isArray(base.ignoreFiles)) {
|
||||
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
|
||||
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
|
||||
if (base.limits && typeof base.limits === 'object') {
|
||||
const limits = {};
|
||||
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
|
||||
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
|
||||
if (Object.keys(limits).length) out.limits = limits;
|
||||
if (Array.isArray(base.ignoreValues)) {
|
||||
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValueEntries(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(ignoreValueEntryKey(entry), entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueEntryKey(entry) {
|
||||
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
|
||||
return `${entry.rule}\0${entry.value}\0${files}`;
|
||||
}
|
||||
|
||||
function statusReport(cwd) {
|
||||
const shared = readRawConfigFile(getConfigPath(cwd));
|
||||
const local = readRawConfigFile(getLocalConfigPath(cwd));
|
||||
@@ -216,14 +280,14 @@ function statusReport(cwd) {
|
||||
}
|
||||
|
||||
function setEnabled(cwd, value) {
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeHookConfig(readRawHookConfig(cwd));
|
||||
config.enabled = value;
|
||||
const target = writeConfig(cwd, config);
|
||||
const target = writeHookConfig(cwd, config);
|
||||
if (!value) {
|
||||
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
|
||||
const repaired = repairHookManifests(cwd);
|
||||
const parts = [
|
||||
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
|
||||
@@ -429,18 +493,18 @@ function addIgnoreRule(cwd, args) {
|
||||
if (rule === 'overused-font' && !parsed.allValues) {
|
||||
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
|
||||
}
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
|
||||
}
|
||||
|
||||
function addIgnoreFile(cwd, glob) {
|
||||
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
|
||||
const config = mergeConfig(readRawConfig(cwd));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
|
||||
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
|
||||
writeConfig(cwd, config);
|
||||
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
writeDetectorConfig(cwd, config);
|
||||
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
|
||||
}
|
||||
|
||||
function parseIgnoreValueArgs(args) {
|
||||
@@ -489,9 +553,7 @@ function addIgnoreValue(cwd, args) {
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = local
|
||||
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
|
||||
: mergeConfig(readRawConfig(cwd, { local: false }));
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
const key = `${parsed.rule}\0${parsed.value}`;
|
||||
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
|
||||
|
||||
@@ -507,20 +569,20 @@ function addIgnoreValue(cwd, args) {
|
||||
config.ignoreValues.push(entry);
|
||||
}
|
||||
|
||||
const target = writeConfig(cwd, config, { local });
|
||||
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
|
||||
const target = writeDetectorConfig(cwd, config, { local });
|
||||
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
|
||||
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
|
||||
}
|
||||
|
||||
function reset(cwd) {
|
||||
const removed = [];
|
||||
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
|
||||
// hook subtree and keep the rest, deleting the file only if nothing remains.
|
||||
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
try {
|
||||
const raw = readRawConfigFile(filePath).raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
|
||||
const { hook, ...rest } = raw;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
|
||||
const { hook, detector, ...rest } = raw;
|
||||
if (Object.keys(rest).length === 0) {
|
||||
fs.unlinkSync(filePath);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
EDIT_COUNT_THRESHOLD,
|
||||
GENERATED_PATH,
|
||||
SENSITIVE_PATH,
|
||||
appendDesignSystemNote,
|
||||
designSystemOptions,
|
||||
filterFindings,
|
||||
loadDetector,
|
||||
matchesAnyGlob,
|
||||
@@ -415,10 +417,11 @@ async function main() {
|
||||
if (!detector || typeof detector.detectText !== 'function') {
|
||||
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, detector, cwd);
|
||||
|
||||
let findings = [];
|
||||
try {
|
||||
findings = await detector.detectText(content, filePath);
|
||||
findings = await detector.detectText(content, filePath, scanOptions);
|
||||
} catch {
|
||||
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -433,7 +436,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
||||
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
|
||||
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
||||
const cache = readCache(cwd);
|
||||
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
||||
|
||||
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
|
||||
enabled: true,
|
||||
quiet: false,
|
||||
auditLog: null,
|
||||
designSystem: { enabled: true },
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
|
||||
export function readConfig(cwd) {
|
||||
const config = cloneDefaultConfig();
|
||||
// Hook settings live under the `hook` key of config.json (shared) and
|
||||
// config.local.json (per-developer, gitignored); local wins.
|
||||
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
|
||||
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
|
||||
// Hook runtime settings live under `hook`; detector filters live under
|
||||
// `detector`. Back-compat: older configs stored detector filters in `hook`,
|
||||
// so read those first and let canonical `detector` settings win.
|
||||
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
applyConfigSource(config, hookSection(raw));
|
||||
applyDetectorConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -148,6 +153,11 @@ function hookSection(raw) {
|
||||
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
function numberOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_CONFIG.designSystem },
|
||||
limits: { ...DEFAULT_CONFIG.limits },
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectorConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function applyConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
|
||||
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
|
||||
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
|
||||
config.auditLog = raw.auditLog.trim();
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
applyDetectorConfigSource(config, raw);
|
||||
if (raw.limits && typeof raw.limits === 'object') {
|
||||
config.limits = {
|
||||
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
|
||||
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}`, entry);
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
export function readCache(cwd) {
|
||||
const raw = safeReadJson(getCachePath(cwd));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
|
||||
@@ -447,13 +630,39 @@ function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (!rule || !value) return false;
|
||||
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
|
||||
return ignoreValues.some((entry) => {
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(path.sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (rule !== 'overused-font' && rule !== 'bounce-easing') return '';
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
@@ -520,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
const fresh = [];
|
||||
for (const f of findings) {
|
||||
const key = `${f.antipattern}:${f.line || 0}`;
|
||||
const key = findingCacheKey(f);
|
||||
if (known.has(key)) continue;
|
||||
known.add(key);
|
||||
fresh.push(f);
|
||||
@@ -531,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
|
||||
export function rememberFindings(cache, sessionId, filePath, findings) {
|
||||
const fileEntry = ensureFile(cache, sessionId, filePath);
|
||||
const known = new Set(fileEntry.findings || []);
|
||||
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
|
||||
for (const f of findings) known.add(findingCacheKey(f));
|
||||
fileEntry.findings = Array.from(known);
|
||||
ensureSession(cache, sessionId).updatedAt = Date.now();
|
||||
}
|
||||
|
||||
function findingCacheKey(finding) {
|
||||
const line = finding?.line || 0;
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
|
||||
if (line > 0) return `${finding.antipattern}:${line}`;
|
||||
if (value) return `${finding.antipattern}:0:${value}`;
|
||||
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
|
||||
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
|
||||
}
|
||||
|
||||
export function renderTemplate(findings, filePath, config, opts = {}) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return '';
|
||||
const limits = config?.limits || DEFAULT_CONFIG.limits;
|
||||
@@ -942,7 +1161,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
|
||||
const found = candidates.find((c) => fs.existsSync(c));
|
||||
if (!found) return null;
|
||||
const mod = await import(pathToFileURL(found));
|
||||
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
|
||||
detectorCache = {
|
||||
detectText: mod.detectText,
|
||||
detectHtml: mod.detectHtml,
|
||||
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
|
||||
};
|
||||
return detectorCache;
|
||||
}
|
||||
|
||||
@@ -999,6 +1222,22 @@ export function shouldEmitAckForFile(filePath) {
|
||||
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function designSystemOptions(config, detector, projectCwd) {
|
||||
if (config?.designSystem?.enabled === false) return {};
|
||||
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
|
||||
try {
|
||||
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
|
||||
return designSystem ? { designSystem } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function appendDesignSystemNote(text, scanOptions) {
|
||||
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
|
||||
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
|
||||
}
|
||||
|
||||
// The directive footer is the part of the hook output that steers model
|
||||
// behavior. Three intentional moves:
|
||||
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
|
||||
@@ -1086,6 +1325,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
persistCache(projectCwd, cache);
|
||||
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
|
||||
}
|
||||
const scanOptions = designSystemOptions(config, det, projectCwd);
|
||||
|
||||
let pendingWinner = null;
|
||||
let cleanWinner = null;
|
||||
@@ -1143,9 +1383,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
@@ -1176,7 +1416,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
|
||||
if (freshGroups.length > 0) {
|
||||
const firstGroup = freshGroups[0];
|
||||
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
|
||||
const allFindings = freshGroups.flatMap((group) => group.findings);
|
||||
return {
|
||||
exitCode: 0,
|
||||
@@ -1208,7 +1448,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
|
||||
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
@@ -1242,7 +1482,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
}
|
||||
|
||||
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
|
||||
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
|
||||
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: payload(text, 'PostToolUse', harness),
|
||||
|
||||
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user