medesign 1.2.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +223 -129
  2. package/bin/mebolder.js +4 -0
  3. package/bin/medesign.js +992 -200
  4. package/bin/melint.js +4 -0
  5. package/bin/mepolish.js +4 -0
  6. package/bin/mequiet.js +4 -0
  7. package/bin/mesearch.js +4 -0
  8. package/bin/mesnapshot.js +4 -0
  9. package/examples/cadastral-qaqc-slide.html +577 -0
  10. package/examples/executive-summary-report.html +597 -0
  11. package/examples/executive-summary-report.pdf +0 -0
  12. package/examples/geospatial-banner-1200x630.html +370 -0
  13. package/examples/geospatial-banner-1200x630.svg +149 -0
  14. package/examples/linear-issue-board.html +1273 -0
  15. package/examples/snapshots/cadastral-qaqc-slide-desktop-1440x900.png +0 -0
  16. package/examples/snapshots/cadastral-qaqc-slide-mobile-390x844.png +0 -0
  17. package/examples/snapshots/cadastral-qaqc-slide-tablet-820x1180.png +0 -0
  18. package/examples/snapshots/executive-summary-report-desktop-1440x900.png +0 -0
  19. package/examples/snapshots/executive-summary-report-mobile-390x844.png +0 -0
  20. package/examples/snapshots/executive-summary-report-tablet-820x1180.png +0 -0
  21. package/examples/snapshots/geospatial-banner-1200x630-og-banner-1200x630.png +0 -0
  22. package/examples/snapshots/linear-issue-board-desktop-1440x900.png +0 -0
  23. package/examples/snapshots/linear-issue-board-mobile-390x844.png +0 -0
  24. package/examples/snapshots/linear-issue-board-tablet-820x1180.png +0 -0
  25. package/examples/snapshots/spotify-web-player-desktop-1440x900.png +0 -0
  26. package/examples/snapshots/spotify-web-player-mobile-390x844.png +0 -0
  27. package/examples/snapshots/spotify-web-player-tablet-820x1180.png +0 -0
  28. package/examples/spotify-web-player.html +1446 -0
  29. package/package.json +21 -4
  30. package/presets/metha/guidelines.md +26 -17
  31. package/presets/metha/preset.json +16 -16
  32. package/references/ai-tells.md +9 -2
  33. package/references/brand-design-tokens.md +27 -28
  34. package/references/brief-intake.md +90 -0
  35. package/references/catalog.json +1024 -101
  36. package/references/cli-architecture.md +1 -1
  37. package/references/compositor-smoothness.md +161 -0
  38. package/references/design-core.md +11 -4
  39. package/references/executive-reports.md +234 -0
  40. package/references/image-mockup-direction.md +53 -53
  41. package/references/image-to-code.md +46 -46
  42. package/references/modern-craft-invariants.md +55 -9
  43. package/references/prompt-templates.md +49 -0
  44. package/references/quality-gate.md +42 -12
  45. package/references/typography-thai-latin.md +206 -0
  46. package/references/view-transitions-engine.md +89 -0
  47. package/references/web-retrofit-protocol.md +103 -0
  48. package/scripts/export-tokens.js +419 -403
  49. package/tests/browser-audit.js +463 -442
  50. package/tests/linter.js +457 -412
  51. package/tests/snapshot.js +263 -0
