update css
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 模块样式命名空间检查(门禁脚本)
|
||||
*
|
||||
* 平台规则:src/modules 下所有 .css 中选择器必须挂在模块根容器类(命名空间)下,
|
||||
* 禁止全局作用选择器(裸标签 / :root / 通配符 / 裸伪类 / 裸属性选择器等)跨模块污染。
|
||||
*
|
||||
* 实现:状态机逐字符解析(模块内存在数 MB 的 minified CSS,含大量 data URI
|
||||
* 字符串与花括号,不能依赖简单正则)。零依赖,Node >= 18。
|
||||
*/
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const MODULES_DIR = path.join(ROOT, 'src', 'modules');
|
||||
const MAX_LEN = 80;
|
||||
|
||||
/* ---------------------------------- 文件收集 ---------------------------------- */
|
||||
|
||||
function collectCssFiles(dir) {
|
||||
const out = [];
|
||||
let entries;
|
||||
try {
|
||||
entries = readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return out;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
out.push(...collectCssFiles(full));
|
||||
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.css')) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* --------------------------------- 选择器判定 --------------------------------- */
|
||||
|
||||
/**
|
||||
* 判定单个选择器(已 trim)是否为全局作用选择器。
|
||||
* 返回 null 表示合法(挂在类/ID 命名空间下),否则返回原因字符串。
|
||||
*/
|
||||
function classifySelector(sel) {
|
||||
if (!sel || sel.startsWith('@')) return null;
|
||||
|
||||
// 裸伪类/伪元素::root、:focus-visible、::-webkit-scrollbar 等,等价于通配符
|
||||
if (sel.startsWith(':')) {
|
||||
if (/^:root(?![a-zA-Z0-9_-])/.test(sel)) return '裸 :root 选择器(全局作用)';
|
||||
return '裸伪类/伪元素(等价于通配符,全局作用)';
|
||||
}
|
||||
if (sel.startsWith('*')) return '通配符 *(全局作用)';
|
||||
if (sel.startsWith('[')) return '裸属性选择器(全局作用)';
|
||||
|
||||
// 裸标签:首 token 匹配 /^[a-zA-Z][a-zA-Z0-9-]*$/ 且不是 CSS 函数(后面紧跟 "(")
|
||||
const m = sel.match(/^[a-zA-Z][a-zA-Z0-9-]*/);
|
||||
if (m) {
|
||||
const next = sel.charAt(m[0].length);
|
||||
if (next !== '(') {
|
||||
return `裸标签选择器「${m[0]}」(未挂在模块根容器下)`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按顶层逗号拆分选择器列表:括号 ( ) 与属性选择器 [ ] 内的逗号不拆分,
|
||||
* 引号字符串内的逗号不拆分。
|
||||
*/
|
||||
function splitTopLevelCommas(s) {
|
||||
const parts = [];
|
||||
let cur = '';
|
||||
let paren = 0;
|
||||
let bracket = 0;
|
||||
let quote = null;
|
||||
let escaped = false;
|
||||
for (const ch of s) {
|
||||
if (quote) {
|
||||
cur += ch;
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === '\\') escaped = true;
|
||||
else if (ch === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
cur += ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === '(') paren++;
|
||||
else if (ch === ')') paren = Math.max(0, paren - 1);
|
||||
else if (ch === '[') bracket++;
|
||||
else if (ch === ']') bracket = Math.max(0, bracket - 1);
|
||||
if (ch === ',' && paren === 0 && bracket === 0) {
|
||||
parts.push(cur);
|
||||
cur = '';
|
||||
continue;
|
||||
}
|
||||
cur += ch;
|
||||
}
|
||||
parts.push(cur);
|
||||
return parts;
|
||||
}
|
||||
|
||||
function truncate(s) {
|
||||
return s.length > MAX_LEN ? `${s.slice(0, MAX_LEN - 3)}...` : s;
|
||||
}
|
||||
|
||||
/* --------------------------------- 状态机解析 --------------------------------- */
|
||||
|
||||
/**
|
||||
* 逐字符解析 CSS 文本。
|
||||
* - 跳过块注释与字符串内容(data URI 中的 { } ; ( ) 不影响结构);
|
||||
* - 跟踪大括号深度与栈帧:'media'(@media/@supports 内继续扫描)、
|
||||
* 'rule'(普通规则块,声明不扫描)、'skip'(@keyframes/@font-face 等块内不扫描);
|
||||
* - prelude("{" 之前的文本)在扫描态下累积,用于选择器判定与 @import 检查。
|
||||
*
|
||||
* onRule(prelude, line) —— 每条普通规则回调;
|
||||
* onImport(prelude, line) —— 每条顶层(或 @media 内)@import 回调。
|
||||
*/
|
||||
function parseCss(source, onRule, onImport) {
|
||||
const stack = [];
|
||||
let prelude = '';
|
||||
let preludeLine = -1;
|
||||
let line = 1;
|
||||
let inComment = false;
|
||||
let quote = null;
|
||||
let escaped = false;
|
||||
|
||||
const scanMode = () => stack.length === 0 || stack[stack.length - 1] === 'media';
|
||||
const resetPrelude = () => {
|
||||
prelude = '';
|
||||
preludeLine = -1;
|
||||
};
|
||||
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const ch = source[i];
|
||||
|
||||
if (ch === '\n') line++;
|
||||
|
||||
if (inComment) {
|
||||
if (ch === '*' && source[i + 1] === '/') {
|
||||
inComment = false;
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (quote) {
|
||||
// 字符串内容原样跳过(不解析其中的 { } ; 等);
|
||||
// 为支持 @import 目标检查,扫描态下仍原样记录进 prelude。
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (ch === '\\') {
|
||||
escaped = true;
|
||||
} else if (ch === quote) {
|
||||
quote = null;
|
||||
}
|
||||
if (scanMode()) prelude += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
if (scanMode()) {
|
||||
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
|
||||
prelude += ch;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '/' && source[i + 1] === '*') {
|
||||
inComment = true;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '{') {
|
||||
const trimmed = prelude.trim();
|
||||
let frame;
|
||||
if (scanMode() && trimmed.startsWith('@')) {
|
||||
const m = trimmed.match(/^@([a-zA-Z0-9-]+)/);
|
||||
const name = m ? m[1].toLowerCase() : '';
|
||||
// @media / @supports 递归继续扫描内部规则;其余 at-rule 跳过块内选择器
|
||||
frame = name === 'media' || name === 'supports' ? 'media' : 'skip';
|
||||
} else if (scanMode()) {
|
||||
if (trimmed) onRule(trimmed, preludeLine === -1 ? line : preludeLine);
|
||||
frame = 'rule';
|
||||
} else {
|
||||
frame = 'skip';
|
||||
}
|
||||
stack.push(frame);
|
||||
resetPrelude();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '}') {
|
||||
if (stack.length) stack.pop();
|
||||
resetPrelude();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === ';') {
|
||||
if (scanMode()) {
|
||||
const trimmed = prelude.trim();
|
||||
if (/^@import\b/.test(trimmed)) {
|
||||
onImport(trimmed, preludeLine === -1 ? line : preludeLine);
|
||||
}
|
||||
}
|
||||
resetPrelude();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (scanMode()) {
|
||||
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
|
||||
prelude += ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------ 主流程 ----------------------------------- */
|
||||
|
||||
function main() {
|
||||
const files = collectCssFiles(MODULES_DIR).sort();
|
||||
const violations = [];
|
||||
|
||||
const addViolation = (rel, line, selector, reason) => {
|
||||
violations.push(`[违规] ${rel}:${line} ${truncate(selector)} ${reason}`);
|
||||
};
|
||||
|
||||
for (const file of files) {
|
||||
const rel = path.relative(ROOT, file).split(path.sep).join('/');
|
||||
const source = readFileSync(file, 'utf8');
|
||||
|
||||
parseCss(
|
||||
source,
|
||||
(prelude, line) => {
|
||||
for (const part of splitTopLevelCommas(prelude)) {
|
||||
const sel = part.trim();
|
||||
const reason = classifySelector(sel);
|
||||
if (reason) addViolation(rel, line, sel, reason);
|
||||
}
|
||||
},
|
||||
(prelude, line) => {
|
||||
if (/(^|[^a-z0-9])(reset|normalize)/i.test(prelude)) {
|
||||
addViolation(rel, line, prelude, '@import 引入 reset/normalize 样式(全局污染)');
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (violations.length > 0) {
|
||||
for (const v of violations) console.log(v);
|
||||
const badFiles = new Set(violations.map((v) => v.split(' ')[0])).size;
|
||||
console.log(
|
||||
`[汇总] 模块样式命名空间检查失败:共 ${violations.length} 条违规,涉及 ${badFiles} 个文件(共扫描 ${files.length} 个文件)`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`✓ 模块样式检查通过(扫描 ${files.length} 个文件)`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user