mirror of
https://github.com/makecindy/cindy.git
synced 2026-12-02 05:00:10 +08:00
* ci(design-system): 加固设计门禁:豁免过期、规范外圆角、手机字色与 PR 设计依据 颜色豁免表只保留窄豁免,43 条早已不生效的整文件记录移入归档;窄豁免过期后不再放行新增行(Toast、hljs、灵动岛素材色、实体键盘复刻色按用户决定续期到 2027-04-30)。Desktop 渲染层新增行里解析到 DESIGN §5 圆角清单之外的值会被阻断,内容自身形状可用 design: intrinsic-geometry 注释声明。Mobile 新增五档字色与占位字的全仓测试,存量名单只许减少。PR 设计依据检查补齐 Mobile 界面路径、按确切规范文件名匹配,并补 workflow 一致性测试。附 100 个合并与 150 个 PR 的回放证据。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 按评审意见补全门禁扫描范围并收紧文件名与声明校验 手机字色测试覆盖样式数组、条件分支、theme.colors 与占位字的其他写法,存量按次数登记,登录 token 只在登录画布放行;多值与 !important 的字面圆角逐值校验;intrinsic-geometry 声明须为带理由的注释;设计依据文件名加完整边界。证据按新脚本 hash 重跑。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 圆角仅在确认的样式语境阻断,字色扫描拆入 guard 层并按实际用法追踪样式 圆角:class 属性、cn() 等调用、纯类名字符串、样式对象与 CSS 文件才阻断,文案里的字样只报告;支持无前导零的小数与大小写单位。手机字色:全仓扫描拆到 textColorDiscipline.test.ts 并登记到 guard 层,命名样式按是否实际用在 Text 上判断。证据说明改为引用 JSON 里的脚本 hash。 Signed-off-by: kirozeng <kirozeng@gmail.com> (cherry picked from commit 4c31a2e9403769c8cdd453e4757d2f5dbd415c06) * docs(design-evidence): 回放证据按最终脚本重跑并记录近期真命中 Signed-off-by: kirozeng <kirozeng@gmail.com> (cherry picked from commit f3f4aaa23146b5de72be4f90e9a69a46092bad1a) * ci(design-system): 补全字色扫描控件、声明注释与多行圆角的词法处理,reviewDate 校验真实日期 手机字色扫描支持 textStyle 与 SwiftUI TextField 等文字控件;intrinsic-geometry 声明只认真正的注释;字面圆角跨行 shorthand 逐值解析,字符串状态跨行追踪;豁免 reviewDate 须是真实日历日。 Signed-off-by: kirozeng <kirozeng@gmail.com> * docs(design-evidence): 回放证据按最终脚本重新生成 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 圆角门禁覆盖角与赋值写法并按跨行变更判定,手机字色扫描覆盖可复用修饰器 圆角候选补 border-*-radius / border*Radius 的各角与逻辑角写法、style 赋值与 setProperty;跨行声明只要涉及的任一行有变更就检查;手机 SwiftUI foregroundStyle 改为排除形状与图标后其余都算文字色,覆盖没有 JSX 标签的可复用修饰器;设计指南指向 textColorDiscipline.test.ts。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 圆角门禁解析 Tailwind 任意值简写,手机字色扫描追踪局部别名与对象简写 rounded-[8px_10px] 这类任意值按 _ 和 / 拆开逐项校验;手机字色扫描追踪 const/let 的简单别名(最多两层)与 { color } 简写,排除 login 命名空间别名;登记 main 上新合入的 5 处有色文字存量(额度文字 2、新回复分隔线、导入警告文字、就绪阶段文字)。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 手机字色别名按词法作用域解析并覆盖占位字别名,回放证据按最终脚本重新生成 同名别名在不同组件里不再互相覆盖(按声明所在块与使用位置解析);placeholderTextColor 经局部变量传入也会解析。回放 JSON 的 scriptHashes 与提交时的脚本一致,近期命中更新为 #8092 的 3 处 rounded-md。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 圆角门禁识别带引号的样式键,手机字色扫描覆盖 textColor 类 prop 与 foregroundStyle 别名 'borderRadius': 6 与 style['borderRadius'] = … 视为代码;textColor / labelColor 等文字颜色 prop 与 foregroundStyle(fg) 里的局部别名都会追踪;登记 ContextSheetGoalView 的 statusRecording 文字存量。 Signed-off-by: kirozeng <kirozeng@gmail.com> * docs(design-evidence): 回放与字色存量按最终脚本和扫描器重新生成 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 圆角门禁支持科学计数法与跨行类名模板,手机字色扫描覆盖对象型颜色配置 6e0px 这类 CSS 数字按完整语法解析;跨行模板字符串按整串判断是否是纯类名列表(${…} 部分留空);elementColors={{ textColor, disabledTextColor }} 这类对象键里的文字色会追踪。 Signed-off-by: kirozeng <kirozeng@gmail.com> * docs(design-evidence): 回放按最终脚本重新生成并补充对象型颜色键覆盖说明 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 字色守卫补调色板语义键与 placeholderColor,分隔标签改为精确登记例外,圆角门禁补任意属性与正号数值 botUnread 移出全局白名单,计数文字登记为存量;threadUnreadDivider 按规范作为 BotGroupChatScreen 精确例外;SessionPrLinks 占位字登记;theme={{ placeholder, text }} 与语义键调色板纳入扫描;[border-radius:6px] 与 +6px 阻断。 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 设计依据覆盖手机视觉 .ts,字色守卫识别 Text 包装组件并移出 statusError 全局放行,回放证据按最终脚本更新 Signed-off-by: kirozeng <kirozeng@gmail.com> * ci(design-system): 登记 main 新合入的 TextDocumentPreview 占位字存量 Signed-off-by: kirozeng <kirozeng@gmail.com> --------- Signed-off-by: kirozeng <kirozeng@gmail.com>
257 lines
14 KiB
JavaScript
257 lines
14 KiB
JavaScript
#!/usr/bin/env node
|
|
/** Added-line design audit. Report first, then block only the mature colour scope.
|
|
* Explicit refs are compared directly; --worktree includes staged, unstaged and
|
|
* untracked source files. No shell interpolation, index writes or commits. */
|
|
import { execFileSync } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { findBareColors, maskColorComments } from './shared/hardcoded-color-match.mjs';
|
|
import { reportDesignLayers, readSpacingVariables } from './shared/design-layer-report.mjs';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const hash = (text) => createHash('sha256').update(text).digest('hex');
|
|
const EXTENSIONS = /\.(?:[cm]?[jt]sx?|css|html|md|json|svg)$/;
|
|
export function git(root, args) {
|
|
return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
}
|
|
|
|
/** Existing Mobile discipline continues independently; new diff blocking starts
|
|
* with Desktop renderer consumers. Other sources stay visible as report/allowed. */
|
|
export function colorScope(file) {
|
|
if (/\/(?:__tests__|__mocks__|fixtures)\/|\.(?:test|spec)\./.test(file)) return 'test';
|
|
if (file === 'apps/desktop/src/renderer/themes/colors.ts'
|
|
|| /^apps\/desktop\/src\/renderer\/themes\/builtin\/[^/]+\.ts$/.test(file)
|
|
|| file === 'apps/mobile/src/theme/tokens.ts') return 'source';
|
|
if (file.startsWith('apps/desktop/src/renderer/')
|
|
&& !/\/(?:assets|vendor)\//.test(file) && /\.(?:[cm]?[jt]sx?|css|html)$/.test(file)) return 'block';
|
|
return 'report';
|
|
}
|
|
|
|
export function readExemptions(root) {
|
|
return validateExemptions(JSON.parse(fs.readFileSync(path.join(root, 'scripts/hardcoded-color-exemptions.json'), 'utf8')));
|
|
}
|
|
|
|
export function validateExemptions(data) {
|
|
if (!Array.isArray(data) || data.some(e => !e.glob || !e.reason || !e.owner)) {
|
|
throw new Error('Invalid hardcoded-color-exemptions.json; expected glob/reason/owner');
|
|
}
|
|
for (const entry of data) {
|
|
if (entry.matches !== undefined && !Array.isArray(entry.matches)) throw new Error(`Invalid matches: ${entry.glob}`);
|
|
for (const rule of entry.matches ?? []) {
|
|
if (typeof rule.value !== 'string' || typeof rule.before !== 'string' || !rule.before || !entry.reviewDate) throw new Error(`Invalid narrow exemption: ${entry.glob}`);
|
|
if (rule.object !== undefined && !(typeof rule.object === 'string' ? rule.object
|
|
: Array.isArray(rule.object) && rule.object.length && rule.object.every(o => typeof o === 'string' && o))) {
|
|
throw new Error(`Invalid object binding: ${entry.glob}`);
|
|
}
|
|
new RegExp(rule.before);
|
|
}
|
|
if (entry.matches !== undefined && !isCalendarDate(entry.reviewDate)) throw new Error(`Invalid reviewDate: ${entry.glob}`);
|
|
}
|
|
return data;
|
|
}
|
|
|
|
/** YYYY-MM-DD that is a real calendar day (9999-99-99 or 2026-02-30 would otherwise never expire). */
|
|
export function isCalendarDate(value) {
|
|
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
const date = new Date(`${value}T00:00:00Z`);
|
|
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
|
}
|
|
|
|
/** UTC calendar date; an exemption is valid through its reviewDate. */
|
|
export const currentDate = () => new Date().toISOString().slice(0, 10);
|
|
export const isExpired = (entry, today) => Boolean(entry.reviewDate) && entry.reviewDate < today;
|
|
|
|
/** Key path of the object literals enclosing index, outermost first — e.g.
|
|
* ['VARIANT_MAP', 'info'] for a colour inside `VARIANT_MAP = { info: { … } }`.
|
|
* Anonymous blocks (function bodies, call arguments, array literals) add no
|
|
* segment; string contents are skipped. Lexical, like the rest of this
|
|
* scanner: unbalanced braces inside regex literals can only fail closed
|
|
* (the binding stops matching and the hit is reported). */
|
|
export function objectPathAt(source, index) {
|
|
const stack = [];
|
|
let quote = '';
|
|
for (let i = 0; i < index; i++) {
|
|
const char = source[i];
|
|
if (quote) {
|
|
if (char === '\\') i++;
|
|
else if (char === quote) quote = '';
|
|
continue;
|
|
}
|
|
if (char === '"' || char === "'" || char === '`') { quote = char; continue; }
|
|
if (char === '{') {
|
|
const head = source.slice(Math.max(0, i - 200), i);
|
|
// `key: {` (optionally quoted), `NAME = {` and `NAME: Type = {`; the
|
|
// type annotation may not cross statement or block boundaries, and the
|
|
// 200-char window bounds how far back we look for the declared name.
|
|
const prop = /["']?([A-Za-z_$][\w$]*)["']?\s*:\s*$/.exec(head);
|
|
const decl = /([A-Za-z_$][\w$]*)\s*(?::[^;{}=]*)?=\s*$/.exec(head);
|
|
stack.push(prop ? prop[1] : decl ? decl[1] : null);
|
|
} else if (char === '}' && stack.length) stack.pop();
|
|
}
|
|
return stack.filter(Boolean);
|
|
}
|
|
|
|
export function approvedColor(file, source, hit, exemptions) {
|
|
let enclosing; // lazy: object key path at the hit, shared by every rule below
|
|
return exemptions.find(entry => {
|
|
const glob = new RegExp('^' + entry.glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
|
|
if (!glob.test(file)) return false;
|
|
// Old broad entries are historical records, never consumer-file bypasses.
|
|
return (entry.matches ?? []).some(rule => {
|
|
if (hit.value.toLowerCase().replace(/\s/g, '') !== rule.value.toLowerCase().replace(/\s/g, '')) return false;
|
|
if (!new RegExp(`(?:^|[^\\w-])(?:${rule.before})$`).test(source.slice(0, hit.index))) return false;
|
|
if (rule.selector) {
|
|
const open = source.lastIndexOf('{', hit.index);
|
|
const prevClose = source.lastIndexOf('}', open);
|
|
const normalize = value => value.replace(/'/g, '"').replace(/\s+/g, ' ').trim();
|
|
if (normalize(source.slice(prevClose + 1, open)) !== normalize(rule.selector)) return false;
|
|
}
|
|
// Bind the exception to the approved object (and variant/skin): the same
|
|
// value under the same property in any other object of the file stays a
|
|
// violation. Without this, a new object could reuse an approved colour.
|
|
if (rule.object) {
|
|
enclosing ??= objectPathAt(source, hit.index).join('.');
|
|
const objects = Array.isArray(rule.object) ? rule.object : [rule.object];
|
|
if (!objects.includes(enclosing)) return false;
|
|
}
|
|
return true;
|
|
});
|
|
});
|
|
}
|
|
|
|
export function addedLines(diff) {
|
|
const lines = new Set();
|
|
let current = null;
|
|
for (const line of diff.split('\n')) {
|
|
if (line.startsWith('@@')) {
|
|
const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
|
|
if (!match) throw new Error('Malformed diff hunk');
|
|
current = Number(match[1]);
|
|
} else if (current !== null && line.startsWith('+')) lines.add(current++);
|
|
else if (current !== null && line.startsWith(' ')) current++;
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
export function inspectFile(file, source, changed, exemptions, spacingVariables, today = currentDate()) {
|
|
const starts = [0];
|
|
for (let i = 0; i < source.length; i++) if (source[i] === '\n') starts.push(i + 1);
|
|
const locate = index => {
|
|
let low = 0, high = starts.length;
|
|
while (low + 1 < high) { const mid = (low + high) >> 1; if (starts[mid] <= index) low = mid; else high = mid; }
|
|
return { line: low + 1, column: index - starts[low] + 1 };
|
|
};
|
|
const scope = colorScope(file);
|
|
const clean = maskColorComments(source);
|
|
const colors = findBareColors(source).flatMap(hit => {
|
|
const pos = locate(hit.index);
|
|
const end = locate(hit.end - 1).line;
|
|
const addedLine = [...changed].filter(line => line >= pos.line && line <= end).sort((a, b) => a - b)[0];
|
|
if (addedLine === undefined) return [];
|
|
const candidatePos = addedLine === pos.line ? pos : { line: addedLine, column: 1 };
|
|
const matched = approvedColor(file, clean, hit, exemptions);
|
|
// An expired narrow exemption no longer approves new lines: renew it through
|
|
// design review (new reviewDate) or move the value to a theme role.
|
|
const expired = matched && isExpired(matched, today) ? matched : null;
|
|
const exemption = expired ? null : matched;
|
|
const disposition = exemption || scope === 'source' || scope === 'test' ? 'allowed' : scope;
|
|
return [{ file, ...candidatePos, literalStart: pos, rule: 'bare-color', value: hit.value, disposition,
|
|
reason: exemption?.reason ?? (expired && scope !== 'source' && scope !== 'test'
|
|
? `Exemption for ${expired.glob} expired on ${expired.reviewDate}; renew it through design review (new reviewDate) or use a theme role.`
|
|
: scope === 'source' ? 'Governed colour source; existing theme guards still apply.'
|
|
: scope === 'test' ? 'Test/fixture colour, not a production consumer.'
|
|
: scope === 'report' ? 'Literal colour outside the newly blocking scope; inspect its role (documentation, asset, runtime or future UI scope), not automatically a violation.'
|
|
: 'Literal colour bypasses semantic Light/Dark theme roles (including literal fallbacks).'),
|
|
suggestion: 'Desktop: find the matching role in themes/colors.ts and consume var(--role) / hsl(var(--role)); preserve local aliases. Mobile: use ThemeColors. If no role fits, request a design decision; do not guess a token.',
|
|
}];
|
|
});
|
|
const layers = scope === 'block' ? reportDesignLayers(file, clean, changed, locate, spacingVariables, source) : [];
|
|
return [...colors, ...layers];
|
|
}
|
|
|
|
export function audit({ root = ROOT, baseRef = 'origin/main', headRef = 'HEAD', worktree = false, today = currentDate() } = {}) {
|
|
const resolve = ref => git(root, ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`]).trim();
|
|
const base = resolve(baseRef), head = resolve(headRef);
|
|
const exemptions = readExemptions(root);
|
|
// Load and validate the spacing contract from the audited root on every
|
|
// run: a docs- or colour-only diff never reaches the lazy read inside
|
|
// classifySpacing, and hashing alone would accept a corrupt contract.
|
|
const spacingVariables = readSpacingVariables(root);
|
|
const range = worktree ? [base] : [base, head];
|
|
const diffArgs = ['diff', '--no-ext-diff', '--no-textconv', '--no-renames'];
|
|
const tracked = git(root, [...diffArgs, '--name-only', '-z', ...range, '--']).split('\0').filter(Boolean);
|
|
const untracked = worktree ? git(root, ['ls-files', '--others', '--exclude-standard', '-z', '--', 'apps', 'packages', 'scripts', 'docs', '.github']).split('\0').filter(Boolean) : [];
|
|
const files = [...new Set([...tracked, ...untracked])].filter(f => EXTENSIONS.test(f)).sort();
|
|
const findings = [], sources = [];
|
|
for (const file of files) {
|
|
let source;
|
|
if (worktree) {
|
|
const absolute = path.join(root, ...file.split('/'));
|
|
if (!fs.existsSync(absolute)) continue; // deleted file
|
|
if (!fs.lstatSync(absolute).isFile()) throw new Error(`Not a regular source file: ${file}`);
|
|
source = fs.readFileSync(absolute, 'utf8');
|
|
} else {
|
|
const entry = git(root, ['ls-tree', head, '--', file]);
|
|
if (!entry) continue;
|
|
if (!/^100(?:644|755) blob /.test(entry)) continue; // symlink/gitlink is not source
|
|
source = git(root, ['show', `${head}:${file}`]);
|
|
}
|
|
const changed = untracked.includes(file) ? new Set(source.split('\n').map((_, i) => i + 1))
|
|
: addedLines(git(root, [...diffArgs, '--unified=0', ...range, '--', file]));
|
|
sources.push({ file, sha256: hash(source), addedLines: [...changed] });
|
|
try { findings.push(...inspectFile(file, source, changed, exemptions, spacingVariables, today)); }
|
|
catch (error) { throw new Error(`${file}: ${error.message}`); }
|
|
}
|
|
// Code hashes bind the running scripts; input hashes bind the audited
|
|
// root's contract inputs, so audit({root}) reports that checkout's inputs.
|
|
const scriptFiles = ['scripts/hardcoded-color-audit.mjs', 'scripts/shared/hardcoded-color-match.mjs',
|
|
'scripts/shared/design-layer-report.mjs'];
|
|
const inputFiles = ['scripts/hardcoded-color-exemptions.json', 'packages/design-tokens/src/desktop-bindings.json',
|
|
'packages/design-tokens/src/semantic/foundations.json'];
|
|
const scriptHashes = Object.fromEntries([
|
|
...scriptFiles.map(f => [f, hash(fs.readFileSync(path.join(ROOT, f)))]),
|
|
...inputFiles.map(f => [f, hash(fs.readFileSync(path.join(root, f)))]),
|
|
]);
|
|
const colors = findings.filter(f => f.rule === 'bare-color');
|
|
const expiredExemptions = exemptions.filter(e => e.matches && isExpired(e, today))
|
|
.map(e => ({ glob: e.glob, reviewDate: e.reviewDate, owner: e.owner }));
|
|
return { schemaVersion: 1, base, head, candidate: worktree ? 'worktree (staged + unstaged + untracked)' : 'commit',
|
|
scriptHashes, candidateHash: hash(JSON.stringify(sources)), sources, today, expiredExemptions,
|
|
counts: { raw: colors.length, allowed: colors.filter(f => f.disposition === 'allowed').length,
|
|
unexpected: findings.filter(f => f.disposition === 'block').length,
|
|
report: findings.filter(f => f.disposition === 'report').length }, findings };
|
|
}
|
|
|
|
export function main(args = process.argv.slice(2)) {
|
|
const options = {};
|
|
let report = false, json = false;
|
|
for (let i = 0; i < args.length; i++) {
|
|
if (args[i] === '--report') report = true;
|
|
else if (args[i] === '--json') json = true;
|
|
else if (args[i] === '--worktree') options.worktree = true;
|
|
else if (['--base-ref', '--head-ref'].includes(args[i])) {
|
|
if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing value for ${args[i]}`);
|
|
options[args[i] === '--base-ref' ? 'baseRef' : 'headRef'] = args[++i];
|
|
} else throw new Error(`Unknown argument: ${args[i]}`);
|
|
}
|
|
if (options.worktree && options.headRef) throw new Error('--worktree and --head-ref are mutually exclusive');
|
|
const result = audit(options);
|
|
if (json) console.log(JSON.stringify(result, null, 2));
|
|
else {
|
|
console.log(`BASE ${result.base} HEAD ${result.head} ${result.candidate}\n${JSON.stringify(result.counts)}`);
|
|
for (const e of result.expiredExemptions) {
|
|
console.log(`[expired-exemption] ${e.glob} reviewDate ${e.reviewDate} (owner ${e.owner}): no longer approves new lines; renew through design review or remove.`);
|
|
}
|
|
for (const f of result.findings.filter(f => f.disposition !== 'allowed')) {
|
|
console.log(`${f.file}:${f.line}:${f.column} [${f.disposition}/${f.rule}] ${f.value}\n ${f.reason}\n ${f.suggestion}`);
|
|
}
|
|
}
|
|
return !report && result.counts.unexpected > 0 ? 1 : 0;
|
|
}
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
try { process.exitCode = main(); }
|
|
catch (error) { console.error(`[design-audit] ${error.message}`); process.exitCode = 2; }
|
|
}
|