@@ -1,442 +1,463 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * ME-DESIGN Phase 2 — Rendered DOM & Headless Browser Verification Engine
5
- * Direct Chrome DevTools Protocol (CDP) client over native WebSocket.
6
- * Zero external npm dependencies.
7
- *
8
- * Verifies:
9
- * 1. Real Computed Contrast Ratio across backgrounds
10
- * 2. Real Keyboard Tab Navigation & Focus Ring rendering (:focus-visible)
11
- * 3. Windows High Contrast Mode (forced-colors: active) physical outline persistence
12
- * 4. Hit-Target Bounding Dimensions (44px min touch standard)
13
- * 5. Responsive Viewports (Mobile 390px, Tablet 820px, Desktop 1440px)
14
- * 6. Theme Modes (Dark & Light)
15
- *
16
- * Usage: node tests/browser-audit.js <filepath> [--json]
17
- */
18
-
19
- const fs = require('fs');
20
- const path = require('path');
21
- const { spawn } = require('child_process');
22
-
23
- const ANSI_RESET = '\x1b[0m';
24
- const ANSI_BOLD = '\x1b[1m';
25
- const ANSI_GREEN = '\x1b[32m';
26
- const ANSI_RED = '\x1b[31m';
27
- const ANSI_YELLOW = '\x1b[33m';
28
- const ANSI_CYAN = '\x1b[36m';
29
- const ANSI_GRAY = '\x1b[90m';
30
-
31
- const args = process.argv.slice(2);
32
- let targetFile = null;
33
- let isJson = false;
34
-
35
- for (let i = 0; i < args.length; i++) {
36
- if (args[i] === '--json') {
37
- isJson = true;
38
- } else if (!targetFile && !args[i].startsWith('--')) {
39
- targetFile = args[i];
40
- }
41
- }
42
-
43
- targetFile = targetFile || path.join(__dirname, 'fixtures', 'valid', 'metha-cadastre-dashboard.html');
44
-
45
- if (!fs.existsSync(targetFile)) {
46
- console.error(`Error: File not found: ${targetFile}`);
47
- process.exit(2);
48
- }
49
-
50
- const resolvedPath = path.resolve(targetFile);
51
- const fileUrl = 'file:///' + resolvedPath.replace(/\\/g, '/');
52
-
53
- // Locate Chromium executable across Windows, Linux, and macOS
54
- function findChromium() {
55
- const envPath = process.env.CHROME_PATH || process.env.CHROME_BIN;
56
- if (envPath && fs.existsSync(envPath)) return envPath;
57
-
58
- const localApp = process.env.LOCALAPPDATA || '';
59
- const candidate = path.join(localApp, 'ms-playwright', 'chromium-1248', 'chrome-win64', 'chrome.exe');
60
- if (fs.existsSync(candidate)) return candidate;
61
-
62
- const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';
63
- const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
64
-
65
- const alternatives = [
66
- // Windows
67
- path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
68
- path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
69
- path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
70
- // Linux (CI & Debian/Ubuntu)
71
- '/usr/bin/google-chrome',
72
- '/usr/bin/google-chrome-stable',
73
- '/usr/bin/chromium',
74
- '/usr/bin/chromium-browser',
75
- '/snap/bin/chromium',
76
- // macOS
77
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
78
- '/Applications/Chromium.app/Contents/MacOS/Chromium'
79
- ];
80
-
81
- for (const p of alternatives) {
82
- if (fs.existsSync(p)) return p;
83
- }
84
- return null;
85
- }
86
-
87
- const chromePath = findChromium();
88
- if (!chromePath) {
89
- console.error('Error: Chromium/Chrome binary not found on system.');
90
- process.exit(2);
91
- }
92
-
93
- // Minimal JSON-RPC CDP Client over Node's native global WebSocket
94
- class CDPClient {
95
- constructor(port) {
96
- this.port = port;
97
- this.ws = null;
98
- this.msgId = 0;
99
- this.callbacks = new Map();
100
- }
101
-
102
- async connect(targetUrl) {
103
- const res = await fetch(`http://127.0.0.1:${this.port}/json/new`, { method: 'PUT' });
104
- const target = await res.json();
105
- this.targetId = target.id;
106
- this.ws = new WebSocket(target.webSocketDebuggerUrl);
107
-
108
- await new Promise((resolve, reject) => {
109
- this.ws.onopen = resolve;
110
- this.ws.onerror = reject;
111
- });
112
-
113
- this.ws.onmessage = (event) => {
114
- const msg = JSON.parse(event.data);
115
- if (msg.id && this.callbacks.has(msg.id)) {
116
- const { resolve, reject } = this.callbacks.get(msg.id);
117
- this.callbacks.delete(msg.id);
118
- if (msg.error) reject(msg.error);
119
- else resolve(msg.result);
120
- }
121
- };
122
- }
123
-
124
- send(method, params = {}) {
125
- return new Promise((resolve, reject) => {
126
- const id = ++this.msgId;
127
- this.callbacks.set(id, { resolve, reject });
128
- this.ws.send(JSON.stringify({ id, method, params }));
129
- });
130
- }
131
-
132
- async close() {
133
- if (this.ws) {
134
- try { this.ws.close(); } catch (e) {}
135
- }
136
- try {
137
- await fetch(`http://127.0.0.1:${this.port}/json/close/${this.targetId}`, { method: 'PUT' });
138
- } catch (e) {}
139
- }
140
- }
141
-
142
- async function runAudit() {
143
- const cdpPort = 9444 + Math.floor(Math.random() * 200);
144
- const chromeProcess = spawn(chromePath, [
145
- '--headless=new',
146
- `--remote-debugging-port=${cdpPort}`,
147
- '--no-first-run',
148
- '--disable-gpu',
149
- '--no-sandbox',
150
- '--disable-extensions',
151
- '--mute-audio',
152
- '--hide-scrollbars'
153
- ]);
154
-
155
- // Wait for CDP readiness
156
- let ready = false;
157
- for (let i = 0; i < 25; i++) {
158
- try {
159
- const r = await fetch(`http://127.0.0.1:${cdpPort}/json/version`);
160
- if (r.ok) { ready = true; break; }
161
- } catch (e) {}
162
- await new Promise(res => setTimeout(res, 100));
163
- }
164
-
165
- if (!ready) {
166
- chromeProcess.kill();
167
- console.error('Failed to connect to headless Chromium instance.');
168
- process.exit(1);
169
- }
170
-
171
- const client = new CDPClient(cdpPort);
172
- await client.connect();
173
-
174
- // Full 7-Condition Test Matrix:
175
- // 3 Viewports (Mobile, Tablet, Desktop) × 2 Themes (Dark, Light) + Windows High Contrast (forced-colors: active)
176
- const testMatrix = [
177
- { viewport: { name: 'Mobile', width: 390, height: 844, isMobile: true }, theme: 'dark', forcedColors: false },
178
- { viewport: { name: 'Mobile', width: 390, height: 844, isMobile: true }, theme: 'light', forcedColors: false },
179
- { viewport: { name: 'Tablet', width: 820, height: 1180, isMobile: true }, theme: 'dark', forcedColors: false },
180
- { viewport: { name: 'Tablet', width: 820, height: 1180, isMobile: true }, theme: 'light', forcedColors: false },
181
- { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'dark', forcedColors: false },
182
- { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'light', forcedColors: false },
183
- // Condition 7: Windows High Contrast Emulation (forced-colors: active)
184
- { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'forced-colors', forcedColors: true }
185
- ];
186
-
187
- const auditResults = [];
188
-
189
- try {
190
- await client.send('Page.enable');
191
- await client.send('DOM.enable');
192
- await client.send('Runtime.enable');
193
-
194
- for (const testCase of testMatrix) {
195
- const vp = testCase.viewport;
196
- const th = testCase.theme;
197
-
198
- // Set Device Metrics
199
- await client.send('Emulation.setDeviceMetricsOverride', {
200
- width: vp.width,
201
- height: vp.height,
202
- deviceScaleFactor: 2,
203
- mobile: vp.isMobile
204
- });
205
-
206
- // Set Emulated Color Scheme and Forced Colors
207
- const features = [
208
- { name: 'prefers-color-scheme', value: testCase.forcedColors ? 'dark' : th }
209
- ];
210
- if (testCase.forcedColors) {
211
- features.push({ name: 'forced-colors', value: 'active' });
212
- } else {
213
- features.push({ name: 'forced-colors', value: 'none' });
214
- }
215
-
216
- await client.send('Emulation.setEmulatedMedia', {
217
- media: 'screen',
218
- features
219
- });
220
-
221
- // Navigate
222
- await client.send('Page.navigate', { url: fileUrl });
223
- await new Promise(res => setTimeout(res, 250)); // Wait for render and styles to settle
224
-
225
- // Dispatch real keyboard Tab navigation event
226
- await client.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
227
- await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
228
- await new Promise(res => setTimeout(res, 50));
229
-
230
- // Perform in-page inspection
231
- const inspectExpr = `
232
- (() => {
233
- // Relative luminance calculator
234
- function getLuminance(r, g, b) {
235
- const [rs, gs, bs] = [r, g, b].map(c => {
236
- c = c / 255;
237
- return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
238
- });
239
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
240
- }
241
-
242
- // Shared 1x1 canvas for hardware-exact pixel color rasterization
243
- const pixelCanvas = document.createElement('canvas');
244
- pixelCanvas.width = 1;
245
- pixelCanvas.height = 1;
246
- const pixelCtx = pixelCanvas.getContext('2d', { willReadFrequently: true });
247
-
248
- function parseRgba(colorStr) {
249
- if (!colorStr) return [0, 0, 0, 1];
250
- try {
251
- pixelCtx.clearRect(0, 0, 1, 1);
252
- pixelCtx.fillStyle = colorStr;
253
- pixelCtx.fillRect(0, 0, 1, 1);
254
- const d = pixelCtx.getImageData(0, 0, 1, 1).data;
255
- return [d[0], d[1], d[2], d[3] / 255];
256
- } catch (e) {
257
- return [255, 255, 255, 1];
258
- }
259
- }
260
-
261
- function getContrastRatio(fgRgb, bgRgb) {
262
- const l1 = getLuminance(fgRgb[0], fgRgb[1], fgRgb[2]);
263
- const l2 = getLuminance(bgRgb[0], bgRgb[1], bgRgb[2]);
264
- const lighter = Math.max(l1, l2);
265
- const darker = Math.min(l1, l2);
266
- return (lighter + 0.05) / (darker + 0.05);
267
- }
268
-
269
- function isDemoAntiPattern(el) {
270
- return el.closest('.con') || el.classList.contains('con') || el.closest('[data-anti-pattern]') || el.classList.contains('btn-slop') || el.closest('.cmp-col:has(.btn-slop)') || el.closest('.cmp-col:has(.thai-crop-bad)');
271
- }
272
-
273
- // Test 1: Hit-Target Dimensions (min 44x44px for touch)
274
- const buttons = Array.from(document.querySelectorAll('button, [role="button"], a.btn, .action-btn, .pill-btn-container, .telemetry-btn, .btn-ring')).filter(b => !isDemoAntiPattern(b));
275
- const hitTargetViolations = [];
276
- buttons.forEach(b => {
277
- const rect = b.getBoundingClientRect();
278
- if (rect.width > 0 && rect.height > 0) {
279
- if (rect.width < 43.5 || rect.height < 43.5) {
280
- hitTargetViolations.push({
281
- tag: b.tagName.toLowerCase(),
282
- text: b.textContent.trim().slice(0, 20),
283
- width: Math.round(rect.width),
284
- height: Math.round(rect.height)
285
- });
286
- }
287
- }
288
- });
289
-
290
- // Test 2: Real Computed Contrast Ratio against actual background
291
- const texts = Array.from(document.querySelectorAll('h1, h2, h3, p, td, th, span, label, .visual-surface')).filter(el => {
292
- return !isDemoAntiPattern(el) && el.children.length === 0 && el.textContent.trim().length > 0;
293
- }).slice(0, 20);
294
-
295
- let minContrast = 21.0;
296
- const debugContrast = [];
297
-
298
- texts.forEach(el => {
299
- const cs = window.getComputedStyle(el);
300
- if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return;
301
-
302
- const fg = parseRgba(cs.color);
303
- let solidBg = [9, 9, 11];
304
- const overlays = [];
305
-
306
- let p = el;
307
- while (p && p !== document) {
308
- const bgStr = window.getComputedStyle(p).backgroundColor;
309
- if (bgStr && bgStr !== 'transparent') {
310
- const rgba = parseRgba(bgStr);
311
- if (rgba[3] >= 0.90) {
312
- solidBg = [rgba[0], rgba[1], rgba[2]];
313
- break;
314
- } else if (rgba[3] > 0) {
315
- overlays.unshift(rgba);
316
- }
317
- }
318
- p = p.parentElement;
319
- }
320
-
321
- let compositeBg = [...solidBg];
322
- overlays.forEach(([r, g, b, a]) => {
323
- compositeBg[0] = Math.round(r * a + compositeBg[0] * (1 - a));
324
- compositeBg[1] = Math.round(g * a + compositeBg[1] * (1 - a));
325
- compositeBg[2] = Math.round(b * a + compositeBg[2] * (1 - a));
326
- });
327
- const cr = getContrastRatio(fg, compositeBg);
328
- debugContrast.push({ tag: el.tagName, text: el.textContent.trim().slice(0, 20), fg: fg.slice(0,3), bg: compositeBg, cr: Math.round(cr * 10) / 10 });
329
- if (cr < minContrast) minContrast = cr;
330
- });
331
-
332
- // Test 3: Active Element Tab Focus Outline
333
- let focusVisibleRendered = false;
334
- let highContrastOutlineRendered = false;
335
- const targetEl = (document.activeElement && document.activeElement !== document.body)
336
- ? document.activeElement
337
- : buttons[0];
338
-
339
- if (targetEl) {
340
- targetEl.focus();
341
- const fs = window.getComputedStyle(targetEl);
342
- const hasOutline = fs.outlineStyle !== 'none' && parseFloat(fs.outlineWidth) > 0;
343
- const hasShadow = fs.boxShadow && fs.boxShadow !== 'none';
344
- focusVisibleRendered = hasOutline || hasShadow;
345
- // Physical outline required for forced-colors: active
346
- highContrastOutlineRendered = hasOutline;
347
- }
348
-
349
- return {
350
- buttonCount: buttons.length,
351
- hitTargetViolations,
352
- minContrastRatio: Math.round(minContrast * 10) / 10,
353
- focusVisibleRendered,
354
- highContrastOutlineRendered,
355
- debugContrast
356
- };
357
- })()
358
- `;
359
-
360
- const evalRes = await client.send('Runtime.evaluate', {
361
- expression: inspectExpr,
362
- returnByValue: true
363
- });
364
-
365
- const data = evalRes.result.value || {};
366
- auditResults.push({
367
- viewport: vp.name,
368
- dimensions: `${vp.width}x${vp.height}`,
369
- theme: th,
370
- ...data
371
- });
372
- }
373
- } finally {
374
- await client.close();
375
- chromeProcess.kill();
376
- }
377
-
378
- let overallPass = true;
379
- auditResults.forEach(r => {
380
- const isForced = r.theme === 'forced-colors';
381
- const contrastPass = isForced ? true : r.minContrastRatio >= 4.5;
382
- const hitTargetPass = r.hitTargetViolations.length === 0;
383
- const focusPass = isForced
384
- ? (r.highContrastOutlineRendered || r.buttonCount === 0)
385
- : (r.focusVisibleRendered || r.buttonCount === 0);
386
-
387
- if (!contrastPass || !hitTargetPass || !focusPass) overallPass = false;
388
- });
389
-
390
- if (isJson) {
391
- console.log(JSON.stringify({
392
- target: targetFile,
393
- passed: overallPass,
394
- matrix: auditResults
395
- }, null, 2));
396
- process.exit(overallPass ? 0 : 1);
397
- }
398
-
399
- // Render Matrix Card
400
- console.log(`\n${ANSI_BOLD}ME-DESIGN Phase 2 — Browser Verification Matrix${ANSI_RESET}`);
401
- console.log(`${ANSI_CYAN}Headless Chromium Runtime Engine (CDP v156)${ANSI_RESET}`);
402
- console.log(`${ANSI_GRAY}────────────────────────────────────────────────────────────────────────${ANSI_RESET}`);
403
- console.log(`Target: ${path.basename(targetFile)}\n`);
404
-
405
- console.log(`${'VIEWPORT'.padEnd(10)} | ${'MODE'.padEnd(14)} | ${'CONTRAST'.padEnd(10)} | ${'HIT-TARGET (≥44px)'.padEnd(20)} | ${'TAB FOCUS'.padEnd(10)}`);
406
- console.log(`${ANSI_GRAY}------------------------------------------------------------------------${ANSI_RESET}`);
407
-
408
- auditResults.forEach(r => {
409
- const isForced = r.theme === 'forced-colors';
410
- const contrastPass = isForced ? true : r.minContrastRatio >= 4.5;
411
- const hitTargetPass = r.hitTargetViolations.length === 0;
412
- const focusPass = isForced
413
- ? (r.highContrastOutlineRendered || r.buttonCount === 0)
414
- : (r.focusVisibleRendered || r.buttonCount === 0);
415
-
416
- const contrastStr = isForced
417
- ? ANSI_CYAN + 'SYS-HIGH' + ANSI_RESET
418
- : (contrastPass ? ANSI_GREEN : ANSI_RED) + `${r.minContrastRatio}:1` + ANSI_RESET;
419
-
420
- const hitStr = hitTargetPass
421
- ? ANSI_GREEN + 'OK (All ≥44px)' + ANSI_RESET
422
- : ANSI_RED + `FAIL (${r.hitTargetViolations.length} under 44px)` + ANSI_RESET;
423
-
424
- const focusStr = (focusPass ? ANSI_GREEN : ANSI_RED) + (focusPass ? (isForced ? 'OUTLINE OK' : 'VERIFIED') : (isForced ? 'NO OUTLINE' : 'NO FOCUS')) + ANSI_RESET;
425
-
426
- console.log(`${r.viewport.padEnd(10)} | ${r.theme.padEnd(14)} | ${contrastStr.padEnd(19)} | ${hitStr.padEnd(31)} | ${focusStr}`);
427
- });
428
-
429
- console.log(`${ANSI_GRAY}────────────────────────────────────────────────────────────────────────${ANSI_RESET}`);
430
- if (overallPass) {
431
- console.log(`${ANSI_GREEN}${ANSI_BOLD}BROWSER MATRIX VERIFICATION: PASS (Exit Code: 0)${ANSI_RESET}\n`);
432
- process.exit(0);
433
- } else {
434
- console.log(`${ANSI_RED}${ANSI_BOLD}BROWSER MATRIX VERIFICATION: FAIL (Exit Code: 1)${ANSI_RESET}\n`);
435
- process.exit(1);
436
- }
437
- }
438
-
439
- runAudit().catch(err => {
440
- console.error('Browser Audit Error:', err);
441
- process.exit(1);
442
- });
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * ME-DESIGN Phase 2 — Rendered DOM & Headless Browser Verification Engine
5
+ * Direct Chrome DevTools Protocol (CDP) client over native WebSocket.
6
+ * Zero external npm dependencies.
7
+ *
8
+ * Verifies:
9
+ * 1. Real Computed Contrast Ratio across backgrounds
10
+ * 2. Real Keyboard Tab Navigation & Focus Ring rendering (:focus-visible)
11
+ * 3. Windows High Contrast Mode (forced-colors: active) physical outline persistence
12
+ * 4. Hit-Target Bounding Dimensions (44px min touch standard)
13
+ * 5. Responsive Viewports (Mobile 390px, Tablet 820px, Desktop 1440px)
14
+ * 6. Theme Modes (Dark & Light)
15
+ *
16
+ * Usage: node tests/browser-audit.js <filepath> [--json]
17
+ */
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const { spawn } = require('child_process');
22
+
23
+ const ANSI_RESET = '\x1b[0m';
24
+ const ANSI_BOLD = '\x1b[1m';
25
+ const ANSI_GREEN = '\x1b[32m';
26
+ const ANSI_RED = '\x1b[31m';
27
+ const ANSI_YELLOW = '\x1b[33m';
28
+ const ANSI_CYAN = '\x1b[36m';
29
+ const ANSI_GRAY = '\x1b[90m';
30
+
31
+ const args = process.argv.slice(2);
32
+
33
+ if (args.includes('--help') || args.includes('-h')) {
34
+ console.log(`
35
+ \x1b[1mME-DESIGN Browser Audit Engine\x1b[0m
36
+ \x1b[90mHeadless Chrome DevTools Protocol verification matrix (7 conditions)\x1b[0m
37
+
38
+ \x1b[1mUsage:\x1b[0m
39
+ medesign audit <file> [options]
40
+
41
+ \x1b[1mOptions:\x1b[0m
42
+ --json Output results in JSON format
43
+ `);
44
+ process.exit(0);
45
+ }
46
+ let targetFile = null;
47
+ let isJson = false;
48
+
49
+ for (let i = 0; i < args.length; i++) {
50
+ if (args[i] === '--json') {
51
+ isJson = true;
52
+ } else if (!targetFile && !args[i].startsWith('--')) {
53
+ targetFile = args[i];
54
+ }
55
+ }
56
+
57
+ targetFile = targetFile || path.join(__dirname, 'fixtures', 'valid', 'metha-cadastre-dashboard.html');
58
+
59
+ if (!fs.existsSync(targetFile)) {
60
+ console.error(`Error: File not found: ${targetFile}`);
61
+ process.exit(2);
62
+ }
63
+
64
+ const resolvedPath = path.resolve(targetFile);
65
+ const fileUrl = 'file:///' + resolvedPath.replace(/\\/g, '/');
66
+
67
+ // Locate Chromium executable across Windows, Linux, and macOS
68
+ function findChromium() {
69
+ const envPath = process.env.CHROME_PATH || process.env.CHROME_BIN;
70
+ if (envPath && fs.existsSync(envPath)) return envPath;
71
+
72
+ const localApp = process.env.LOCALAPPDATA || '';
73
+ const pwDir = path.join(localApp, 'ms-playwright');
74
+ if (fs.existsSync(pwDir)) {
75
+ try {
76
+ const entries = fs.readdirSync(pwDir);
77
+ const chromiumDirs = entries.filter(e => e.startsWith('chromium-')).sort().reverse();
78
+ for (const cDir of chromiumDirs) {
79
+ const p = path.join(pwDir, cDir, 'chrome-win64', 'chrome.exe');
80
+ if (fs.existsSync(p)) return p;
81
+ }
82
+ } catch (e) {}
83
+ }
84
+
85
+ const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';
86
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
87
+
88
+ const alternatives = [
89
+ path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
90
+ path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
91
+ path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
92
+ path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
93
+ '/usr/bin/google-chrome',
94
+ '/usr/bin/google-chrome-stable',
95
+ '/usr/bin/chromium',
96
+ '/usr/bin/chromium-browser',
97
+ '/snap/bin/chromium',
98
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
99
+ '/Applications/Chromium.app/Contents/MacOS/Chromium'
100
+ ];
101
+
102
+ for (const p of alternatives) {
103
+ if (fs.existsSync(p)) return p;
104
+ }
105
+ return null;
106
+ }
107
+
108
+ const chromePath = findChromium();
109
+ if (!chromePath) {
110
+ console.error('Error: Chromium/Chrome binary not found on system.');
111
+ process.exit(2);
112
+ }
113
+
114
+ // Minimal JSON-RPC CDP Client over Node's native global WebSocket
115
+ class CDPClient {
116
+ constructor(port) {
117
+ this.port = port;
118
+ this.ws = null;
119
+ this.msgId = 0;
120
+ this.callbacks = new Map();
121
+ }
122
+
123
+ async connect(targetUrl) {
124
+ const res = await fetch(`http://127.0.0.1:${this.port}/json/new`, { method: 'PUT' });
125
+ const target = await res.json();
126
+ this.targetId = target.id;
127
+ this.ws = new WebSocket(target.webSocketDebuggerUrl);
128
+
129
+ await new Promise((resolve, reject) => {
130
+ this.ws.onopen = resolve;
131
+ this.ws.onerror = reject;
132
+ });
133
+
134
+ this.ws.onmessage = (event) => {
135
+ const msg = JSON.parse(event.data);
136
+ if (msg.id && this.callbacks.has(msg.id)) {
137
+ const { resolve, reject } = this.callbacks.get(msg.id);
138
+ this.callbacks.delete(msg.id);
139
+ if (msg.error) reject(msg.error);
140
+ else resolve(msg.result);
141
+ }
142
+ };
143
+ }
144
+
145
+ send(method, params = {}) {
146
+ return new Promise((resolve, reject) => {
147
+ const id = ++this.msgId;
148
+ this.callbacks.set(id, { resolve, reject });
149
+ this.ws.send(JSON.stringify({ id, method, params }));
150
+ });
151
+ }
152
+
153
+ async close() {
154
+ if (this.ws) {
155
+ try { this.ws.close(); } catch (e) {}
156
+ }
157
+ try {
158
+ await fetch(`http://127.0.0.1:${this.port}/json/close/${this.targetId}`, { method: 'PUT' });
159
+ } catch (e) {}
160
+ }
161
+ }
162
+
163
+ async function runAudit() {
164
+ const cdpPort = 9444 + Math.floor(Math.random() * 200);
165
+ const chromeProcess = spawn(chromePath, [
166
+ '--headless=new',
167
+ `--remote-debugging-port=${cdpPort}`,
168
+ '--no-first-run',
169
+ '--disable-gpu',
170
+ '--no-sandbox',
171
+ '--disable-extensions',
172
+ '--mute-audio',
173
+ '--hide-scrollbars'
174
+ ]);
175
+
176
+ // Wait for CDP readiness
177
+ let ready = false;
178
+ for (let i = 0; i < 25; i++) {
179
+ try {
180
+ const r = await fetch(`http://127.0.0.1:${cdpPort}/json/version`);
181
+ if (r.ok) { ready = true; break; }
182
+ } catch (e) {}
183
+ await new Promise(res => setTimeout(res, 100));
184
+ }
185
+
186
+ if (!ready) {
187
+ chromeProcess.kill();
188
+ console.error('Failed to connect to headless Chromium instance.');
189
+ process.exit(1);
190
+ }
191
+
192
+ const client = new CDPClient(cdpPort);
193
+ await client.connect();
194
+
195
+ // Full 7-Condition Test Matrix:
196
+ // 3 Viewports (Mobile, Tablet, Desktop) × 2 Themes (Dark, Light) + Windows High Contrast (forced-colors: active)
197
+ const testMatrix = [
198
+ { viewport: { name: 'Mobile', width: 390, height: 844, isMobile: true }, theme: 'dark', forcedColors: false },
199
+ { viewport: { name: 'Mobile', width: 390, height: 844, isMobile: true }, theme: 'light', forcedColors: false },
200
+ { viewport: { name: 'Tablet', width: 820, height: 1180, isMobile: true }, theme: 'dark', forcedColors: false },
201
+ { viewport: { name: 'Tablet', width: 820, height: 1180, isMobile: true }, theme: 'light', forcedColors: false },
202
+ { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'dark', forcedColors: false },
203
+ { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'light', forcedColors: false },
204
+ // Condition 7: Windows High Contrast Emulation (forced-colors: active)
205
+ { viewport: { name: 'Desktop', width: 1440, height: 900, isMobile: false }, theme: 'forced-colors', forcedColors: true }
206
+ ];
207
+
208
+ const auditResults = [];
209
+
210
+ try {
211
+ await client.send('Page.enable');
212
+ await client.send('DOM.enable');
213
+ await client.send('Runtime.enable');
214
+
215
+ for (const testCase of testMatrix) {
216
+ const vp = testCase.viewport;
217
+ const th = testCase.theme;
218
+
219
+ // Set Device Metrics
220
+ await client.send('Emulation.setDeviceMetricsOverride', {
221
+ width: vp.width,
222
+ height: vp.height,
223
+ deviceScaleFactor: 2,
224
+ mobile: vp.isMobile
225
+ });
226
+
227
+ // Set Emulated Color Scheme and Forced Colors
228
+ const features = [
229
+ { name: 'prefers-color-scheme', value: testCase.forcedColors ? 'dark' : th }
230
+ ];
231
+ if (testCase.forcedColors) {
232
+ features.push({ name: 'forced-colors', value: 'active' });
233
+ } else {
234
+ features.push({ name: 'forced-colors', value: 'none' });
235
+ }
236
+
237
+ await client.send('Emulation.setEmulatedMedia', {
238
+ media: 'screen',
239
+ features
240
+ });
241
+
242
+ // Navigate
243
+ await client.send('Page.navigate', { url: fileUrl });
244
+ await new Promise(res => setTimeout(res, 250)); // Wait for render and styles to settle
245
+
246
+ // Dispatch real keyboard Tab navigation event
247
+ await client.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
248
+ await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
249
+ await new Promise(res => setTimeout(res, 50));
250
+
251
+ // Perform in-page inspection
252
+ const inspectExpr = `
253
+ (() => {
254
+ // Relative luminance calculator
255
+ function getLuminance(r, g, b) {
256
+ const [rs, gs, bs] = [r, g, b].map(c => {
257
+ c = c / 255;
258
+ return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
259
+ });
260
+ return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
261
+ }
262
+
263
+ // Shared 1x1 canvas for hardware-exact pixel color rasterization
264
+ const pixelCanvas = document.createElement('canvas');
265
+ pixelCanvas.width = 1;
266
+ pixelCanvas.height = 1;
267
+ const pixelCtx = pixelCanvas.getContext('2d', { willReadFrequently: true });
268
+
269
+ function parseRgba(colorStr) {
270
+ if (!colorStr) return [0, 0, 0, 1];
271
+ try {
272
+ pixelCtx.clearRect(0, 0, 1, 1);
273
+ pixelCtx.fillStyle = colorStr;
274
+ pixelCtx.fillRect(0, 0, 1, 1);
275
+ const d = pixelCtx.getImageData(0, 0, 1, 1).data;
276
+ return [d[0], d[1], d[2], d[3] / 255];
277
+ } catch (e) {
278
+ return [255, 255, 255, 1];
279
+ }
280
+ }
281
+
282
+ function getContrastRatio(fgRgb, bgRgb) {
283
+ const l1 = getLuminance(fgRgb[0], fgRgb[1], fgRgb[2]);
284
+ const l2 = getLuminance(bgRgb[0], bgRgb[1], bgRgb[2]);
285
+ const lighter = Math.max(l1, l2);
286
+ const darker = Math.min(l1, l2);
287
+ return (lighter + 0.05) / (darker + 0.05);
288
+ }
289
+
290
+ function isDemoAntiPattern(el) {
291
+ return el.closest('.con') || el.classList.contains('con') || el.closest('[data-anti-pattern]') || el.classList.contains('btn-slop') || el.closest('.cmp-col:has(.btn-slop)') || el.closest('.cmp-col:has(.thai-crop-bad)');
292
+ }
293
+
294
+ // Test 1: Hit-Target Dimensions (min 44x44px for touch)
295
+ const buttons = Array.from(document.querySelectorAll('button, [role="button"], a.btn, .action-btn, .pill-btn-container, .telemetry-btn, .btn-ring')).filter(b => !isDemoAntiPattern(b));
296
+ const hitTargetViolations = [];
297
+ buttons.forEach(b => {
298
+ const rect = b.getBoundingClientRect();
299
+ if (rect.width > 0 && rect.height > 0) {
300
+ if (rect.width < 43.5 || rect.height < 43.5) {
301
+ hitTargetViolations.push({
302
+ tag: b.tagName.toLowerCase(),
303
+ text: b.textContent.trim().slice(0, 20),
304
+ width: Math.round(rect.width),
305
+ height: Math.round(rect.height)
306
+ });
307
+ }
308
+ }
309
+ });
310
+
311
+ // Test 2: Real Computed Contrast Ratio against actual background
312
+ const texts = Array.from(document.querySelectorAll('h1, h2, h3, p, td, th, span, label, .visual-surface')).filter(el => {
313
+ return !isDemoAntiPattern(el) && el.children.length === 0 && el.textContent.trim().length > 0;
314
+ }).slice(0, 20);
315
+
316
+ let minContrast = 21.0;
317
+ const debugContrast = [];
318
+
319
+ texts.forEach(el => {
320
+ const cs = window.getComputedStyle(el);
321
+ if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return;
322
+
323
+ const fg = parseRgba(cs.color);
324
+ let solidBg = [9, 9, 11];
325
+ const overlays = [];
326
+
327
+ let p = el;
328
+ while (p && p !== document) {
329
+ const bgStr = window.getComputedStyle(p).backgroundColor;
330
+ if (bgStr && bgStr !== 'transparent') {
331
+ const rgba = parseRgba(bgStr);
332
+ if (rgba[3] >= 0.90) {
333
+ solidBg = [rgba[0], rgba[1], rgba[2]];
334
+ break;
335
+ } else if (rgba[3] > 0) {
336
+ overlays.unshift(rgba);
337
+ }
338
+ }
339
+ p = p.parentElement;
340
+ }
341
+
342
+ let compositeBg = [...solidBg];
343
+ overlays.forEach(([r, g, b, a]) => {
344
+ compositeBg[0] = Math.round(r * a + compositeBg[0] * (1 - a));
345
+ compositeBg[1] = Math.round(g * a + compositeBg[1] * (1 - a));
346
+ compositeBg[2] = Math.round(b * a + compositeBg[2] * (1 - a));
347
+ });
348
+ const cr = getContrastRatio(fg, compositeBg);
349
+ debugContrast.push({ tag: el.tagName, text: el.textContent.trim().slice(0, 20), fg: fg.slice(0,3), bg: compositeBg, cr: Math.round(cr * 10) / 10 });
350
+ if (cr < minContrast) minContrast = cr;
351
+ });
352
+
353
+ // Test 3: Active Element Tab Focus Outline
354
+ let focusVisibleRendered = false;
355
+ let highContrastOutlineRendered = false;
356
+ const targetEl = (document.activeElement && document.activeElement !== document.body)
357
+ ? document.activeElement
358
+ : buttons[0];
359
+
360
+ if (targetEl) {
361
+ targetEl.focus();
362
+ const fs = window.getComputedStyle(targetEl);
363
+ const hasOutline = fs.outlineStyle !== 'none' && parseFloat(fs.outlineWidth) > 0;
364
+ const hasShadow = fs.boxShadow && fs.boxShadow !== 'none';
365
+ focusVisibleRendered = hasOutline || hasShadow;
366
+ // Physical outline required for forced-colors: active
367
+ highContrastOutlineRendered = hasOutline;
368
+ }
369
+
370
+ return {
371
+ buttonCount: buttons.length,
372
+ hitTargetViolations,
373
+ minContrastRatio: Math.round(minContrast * 10) / 10,
374
+ focusVisibleRendered,
375
+ highContrastOutlineRendered,
376
+ debugContrast
377
+ };
378
+ })()
379
+ `;
380
+
381
+ const evalRes = await client.send('Runtime.evaluate', {
382
+ expression: inspectExpr,
383
+ returnByValue: true
384
+ });
385
+
386
+ const data = evalRes.result.value || {};
387
+ auditResults.push({
388
+ viewport: vp.name,
389
+ dimensions: `${vp.width}x${vp.height}`,
390
+ theme: th,
391
+ ...data
392
+ });
393
+ }
394
+ } finally {
395
+ await client.close();
396
+ chromeProcess.kill();
397
+ }
398
+
399
+ let overallPass = true;
400
+ auditResults.forEach(r => {
401
+ const isForced = r.theme === 'forced-colors';
402
+ const contrastPass = isForced ? true : r.minContrastRatio >= 4.5;
403
+ const hitTargetPass = r.hitTargetViolations.length === 0;
404
+ const focusPass = isForced
405
+ ? (r.highContrastOutlineRendered || r.buttonCount === 0)
406
+ : (r.focusVisibleRendered || r.buttonCount === 0);
407
+
408
+ if (!contrastPass || !hitTargetPass || !focusPass) overallPass = false;
409
+ });
410
+
411
+ if (isJson) {
412
+ console.log(JSON.stringify({
413
+ target: targetFile,
414
+ passed: overallPass,
415
+ matrix: auditResults
416
+ }, null, 2));
417
+ process.exit(overallPass ? 0 : 1);
418
+ }
419
+
420
+ // Render Matrix Card
421
+ console.log(`\n${ANSI_BOLD}ME-DESIGN Phase 2 — Browser Verification Matrix${ANSI_RESET}`);
422
+ console.log(`${ANSI_CYAN}Headless Chromium Runtime Engine (CDP v156)${ANSI_RESET}`);
423
+ console.log(`${ANSI_GRAY}────────────────────────────────────────────────────────────────────────${ANSI_RESET}`);
424
+ console.log(`Target: ${path.basename(targetFile)}\n`);
425
+
426
+ console.log(`${'VIEWPORT'.padEnd(10)} | ${'MODE'.padEnd(14)} | ${'CONTRAST'.padEnd(10)} | ${'HIT-TARGET (≥44px)'.padEnd(20)} | ${'TAB FOCUS'.padEnd(10)}`);
427
+ console.log(`${ANSI_GRAY}------------------------------------------------------------------------${ANSI_RESET}`);
428
+
429
+ auditResults.forEach(r => {
430
+ const isForced = r.theme === 'forced-colors';
431
+ const contrastPass = isForced ? true : r.minContrastRatio >= 4.5;
432
+ const hitTargetPass = r.hitTargetViolations.length === 0;
433
+ const focusPass = isForced
434
+ ? (r.highContrastOutlineRendered || r.buttonCount === 0)
435
+ : (r.focusVisibleRendered || r.buttonCount === 0);
436
+
437
+ const contrastStr = isForced
438
+ ? ANSI_CYAN + 'SYS-HIGH' + ANSI_RESET
439
+ : (contrastPass ? ANSI_GREEN : ANSI_RED) + `${r.minContrastRatio}:1` + ANSI_RESET;
440
+
441
+ const hitStr = hitTargetPass
442
+ ? ANSI_GREEN + 'OK (All ≥44px)' + ANSI_RESET
443
+ : ANSI_RED + `FAIL (${r.hitTargetViolations.length} under 44px)` + ANSI_RESET;
444
+
445
+ const focusStr = (focusPass ? ANSI_GREEN : ANSI_RED) + (focusPass ? (isForced ? 'OUTLINE OK' : 'VERIFIED') : (isForced ? 'NO OUTLINE' : 'NO FOCUS')) + ANSI_RESET;
446
+
447
+ console.log(`${r.viewport.padEnd(10)} | ${r.theme.padEnd(14)} | ${contrastStr.padEnd(19)} | ${hitStr.padEnd(31)} | ${focusStr}`);
448
+ });
449
+
450
+ console.log(`${ANSI_GRAY}────────────────────────────────────────────────────────────────────────${ANSI_RESET}`);
451
+ if (overallPass) {
452
+ console.log(`${ANSI_GREEN}${ANSI_BOLD}BROWSER MATRIX VERIFICATION: PASS (Exit Code: 0)${ANSI_RESET}\n`);
453
+ process.exit(0);
454
+ } else {
455
+ console.log(`${ANSI_RED}${ANSI_BOLD}BROWSER MATRIX VERIFICATION: FAIL (Exit Code: 1)${ANSI_RESET}\n`);
456
+ process.exit(1);
457
+ }
458
+ }
459
+
460
+ runAudit().catch(err => {
461
+ console.error('Browser Audit Error:', err);
462
+ process.exit(1);
463
+ });