import { mkdir, readFile, readdir } from "node:fs/promises"; import { designSystemReportArtifactSchema } from "./contracts/release-artifacts.ts"; import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts"; import path from "node:path"; import { REQUIRED_COMPONENT_TOKENS, REQUIRED_PRIMITIVE_TOKENS, REQUIRED_SEMANTIC_TOKENS } from "../src/presentation/design-system/tokens/token-contract.ts"; import { contrastRatio, readCustomProperties, resolveColor } from "./lib/oklch-contrast.ts"; const fixtureMode = process.argv.includes("--fixture"); const failures: string[] = []; const tokenFiles = { primitive: "src/presentation/design-system/tokens/primitive.css", semantic: "src/presentation/design-system/tokens/semantic.css", component: "src/presentation/design-system/tokens/component.css", }; const tokenLayers: Array = [ ["primitive", tokenFiles.primitive, REQUIRED_PRIMITIVE_TOKENS], ["semantic", tokenFiles.semantic, REQUIRED_SEMANTIC_TOKENS], ["component", tokenFiles.component, REQUIRED_COMPONENT_TOKENS], ]; for (const [layer, file, tokens] of tokenLayers) { const source = await readFile(file, "utf8"); for (const token of tokens) { if (!source.includes(`${token}:`)) { failures.push(`${layer} token is missing: ${token}`); } } } // theme.css only imports the files under styles/theme/, so check them all. const styleFiles = ( await readdir("src/presentation/styles", { recursive: true }) ) .filter((file) => file.endsWith(".css")) .map((file) => path.join("src/presentation/styles", file)); const cssSources = await Promise.all( [...Object.values(tokenFiles), ...styleFiles].map( async (file) => ({ file, source: await readFile(file, "utf8") }), ), ); const definitions = new Set( cssSources.flatMap(({ source }) => [...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1]), ), ); for (const { file, source } of cssSources) { for (const match of source.matchAll(/var\((--[a-z0-9-]+)/g)) { if (!definitions.has(match[1])) { failures.push(`${file} uses undefined token ${match[1]}`); } } // UI-02. Hue-based spaces interpolate the hue angle, and an achromatic // stop such as oklch(1 0 0) carries hue 0: 14% blue into white came out // pink. oklab mixes on straight lines and has no hue to drag. for (const match of source.matchAll(/color-mix\(\s*in\s+(oklch|lch|hsl|hwb)\b/g)) { failures.push(`${file} mixes colours in ${match[1]}; use oklab`); } } const semanticSource = await readFile(tokenFiles.semantic, "utf8"); const darkSource = semanticSource.match(/:root\[data-theme="dark"\]\s*\{([\s\S]*?)\n\}/)?.[1] ?? ""; for (const token of [ "--color-surface", "--color-surface-muted", "--color-surface-elevated", "--color-content", "--color-content-muted", "--color-content-inverse", "--color-border", "--color-border-strong", "--color-action", "--color-action-hover", "--color-action-pressed", "--color-danger", "--color-focus", "--color-disabled-content", "--color-disabled-surface", ]) { if (!darkSource.includes(`${token}:`)) { failures.push(`dark theme token is missing: ${token}`); } } // UI-01. The focus ring is drawn 3px away from its control, so the colour // next to it is the surface behind the control, not the control itself. // WCAG 1.4.11 asks 3:1 against that neighbour, in both themes. const FOCUS_RING_BACKGROUNDS = [ "--color-surface", "--color-surface-muted", "--color-panel", "--color-surface-elevated", "--color-info-surface", "--color-success-surface", "--color-warning-surface", "--color-danger-surface", ] as const; const lightProperties = new Map([ ...readCustomProperties(await readFile(tokenFiles.primitive, "utf8")), ...readCustomProperties(semanticSource.split(':root[data-theme="dark"]')[0]), ]); const darkProperties = new Map([ ...lightProperties, ...readCustomProperties(darkSource), ]); for (const [theme, properties] of [ ["light", lightProperties], ["dark", darkProperties], ] as const) { const focus = resolveColor("--color-focus", properties); for (const background of FOCUS_RING_BACKGROUNDS) { const surface = resolveColor(background, properties); if (!focus || !surface) { failures.push(`${theme} --color-focus or ${background} is not a plain oklch() value`); continue; } const ratio = contrastRatio(focus, surface); if (ratio < 3) { failures.push( `${theme} --color-focus contrast ${ratio.toFixed(2)}:1 against ${background} is below 3:1`, ); } } } // UI-03. A component token nobody reads is a second copy of a decision: // the style that should use it repeats the formula instead, and a product // that rebrands through the token sees nothing change. const styleSources = cssSources.filter(({ file }) => file !== tokenFiles.component); for (const token of REQUIRED_COMPONENT_TOKENS) { if (!styleSources.some(({ source }) => source.includes(`var(${token}`))) { failures.push(`component token ${token} is defined but no style reads it`); } } // UI-05. --font-sans named Inter first, but nothing loads Inter, so most // machines drew another font and Hangul never came from Inter at all. // The first family must be a generic keyword or one this repo ships. const GENERIC_FONT_FAMILIES = new Set([ "system-ui", "ui-sans-serif", "ui-serif", "ui-monospace", "sans-serif", "serif", "monospace", ]); const shippedFontFamilies = new Set( cssSources.flatMap(({ source }) => [...source.matchAll(/@font-face\s*\{[^}]*font-family:\s*["']?([^;"']+)/g)] .map((match) => match[1].trim()), ), ); const fontSans = lightProperties.get("--font-sans") ?? ""; const firstFontFamily = fontSans.split(",")[0]?.trim().replace(/^["']|["']$/g, "") ?? ""; if (!GENERIC_FONT_FAMILIES.has(firstFontFamily) && !shippedFontFamilies.has(firstFontFamily)) { failures.push( `--font-sans starts with "${firstFontFamily}", which is neither a generic family nor loaded by @font-face`, ); } const componentSource = await readFile(tokenFiles.component, "utf8"); if (!componentSource.includes("@media (forced-colors: active)")) { failures.push("forced-colors token fallback is missing"); } async function listSourceFiles(directory: string): Promise { const result: string[] = []; for (const entry of await readdir(directory, { withFileTypes: true })) { const target = path.join(directory, entry.name); if (entry.isDirectory()) result.push(...(await listSourceFiles(target))); else if (/\.(?:ts|tsx|mts|cts)$/.test(entry.name)) result.push(target); } return result; } const sources = fixtureMode ? await listSourceFiles("tests/fixtures/design-system/forbidden") : await listSourceFiles("src"); for (const file of sources) { const source = await readFile(file, "utf8"); // Icon vendor and design-system deep imports are graph rules in // .dependency-cruiser.json (check:architecture), which also sees relative, // dynamic and type imports (12-08, 12-10). if ( /from\s+["'](?:react-aria-components|@radix-ui\/[^"']+)["']/.test(source) ) { failures.push(`direct headless vendor import in ${file}`); } if ( !file.includes("src/presentation/design-system/tokens/") && /(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source) ) { failures.push(`raw palette value in ${file}`); } if ( file.includes("tests/fixtures/design-system/forbidden") && source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION") ) { failures.push(`tooltip-only required information in ${file}`); } } const report = designSystemReportArtifactSchema.parse({ schemaVersion: 1, mode: fixtureMode ? "negative-fixture" : "source", checkedTokenCount: REQUIRED_PRIMITIVE_TOKENS.length + REQUIRED_SEMANTIC_TOKENS.length + REQUIRED_COMPONENT_TOKENS.length, failures, passed: failures.length === 0, }); await mkdir("artifacts/quality", { recursive: true }); await writeValidatedJsonArtifact({ path: fixtureMode ? "artifacts/quality/design-system-fixture.json" : "artifacts/quality/design-system.json", schema: designSystemReportArtifactSchema, value: report, }); if (failures.length > 0) { process.stderr.write(`Design system contract failed:\n${failures.join("\n")}\n`); process.exit(1); } process.stdout.write( `Design system contract: ${report.checkedTokenCount} tokens and headless vendor boundary PASS\n`, );