- scripts/token-lint.js:只查 diff 新增行(默认 HEAD,--base 查已提交批次,--file 整文件)
· 禁裸 #hex/rgba()、禁裸 px(字号/圆角/内距/间距/外边距)、禁裸 z-index(插件不得高于 --iwb-z-anchor)
· 四类白名单:内容色 /*iwb:content*/、var() 兜底、布局尺寸不查、临时例外 /*iwb:raw-until=X*/
· JS 两套判据:CSS 文本按 px 单位判(不误伤 { gap: 20 } 布局参数)、React 对象按 camelCase 判
- tests/design-token-ratchet-test.js + fixtures/token-baseline.json:13 项计数只降不升;var() 目标必须存在;禁自我兜底
- tests/theme-contrast-test.js:亮/暗 × 文字 × 表面 114 对,阈值取 theme-tokens.js 的 RATIO(text 7 / text2 4.5 / dim 3 / canvas 6 / onBrand 4.5)
- 三条接进 verify:ci(lint:tokens + 两个测试进 test:unit),各做一次打红验证
- 顺手堵漏:首启动「选择资料目录」弹窗是全仓唯一完全未 token 化的界面(12.5px / #fff / #2563eb),已 token 化并给每个 var() 加字面兜底;遮罩 rgba 登记为例外待 RFC
- 存量计数零变化(字号 170 / 圆角 103 / 间距 415 / z-index 31)
235 lines
11 KiB
JavaScript
235 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
||
/* token-lint.js —— 设计 token 的「新增行」闸门(M5-T5.1 / T5.5)
|
||
*
|
||
* 只查**新增行**,不查存量:M4 结束时 style.css 里还有 170 处写死字号、55 处裸 z-index,
|
||
* 一次性要求全清零只会逼人加白名单。闸门的作用是**不让数字再涨**(存量交给棘轮测试慢慢降)。
|
||
*
|
||
* 四条白名单(缺一条都会逼人绕路,绕路比违规更难发现):
|
||
* ① 内容色:行内 `/*iwb:content*/` —— 画布内容(图片上的纯白文字、截图底色)不是主题表面色,
|
||
* 同一个 #fff 在按钮上是 bug、在图片上是内容,值分不出来,只能靠标记。
|
||
* ② 变量兜底:`var(--x, 8px)` 里的 8px 不查 —— 兜底值不生效时才是问题,而那时 var 本身就会红。
|
||
* ③ 布局尺寸:只查排版属性(字号/圆角/内距/间距/外边距)。width/height/left/top 没有闭集,
|
||
* 强行 token 化只会发明一堆只用一次的名字。
|
||
* ④ 临时例外:行内 `/*iwb:raw-until=3.27.0*/` —— **必须带到期版本**,到期后本脚本把它当失败,
|
||
* 不会像普通白名单那样悄悄变成永久免死金牌。
|
||
*
|
||
* 用法:
|
||
* node scripts/token-lint.js # 查工作区未提交的改动(diff vs HEAD)
|
||
* node scripts/token-lint.js --base origin/main # 查 base..HEAD 的改动(CI / 发版前)
|
||
* node scripts/token-lint.js --file style.css # 查整个文件(迁移时看全局)
|
||
* node scripts/token-lint.js --json
|
||
*/
|
||
'use strict'
|
||
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const { execFileSync } = require('child_process')
|
||
|
||
const ROOT = path.join(__dirname, '..')
|
||
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version
|
||
|
||
// 排版属性:这些值必须来自闭集。其余属性(width/height/top/left/flex/…)没有闭集,不查。
|
||
const SIZE_PROPS = new Set([
|
||
'font-size', 'border-radius', 'gap', 'row-gap', 'column-gap'
|
||
])
|
||
const SIZE_PREFIX = /^(padding|margin)(-(top|right|bottom|left|block|inline)(-(start|end))?)?$/
|
||
|
||
// 颜色属性:表面色/文字色必须来自语义 token。
|
||
// box-shadow 不在其中 —— 它已由 --iwb-elevation-* 四档收口,阴影里的 rgba 是笔画而不是表面。
|
||
const COLOR_PROPS = new Set([
|
||
'color', 'background', 'background-color',
|
||
'border-color', 'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color',
|
||
'fill', 'stroke', 'outline-color'
|
||
])
|
||
|
||
// 生成物与第三方:token 定义本身当然满地是值;站点是另一套系统(自己的 --*-变量)
|
||
const SKIP_FILE = /^(src\/design-tokens\.css|dist\/|node_modules\/|site\/|docs\/)/
|
||
// 插件产物由 tests/plugin-theme-contract-test.js 按「私有皮肤 / 强调色 / 中性色」分类治理,
|
||
// 这里只对插件查层级(插件内部若写死 9999,会盖住宿主的弹窗与确认框)。
|
||
const PLUGIN_FILE = /^plugins\//
|
||
|
||
const CONTENT_MARK = /\/\*iwb:content\*\//
|
||
const EXCEPTION_MARK = /\/\*iwb:raw-until=(\d+\.\d+\.\d+)\*\//
|
||
|
||
const argv = process.argv.slice(2)
|
||
const argOf = (name) => {
|
||
const i = argv.indexOf(name)
|
||
return i >= 0 ? argv[i + 1] : null
|
||
}
|
||
const jsonOut = argv.includes('--json')
|
||
const base = argOf('--base')
|
||
const onlyFile = argOf('--file')
|
||
|
||
/* ── 1. 取「要检查的行」:{file, line, text} ───────────────────────────── */
|
||
function linesFromDiff () {
|
||
const args = ['-C', ROOT, 'diff', '--no-color', '--unified=0', '--no-ext-diff']
|
||
// 默认 diff HEAD 会把已暂存与未暂存都算进来(工作区真实状态);--base 则是「已提交的这批」
|
||
args.push(base ? base + '...HEAD' : 'HEAD')
|
||
args.push('--', '*.css', 'app.js', 'src', 'plugins')
|
||
|
||
let out = ''
|
||
try {
|
||
out = execFileSync('git', args, { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })
|
||
} catch (e) {
|
||
// 不是 git 仓库(或浅克隆取不到 base)时不要假装通过:直接报错,让人显式用 --file
|
||
console.error('token-lint: 无法取到 git diff(' + (e.message || e) + ')')
|
||
console.error(' 不在 git 仓库里时用 --file <path> 指定要查的文件')
|
||
process.exit(2)
|
||
}
|
||
|
||
const rows = []
|
||
let file = null
|
||
let next = 0
|
||
for (const raw of out.split('\n')) {
|
||
if (raw.startsWith('+++ b/')) { file = raw.slice(6); continue }
|
||
if (raw.startsWith('+++ /dev/null')) { file = null; continue }
|
||
const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(raw)
|
||
if (h) { next = Number(h[1]); continue }
|
||
if (!file) continue
|
||
if (raw.startsWith('+')) { rows.push({ file, line: next, text: raw.slice(1) }); next++ }
|
||
}
|
||
return rows
|
||
}
|
||
|
||
function linesFromFile (p) {
|
||
const abs = path.isAbsolute(p) ? p : path.join(ROOT, p)
|
||
const rel = path.relative(ROOT, abs).split(path.sep).join('/')
|
||
return fs.readFileSync(abs, 'utf8').split('\n').map((text, i) => ({ file: rel, line: i + 1, text }))
|
||
}
|
||
|
||
/* ── 2. 判定 ──────────────────────────────────────────────────────────── */
|
||
const cmpVer = (a, b) => {
|
||
const pa = a.split('.').map(Number)
|
||
const pb = b.split('.').map(Number)
|
||
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i]
|
||
return 0
|
||
}
|
||
|
||
// 把 var(...) 整段抠掉:兜底值不查(见白名单 ②),剩下的才是「裸值」
|
||
const stripVar = (v) => v.replace(/var\([^()]*\)/g, 'var')
|
||
|
||
const problems = []
|
||
const warn = []
|
||
|
||
// JS 里的样式有两种写法,判据必须分开(否则会误伤布局参数):
|
||
// ① CSS 文本:`cssText = 'padding:16px;font-size:12px'`、`innerHTML = '<div style="color:#333">'`
|
||
// —— 只有**带 px 单位**或带 #/rgb 颜色才算样式;`{ gap: 20 }` 这种是画布布局参数,不能管
|
||
// ② React 内联对象:`style={{ fontSize: 13 }}` —— 数字即 px,但键名要用**无歧义**的
|
||
// camelCase(fontSize / marginLeft / zIndex…);`gap` / `padding` 在 JS 对象里可能是
|
||
// 任何东西(CanvasGeometry 的 snapToFreeSpot 就吃 `{ gap: 20 }`),所以不查
|
||
const JS_PX = /(font-size|border-radius|padding[a-z-]*|gap|row-gap|column-gap|margin[a-z-]*)\s*:\s*(-?\d*\.?\d+)px/g
|
||
const JS_COLOR = /(color|background|border-color)\s*:\s*(#[0-9a-f]{3,8}|rgba?\([^)]*\))/gi
|
||
const JS_Z = /z-index\s*:\s*(-?\d+)/g
|
||
const JS_CAMEL = /(fontSize|borderRadius|paddingTop|paddingBottom|paddingLeft|paddingRight|marginTop|marginBottom|marginLeft|marginRight|rowGap|columnGap|zIndex)\s*:\s*(\d+)/g
|
||
|
||
function check (row) {
|
||
const { file, line, text } = row
|
||
if (!text || !text.includes(':')) return
|
||
if (SKIP_FILE.test(file)) return
|
||
|
||
const isPlugin = PLUGIN_FILE.test(file)
|
||
const isJs = /\.js$/.test(file)
|
||
const contentOk = CONTENT_MARK.test(text)
|
||
const ex = EXCEPTION_MARK.exec(text)
|
||
const expired = ex ? cmpVer(VERSION, ex[1]) >= 0 : false
|
||
const bucket = (msg, hard) => {
|
||
if (ex && !expired) {
|
||
warn.push({ file, line, msg, until: ex[1] })
|
||
return
|
||
}
|
||
if (expired) msg += '(例外已过期:raw-until=' + ex[1] + ',当前 ' + VERSION + ')'
|
||
if (hard) problems.push({ file, line, msg })
|
||
else warn.push({ file, line, msg })
|
||
}
|
||
|
||
if (isJs) {
|
||
// 纯注释行跳过:注释里写「z-index:2 是局部层级」这种说明不该被判违规
|
||
if (/^\s*(\/\/|\/\*|\*)/.test(text)) return
|
||
// 插件产物里的颜色/字号交给插件契约测试;层级照样管(见下)
|
||
const scanPx = !isPlugin
|
||
if (scanPx) {
|
||
for (const m of text.matchAll(JS_PX)) {
|
||
if (Number(m[2]) === 0) continue
|
||
bucket(m[1] + ': ' + m[2] + 'px → 用 --iwb-(font|radius|space)-* 闭集', true)
|
||
}
|
||
for (const m of text.matchAll(JS_CAMEL)) {
|
||
if (m[1] === 'zIndex') continue // 层级单独报,避免同一条重复计数
|
||
if (Number(m[2]) === 0) continue
|
||
bucket(m[1] + ': ' + m[2] + ' → 用 --iwb-(font|radius|space)-* 闭集(数字即 px)', true)
|
||
}
|
||
for (const m of text.matchAll(JS_COLOR)) {
|
||
const white = m[1].toLowerCase() === 'color' && /^#(fff|ffffff)$/i.test(m[2])
|
||
if (contentOk || white) continue
|
||
bucket(m[1] + ': ' + m[2] + ' → 用语义色 token(内容色加 /*iwb:content*/ 标记)', true)
|
||
}
|
||
}
|
||
for (const m of text.matchAll(JS_Z)) {
|
||
bucket('z-index: ' + m[1] + ' → 用 --iwb-z-*(插件不得高于 --iwb-z-anchor / 3200)', true)
|
||
}
|
||
for (const m of text.matchAll(JS_CAMEL)) {
|
||
if (m[1] !== 'zIndex') continue
|
||
bucket('zIndex: ' + m[2] + ' → 用 --iwb-z-*', true)
|
||
}
|
||
return
|
||
}
|
||
|
||
for (const m of text.matchAll(/([a-z-]+)\s*:\s*([^;{}]+)/g)) {
|
||
const prop = m[1].toLowerCase()
|
||
const value = m[2].trim()
|
||
const bare = stripVar(value)
|
||
|
||
// z-index:任何裸数字都不行(层级表见 docs/standards/design-tokens.md §3.4)
|
||
if (prop === 'z-index') {
|
||
if (/^-?\d+$/.test(bare)) {
|
||
bucket('z-index: ' + bare + ' → 用 --iwb-z-*(插件不得高于 --iwb-z-anchor / 3200)', true)
|
||
}
|
||
continue
|
||
}
|
||
// 插件内部除了层级,其余交给插件契约测试(私有皮肤是允许整套调色板的)
|
||
if (isPlugin) continue
|
||
|
||
if (SIZE_PROPS.has(prop) || SIZE_PREFIX.test(prop)) {
|
||
const hit = /(-?\d*\.?\d+)px/.exec(bare)
|
||
if (hit && Number(hit[1]) !== 0) {
|
||
bucket(prop + ': ' + value + ' → 用 --iwb-(font|radius|space)-* 闭集', true)
|
||
}
|
||
continue
|
||
}
|
||
|
||
if (COLOR_PROPS.has(prop)) {
|
||
const hex = /#[0-9a-f]{3,8}\b/i.test(bare)
|
||
const rgb = /rgba?\(/i.test(bare)
|
||
if (!hex && !rgb) continue
|
||
// 纯白文字压在图片/色块上:内容对比,不是主题表面色(与插件契约同款例外)
|
||
const whiteText = prop === 'color' && /^#(fff|ffffff)$/i.test(bare)
|
||
if (contentOk || whiteText) continue
|
||
bucket(prop + ': ' + value + ' → 用语义色 token(内容色加 /*iwb:content*/ 标记)', true)
|
||
}
|
||
}
|
||
}
|
||
|
||
/* ── 3. 跑 ────────────────────────────────────────────────────────────── */
|
||
const rows = onlyFile ? linesFromFile(onlyFile) : linesFromDiff()
|
||
for (const r of rows) check(r)
|
||
|
||
const anchor = (() => {
|
||
const css = fs.readFileSync(path.join(ROOT, 'src', 'design-tokens.css'), 'utf8')
|
||
const m = /--iwb-z-anchor:\s*(\d+)/.exec(css)
|
||
return m ? Number(m[1]) : null
|
||
})()
|
||
|
||
if (jsonOut) {
|
||
console.log(JSON.stringify({ version: VERSION, mode: onlyFile ? 'file' : (base || 'HEAD'), checked: rows.length, problems, warn, pluginZCeiling: anchor }, null, 2))
|
||
process.exit(problems.length ? 1 : 0)
|
||
}
|
||
|
||
const mode = onlyFile ? '整个文件 ' + onlyFile : (base ? base + '...HEAD' : '工作区未提交改动')
|
||
console.log('token-lint: ' + mode + ',检查 ' + rows.length + ' 行新增' + (anchor ? '(插件层级上限 ' + anchor + ')' : ''))
|
||
for (const w of warn) console.log(' · ' + w.file + ':' + w.line + ' ' + w.msg + (w.until ? ' [例外至 ' + w.until + ']' : ''))
|
||
if (problems.length) {
|
||
for (const p of problems) console.log(' ✗ ' + p.file + ':' + p.line + ' ' + p.msg)
|
||
console.log('\ntoken-lint: ' + problems.length + ' 处新增裸值 —— 失败。理由与白名单见 docs/standards/design-tokens.md §5')
|
||
process.exit(1)
|
||
}
|
||
console.log('token-lint: 通过(0 处新增裸值' + (warn.length ? ',' + warn.length + ' 条已登记的例外' : '') + ')')
|