auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

align.mjs (15971B)


      1 #!/usr/bin/env node
      2 // Table alignment gate: zero-size inline-block baseline probes, zero spread.
      3 // Rows whose computed display is none (pager/search-hidden) are skipped.
      4 //
      5 //   node tools/css-check/align.mjs
      6 //   node tools/css-check/align.mjs --fixture tools/css-check/fixtures/negative-misaligned.html
      7 //   node tools/css-check/align.mjs --url http://127.0.0.1:8080/index.html
      8 //
      9 // Options: --url, --fixture <file> (repeatable), --widths 1440,390,
     10 //          --themes auto,light,dark, --chrome <binary>
     11 
     12 import { spawn } from 'node:child_process';
     13 import fs from 'node:fs';
     14 import os from 'node:os';
     15 import path from 'node:path';
     16 import process from 'node:process';
     17 
     18 const FIXTURE_DIR = path.join(import.meta.dirname, 'fixtures');
     19 
     20 function flagValue(name, dflt) {
     21   const i = process.argv.indexOf(name);
     22   return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : dflt;
     23 }
     24 
     25 function flagAll(name) {
     26   const out = [];
     27   for (let i = 0; i < process.argv.length; i += 1) {
     28     if (process.argv[i] === name && process.argv[i + 1]) out.push(process.argv[i + 1]);
     29   }
     30   return out;
     31 }
     32 
     33 const CHROME = flagValue(
     34   '--chrome',
     35   process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
     36 );
     37 const WIDTHS = flagValue('--widths', '1440,390').split(',').map(Number);
     38 const THEMES = flagValue('--themes', 'auto,light,dark').split(',');
     39 
     40 function targetList() {
     41   const url = flagValue('--url', null);
     42   if (url) return [{ label: url, url, negative: false }];
     43   const fixtures = flagAll('--fixture');
     44   if (fixtures.length) {
     45     return fixtures.map((f) => {
     46       const full = path.resolve(f);
     47       return {
     48         label: path.basename(full),
     49         url: new URL(`file://${full}`).href,
     50         negative: path.basename(full).startsWith('negative-'),
     51       };
     52     });
     53   }
     54   return fs
     55     .readdirSync(FIXTURE_DIR)
     56     .filter((f) => f.endsWith('.html'))
     57     .sort()
     58     .map((f) => ({
     59       label: f,
     60       url: new URL(`file://${path.join(FIXTURE_DIR, f)}`).href,
     61       negative: f.startsWith('negative-'),
     62     }));
     63 }
     64 
     65 const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
     66 
     67 async function waitForPort(userDir, timeoutMs = 25000) {
     68   const file = path.join(userDir, 'DevToolsActivePort');
     69   const deadline = Date.now() + timeoutMs;
     70   while (Date.now() < deadline) {
     71     if (fs.existsSync(file)) {
     72       const text = fs.readFileSync(file, 'utf8').trim();
     73       if (text) return text.split('\n')[0].trim();
     74     }
     75     await sleep(100);
     76   }
     77   throw new Error('chrome did not write DevToolsActivePort');
     78 }
     79 
     80 function connectCdp(wsUrl) {
     81   const ws = new WebSocket(wsUrl);
     82   const pending = new Map();
     83   const eventWaiters = [];
     84   let nextId = 1;
     85 
     86   ws.addEventListener('message', (event) => {
     87     const msg = JSON.parse(event.data);
     88     if (msg.id && pending.has(msg.id)) {
     89       const { resolve, reject } = pending.get(msg.id);
     90       pending.delete(msg.id);
     91       if (msg.error) reject(new Error(`${msg.error.message} (${msg.method})`));
     92       else resolve(msg.result);
     93     } else if (msg.method) {
     94       for (let i = eventWaiters.length - 1; i >= 0; i -= 1) {
     95         const w = eventWaiters[i];
     96         if (w.method === msg.method) {
     97           eventWaiters.splice(i, 1);
     98           w.resolve(msg);
     99         }
    100       }
    101     }
    102   });
    103 
    104   return new Promise((resolveInit, rejectInit) => {
    105     ws.addEventListener('error', () => rejectInit(new Error(`cdp websocket failed: ${wsUrl}`)));
    106     ws.addEventListener('open', () => {
    107       resolveInit({
    108         send(method, params = {}) {
    109           const id = nextId;
    110           nextId += 1;
    111           ws.send(JSON.stringify({ id, method, params }));
    112           return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
    113         },
    114         waitEvent(method, timeoutMs = 20000) {
    115           return new Promise((resolve, reject) => {
    116             const timer = setTimeout(() => reject(new Error(`timeout waiting for ${method}`)), timeoutMs);
    117             eventWaiters.push({
    118               method,
    119               resolve: (msg) => {
    120                 clearTimeout(timer);
    121                 resolve(msg);
    122               },
    123             });
    124           });
    125         },
    126         close() {
    127           ws.close();
    128         },
    129       });
    130     });
    131   });
    132 }
    133 
    134 function measurementExpression(theme) {
    135   return `
    136 (function () {
    137   if (${JSON.stringify(theme)} === 'auto') {
    138     document.documentElement.removeAttribute('data-theme');
    139   } else {
    140     document.documentElement.setAttribute('data-theme', ${JSON.stringify(theme)});
    141   }
    142   var Q = 64; // browser layout precision: multiples of 1/64 of a CSS pixel
    143   function q(v) { return Math.round(v * Q); }
    144 
    145   var out = {
    146     tables: 0, rows: 0, hiddenRows: 0, multiCells: 0, allTallRows: 0, mode: 'none',
    147     maxSpreadGrid: 0, captions: 0, fail: []
    148   };
    149 
    150   function hasBlockChild(cell) {
    151     var kids = cell.children;
    152     for (var i = 0; i < kids.length; i += 1) {
    153       var d = window.getComputedStyle(kids[i]).display;
    154       if (d !== 'inline' && d !== 'inline-block' && d !== 'none') return true;
    155     }
    156     return false;
    157   }
    158 
    159   function lineBands(cell) {
    160     var range = document.createRange();
    161     range.selectNodeContents(cell);
    162     var rects = range.getClientRects();
    163     var sorted = [];
    164     for (var i = 0; i < rects.length; i += 1) {
    165       if (rects[i].height > 0) sorted.push(rects[i]);
    166     }
    167     sorted.sort(function (a, b) { return a.top - b.top; });
    168     var bands = 0;
    169     var bottom = -Infinity;
    170     for (var j = 0; j < sorted.length; j += 1) {
    171       if (sorted[j].top > bottom) { bands += 1; bottom = sorted[j].bottom; }
    172       else if (sorted[j].bottom > bottom) bottom = sorted[j].bottom;
    173     }
    174     return bands;
    175   }
    176 
    177   function probeBaseline(cell, where) {
    178     var probe = document.createElement('span');
    179     probe.style.cssText = 'display:inline-block;width:0;height:0;';
    180     cell.appendChild(probe);
    181     var rect = probe.getBoundingClientRect();
    182     cell.removeChild(probe);
    183     if (rect.width !== 0 || rect.height !== 0 || !isFinite(rect.bottom)) {
    184       out.fail.push(where + ': probe is not a zero-size inline-block');
    185       return null;
    186     }
    187     return rect.bottom;
    188   }
    189 
    190   var tables = document.querySelectorAll('table.table');
    191   out.tables = tables.length;
    192   if (!tables.length) {
    193     out.fail.push('no table.table found on the page');
    194     return JSON.stringify(out);
    195   }
    196   var tableMode = window.matchMedia('(min-width: 40em)').matches;
    197   out.mode = tableMode ? 'table' : 'card';
    198 
    199   for (var t = 0; t < tables.length; t += 1) {
    200     var table = tables[t];
    201     var at = 'table ' + (t + 1);
    202     var rows = table.querySelectorAll('tbody tr');
    203     if (!rows.length) {
    204       out.fail.push(at + ': no tbody rows (degenerate table)');
    205       continue;
    206     }
    207 
    208     if (tableMode) {
    209       var thead = table.querySelector('thead');
    210       if (!thead || window.getComputedStyle(thead).display === 'none') {
    211         out.fail.push(at + ': thead is not rendered in table mode');
    212       }
    213       for (var r = 0; r < rows.length; r += 1) {
    214         if (window.getComputedStyle(rows[r]).display === 'none') {
    215           out.hiddenRows += 1;
    216           continue;
    217         }
    218         var cells = rows[r].querySelectorAll('td');
    219         var baselines = [];
    220         var filledCells = 0;
    221         var tallCells = 0;
    222         var where = at + ' row ' + (r + 1);
    223         for (var c = 0; c < cells.length; c += 1) {
    224           var cell = cells[c];
    225           var cs = window.getComputedStyle(cell);
    226           if (cs.display === 'none') continue;
    227           if (cs.display !== 'table-cell') {
    228             out.fail.push(where + ' cell ' + (c + 1) + ': display is "' + cs.display + '", expected table-cell');
    229           }
    230           var caption = window.getComputedStyle(cell, '::before').content;
    231           if (cell.hasAttribute('data-label') && caption && caption !== 'none' && caption !== 'normal') {
    232             out.fail.push(where + ' cell ' + (c + 1) + ': data-label caption still renders in table mode');
    233           }
    234           if (cell.textContent.trim() === '' && !cell.children.length) continue;
    235           filledCells += 1;
    236           if (hasBlockChild(cell) || lineBands(cell) > 1) {
    237             out.multiCells += 1;
    238             tallCells += 1;
    239             continue;
    240           }
    241           var base = probeBaseline(cell, where + ' cell ' + (c + 1));
    242           if (base !== null) baselines.push(base);
    243         }
    244         out.rows += 1;
    245         // A row needs two single-line cells to disagree. With fewer than two
    246         // non-empty cells, or no measurable content at all, it is degenerate.
    247         if (filledCells < 2 || baselines.length + tallCells === 0) {
    248           out.fail.push(where + ': degenerate row (' + filledCells + ' non-empty cell(s), ' + (baselines.length + tallCells) + ' measured)');
    249           continue;
    250         }
    251         // A well-formed all-tall row centers by the UA default and has no
    252         // pair of single-line cells to compare; it is exempt, not vacuous.
    253         if (baselines.length < 2) {
    254           out.allTallRows += 1;
    255           continue;
    256         }
    257         var lo = Math.min.apply(null, baselines);
    258         var hi = Math.max.apply(null, baselines);
    259         var glo = q(lo);
    260         var ghi = q(hi);
    261         if (ghi - glo !== 0) {
    262           out.fail.push(where + ': baseline spread = ' + (ghi - glo) + '/64 across ' + baselines.length + ' single-line cells');
    263         }
    264         if (ghi - glo > out.maxSpreadGrid) {
    265           out.maxSpreadGrid = ghi - glo;
    266         }
    267       }
    268     } else {
    269       var thead2 = table.querySelector('thead');
    270       if (thead2 && window.getComputedStyle(thead2).display !== 'none') {
    271         out.fail.push(at + ': thead is visible in card mode');
    272       }
    273       for (var r2 = 0; r2 < rows.length; r2 += 1) {
    274         if (window.getComputedStyle(rows[r2]).display === 'none') {
    275           out.hiddenRows += 1;
    276           continue;
    277         }
    278         var cells2 = rows[r2].querySelectorAll('td');
    279         if (!cells2.length) {
    280           out.fail.push(at + ' row ' + (r2 + 1) + ': no cells to stack');
    281           continue;
    282         }
    283         out.rows += 1;
    284         var trDisplay = window.getComputedStyle(rows[r2]).display;
    285         if (trDisplay !== 'block') {
    286           out.fail.push(at + ' row ' + (r2 + 1) + ': tr display is "' + trDisplay + '", expected block');
    287         }
    288         var widths = [];
    289         var lastTop = -Infinity;
    290         for (var c2 = 0; c2 < cells2.length; c2 += 1) {
    291           var cell2 = cells2[c2];
    292           var cs2 = window.getComputedStyle(cell2);
    293           if (cs2.display !== 'block') {
    294             out.fail.push(at + ' row ' + (r2 + 1) + ' cell ' + (c2 + 1) + ': display is "' + cs2.display + '", expected block');
    295           }
    296           var rect2 = cell2.getBoundingClientRect();
    297           widths.push(q(rect2.width));
    298           if (rect2.top < lastTop) {
    299             out.fail.push(at + ' row ' + (r2 + 1) + ' cell ' + (c2 + 1) + ': not stacked below its sibling');
    300           }
    301           lastTop = rect2.top;
    302           var label = cell2.getAttribute('data-label');
    303           if (label !== null) {
    304             var before = window.getComputedStyle(cell2, '::before');
    305             if (before.display === 'none' || before.content !== JSON.stringify(label)) {
    306               out.fail.push(at + ' row ' + (r2 + 1) + ' cell ' + (c2 + 1) + ': data-label caption "' + label + '" does not render (content ' + before.content + ')');
    307             } else {
    308               out.captions += 1;
    309             }
    310           }
    311         }
    312         for (var k = 1; k < widths.length; k += 1) {
    313           if (widths[k] !== widths[0]) {
    314             out.fail.push(at + ' row ' + (r2 + 1) + ': cells are not one full-width column');
    315             break;
    316           }
    317         }
    318       }
    319     }
    320   }
    321   return JSON.stringify(out);
    322 })()
    323 `;
    324 }
    325 
    326 async function main() {
    327   if (!fs.existsSync(CHROME)) {
    328     console.error(`align: chrome binary not found: ${CHROME}`);
    329     process.exit(1);
    330   }
    331   const targets = targetList();
    332   const userDir = fs.mkdtempSync(path.join(os.tmpdir(), 'css-check-chrome-'));
    333   const chrome = spawn(
    334     CHROME,
    335     [
    336       '--headless=new',
    337       '--disable-gpu',
    338       '--hide-scrollbars',
    339       '--no-first-run',
    340       '--no-default-browser-check',
    341       '--remote-debugging-port=0',
    342       `--user-data-dir=${userDir}`,
    343       'about:blank',
    344     ],
    345     { stdio: 'ignore' },
    346   );
    347 
    348   let exitCode = 1;
    349   try {
    350     const port = await waitForPort(userDir);
    351     const cdpTargets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
    352     const page = cdpTargets.find((x) => x.type === 'page');
    353     if (!page) throw new Error('no page target');
    354     const cdp = await connectCdp(page.webSocketDebuggerUrl);
    355 
    356     await cdp.send('Page.enable');
    357     await cdp.send('Runtime.enable');
    358 
    359     console.log(`align: probe gate (zero-size inline-block baseline, zero spread) widths=${WIDTHS.join(',')} themes=${THEMES.join(',')}`);
    360 
    361     let failures = 0;
    362     for (const target of targets) {
    363       for (const width of WIDTHS) {
    364         for (const theme of THEMES) {
    365           const scheme = theme === 'dark' ? 'dark' : theme === 'light' ? 'light' : 'no-preference';
    366           await cdp.send('Emulation.setDeviceMetricsOverride', {
    367             width,
    368             height: 900,
    369             deviceScaleFactor: 1,
    370             mobile: width < 500,
    371           });
    372           await cdp.send('Emulation.setEmulatedMedia', {
    373             features: [{ name: 'prefers-color-scheme', value: scheme }],
    374           });
    375           const loaded = cdp.waitEvent('Page.loadEventFired');
    376           await cdp.send('Page.navigate', { url: target.url });
    377           await loaded;
    378           await sleep(150);
    379           const evaluated = await cdp.send('Runtime.evaluate', {
    380             expression: measurementExpression(theme),
    381             returnByValue: true,
    382           });
    383           if (evaluated.exceptionDetails) {
    384             throw new Error(`page evaluation failed for ${target.label} at ${width}/${theme}`);
    385           }
    386           const m = JSON.parse(evaluated.result.value);
    387           const gateRed = m.fail.length > 0 || m.tables === 0 || m.rows === 0;
    388 
    389           const head = `${target.label}  ${String(width).padStart(4)} ${theme.padEnd(4)}`;
    390           const stats =
    391             m.mode === 'table'
    392               ? `mode=table tables=${m.tables} rows=${m.rows} hidden=${m.hiddenRows} multi-cells=${m.multiCells} all-tall-rows=${m.allTallRows} max-baseline-spread=${m.maxSpreadGrid}/64`
    393               : `mode=card tables=${m.tables} rows=${m.rows} hidden=${m.hiddenRows} captions=${m.captions}`;
    394 
    395           if (target.negative && m.mode === 'table') {
    396             if (gateRed) {
    397               console.log(`  ${head}  RED-AS-EXPECTED  ${stats}`);
    398               for (const f of m.fail.slice(0, 3)) console.log(`      gate caught: ${f}`);
    399             } else {
    400               failures += 1;
    401               console.log(`  ${head}  FAIL  ${stats}`);
    402               console.log('      negative-control PASSED: the baseline gate is not measuring probes');
    403             }
    404           } else if (gateRed) {
    405             failures += 1;
    406             console.log(`  ${head}  FAIL  ${stats}`);
    407             for (const f of m.fail.slice(0, 5)) console.log(`      ${f}`);
    408           } else {
    409             console.log(`  ${head}  PASS  ${stats}`);
    410           }
    411         }
    412       }
    413     }
    414 
    415     if (failures) {
    416       console.log(`align: FAIL (${failures} failing combination(s))`);
    417       exitCode = 1;
    418     } else {
    419       console.log('align: PASS (all fixtures x widths x themes)');
    420       exitCode = 0;
    421     }
    422     cdp.close();
    423   } catch (err) {
    424     console.error(`align: ${err && err.message ? err.message : err}`);
    425     exitCode = 1;
    426   } finally {
    427     chrome.kill('SIGKILL');
    428     await new Promise((resolve) => {
    429       const timer = setTimeout(resolve, 3000);
    430       chrome.once('exit', () => {
    431         clearTimeout(timer);
    432         resolve(null);
    433       });
    434     });
    435     try {
    436       fs.rmSync(userDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
    437     } catch {
    438       // leftover temp profile is disposable
    439     }
    440   }
    441   process.exit(exitCode);
    442 }
    443 
    444 main();