@blackbelt-technology/frontend-mockup-loop 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Design-system preset registry.
3
+ *
4
+ * One entry per selectable design system. Each preset declares its platform,
5
+ * generation substrate, contract source, touch-target minimum, spacing scale,
6
+ * and the validator layers (L1–L4) that apply. The loop reads this to drive
7
+ * generation conventions and the validation pipeline.
8
+ *
9
+ * v1: shadcn, mui, material-3, fluent-2, apple-hig.
10
+ */
11
+
12
+ export type Platform = "web" | "ios";
13
+
14
+ /** Where a preset's token contract comes from. */
15
+ export type ContractSource = "imported-tokens" | "rule-pack";
16
+
17
+ export type ValidatorLayer = "L1" | "L2" | "L3" | "L4";
18
+
19
+ /**
20
+ * One validator wired into a preset.
21
+ * - `gate` — hard gate (blocks `pass`) vs advisory (scores only).
22
+ * - `bundled` — a hard dependency shipped with the package vs an optional
23
+ * tool resolved at runtime (skipped + noted when absent).
24
+ */
25
+ export interface ValidatorSpec {
26
+ layer: ValidatorLayer;
27
+ tool: string;
28
+ gate: boolean;
29
+ bundled: boolean;
30
+ }
31
+
32
+ export interface DesignSystemPreset {
33
+ id: string;
34
+ label: string;
35
+ platform: Platform;
36
+ /** Generation substrate, e.g. "html-tailwind", "html-approx + swiftui-on-promote". */
37
+ substrate: string;
38
+ contractSource: ContractSource;
39
+ /** Minimum touch target, in CSS px (web) or pt (ios). */
40
+ minTouchTarget: number;
41
+ spacingScale: number[];
42
+ validators: ValidatorSpec[];
43
+ }
44
+
45
+ /** L2 a11y floor — bundled, hard gate, applies to every preset. */
46
+ const L2_FLOOR: ValidatorSpec = {
47
+ layer: "L2",
48
+ tool: "@axe-core/playwright",
49
+ gate: true,
50
+ bundled: true,
51
+ };
52
+
53
+ export const PRESETS: DesignSystemPreset[] = [
54
+ {
55
+ id: "shadcn",
56
+ label: "shadcn/ui + Tailwind",
57
+ platform: "web",
58
+ substrate: "html-tailwind",
59
+ contractSource: "imported-tokens",
60
+ minTouchTarget: 44,
61
+ spacingScale: [4, 8, 12, 16, 24, 32, 48, 64],
62
+ validators: [
63
+ { layer: "L1", tool: "eslint-plugin-tailwindcss", gate: true, bundled: true },
64
+ L2_FLOOR,
65
+ { layer: "L4", tool: "rubric", gate: false, bundled: true },
66
+ ],
67
+ },
68
+ {
69
+ id: "mui",
70
+ label: "Material UI (MUI)",
71
+ platform: "web",
72
+ substrate: "html-mui",
73
+ contractSource: "imported-tokens",
74
+ minTouchTarget: 48,
75
+ spacingScale: [4, 8, 16, 24, 32, 40, 48],
76
+ validators: [
77
+ { layer: "L1", tool: "eslint-plugin-material-ui", gate: false, bundled: false },
78
+ L2_FLOOR,
79
+ { layer: "L3", tool: "mui-mcp", gate: false, bundled: false },
80
+ { layer: "L4", tool: "rubric", gate: false, bundled: true },
81
+ ],
82
+ },
83
+ {
84
+ id: "material-3",
85
+ label: "Material Design 3",
86
+ platform: "web",
87
+ substrate: "html-md3",
88
+ contractSource: "imported-tokens",
89
+ minTouchTarget: 48,
90
+ spacingScale: [4, 8, 16, 24, 32, 40, 48, 56],
91
+ validators: [
92
+ { layer: "L1", tool: "stylelint-scales", gate: true, bundled: true },
93
+ L2_FLOOR,
94
+ { layer: "L3", tool: "material3-mcp", gate: false, bundled: false },
95
+ { layer: "L4", tool: "rubric", gate: false, bundled: true },
96
+ ],
97
+ },
98
+ {
99
+ id: "fluent-2",
100
+ label: "Fluent 2",
101
+ platform: "web",
102
+ substrate: "html-fluent",
103
+ contractSource: "imported-tokens",
104
+ minTouchTarget: 44,
105
+ spacingScale: [4, 8, 12, 16, 20, 24, 32],
106
+ validators: [
107
+ { layer: "L1", tool: "eslint-plugin-fluentui-jsx-a11y", gate: false, bundled: false },
108
+ L2_FLOOR,
109
+ { layer: "L4", tool: "rubric", gate: false, bundled: true },
110
+ ],
111
+ },
112
+ {
113
+ id: "apple-hig",
114
+ label: "Apple Human Interface Guidelines",
115
+ platform: "ios",
116
+ substrate: "html-approx + swiftui-on-promote",
117
+ contractSource: "rule-pack",
118
+ minTouchTarget: 44,
119
+ spacingScale: [4, 8, 16, 20, 24, 32, 44],
120
+ validators: [
121
+ L2_FLOOR,
122
+ { layer: "L3", tool: "hig-doctor", gate: false, bundled: false },
123
+ { layer: "L4", tool: "rubric", gate: false, bundled: true },
124
+ ],
125
+ },
126
+ ];
127
+
128
+ export function listPresets(): DesignSystemPreset[] {
129
+ return PRESETS;
130
+ }
131
+
132
+ export function getPreset(id: string): DesignSystemPreset | undefined {
133
+ return PRESETS.find((p) => p.id === id);
134
+ }
135
+
136
+ export function presetIds(): string[] {
137
+ return PRESETS.map((p) => p.id);
138
+ }
139
+
140
+ /**
141
+ * Resolve a preset or return a structured error naming valid ids.
142
+ * Tools call this to reject unknown `system` values without throwing.
143
+ */
144
+ export function resolvePreset(
145
+ id: string,
146
+ ): { preset: DesignSystemPreset } | { error: string } {
147
+ const preset = getPreset(id);
148
+ if (!preset) {
149
+ return {
150
+ error: `Unknown design system "${id}". Valid ids: ${presetIds().join(", ")}.`,
151
+ };
152
+ }
153
+ return { preset };
154
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Layered validation pipeline (L1–L4), parameterized by a selected preset.
3
+ *
4
+ * L1 token-lint — static, hard GATE when a token-linter applies.
5
+ * L2 a11y floor — rendered axe + WCAG contrast, hard GATE (all systems).
6
+ * L3 named auditor— shell out to system tool if present, ADVISORY.
7
+ * L4 vision rubric— per-preset boolean checks, score = pass/N, ADVISORY.
8
+ *
9
+ * Gate layers determine `pass`; advisory layers only score. Every optional
10
+ * tool degrades to "skipped + noted" when absent — the pipeline never throws
11
+ * for a missing validator.
12
+ */
13
+
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import type { DesignSystemPreset } from "./registry.js";
17
+ import { rubricPath } from "./contract.js";
18
+
19
+ export type LayerStatus = "pass" | "fail" | "skipped";
20
+
21
+ export interface LayerResult {
22
+ layer: "L1" | "L2" | "L3" | "L4";
23
+ tool: string;
24
+ status: LayerStatus;
25
+ gate: boolean;
26
+ messages: string[];
27
+ }
28
+
29
+ export interface RubricCheck {
30
+ id: string;
31
+ text: string;
32
+ }
33
+
34
+ export interface L4Result extends LayerResult {
35
+ checks: RubricCheck[];
36
+ score: number | null;
37
+ }
38
+
39
+ export interface ValidateResult {
40
+ system: string;
41
+ gates: { l1: LayerResult; l2: LayerResult };
42
+ advisory: { l3: LayerResult; l4: L4Result };
43
+ pass: boolean;
44
+ }
45
+
46
+ // ── helpers ────────────────────────────────────────────────────────────────
47
+
48
+ /**
49
+ * True when an executable resolves on PATH. Pure filesystem scan (no
50
+ * subprocess spawn): splits `PATH` on `path.delimiter` and probes the bare
51
+ * name plus common Windows extensions. Checking `.exe`/`.cmd`/`.bat` on POSIX
52
+ * is harmless (those files don't exist), so no platform branch is needed.
53
+ */
54
+ export function isToolAvailable(name: string): boolean {
55
+ const dirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
56
+ const candidates = [name, `${name}.exe`, `${name}.cmd`, `${name}.bat`];
57
+ for (const dir of dirs) {
58
+ for (const c of candidates) {
59
+ try {
60
+ if (fs.existsSync(path.join(dir, c))) return true;
61
+ } catch {
62
+ // ignore unreadable PATH entries
63
+ }
64
+ }
65
+ }
66
+ return false;
67
+ }
68
+
69
+ function listFiles(dir: string, exts: string[]): string[] {
70
+ const out: string[] = [];
71
+ const walk = (d: string) => {
72
+ let entries: fs.Dirent[] = [];
73
+ try {
74
+ entries = fs.readdirSync(d, { withFileTypes: true });
75
+ } catch {
76
+ return;
77
+ }
78
+ for (const e of entries) {
79
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
80
+ const full = path.join(d, e.name);
81
+ if (e.isDirectory()) walk(full);
82
+ else if (exts.includes(path.extname(e.name).toLowerCase())) out.push(full);
83
+ }
84
+ };
85
+ walk(dir);
86
+ return out;
87
+ }
88
+
89
+ // ── WCAG contrast (inline, no dep) ──────────────────────────────────────────
90
+
91
+ function srgbToLin(c: number): number {
92
+ const s = c / 255;
93
+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
94
+ }
95
+
96
+ function relLuminance(r: number, g: number, b: number): number {
97
+ return 0.2126 * srgbToLin(r) + 0.7152 * srgbToLin(g) + 0.0722 * srgbToLin(b);
98
+ }
99
+
100
+ export function contrastRatio(a: [number, number, number], b: [number, number, number]): number {
101
+ const la = relLuminance(...a);
102
+ const lb = relLuminance(...b);
103
+ const [hi, lo] = la >= lb ? [la, lb] : [lb, la];
104
+ return (hi + 0.05) / (lo + 0.05);
105
+ }
106
+
107
+ /** Parse a #rgb / #rrggbb hex into an [r,g,b] triple, or null. */
108
+ export function parseHex(hex: string): [number, number, number] | null {
109
+ let h = hex.replace("#", "");
110
+ if (h.length === 3) h = h.split("").map((c) => c + c).join("");
111
+ if (h.length !== 6) return null;
112
+ const n = parseInt(h, 16);
113
+ if (Number.isNaN(n)) return null;
114
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
115
+ }
116
+
117
+ const HEX_RE = /#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?\b/g;
118
+ /** A line that defines a CSS custom property (a token definition, not usage). */
119
+ const TOKEN_DEF_RE = /--[\w-]+\s*:/;
120
+
121
+ // ── L1: static token-lint ───────────────────────────────────────────────────
122
+
123
+ /**
124
+ * Built-in token-lint gate: flags raw hex color literals used outside CSS
125
+ * custom-property definitions (= off-token usage). Applies when the preset's
126
+ * L1 validator is bundled (shadcn, material-3). Optional external linters
127
+ * (mui/fluent) are noted as available/absent but not run here.
128
+ */
129
+ export function runL1(preset: DesignSystemPreset, dir?: string): LayerResult {
130
+ const spec = preset.validators.find((v) => v.layer === "L1");
131
+ if (!spec) {
132
+ return { layer: "L1", tool: "(none)", status: "skipped", gate: false, messages: ["No L1 token-lint for this system."] };
133
+ }
134
+ if (!spec.bundled) {
135
+ const present = isToolAvailable(spec.tool);
136
+ return {
137
+ layer: "L1",
138
+ tool: spec.tool,
139
+ status: "skipped",
140
+ gate: false,
141
+ messages: [present ? `${spec.tool} present (optional — run separately).` : `${spec.tool} not found — skipped + noted.`],
142
+ };
143
+ }
144
+ if (!dir || !fs.existsSync(dir)) {
145
+ return { layer: "L1", tool: spec.tool, status: "skipped", gate: spec.gate, messages: ["No mockup dir to lint."] };
146
+ }
147
+ const files = listFiles(dir, [".html", ".htm", ".css", ".tsx", ".jsx", ".vue"]);
148
+ const offending: string[] = [];
149
+ for (const file of files) {
150
+ const lines = fs.readFileSync(file, "utf8").split("\n");
151
+ lines.forEach((line, i) => {
152
+ if (TOKEN_DEF_RE.test(line)) return;
153
+ const hits = line.match(HEX_RE);
154
+ if (hits) offending.push(`${path.relative(dir, file)}:${i + 1} raw hex ${hits.join(", ")}`);
155
+ });
156
+ }
157
+ if (offending.length) {
158
+ return { layer: "L1", tool: spec.tool, status: "fail", gate: spec.gate, messages: ["Off-token color literals:", ...offending.slice(0, 20)] };
159
+ }
160
+ return { layer: "L1", tool: spec.tool, status: "pass", gate: spec.gate, messages: ["No off-token color literals."] };
161
+ }
162
+
163
+ // ── L2: a11y floor (axe if present + built-in contrast) ─────────────────────
164
+
165
+ /**
166
+ * Built-in WCAG contrast scan: finds `color` + `background[-color]` hex pairs
167
+ * declared in the same CSS rule or inline style and flags ratios < 4.5:1.
168
+ * Deterministic + offline; the gate for the L2 floor. axe-core augments when
169
+ * @axe-core/playwright + playwright resolve (advisory message only here).
170
+ */
171
+ export function runL2(_preset: DesignSystemPreset, dir?: string): LayerResult {
172
+ if (!dir || !fs.existsSync(dir)) {
173
+ return { layer: "L2", tool: "@axe-core/playwright", status: "skipped", gate: true, messages: ["No mockup dir to scan."] };
174
+ }
175
+ const files = listFiles(dir, [".html", ".htm", ".css"]);
176
+ const failures: string[] = [];
177
+ // Match a CSS-declaration block or inline style; pull color + background.
178
+ const blockRe = /\{[^}]*\}|style\s*=\s*"[^"]*"/g;
179
+ for (const file of files) {
180
+ const text = fs.readFileSync(file, "utf8");
181
+ const blocks = text.match(blockRe) ?? [];
182
+ for (const block of blocks) {
183
+ const fg = /(?:^|[^-])color\s*:\s*(#[0-9a-fA-F]{3,8})/.exec(block);
184
+ const bg = /background(?:-color)?\s*:\s*(#[0-9a-fA-F]{3,8})/.exec(block);
185
+ if (fg && bg) {
186
+ const a = parseHex(fg[1]);
187
+ const b = parseHex(bg[1]);
188
+ if (a && b) {
189
+ const ratio = contrastRatio(a, b);
190
+ if (ratio < 4.5) failures.push(`${path.basename(file)}: ${fg[1]} on ${bg[1]} = ${ratio.toFixed(2)}:1 (< 4.5)`);
191
+ }
192
+ }
193
+ }
194
+ }
195
+ const axe = isToolAvailable("playwright") ? "axe-core available" : "axe-core/playwright absent (built-in contrast scan only)";
196
+ if (failures.length) {
197
+ return { layer: "L2", tool: "@axe-core/playwright", status: "fail", gate: true, messages: [`Contrast failures (${axe}):`, ...failures.slice(0, 20)] };
198
+ }
199
+ return { layer: "L2", tool: "@axe-core/playwright", status: "pass", gate: true, messages: [`Contrast floor OK (${axe}).`] };
200
+ }
201
+
202
+ // ── L3: named-system auditor (shell-out-if-present) ─────────────────────────
203
+
204
+ export function runL3(preset: DesignSystemPreset): LayerResult {
205
+ const spec = preset.validators.find((v) => v.layer === "L3");
206
+ if (!spec) {
207
+ return { layer: "L3", tool: "(none)", status: "skipped", gate: false, messages: ["No named-system auditor for this system."] };
208
+ }
209
+ if (!isToolAvailable(spec.tool)) {
210
+ return { layer: "L3", tool: spec.tool, status: "skipped", gate: false, messages: [`skipped (${spec.tool} not found)`] };
211
+ }
212
+ return { layer: "L3", tool: spec.tool, status: "pass", gate: false, messages: [`${spec.tool} present — run it against the mockup for advisory findings.`] };
213
+ }
214
+
215
+ // ── L4: vision rubric ───────────────────────────────────────────────────────
216
+
217
+ export function loadRubric(id: string): RubricCheck[] {
218
+ const file = rubricPath(id);
219
+ if (!fs.existsSync(file)) return [];
220
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { checks?: RubricCheck[] };
221
+ return parsed.checks ?? [];
222
+ }
223
+
224
+ /**
225
+ * L4 vision judge. Returns the preset's boolean rubric for the agent to fill.
226
+ * When `answers` (id → boolean) are supplied, derives `score = passCount / N`
227
+ * in code — the model never emits the aggregate float itself.
228
+ */
229
+ export function runL4(preset: DesignSystemPreset, answers?: Record<string, boolean>): L4Result {
230
+ const checks = loadRubric(preset.id);
231
+ let score: number | null = null;
232
+ const messages: string[] = [];
233
+ if (!checks.length) {
234
+ messages.push("No rubric for this system.");
235
+ } else if (answers && Object.keys(answers).length) {
236
+ const passCount = checks.filter((c) => answers[c.id] === true).length;
237
+ score = passCount / checks.length;
238
+ messages.push(`Rubric score ${passCount}/${checks.length} = ${(score * 100).toFixed(0)}%.`);
239
+ } else {
240
+ messages.push(`Answer each of the ${checks.length} boolean checks (PASS/FAIL + one-line reason); score = pass/N.`);
241
+ }
242
+ return { layer: "L4", tool: "rubric", status: "skipped", gate: false, messages, checks, score };
243
+ }
244
+
245
+ // ── orchestrator ────────────────────────────────────────────────────────────
246
+
247
+ export function validateMockup(opts: {
248
+ preset: DesignSystemPreset;
249
+ dir?: string;
250
+ answers?: Record<string, boolean>;
251
+ }): ValidateResult {
252
+ const { preset, dir, answers } = opts;
253
+ const l1 = runL1(preset, dir);
254
+ const l2 = runL2(preset, dir);
255
+ const l3 = runL3(preset);
256
+ const l4 = runL4(preset, answers);
257
+ // Gate layers determine pass: only an explicit gate `fail` blocks.
258
+ const gateBlocked = [l1, l2].some((r) => r.gate && r.status === "fail");
259
+ return {
260
+ system: preset.id,
261
+ gates: { l1, l2 },
262
+ advisory: { l3, l4 },
263
+ pass: !gateBlocked,
264
+ };
265
+ }