check-tokens.mjs 2.72 KB
/**
 * 设计令牌对账 + 子应用颜色门禁。
 *
 * 两个判据,都能用代码跑,不依赖人肉 review:
 *  1) palette.ts(交给 antd 的 JS 侧真源)里每个色值都必须能在 tokens.css 找到 ——
 *     否则就是「组件按 A 配色、自定义 CSS 按 B 配色」,肉眼能看出那条线不干净。
 *  2) 子应用源码里不允许出现写死的十六进制颜色 —— 一律用 var(--uj-*)。
 *     需求原话是「精致、统一」,靠提示词约束不住;这里做成跑不过就红。
 *
 * 主壳 design.css 暂不纳入第 2 条:它是主壳自己的视觉稿,且还带着历史色值,
 * 收敛它属于另一轮改造,先把子应用这条线守住。
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8');

const errors = [];

/* ---------- 1. palette.ts → tokens.css ---------- */
const paletteSource = read('packages/design-tokens/src/palette.ts');
const tokensCss = read('packages/design-tokens/src/tokens.css');

const paletteHexes = new Set(
  [...paletteSource.matchAll(/'#([0-9a-fA-F]{6})'/g)].map((m) => m[1].toLowerCase()),
);
const cssHexes = new Set(
  [...tokensCss.matchAll(/#([0-9a-fA-F]{6})\b/g)].map((m) => m[1].toLowerCase()),
);
for (const hex of paletteHexes) {
  if (!cssHexes.has(hex)) {
    errors.push(`palette.ts 的 #${hex} 在 tokens.css 里没有对应变量(JS 与 CSS 已漂移)`);
  }
}

/* ---------- 2. 子应用不得写死颜色 ---------- */
const SUBAPP_ROOTS = ['system', 'store', 'points'].map((name) =>
  path.join(ROOT, 'apps/web/subapps', name, 'src'),
);

const walk = (dir, out = []) => {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) walk(full, out);
    else if (/\.(css|tsx?)$/.test(entry.name)) out.push(full);
  }
  return out;
};

for (const root of SUBAPP_ROOTS) {
  if (!fs.existsSync(root)) continue;
  for (const file of walk(root)) {
    const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
    lines.forEach((line, index) => {
      const hit = /#[0-9a-fA-F]{3,8}\b/.exec(line);
      if (hit) {
        errors.push(
          `${path.relative(ROOT, file)}:${index + 1} 写死颜色 ${hit[0]},请改用 var(--uj-*) 令牌`,
        );
      }
    });
  }
}

if (errors.length) {
  console.error(`[tokens] 未通过 ${errors.length} 项:`);
  for (const error of errors) console.error(`  - ${error}`);
  process.exit(1);
}
console.log(
  `[tokens] 通过:palette ${paletteHexes.size} 个色值与 tokens.css 对齐,子应用无写死颜色。`,
);