auth

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

check.mjs (22374B)


      1 #!/usr/bin/env node
      2 // Static CSS verification for the shared framework and its consumers.
      3 // Dependency-free plain Node. Run from anywhere:
      4 //   node tools/css-check/check.mjs --scope repo
      5 //   node tools/css-check/check.mjs --scope app --app admin
      6 // Exit code 0 = green (warnings allowed while the transition allow-list is
      7 // populated), 1 = red.
      8 
      9 import fs from 'node:fs';
     10 import path from 'node:path';
     11 import process from 'node:process';
     12 
     13 const REPO = path.resolve(import.meta.dirname, '..', '..');
     14 
     15 // ---------------------------------------------------------------------------
     16 // transition allow-list: files that are being phased out by the migration.
     17 // While any of these exist, the no-copy guard runs warn-only, and token
     18 // violations inside them are warnings. Empty the list to make both hard.
     19 // ---------------------------------------------------------------------------
     20 const TRANSITION_ALLOW = [];
     21 
     22 const FRAMEWORK_CSS = 'app/shared/style/global.css';
     23 const COMPONENT_CSS_DIR = 'app/shared/component';
     24 const MOCKUP_DIR = 'mockup/plain';
     25 
     26 // source trees the framework governs: shared framework, consumers, mockups,
     27 // and this harness
     28 const MIGRATION_PREFIXES = ['app/', `${MOCKUP_DIR}/`, 'tools/'];
     29 // every source tree checked for plain-ASCII and code-comment hygiene
     30 const SCAN_ROOTS = ['app', 'mockup', 'tools'];
     31 const CSS_EXT = ['.css'];
     32 const CODE_EXT = ['.css', '.js', '.cjs', '.mjs', '.ts', '.tsx', '.html'];
     33 const SKIP_DIRS = new Set(['node_modules', 'dist', '.git']);
     34 
     35 // selectors from the old naming that must not gain new homes in mockup page
     36 // style blocks; the rename targets are defined by the framework instead.
     37 const OLD_NAME_PATTERNS = [
     38   /\.(?:data-table(?:-primary|-sub|-status|-static|-wrap)?|table-panel|table-toolbar|table-search|table-actions|action-button|modal-overlay|form-field|checkbox-row|client-breadcrumb|auth-link|link-button|consent-account-link|realm-select|domain-status(?:-dot)?|provider-status|session-badge|client-badge|host-name|host-added|table-icon(?:-column)?)(?![\w-])/g,
     39   /\.[\w-]+-row-action(?![\w-])/g,
     40   /\.[\w-]+-stack(?![\w-])/g,
     41 ];
     42 
     43 // register of surfaces whose source still carries non-ASCII characters:
     44 // any byte above 0x7F outside this list fails the build, entries that are
     45 // already pure ASCII are reported obsolete, and the register must stay empty
     46 const PREEXISTING_NON_ASCII = [];
     47 
     48 // ---------------------------------------------------------------------------
     49 // helpers
     50 // ---------------------------------------------------------------------------
     51 
     52 function rel(file) {
     53   return path.relative(REPO, file).split(path.sep).join('/');
     54 }
     55 
     56 function walk(dir, out) {
     57   for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
     58     if (SKIP_DIRS.has(entry.name)) continue;
     59     const full = path.join(dir, entry.name);
     60     if (entry.isDirectory()) walk(full, out);
     61     else out.push(full);
     62   }
     63   return out;
     64 }
     65 
     66 function listFiles(exts) {
     67   const out = [];
     68   for (const root of SCAN_ROOTS) {
     69     const dir = path.join(REPO, root);
     70     if (!fs.existsSync(dir)) continue;
     71     for (const file of walk(dir, [])) {
     72       if (exts.includes(path.extname(file))) out.push(file);
     73     }
     74   }
     75   return out.sort();
     76 }
     77 
     78 function scoped(files) {
     79   const base = files.filter((f) => MIGRATION_PREFIXES.some((p) => rel(f).startsWith(p)));
     80   if (SCOPE === 'repo') return base;
     81   const prefix = `app/${APP_NAME}/`;
     82   return base.filter((f) => {
     83     const r = rel(f);
     84     return r.startsWith(prefix) || r.startsWith('app/shared/');
     85   });
     86 }
     87 
     88 function allowed(r) {
     89   return TRANSITION_ALLOW.includes(r);
     90 }
     91 
     92 function stripComments(text) {
     93   return text.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/<!--[\s\S]*?-->/g, ' ');
     94 }
     95 
     96 // blanks comments preserving byte offsets and line numbers
     97 function blankCommentsKeepLines(text) {
     98   return text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
     99 }
    100 
    101 function lineAt(text, index) {
    102   let line = 1;
    103   for (let i = 0; i < index; i += 1) if (text.charCodeAt(i) === 10) line += 1;
    104   return line;
    105 }
    106 
    107 // css files policed by the unit guards
    108 function unitGuardFiles() {
    109   const files = new Set();
    110   const dirs = new Set([COMPONENT_CSS_DIR]);
    111   const appRoot = path.join(REPO, 'app');
    112   if (fs.existsSync(appRoot)) {
    113     for (const entry of fs.readdirSync(appRoot, { withFileTypes: true })) {
    114       if (!entry.isDirectory()) continue;
    115       for (const sub of ['src/style', 'src/assets', 'dist']) {
    116         dirs.add(`app/${entry.name}/${sub}`);
    117       }
    118     }
    119   }
    120   for (const d of dirs) {
    121     const full = path.join(REPO, d);
    122     if (fs.existsSync(full) && fs.statSync(full).isDirectory()) {
    123       for (const f of walk(full, [])) if (f.endsWith('.css')) files.add(f);
    124     }
    125   }
    126   const fw = path.join(REPO, FRAMEWORK_CSS);
    127   if (fs.existsSync(fw)) files.add(fw);
    128   for (const f of TRANSITION_ALLOW) {
    129     const full = path.join(REPO, f);
    130     if (fs.existsSync(full)) files.add(full);
    131   }
    132   return [...files].sort();
    133 }
    134 
    135 // Minimal block parser: yields { selector, body, chain } for every style
    136 // rule, where chain is the list of enclosing at-rule preludes.
    137 function parseRules(text) {
    138   const clean = stripComments(text);
    139   const rules = [];
    140   const stack = [];
    141   let buf = '';
    142   let i = 0;
    143   while (i < clean.length) {
    144     const ch = clean[i];
    145     if (ch === '{') {
    146       const prelude = buf.trim();
    147       buf = '';
    148       i += 1;
    149       let depth = 1;
    150       const start = i;
    151       while (i < clean.length && depth > 0) {
    152         if (clean[i] === '{') depth += 1;
    153         else if (clean[i] === '}') depth -= 1;
    154         i += 1;
    155       }
    156       const body = clean.slice(start, i - 1);
    157       if (prelude.startsWith('@')) {
    158         stack.push(prelude);
    159         rules.push(...parseRules(body).map((r) => ({ ...r, chain: [...stack, ...r.chain] })));
    160         stack.pop();
    161       } else {
    162         rules.push({ selector: prelude, body, chain: [...stack] });
    163       }
    164       continue;
    165     }
    166     if (ch === ';') {
    167       // an at-rule statement such as an @layer order declaration
    168       buf = '';
    169       i += 1;
    170       continue;
    171     }
    172     buf += ch;
    173     i += 1;
    174   }
    175   return rules;
    176 }
    177 
    178 function classTokens(selector) {
    179   const names = [];
    180   const re = /\.([A-Za-z][A-Za-z0-9_-]*)/g;
    181   // ignore attribute-selector contents to avoid false class hits
    182   const plain = selector.replace(/\[[^\]]*\]/g, '');
    183   let m;
    184   while ((m = re.exec(plain))) names.push(m[1]);
    185   return names;
    186 }
    187 
    188 function hasTableClass(selector) {
    189   return /(^|[^-\w.])\.table(?![\w-])/.test(selector.replace(/\[[^\]]*\]/g, ''));
    190 }
    191 
    192 function hasCellCompound(selector) {
    193   // a compound selector mentioning a td/th element, or a table part class
    194   return /(^|[\s>+~])t[hd](?![\w-])/.test(selector) || hasTableClass(selector);
    195 }
    196 
    197 function decls(body) {
    198   return body
    199     .split(';')
    200     .map((d) => d.trim())
    201     .filter(Boolean)
    202     .map((d) => {
    203       const idx = d.indexOf(':');
    204       return { prop: d.slice(0, idx).trim(), value: d.slice(idx + 1).trim() };
    205     });
    206 }
    207 
    208 // comments and string literals only; regex literals are not inspected
    209 function htmlExtract(text) {
    210   const found = [];
    211   found.push(...text.match(/<!--[\s\S]*?-->/g) || []);
    212   found.push(...text.match(/<script[\s\S]*?<\/script>/gi) || []);
    213   return found;
    214 }
    215 
    216 function jsExtract(text) {
    217   return text.match(
    218     /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`/g,
    219   ) || [];
    220 }
    221 
    222 function cssExtract(text) {
    223   return [...(text.match(/\/\*[\s\S]*?\*\//g) || []), ...(text.match(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g) || [])];
    224 }
    225 
    226 // ---------------------------------------------------------------------------
    227 // guards
    228 // ---------------------------------------------------------------------------
    229 
    230 const errors = [];
    231 const warningGroups = new Map();
    232 
    233 function addError(line) {
    234   errors.push(line);
    235 }
    236 
    237 function addWarning(key, detail) {
    238   if (!warningGroups.has(key)) warningGroups.set(key, { count: 0, examples: [] });
    239   const g = warningGroups.get(key);
    240   g.count += 1;
    241   if (detail && g.examples.length < 3 && !g.examples.includes(detail)) g.examples.push(detail);
    242 }
    243 
    244 function report(file, guard, msg, hard) {
    245   const line = `${rel(file)} [${guard}] ${msg}`;
    246   if (hard) addError(line);
    247   else addWarning(line, '');
    248 }
    249 
    250 const args = process.argv.slice(2);
    251 function flagValue(name, dflt) {
    252   const i = args.indexOf(name);
    253   return i >= 0 && args[i + 1] ? args[i + 1] : dflt;
    254 }
    255 const SCOPE = flagValue('--scope', 'repo');
    256 const APP_NAME = flagValue('--app', SCOPE === 'repo' ? null : 'admin');
    257 
    258 function main() {
    259   const cssFiles = scoped(listFiles(CSS_EXT));
    260   const allCode = listFiles(CODE_EXT);
    261   const codeFiles =
    262     SCOPE === 'repo'
    263       ? allCode
    264       : allCode.filter((f) => {
    265           const r = rel(f);
    266           return r.startsWith(`app/${APP_NAME}/`) || r.startsWith('app/shared/');
    267         });
    268 
    269   // ---- guard 1: static alignment rules -----------------------------------
    270   for (const file of cssFiles) {
    271     const r = rel(file);
    272     const hard = !allowed(r);
    273     for (const rule of parseRules(fs.readFileSync(file, 'utf8'))) {
    274       const sel = rule.selector.replace(/\s+/g, ' ');
    275       const mentionsTable = hasTableClass(rule.selector);
    276       for (const d of decls(rule.body)) {
    277         const prop = d.prop.toLowerCase();
    278         const value = d.value.toLowerCase();
    279         const badDisplay = prop === 'display' && /flex|grid|inline-flex|inline-grid/.test(value);
    280         if ((badDisplay || prop === 'min-height') && mentionsTable) {
    281           report(file, 'align', `cell rule "${sel}" declares ${d.prop}: ${d.value}`, hard);
    282         }
    283         if (prop === 'vertical-align') {
    284           if (hasCellCompound(rule.selector)) {
    285             report(file, 'align', `"${sel}" declares ${d.prop}: ${d.value}`, hard);
    286           }
    287         }
    288       }
    289     }
    290   }
    291 
    292   // ---- guard 1b: hard px and pt unit guards --------------------------------
    293   for (const file of unitGuardFiles()) {
    294     const r = rel(file);
    295     if (SCOPE !== 'repo') {
    296       const prefix = `app/${APP_NAME}/`;
    297       if (!r.startsWith(prefix) && !r.startsWith('app/shared/') && !allowed(r)) continue;
    298     }
    299     const hard = !allowed(r);
    300     const text = fs.readFileSync(file, 'utf8');
    301     const clean = blankCommentsKeepLines(text);
    302     const pxRe = /(?:\d+(?:\.\d+)?|\.\d+)px(?![A-Za-z0-9_-])/g;
    303     let pxm;
    304     while ((pxm = pxRe.exec(clean))) {
    305       report(file, 'unit', `px unit on line ${lineAt(clean, pxm.index)}: "${pxm[0]}"`, hard);
    306     }
    307     for (const rule of parseRules(text)) {
    308       for (const d of decls(rule.body)) {
    309         if (!/(?:\d+(?:\.\d+)?|\.\d+)pt/.test(d.value)) continue;
    310         const prop = d.prop.toLowerCase();
    311         const borderish = /^(?:border|outline)/.test(prop);
    312         // 1pt hairline lengths on clip, separator, and shadow properties
    313         const ptTokens = d.value.match(/-?(?:\d+(?:\.\d+)?|\.\d+)pt/g) || [];
    314         const allHairline = ptTokens.every((t) => t === '1pt' || t === '-1pt');
    315         const hairlineGeom = /^(?:width|height|margin|box-shadow)$/.test(prop) && allHairline;
    316         if (!borderish && !hairlineGeom) {
    317           report(file, 'unit', `pt unit on ${d.prop}: ${d.value} (${rule.selector.replace(/\s+/g, ' ')})`, hard);
    318         }
    319       }
    320     }
    321   }
    322 
    323   // ---- framework class inventory (for the no-copy guard) ------------------
    324   const frameworkClasses = new Set();
    325   const frameworkFiles = [path.join(REPO, FRAMEWORK_CSS), path.join(REPO, COMPONENT_CSS_DIR)];
    326   const collectFrom = (file) => {
    327     for (const rule of parseRules(fs.readFileSync(file, 'utf8'))) {
    328       for (const name of classTokens(rule.selector)) {
    329         // CUBE state classes are shared vocabulary, not redefinable blocks
    330         if (/^(?:is|has)-/.test(name)) continue;
    331         frameworkClasses.add(name);
    332       }
    333     }
    334   };
    335   const collectDir = (dir) => {
    336     for (const f of walk(dir, [])) if (f.endsWith('.css')) collectFrom(f);
    337   };
    338   if (fs.existsSync(frameworkFiles[0])) collectFrom(frameworkFiles[0]);
    339   if (fs.existsSync(frameworkFiles[1])) collectDir(frameworkFiles[1]);
    340 
    341   // consumers = css files that are not the framework files themselves
    342   const frameworkSet = new Set([
    343     rel(path.join(REPO, FRAMEWORK_CSS)),
    344     ...listIn(path.join(REPO, COMPONENT_CSS_DIR)),
    345   ]);
    346   function listIn(dir) {
    347     if (!fs.existsSync(dir)) return [];
    348     return walk(dir, []).filter((f) => f.endsWith('.css')).map(rel);
    349   }
    350   const consumers = cssFiles.filter((f) => !frameworkSet.has(rel(f)));
    351 
    352   // no-copy guard runs warn-only repo-wide while the allow-list is populated
    353   const allowAlive = TRANSITION_ALLOW.some((f) => fs.existsSync(path.join(REPO, f)));
    354   const noCopyHard = !allowAlive;
    355   for (const f of TRANSITION_ALLOW) {
    356     if (fs.existsSync(path.join(REPO, f))) {
    357       addWarning(`${f} [no-copy] transition allow-list entry still present`, noCopyHard ? 'must be deleted' : 'warn-only until deleted');
    358     }
    359   }
    360 
    361   // ---- guard 2: no-copy ----------------------------------------------------
    362   for (const file of consumers) {
    363     const r = rel(file);
    364     const text = fs.readFileSync(file, 'utf8');
    365     const selectors = [];
    366     for (const block of extractStyleBlocks(text, file)) {
    367       selectors.push(...parseRules(block).map((x) => x.selector));
    368     }
    369     if (r.endsWith('.css')) {
    370       for (const rule of parseRules(text)) selectors.push(rule.selector);
    371     }
    372     const redefined = new Set();
    373     for (const selector of selectors) {
    374       for (const name of classTokens(selector)) {
    375         if (frameworkClasses.has(name)) redefined.add(`.${name}`);
    376       }
    377     }
    378     if (redefined.size) {
    379       report(file, 'no-copy', `redefines framework class(es): ${[...redefined].sort().join(', ')}`, noCopyHard);
    380     }
    381   }
    382 
    383   // mockup page style blocks must not carry old-name selectors
    384   if (SCOPE === 'repo') {
    385     const htmlFiles = listFiles(['.html']).filter((f) => rel(f).startsWith(`${MOCKUP_DIR}/`));
    386     for (const file of htmlFiles) {
    387       const text = fs.readFileSync(file, 'utf8');
    388       const hits = new Set();
    389       for (const block of extractStyleBlocks(text, file)) {
    390         for (const re of OLD_NAME_PATTERNS) {
    391           re.lastIndex = 0;
    392           let m;
    393           while ((m = re.exec(block))) hits.add(m[0]);
    394         }
    395       }
    396       if (hits.size) {
    397         report(file, 'no-copy', `page style block targets old class(es): ${[...hits].sort().join(', ')}`, noCopyHard);
    398       }
    399     }
    400   }
    401 
    402   // ---- guard 3: tokens -----------------------------------------------------
    403   for (const file of cssFiles) {
    404     const r = rel(file);
    405     const isFramework = r === FRAMEWORK_CSS;
    406     const hard = !allowed(r);
    407     const text = fs.readFileSync(file, 'utf8');
    408     const rules = parseRules(stripComments(text));
    409     const hexHits = [];
    410     const mixHits = [];
    411     const impHits = [];
    412     for (const rule of rules) {
    413       const layerNames = new Set(
    414         rule.chain
    415           .filter((c) => /^@layer\s+[A-Za-z]/.test(c) && !c.includes(','))
    416           .map((c) => c.replace('@layer', '').replace('{', '').trim()),
    417       );
    418       const inTokenLayer = isFramework && (layerNames.has('tokens') || layerNames.has('themes'));
    419       const isHiddenTail = isFramework && rule.chain.length === 0 && rule.selector.replace(/\s/g, '') === '[hidden]';
    420       const oneLine = rule.selector.replace(/\s+/g, ' ');
    421       for (const d of decls(rule.body)) {
    422         const prop = d.prop;
    423         const value = d.value.replace(/\s+/g, ' ');
    424         if (prop.startsWith('--')) {
    425           // custom property definitions are the token channel: literal colors
    426           // are allowed there until the consumer sheets move into the layers
    427         } else if (/(^|[\s,;(])#[0-9a-fA-F]{3,8}\b/.test(value)) {
    428           if (!inTokenLayer) hexHits.push(`${prop}: ${value} (${oneLine})`);
    429         }
    430         if (/color-mix\(/i.test(value) && !/color-mix\(\s*in\s+oklch/i.test(value)) {
    431           mixHits.push(`${prop}: ${value} (${oneLine})`);
    432         }
    433         if (/!important/i.test(value) && !isHiddenTail) {
    434           impHits.push(`${prop}: ${value} (${oneLine})`);
    435         }
    436       }
    437     }
    438     for (const hit of dedupe(hexHits)) report(file, 'token', `hex literal outside the token layers: ${hit}`, hard);
    439     for (const hit of dedupe(mixHits)) report(file, 'token', `color-mix must mix in oklch: ${hit}`, hard);
    440     for (const hit of dedupe(impHits)) report(file, 'token', `!important outside the unlayered [hidden] tail: ${hit}`, hard);
    441   }
    442 
    443   // ---- guard 4: layers -----------------------------------------------------
    444   // order-statement uniqueness is checked across every stylesheet in the repo
    445   const orderStatements = [];
    446   for (const file of listFiles(CSS_EXT)) {
    447     const text = stripComments(fs.readFileSync(file, 'utf8'));
    448     const re = /@layer\s+[^{;]+;/g;
    449     let m;
    450     while ((m = re.exec(text))) {
    451       const line = text.slice(0, m.index).split('\n').length;
    452       orderStatements.push({ file, line, text: m[0] });
    453     }
    454   }
    455   if (SCOPE === 'repo') {
    456     if (orderStatements.length !== 1) {
    457       errors.push(`layer: expected exactly 1 @layer order statement repo-wide, found ${orderStatements.length}`);
    458     }
    459     const fw = path.join(REPO, FRAMEWORK_CSS);
    460     const fwLine = orderStatements.find((s) => s.file === fw);
    461     if (orderStatements.length === 1 && fwLine && fwLine.line !== 1) {
    462       errors.push(`layer: the @layer order statement must be the first line of ${FRAMEWORK_CSS}, found on line ${fwLine.line}`);
    463     }
    464   } else if (orderStatements.some((s) => rel(s.file) !== FRAMEWORK_CSS)) {
    465     for (const s of orderStatements) {
    466       if (rel(s.file) !== FRAMEWORK_CSS) {
    467         errors.push(`${rel(s.file)} [layer] duplicate @layer order statement: ${s.text}`);
    468       }
    469     }
    470   }
    471   for (const file of cssFiles) {
    472     const r = rel(file);
    473     if (allowed(r) || r === FRAMEWORK_CSS) continue;
    474     const text = stripComments(fs.readFileSync(file, 'utf8'));
    475     const re = /@layer\s+([\w-]+(?:\s*,\s*[\w-]+)*)\s*\{/g;
    476     let m;
    477     while ((m = re.exec(text))) {
    478       const names = m[1].split(',').map((n) => n.trim());
    479       const isComponent = r.startsWith(`${COMPONENT_CSS_DIR}/`);
    480       const permitted = isComponent ? ['components'] : ['apps', 'mockups'];
    481       for (const n of names) {
    482         if (!permitted.includes(n)) {
    483           errors.push(`${r} [layer] consumer stylesheet uses @layer ${n} (permitted: ${permitted.join('/')})`);
    484         }
    485       }
    486     }
    487   }
    488   // consumers without a layer wrapper: warn until the app sheets are moved
    489   if (allowAlive) {
    490     for (const file of consumers) {
    491       const r = rel(file);
    492       if (allowed(r)) continue;
    493       if (!r.startsWith('app/') && !r.startsWith(`${MOCKUP_DIR}/`)) continue;
    494       const text = stripComments(fs.readFileSync(file, 'utf8'));
    495       if (!/@layer\s+[\w-]+\s*\{/.test(text)) {
    496         addWarning(`${r} [layer] consumer stylesheet is unlayered`, 'transition: app sheets move into @layer apps');
    497       }
    498     }
    499   }
    500 
    501   // ---- guard 5: source hygiene --------------------------------------------
    502   const nonAscii = (buf) => {
    503     const hits = [];
    504     for (let i = 0; i < buf.length; i += 1) {
    505       if (buf[i] > 0x7f) hits.push({ i, b: buf[i] });
    506     }
    507     return hits;
    508   };
    509   for (const file of codeFiles) {
    510     const r = rel(file);
    511     const buf = fs.readFileSync(file);
    512     const hits = nonAscii(buf);
    513     if (hits.length) {
    514       const detail = `${hits.length} byte(s), first 0x${hits[0].b.toString(16)} at offset ${hits[0].i}`;
    515       if (PREEXISTING_NON_ASCII.includes(r)) {
    516         addWarning(`${r} [hygiene] preexisting non-ASCII characters in user copy`, `transition: fix when this surface migrates (${detail})`);
    517       } else {
    518         addError(`${r} [hygiene] non-ASCII: ${detail}`);
    519       }
    520     } else if (PREEXISTING_NON_ASCII.includes(r)) {
    521       addWarning(`${r} [hygiene] register entry obsolete`, 'file is pure ASCII now; remove it from the register');
    522     }
    523     const text = buf.toString('latin1');
    524     const ext = path.extname(file);
    525     let snippets = [];
    526     if (ext === '.css') snippets = cssExtract(text);
    527     else if (ext === '.html') snippets = htmlExtract(text);
    528     else snippets = jsExtract(text);
    529     for (const s of snippets) {
    530       if (/\.(md|rst)\b/i.test(s) || /\bsection\s+\d/i.test(s) || /CSS[-_]FRAMEWORK/i.test(s) ||
    531           /\b(?:see|per|according to|follow(?:s|ing)?)\s+the\s+spec(?:ification)?\b/i.test(s)) {
    532         errors.push(`${r} [hygiene] document or spec reference inside code: ${s.slice(0, 60)}`);
    533         break;
    534       }
    535     }
    536     // class-name tokens
    537     const bad = [];
    538     if (ext === '.css') {
    539       for (const rule of parseRules(text)) {
    540         for (const name of classTokens(rule.selector)) {
    541           if (name.includes('__') || name.includes('--')) bad.push(`.${name}`);
    542         }
    543       }
    544     } else {
    545       const attr = /class(?:Name)?\s*[:=]\s*["']([^"']+)["']/g;
    546       let m;
    547       while ((m = attr.exec(text))) {
    548         for (const tok of m[1].split(/\s+/)) {
    549           if (tok.includes('__') || tok.includes('--')) bad.push(tok);
    550         }
    551       }
    552       const cl = /classList\.(?:add|remove|toggle)\(\s*["']([^"']+)["']/g;
    553       while ((m = cl.exec(text))) {
    554         for (const tok of m[1].split(/\s+/)) {
    555           if (tok.includes('__') || tok.includes('--')) bad.push(tok);
    556         }
    557       }
    558     }
    559     if (bad.length) {
    560       errors.push(`${r} [hygiene] class names with double-underscore or double-hyphen: ${[...new Set(bad)].join(', ')}`);
    561     }
    562   }
    563 
    564   // ---- summary --------------------------------------------------------------
    565   console.log(`css-check: scope=${SCOPE === 'repo' ? 'repo' : `app/${APP_NAME}`} files(css)=${cssFiles.length} files(code)=${codeFiles.length}`);
    566   let warnCount = 0;
    567   for (const [key, g] of warningGroups) {
    568     warnCount += g.count;
    569     const extra = g.examples.length ? `: ${g.examples.join('; ')}` : '';
    570     console.log(`  warn: ${key}${g.count > 1 ? ` (x${g.count})` : ''}${extra}`);
    571   }
    572   for (const e of errors) console.log(`  FAIL: ${e}`);
    573   console.log(`css-check: ${errors.length} error(s), ${warnCount} warning(s)`);
    574   console.log(`css-check: no-copy guard runs ${noCopyHard ? 'HARD (allow-list empty)' : 'warn-only (transition allow-list active)'}`);
    575   process.exit(errors.length ? 1 : 0);
    576 }
    577 
    578 function dedupe(list) {
    579   return [...new Set(list)];
    580 }
    581 
    582 function extractStyleBlocks(text, file) {
    583   if (!file.endsWith('.html')) return [];
    584   const blocks = [];
    585   const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
    586   let m;
    587   while ((m = re.exec(text))) blocks.push(m[1]);
    588   return blocks;
    589 }
    590 
    591 main();