build(workspace): vendor the approved concept stylesheet with a drift check
This commit is contained in:
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, copyFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import test from 'node:test';
|
||||
import { lintOverlay } from '../../tools/vendor/sync-concept-css.mjs';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const script = join(root, 'tools/vendor/sync-concept-css.mjs');
|
||||
const concept = join(root, 'docs/concepts/workspace/style.css');
|
||||
const copy = join(root, 'web/js/workspace/concept.css');
|
||||
const sha = path => createHash('sha256').update(readFileSync(path)).digest('hex');
|
||||
|
||||
function walk(dir) {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
|
||||
const path = join(dir, entry.name);
|
||||
return entry.isDirectory() ? walk(path) : [path];
|
||||
});
|
||||
}
|
||||
|
||||
test('concept copy is byte-identical', () => {
|
||||
assert.ok(existsSync(copy), 'web/js/workspace/concept.css is missing; run sync-concept-css.mjs --write');
|
||||
assert.equal(sha(copy), sha(concept));
|
||||
const result = spawnSync(process.execPath, [script, '--check'], { cwd: root, encoding: 'utf8' });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
});
|
||||
|
||||
test('check fails on a one-byte drift', () => {
|
||||
const temp = mkdtempSync(join(tmpdir(), 'concept-css-'));
|
||||
try {
|
||||
mkdirSync(join(temp, 'docs/concepts/workspace'), { recursive: true });
|
||||
mkdirSync(join(temp, 'web/js/workspace'), { recursive: true });
|
||||
copyFileSync(concept, join(temp, 'docs/concepts/workspace/style.css'));
|
||||
writeFileSync(join(temp, 'web/js/workspace/concept.css'), Buffer.concat([readFileSync(concept), Buffer.from(' ')]));
|
||||
const run = () => spawnSync(process.execPath, [script, '--check', '--root', temp], { encoding: 'utf8' });
|
||||
const drifted = run();
|
||||
assert.equal(drifted.status, 1);
|
||||
assert.match(drifted.stderr, /drift/i);
|
||||
assert.equal(spawnSync(process.execPath, [script, '--write', '--root', temp]).status, 0);
|
||||
assert.equal(run().status, 0);
|
||||
} finally { rmSync(temp, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('overlay lint requires a decision marker on concept selectors', () => {
|
||||
const conceptCss = '.card, .row { color: red; }\n@media (max-width: 700px) { .card .title { margin: 0; } }\n';
|
||||
assert.deepEqual(lintOverlay(conceptCss, '.error-row { color: red; }').violations, []);
|
||||
assert.equal(lintOverlay(conceptCss, '.x, .card { color: blue; }').violations.length, 1);
|
||||
assert.equal(lintOverlay(conceptCss, '@media (max-width: 700px) { .card .title { margin: 1px; } }').violations.length, 1);
|
||||
assert.deepEqual(lintOverlay(conceptCss, '/* D12 */\n.card { color: blue; }').violations, []);
|
||||
assert.deepEqual(lintOverlay(conceptCss, '.card { /* D3 */ color: blue; }').violations, []);
|
||||
assert.equal(lintOverlay(conceptCss, '/* tweak */ .card { color: blue; }').violations.length, 1);
|
||||
assert.equal(lintOverlay(conceptCss, '/* D1 */ .card { color: blue; }\n.row { gap: 1px; }').violations.length, 1);
|
||||
});
|
||||
|
||||
test('overlay rules on concept selectors carry a decision marker', () => {
|
||||
const overlay = join(root, 'web/js/workspace/workspace.css');
|
||||
if (!existsSync(overlay)) return;
|
||||
const { violations } = lintOverlay(readFileSync(concept, 'utf8'), readFileSync(overlay, 'utf8'));
|
||||
assert.deepEqual(violations, []);
|
||||
});
|
||||
|
||||
test('only workspace.html loads workspace CSS', () => {
|
||||
const offenders = walk(join(root, 'web'))
|
||||
.filter(path => /\.(html|js|mjs)$/.test(path) && !path.includes('/lib/') && !path.includes('/shared/'))
|
||||
.filter(path => /\b(concept|workspace)\.css\b/.test(readFileSync(path, 'utf8')))
|
||||
.map(path => path.slice(root.length + 1));
|
||||
assert.ok(offenders.every(path => path === 'web/workspace.html'), `unexpected consumers: ${offenders.join(', ')}`);
|
||||
});
|
||||
|
||||
// Turned on by Task A2, which rewrites workspace.html to the concept order.
|
||||
test('workspace.html loads controls, viewer, concept, overlay in order', { todo: 'Task A2 rewrites workspace.html' }, () => {
|
||||
const html = readFileSync(join(root, 'web/workspace.html'), 'utf8');
|
||||
const hrefs = [...html.matchAll(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+)"/g)].map(match => match[1]);
|
||||
assert.deepEqual(hrefs, [
|
||||
'js/shared/toolkit/controls.css',
|
||||
'lib/viewerjs/viewer.min.css',
|
||||
'js/workspace/concept.css',
|
||||
'js/workspace/workspace.css',
|
||||
]);
|
||||
});
|
||||
Vendored
+2
-1
@@ -5,7 +5,8 @@
|
||||
"description": "Maintainer-only tools for reproducible browser dependencies",
|
||||
"scripts": {
|
||||
"sync": "node vendor-viewerjs.mjs",
|
||||
"check": "node vendor-viewerjs.mjs --check && node vendor-toolkit.mjs --check",
|
||||
"check": "node vendor-viewerjs.mjs --check && node vendor-toolkit.mjs --check && node sync-concept-css.mjs --check",
|
||||
"sync:concept": "node sync-concept-css.mjs --write",
|
||||
"sync:toolkit": "node vendor-toolkit.mjs",
|
||||
"update": "node update-viewerjs.mjs",
|
||||
"test": "node --test ../../tests/vendor/*.test.mjs",
|
||||
|
||||
Vendored
+123
@@ -0,0 +1,123 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { repositoryRoot } from './vendor-viewerjs.mjs';
|
||||
|
||||
const CONCEPT = 'docs/concepts/workspace/style.css';
|
||||
const COPY = 'web/js/workspace/concept.css';
|
||||
const MARKER = /\/\*[^*]*\bD\d+\b[^*]*\*\//;
|
||||
|
||||
// Minimal tokenizer: walks top-level rules and the bodies of @media/@supports,
|
||||
// returning each rule's normalized selectors and the comments attached to it
|
||||
// (those before its selector and those inside its block).
|
||||
function parseRules(css) {
|
||||
const rules = [];
|
||||
let index = 0;
|
||||
const length = css.length;
|
||||
function readBlock(start) {
|
||||
let depth = 0;
|
||||
let cursor = start;
|
||||
for (; cursor < length; cursor += 1) {
|
||||
if (css.startsWith('/*', cursor)) { cursor = commentEnd(cursor) - 1; continue; }
|
||||
const char = css[cursor];
|
||||
if (char === '"' || char === "'") { cursor = stringEnd(cursor) - 1; continue; }
|
||||
if (char === '{') depth += 1;
|
||||
else if (char === '}') { depth -= 1; if (depth === 0) return cursor; }
|
||||
}
|
||||
return length - 1;
|
||||
}
|
||||
function commentEnd(at) { const end = css.indexOf('*/', at + 2); return end === -1 ? length : end + 2; }
|
||||
function stringEnd(at) {
|
||||
for (let cursor = at + 1; cursor < length; cursor += 1) {
|
||||
if (css[cursor] === '\\') cursor += 1;
|
||||
else if (css[cursor] === css[at]) return cursor + 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
function walk(from, to) {
|
||||
let cursor = from;
|
||||
let comments = [];
|
||||
let prelude = '';
|
||||
while (cursor < to) {
|
||||
if (css.startsWith('/*', cursor)) {
|
||||
const end = commentEnd(cursor);
|
||||
comments.push(css.slice(cursor, end));
|
||||
cursor = end;
|
||||
continue;
|
||||
}
|
||||
const char = css[cursor];
|
||||
if (char === ';') { prelude = ''; comments = []; cursor += 1; continue; }
|
||||
if (char === '{') {
|
||||
const close = readBlock(cursor);
|
||||
const head = prelude.trim();
|
||||
const body = css.slice(cursor + 1, close);
|
||||
if (/^@(media|supports|layer)\b/i.test(head)) walk(cursor + 1, close);
|
||||
else if (!head.startsWith('@')) {
|
||||
rules.push({ selectors: splitSelectors(head), comments: [...comments, ...(body.match(/\/\*[\s\S]*?\*\//g) ?? [])] });
|
||||
}
|
||||
prelude = ''; comments = []; cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
prelude += char;
|
||||
cursor += 1;
|
||||
}
|
||||
}
|
||||
walk(index, length);
|
||||
return rules;
|
||||
}
|
||||
|
||||
function splitSelectors(head) {
|
||||
const out = [];
|
||||
let depth = 0;
|
||||
let current = '';
|
||||
for (const char of head) {
|
||||
if (char === '(' || char === '[') depth += 1;
|
||||
else if (char === ')' || char === ']') depth -= 1;
|
||||
if (char === ',' && depth === 0) { out.push(current); current = ''; } else current += char;
|
||||
}
|
||||
out.push(current);
|
||||
return out.map(selector => selector.replace(/\s+/g, ' ').trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function lintOverlay(conceptCss, overlayCss) {
|
||||
const owned = new Set(parseRules(conceptCss).flatMap(rule => rule.selectors));
|
||||
const violations = [];
|
||||
for (const rule of parseRules(overlayCss)) {
|
||||
const shared = rule.selectors.filter(selector => owned.has(selector));
|
||||
if (shared.length && !rule.comments.some(comment => MARKER.test(comment))) {
|
||||
violations.push(`${shared.join(', ')}: overlay rule on a concept selector needs a /* D<n> */ decision marker`);
|
||||
}
|
||||
}
|
||||
return { violations };
|
||||
}
|
||||
|
||||
export function syncConceptCss({ root = repositoryRoot, check = false } = {}) {
|
||||
const source = readFileSync(join(root, CONCEPT));
|
||||
const target = join(root, COPY);
|
||||
if (check) {
|
||||
let current = null;
|
||||
try { current = readFileSync(target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
if (!current) throw new Error(`Concept stylesheet drift: ${COPY} is missing; run sync-concept-css.mjs --write`);
|
||||
if (!current.equals(source)) {
|
||||
let offset = 0;
|
||||
while (offset < source.length && offset < current.length && source[offset] === current[offset]) offset += 1;
|
||||
throw new Error(`Concept stylesheet drift: ${COPY} (${current.length} bytes) differs from ${CONCEPT} (${source.length} bytes) at byte ${offset}; run sync-concept-css.mjs --write`);
|
||||
}
|
||||
} else {
|
||||
mkdirSync(join(root, 'web/js/workspace'), { recursive: true });
|
||||
writeFileSync(target, source);
|
||||
}
|
||||
return source.length;
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
try {
|
||||
const args = process.argv.slice(2);
|
||||
const rootAt = args.indexOf('--root');
|
||||
const root = rootAt === -1 ? repositoryRoot : resolve(args[rootAt + 1]);
|
||||
const mode = args.filter((arg, at) => arg.startsWith('--') && arg !== '--root' && !(rootAt !== -1 && at === rootAt + 1));
|
||||
if (mode.length !== 1 || !['--write', '--check'].includes(mode[0])) throw new Error('Usage: sync-concept-css.mjs --write | --check [--root <dir>]');
|
||||
const bytes = syncConceptCss({ root, check: mode[0] === '--check' });
|
||||
console.log(`Concept stylesheet ${mode[0] === '--check' ? 'verified' : 'written'} (${bytes} bytes)`);
|
||||
} catch (error) { console.error(error.message); process.exitCode = 1; }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user