Files
image-workbench-desktop/scripts/token-audit.js
T
qiqi c81a107b5f feat(tokens): M4-B6 收尾 —— 半像素清零 + 插件契约文件级豁免归零(3.26.49)
- style.css 剩余 16 处半像素字号并入闭集,删 2 条归并后重复的规则;守卫收紧为全文件断言
- 裁定 --iwb-control-h 不扩到全局控件(并排表单 vs 成组紧凑控件),新增「全局 input 不得写死 height」守卫
- plugin-theme-contract-test 重写:ALLOW_FILES 6 → 0,改为私有皮肤自声明(skin) + chroma 强调色判据 + 行内内容色标记;私有皮肤必须自洽(不引用宿主颜色 token)
- token-audit 插件段同口径分三类报数;插件侧中性色写死归零
- 插件仓同步 4 个版本:browser 1.7.1 / batch-export 1.2.1 / image-annotate 1.20.7 / image-vectorize 0.6.1
- 视觉基线 8 张更新(含画布场景的字号栅格化变化),A/B 回退确认非环境噪声,复核 12/12
2026-11-23 17:09:46 +08:00

236 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* token-audit.js —— 设计 token 现状审计(只读)
*
* 用途:给 docs/standards/design-tokens.md 提供可复核的数字,将来也能当「棘轮」基线。
* 不改任何文件;输出 Markdown 表格 + 关键告警。
*
* 用法:node scripts/token-audit.js [--json]
*/
'use strict'
const fs = require('fs')
const path = require('path')
const ROOT = path.join(__dirname, '..')
const read = (p) => { try { return fs.readFileSync(p, 'utf8') } catch (e) { return '' } }
const css = read(path.join(ROOT, 'style.css'))
// M3 起 token 定义搬进生成的 src/design-tokens.css:变量清单要把两份合起来看,
// 否则「定义的变量」会突然变成 0(脚本比代码先过时,是最容易误导人的失败模式)。
const tokensCss = read(path.join(ROOT, 'src', 'design-tokens.css'))
const allCss = css + '\n' + tokensCss
const siteCss = read(path.join(ROOT, 'site', 'assets', 'style.css'))
function walk (dir, out) {
let ents = []
try { ents = fs.readdirSync(dir, { withFileTypes: true }) } catch (e) { return out }
for (const e of ents) {
const p = path.join(dir, e.name)
if (e.isDirectory()) walk(p, out)
else if (/\.(css|js)$/i.test(e.name)) out.push(p)
}
return out
}
const pluginFiles = walk(path.join(ROOT, 'plugins'), [])
const count = (re, src) => (src.match(re) || []).length
const uniqSorted = (arr, numeric) => Array.from(new Set(arr)).sort(numeric ? (a, b) => a - b : undefined)
/* ---------- 1. 变量:定义 / 引用 / 未定义 / 死变量 ---------- */
// 定义可以写在一行里的任意位置(--rd-sm: 6px; --rd: 8px; 这种),不能只认行首
const defs = uniqSorted((allCss.match(/(?:^|[\s;{])--[a-z0-9-]+\s*:/gim) || []).map((s) => s.trim().replace(/^[;{]/, '').trim().replace(/\s*:$/, '')))
const refs = uniqSorted((allCss.match(/var\(\s*--[a-z0-9-]+/gi) || []).map((s) => s.replace(/var\(\s*/, '')))
// 运行时由 JS 写入的变量(app.js / canvas-*.js 里 setProperty),不算缺失
const RUNTIME_SET = new Set(['--iwb-dock-l', '--iwb-dock-r', '--iwb-fb-k', '--iwb-node-color'])
const undefinedRefs = refs.filter((r) => !defs.includes(r) && !RUNTIME_SET.has(r))
const usedCount = {}
for (const r of refs) usedCount[r] = count(new RegExp('var\\(\\s*' + r + '(?=[,)])', 'g'), css)
const deadTokens = defs.filter((d) => !usedCount[d] && !new RegExp('var\\(\\s*' + d + '\\s*[,)]').test(css))
/* ---------- 2. 命名空间:几套并存 ---------- */
const ns = (re) => uniqSorted((allCss.match(re) || [])).length
const namespaces = {
'--iwb-*(旧宿主)': ns(/--iwb-[a-z0-9-]+/g),
'--sp-*(间距)': ns(/--sp-[a-z0-9-]+/g),
'--rd*(圆角)': ns(/--rd[a-z0-9-]*/g),
'--fs-*(字号)': ns(/--fs-[a-z0-9-]+/g),
'--sh-*(阴影)': ns(/--sh-[a-z0-9-]+/g),
'--tr-*(过渡)': ns(/--tr-[a-z0-9-]+/g)
}
/* ---------- 3. 硬编码 vs token 采用率 ---------- */
const hard = {
'十六进制色值': count(/#[0-9a-fA-F]{3,8}\b/g, css),
'rgba()/rgb()': count(/rgba?\([^)]*\)/g, css),
'font-size 写死': count(/font-size:\s*[0-9.]+px/g, css),
'border-radius 写死': count(/border-radius:\s*[0-9.]+px/g, css),
'padding/margin/gap 写死': count(/(?:padding|margin|gap)[a-z-]*:\s*[0-9.]+px/g, css),
'box-shadow 声明': count(/box-shadow\s*:/g, css),
'z-index 声明': count(/z-index\s*:/g, css)
}
const scale = (re) => {
const vals = (css.match(re) || []).map((s) => parseFloat(String(s).match(/[0-9.]+/)[0]))
return vals
}
const fontSizes = scale(/font-size:\s*[0-9.]+px/g)
const radii = scale(/border-radius:\s*[0-9.]+px/g)
const spacings = scale(/(?:padding|margin|gap)[a-z-]*:\s*[0-9.]+px/g)
const zindex = (css.match(/z-index:\s*-?[0-9]+/g) || []).map((s) => parseInt(String(s).match(/-?[0-9]+$/)[0], 10))
const shadows = uniqSorted((css.match(/box-shadow:[^;}]*/g) || []).map((s) => s.replace(/\s+/g, ' ').trim()))
const tokenUse = {
'var(--sp-*)': count(/var\(--sp-[0-9]/g, css),
'var(--rd*)': count(/var\(--rd/g, css),
'var(--fs-*)': count(/var\(--fs-[0-9a-z]/g, css),
'var(--sh-*)': count(/var\(--sh-/g, css),
'var(--tr-*)': count(/var\(--tr-/g, css)
}
/* ---------- 4. 插件侧 ---------- */
// 与 tests/plugin-theme-contract-test.js 同口径,分三类而不是只数 hex:
// 私有皮肤(manifest 声明 skin:'private')—— 已声明的设计选择,不算欠债,但它不得引用宿主颜色 token
// 强调色(chroma ≥ 24)—— 品牌/危险/成功色,亮暗两端都可读,允许写死
// 中性色(chroma < 24)—— 表面/文字/边框,写死在暗色下必然白板或黑洞,这才是要修的
const chromaOf = (hex) => {
let h = hex.replace('#', '')
if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]
if (h.length !== 6) return 0
const n = parseInt(h, 16)
const c = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
return Math.max(c[0], c[1], c[2]) - Math.min(c[0], c[1], c[2])
}
const pluginBad = []
const pluginPrivate = []
const pluginAccent = []
for (const f of pluginFiles) {
const src = read(f)
const isPrivate = /skin:\s*'private'/.test(src.slice(0, 4096))
const re = /(background(?:-color)?|color|border(?:-color)?)\s*:\s*([^;'"}]{0,80})/gi
let m
let neutral = 0
let accent = 0
while ((m = re.exec(src))) {
const val = m[2]
if (!/#[0-9a-f]{3,8}/i.test(val)) continue
if (/\/\*iwb:content\*\//.test(val)) continue
if (/var\(--[a-z0-9-]+\s*,\s*#[0-9a-f]{3,8}/i.test(val)) continue
// 纯白文字压在图片/色块上:内容对比,不是主题表面色(契约测试同款例外)
if (/^color$/i.test(m[1]) && /^#(?:fff|ffffff)$/i.test(val.trim().replace(/[}\s]+$/, ''))) continue
for (const h of val.match(/#[0-9a-f]{3,8}/gi) || []) {
if (chromaOf(h) >= 24) accent++
else neutral++
}
}
if (isPrivate) { pluginPrivate.push({ file: path.relative(ROOT, f), hex: neutral + accent }); continue }
if (neutral) pluginBad.push({ file: path.relative(ROOT, f), hex: neutral })
if (accent) pluginAccent.push({ file: path.relative(ROOT, f), hex: accent })
}
const pluginTokenUse = pluginFiles.reduce((a, f) => a + count(/var\(--iwb-/g, read(f)), 0)
/* ---------- 5. 官网 / 市场页 ---------- */
const siteVars = uniqSorted((siteCss.match(/--[a-z0-9-]+:/gi) || []).map((s) => s.trim().replace(/:$/, '')))
const report = {
cssLines: css.split('\n').length,
tokenLines: tokensCss.split('\n').length,
defs: defs.length,
refs: refs.length,
undefinedRefs,
deadTokens,
namespaces,
hard,
fontSizes: { distinct: uniqSorted(fontSizes, true), count: fontSizes.length },
radii: { distinct: uniqSorted(radii, true), count: radii.length },
spacings: { distinct: uniqSorted(spacings, true), count: spacings.length },
zindex: { distinct: uniqSorted(zindex, true), count: zindex.length },
shadows: { distinct: shadows.length },
tokenUse,
pluginBad,
pluginTokenUse,
siteVars
}
if (process.argv.includes('--contrast')) {
// 复现 docs/standards/design-tokens.md §1.5 的对比度实测(需要 theme-tokens.js 可独立运行)
const sandbox = {}
try {
new Function('window', read(path.join(ROOT, 'src', 'theme-tokens.js')))(sandbox)
} catch (e) {
console.log('无法加载 theme-tokens.js:' + e.message)
process.exit(1)
}
const T = sandbox.IWBThemeTokens
const SURFACES = ['bg', 'panel', 'layer', 'layer2', 'nodeBg', 'field', 'canvasBg', 'pluginSurface', 'pluginCard']
for (const dark of [false, true]) {
const t = T.derive(T.DEFAULTS, dark)
const MINS = { text: T.RATIO.text, text2: T.RATIO.text2, textDim: T.RATIO.dim }
console.log('\n### ' + (dark ? '暗色' : '亮色') + ':文字对各表面(text≥' + MINS.text + ' / text2≥' + MINS.text2 + ' / textDim≥' + MINS.textDim + ')\n')
console.log('| 表面 | text | text2 | textDim |\n|---|---|---|---|')
for (const s of SURFACES) {
const row = ['text', 'text2', 'textDim'].map((f) => {
const v = T.contrast(t[f], t[s]).toFixed(2)
return Number(v) < MINS[f] ? '**' + v + '**' : v
})
console.log('| ' + s + ' | ' + row.join(' | ') + ' |')
}
}
/* 静态快照 vs derive():v3.26.44 起两者必须完全一致(D2)。
* 之前这里硬编码着旧的「中灰底」值,脚本自己成了过时信息的来源 —— 现在从 .theme-dark 实时解析。 */
console.log('\n### 静态快照 vs derive()(暗色)—— 必须一致\n')
console.log('| token | `.theme-dark` 静态 | derive 默认 | 一致 |\n|---|---|---|---|')
const darkBlock = (tokensCss.match(/\.theme-dark\s*\{([\s\S]*?)\n\}/) || [, ''])[1].replace(/\/\*[\s\S]*?\*\//g, '')
const statDark = {}
for (const m of darkBlock.matchAll(/--(?:iwb-)?([a-z0-9-]+)\s*:\s*(#[0-9a-fA-F]{6})\s*;/g)) statDark[m[1]] = m[2].toLowerCase()
const d = T.derive(T.DEFAULTS, true)
const KEYS = { bg: 'bg', panel: 'panel', layer: 'layer', layer2: 'layer2', 'node-bg': 'nodeBg', field: 'field', text: 'text', text2: 'text2', 'text-dim': 'textDim' }
for (const [k, key] of Object.entries(KEYS)) {
const sv = statDark[k] || '(表达式)'
const ok = sv === d[key]
console.log('| `--iwb-' + k + '` | `' + sv + '` | `' + d[key] + '` | ' + (ok ? '✓' : '**不一致**') + ' |')
}
process.exit(0)
}
if (process.argv.includes('--json')) {
console.log(JSON.stringify(report, null, 2))
process.exit(0)
}
const pad = (s, n) => String(s) + ' '.repeat(Math.max(0, n - String(s).replace(/[\u4e00-\u9fa5]/g, 'xx').length))
console.log('## 1. 变量规模\n')
console.log(`| 指标 | 数值 |\n|---|---|`)
console.log(`| style.css 行数 | ${report.cssLines} |`)
console.log(`| design-tokens.css 行数(生成) | ${report.tokenLines} |`)
console.log(`| 定义的 --* 变量 | ${defs.length} |`)
console.log(`| 被 var() 引用的变量 | ${refs.length} |`)
console.log(`| **引用了但从未定义** | **${undefinedRefs.length}** → ${undefinedRefs.join(' ')} |`)
console.log(`| 定义了但从未引用 | ${deadTokens.length} |`)
console.log('\n## 2. 命名空间并存\n')
console.log('| 命名空间 | 变量个数 |\n|---|---|')
for (const [k, v] of Object.entries(namespaces)) console.log(`| ${k} | ${v} |`)
console.log('\n## 3. 硬编码 vs token\n')
console.log('| 类别 | 写死数量 |\n|---|---|')
for (const [k, v] of Object.entries(hard)) console.log(`| ${k} | ${v} |`)
console.log('\n基础尺寸 token 实际采用:')
for (const [k, v] of Object.entries(tokenUse)) console.log(`- ${k}: ${v} 次`)
console.log('\n## 4. 尺度离散度\n')
console.log('| 尺度 | 取值种类 | 实际分布 |\n|---|---|---|')
console.log(`| 字号 | ${report.fontSizes.distinct.length} | ${report.fontSizes.distinct.join(' / ')} |`)
console.log(`| 圆角 | ${report.radii.distinct.length} | ${report.radii.distinct.join(' / ')} |`)
console.log(`| 间距 | ${report.spacings.distinct.length} | ${report.spacings.distinct.join(' / ')} |`)
console.log(`| z-index | ${report.zindex.distinct.length} | ${report.zindex.distinct.join(' / ')} |`)
console.log(`| box-shadow 写法 | ${report.shadows.distinct} | — |`)
console.log('\n## 5. 插件侧\n')
console.log(`- 插件文件数:${pluginFiles.length},引用 var(--iwb-*) 共 ${pluginTokenUse} 次`)
console.log(`- 文件级豁免:0(B6 起按角色分类,不再整文件放行)`)
console.log(`- 写死「中性色」的文件(暗色下会白板/黑洞,必须修):${pluginBad.length}`)
for (const p of pluginBad.sort((a, b) => b.hex - a.hex)) console.log(` - ${p.file} → ${p.hex} 处`)
console.log(`- 声明了私有皮肤的插件(已确认不跟随主题,代价是不得引用宿主颜色 token):${pluginPrivate.length}`)
for (const p of pluginPrivate) console.log(` - ${p.file} → ${p.hex} 处(skin: 'private')`)
console.log(`- 强调色写死(品牌/危险/成功,亮暗两端可读,允许):${pluginAccent.reduce((a, p) => a + p.hex, 0)} 处 / ${pluginAccent.length} 个文件`)
console.log('\n## 6. 官网样式\n')
console.log(`- site/assets/style.css 定义变量:${siteVars.join(' ') || '(无)'}`)