@moheng-design/ui-skill 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -0
- package/bin/cli.js +35 -0
- package/bin/lib/audit.mjs +138 -0
- package/bin/lib/feedback.mjs +82 -0
- package/bin/lib/install.mjs +61 -0
- package/bin/lib/paths.mjs +47 -0
- package/bin/lib/upgrade.mjs +86 -0
- package/eslint/index.js +94 -0
- package/eslint/lib/factories.js +313 -0
- package/eslint/lib/match.js +188 -0
- package/eslint/lib/tiers.js +27 -0
- package/generated/SKILL.md +696 -0
- package/generated/contracts.json +9270 -0
- package/generated/mappings.schema.json +333 -0
- package/generated/plugin-data.js +6994 -0
- package/generated/reference.md +5651 -0
- package/generated/rules.json +3864 -0
- package/generated/skills/moheng-ui-audit/SKILL.md +66 -0
- package/generated/skills/moheng-ui-bootstrap/SKILL.md +109 -0
- package/generated/skills/moheng-ui-feedback/SKILL.md +65 -0
- package/generated/skills/moheng-ui-page/SKILL.md +75 -0
- package/generated/skills/moheng-ui-review/SKILL.md +55 -0
- package/generated/skills/moheng-ui-upgrade/SKILL.md +40 -0
- package/generated/unenforced.json +57 -0
- package/handwritten/anti-patterns.md +239 -0
- package/handwritten/canvas-model.md +98 -0
- package/handwritten/conventions.md +2082 -0
- package/handwritten/skills/audit.md +54 -0
- package/handwritten/skills/bootstrap.md +99 -0
- package/handwritten/skills/feedback.md +63 -0
- package/handwritten/skills/page.md +44 -0
- package/handwritten/skills/review.md +43 -0
- package/handwritten/skills/upgrade.md +38 -0
- package/handwritten/unenforced.md +27 -0
- package/package.json +66 -0
- package/stylelint/index.js +121 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* upgrade —— 两份 contracts.json 的差异,写出 moheng-upgrade.md。
|
|
3
|
+
*
|
|
4
|
+
* 路线(细节留白,见 handwritten/skills/upgrade.md):
|
|
5
|
+
*
|
|
6
|
+
* --from <旧版 contracts.json> 必填,升级前从 node_modules 拷出来的那份
|
|
7
|
+
* --to <新版 contracts.json> 可选,默认本包 generated/contracts.json
|
|
8
|
+
*
|
|
9
|
+
* 只比三层:组件增删、prop 增删与必填翻转、枚举值增删。契约是唯一事实来源(§6.2),
|
|
10
|
+
* 差异从它算,不从 CHANGELOG 抄。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { join, resolve } from 'node:path'
|
|
15
|
+
|
|
16
|
+
import { GENERATED } from './paths.mjs'
|
|
17
|
+
|
|
18
|
+
const arg = (argv, name) => {
|
|
19
|
+
const i = argv.indexOf(name)
|
|
20
|
+
return i === -1 ? null : argv[i + 1]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function run(argv) {
|
|
24
|
+
const fromPath = arg(argv, '--from')
|
|
25
|
+
const toPath = arg(argv, '--to') ?? join(GENERATED, 'contracts.json')
|
|
26
|
+
if (!fromPath) {
|
|
27
|
+
console.error('✗ 缺少 --from <旧版 contracts.json>。升级前先从 node_modules/@moheng-design/ui-skill/generated/ 拷一份出来。')
|
|
28
|
+
return 1
|
|
29
|
+
}
|
|
30
|
+
for (const p of [fromPath, toPath]) {
|
|
31
|
+
if (!existsSync(resolve(p))) { console.error(`✗ 找不到 ${p}`); return 1 }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const load = (p) => new Map(JSON.parse(readFileSync(resolve(p), 'utf8')).components.map((c) => [c.name, c]))
|
|
35
|
+
const before = load(fromPath)
|
|
36
|
+
const after = load(toPath)
|
|
37
|
+
|
|
38
|
+
const lines = ['# @moheng-design/ui 契约差异', '', `- 旧:${fromPath}`, `- 新:${toPath}`, '']
|
|
39
|
+
let changes = 0
|
|
40
|
+
const section = (title, items) => {
|
|
41
|
+
if (items.length === 0) return
|
|
42
|
+
changes += items.length
|
|
43
|
+
lines.push(`## ${title}`, '', ...items.map((i) => `- ${i}`), '')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
section('删除的组件(引用处必须改)', [...before.keys()].filter((n) => !after.has(n)).map((n) => `\`${n}\``))
|
|
47
|
+
section('新增的组件', [...after.keys()].filter((n) => !before.has(n)).map((n) => `\`${n}\``))
|
|
48
|
+
|
|
49
|
+
const removedProps = []
|
|
50
|
+
const addedProps = []
|
|
51
|
+
const requiredFlips = []
|
|
52
|
+
const removedValues = []
|
|
53
|
+
const addedValues = []
|
|
54
|
+
|
|
55
|
+
for (const [name, next] of after) {
|
|
56
|
+
const prev = before.get(name)
|
|
57
|
+
if (!prev) continue
|
|
58
|
+
const prevProps = new Map(prev.props.map((p) => [p.name, p]))
|
|
59
|
+
const nextProps = new Map(next.props.map((p) => [p.name, p]))
|
|
60
|
+
for (const p of prevProps.keys()) if (!nextProps.has(p)) removedProps.push(`\`${name}.${p}\``)
|
|
61
|
+
for (const p of nextProps.keys()) if (!prevProps.has(p)) addedProps.push(`\`${name}.${p}\``)
|
|
62
|
+
for (const [pname, np] of nextProps) {
|
|
63
|
+
const pp = prevProps.get(pname)
|
|
64
|
+
if (!pp) continue
|
|
65
|
+
if (!pp.required && np.required) requiredFlips.push(`\`${name}.${pname}\` 变为必填`)
|
|
66
|
+
const pv = new Set(pp.values ?? [])
|
|
67
|
+
const nv = new Set(np.values ?? [])
|
|
68
|
+
for (const v of pv) if (!nv.has(v)) removedValues.push(`\`${name}.${pname}\` 不再接受 \`${v}\``)
|
|
69
|
+
for (const v of nv) if (!pv.has(v)) addedValues.push(`\`${name}.${pname}\` 新增 \`${v}\``)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
section('删除的 prop(props-whitelist 会报)', removedProps)
|
|
74
|
+
section('变为必填的 prop', requiredFlips)
|
|
75
|
+
section('删除的枚举值(prop-enum 会报)', removedValues)
|
|
76
|
+
section('新增的 prop', addedProps)
|
|
77
|
+
section('新增的枚举值', addedValues)
|
|
78
|
+
|
|
79
|
+
if (changes === 0) lines.push('两份契约没有差异。', '')
|
|
80
|
+
|
|
81
|
+
const outPath = join(process.cwd(), 'moheng-upgrade.md')
|
|
82
|
+
writeFileSync(outPath, `${lines.join('\n')}\n`)
|
|
83
|
+
console.log(`✓ 已写入 moheng-upgrade.md:${changes} 处差异`)
|
|
84
|
+
console.log(' 下一步:加载 moheng-ui-upgrade 技能,按报告改代码,再 npx @moheng-design/ui-skill install --force。')
|
|
85
|
+
return 0
|
|
86
|
+
}
|
package/eslint/index.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @moheng-design/ui-skill 的 ESLint 插件与四档配置(01 §1.4、§7.3、§7.4)。
|
|
3
|
+
*
|
|
4
|
+
* 四档为 recommended / strict / migration / internal。前三档面向消费方(§7.4 的
|
|
5
|
+
* 渐进启用路径),第四档是组件库自用,不发给消费方。
|
|
6
|
+
*
|
|
7
|
+
* 这个包存在的理由是 §1.4:**Skill 是引导,ESLint 才是强制。**
|
|
8
|
+
* Skill 让 agent 一次写对(减少往返),ESLint 兜底拦截(保证正确)。
|
|
9
|
+
* 一条约束若只写在 SKILL.md 而没有 lint 实现,就会造成
|
|
10
|
+
* 「以为约束住了、实际没有」的假象 —— 那是 §1.4 点名的反模式。
|
|
11
|
+
*
|
|
12
|
+
* 用法:
|
|
13
|
+
*
|
|
14
|
+
* // eslint.config.js
|
|
15
|
+
* import moheng from '@moheng-design/ui-skill/eslint'
|
|
16
|
+
* export default [moheng.recommended]
|
|
17
|
+
*
|
|
18
|
+
* 规则数据来自 generated/plugin-data.js,由 scripts/generate.mjs 从
|
|
19
|
+
* @moheng-design/ui 的 contracts/ 与 mappings.json 生成。**没跑过生成器时本模块
|
|
20
|
+
* 会直接抛错而不是静默导出一个空配置** —— 空配置正是 §1.4 要避免的东西。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import data from '../generated/plugin-data.js'
|
|
24
|
+
import { FACTORIES } from './lib/factories.js'
|
|
25
|
+
import { ESLINT_TIERS, inScope } from './lib/tiers.js'
|
|
26
|
+
|
|
27
|
+
/** 插件命名空间。规则全名形如 `moheng/no-native-button`。 */
|
|
28
|
+
export const NAMESPACE = 'moheng'
|
|
29
|
+
|
|
30
|
+
const rules = {}
|
|
31
|
+
for (const rule of data.rules) {
|
|
32
|
+
const factory = FACTORIES[rule.kind]
|
|
33
|
+
if (!factory) throw new Error(`@moheng-design/ui-skill:未知的规则 kind ${rule.kind}(${rule.id})`)
|
|
34
|
+
rules[rule.id] = factory(rule, data.nativeBases)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const plugin = {
|
|
38
|
+
meta: { name: '@moheng-design/ui-skill', version: '0.0.0' },
|
|
39
|
+
rules,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/* ── 档位 ─────────────────────────────────────────────────────────────────
|
|
43
|
+
*
|
|
44
|
+
* §7.4:不要一上来全开 error。存量项目会红一片,团队第一反应是把规则关掉,
|
|
45
|
+
* 然后就永远关着了。
|
|
46
|
+
*
|
|
47
|
+
* §7.3:scope 决定规则在哪一侧生效。把「禁止硬编码色值」发给用户会吵到
|
|
48
|
+
* 无法使用 —— 用户业务代码里出现色值是完全正常的。
|
|
49
|
+
*/
|
|
50
|
+
function configFor(name) {
|
|
51
|
+
/* 档位的 scope 与 severity 取自 lib/tiers.js —— 文档站的「Lint 规则」页读同一份。 */
|
|
52
|
+
const { scope, severity } = ESLINT_TIERS.find((tier) => tier.name === name)
|
|
53
|
+
const selected = data.rules.filter(inScope(scope))
|
|
54
|
+
const entries = {}
|
|
55
|
+
for (const rule of selected) {
|
|
56
|
+
entries[`${NAMESPACE}/${rule.id}`] = severity ?? rule.severity
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
name: `moheng/${name}`,
|
|
60
|
+
files: ['**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}'],
|
|
61
|
+
plugins: { [NAMESPACE]: plugin },
|
|
62
|
+
rules: entries,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 核心规则 error,其余 warn —— 逐条取规则自述的 severity,本档不强制任何级别。
|
|
68
|
+
*
|
|
69
|
+
* 落到当前规则集即:手写的 forbid-element / forbid-import 为 error,
|
|
70
|
+
* 生成的 props-whitelist / prop-enum 为 warn。划分依据写在
|
|
71
|
+
* scripts/lib/build-rules.mjs 的 GENERATED_SEVERITY 注释里 —— 一句话是
|
|
72
|
+
* 「tsc 已经在报的降为 warn,tsc 看不见的必须 error」。
|
|
73
|
+
*
|
|
74
|
+
* 本档与 strict 的差异**只来自这一处数据**。生成器若把两类规则的 severity 又写回
|
|
75
|
+
* error,recommended 与 strict 会逐条等同,§7.4 的三档退化成两档,且退化前后
|
|
76
|
+
* 这个文件一个字都不用改 —— 因此差异必须由测试钉住,不能靠读代码看出来。
|
|
77
|
+
*/
|
|
78
|
+
export const recommended = configFor('recommended')
|
|
79
|
+
|
|
80
|
+
/** 全部 error。 */
|
|
81
|
+
export const strict = configFor('strict')
|
|
82
|
+
|
|
83
|
+
/** 全部 warn,用于存量项目接入。 */
|
|
84
|
+
export const migration = configFor('migration')
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 库内自用档:scope 为 internal 与 both 的规则,全部 error。
|
|
88
|
+
*
|
|
89
|
+
* §7.3 的三档 scope 里,internal 那一档必须有地方消费,否则「组件源码必须用 token」
|
|
90
|
+
* 就只是一句文档 —— 即 §1.4 的反模式。本仓库的根 eslint.config.js 用的就是它。
|
|
91
|
+
*/
|
|
92
|
+
export const internal = configFor('internal')
|
|
93
|
+
|
|
94
|
+
export default { plugin, recommended, strict, migration, internal, NAMESPACE }
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 五类规则的实现工厂(01 §5.6、§7.2)。
|
|
3
|
+
*
|
|
4
|
+
* 每条 mappings 规则生成一个具名 ESLint 规则,规则名即 mappings.json 里的 id
|
|
5
|
+
* (schema 明确「id 同时是生成出的 ESLint 规则名」)。工厂只有五个,
|
|
6
|
+
* 因为规则之间的差异全在数据里 —— 差异在数据里,实现才不会随规则数量增长。
|
|
7
|
+
*
|
|
8
|
+
* 报错文案一律直接用 rule.message,**不做任何加工**。§5.2 要求文案是可直接执行的
|
|
9
|
+
* 替换指令,且验收标准要求它与 SKILL.md 的替换表逐字一致 —— 在这里改一个字,
|
|
10
|
+
* 那条验收标准就不成立了。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
attrLiteralValue,
|
|
15
|
+
attrStringValue,
|
|
16
|
+
collectImports,
|
|
17
|
+
compileValuePattern,
|
|
18
|
+
hasStyling,
|
|
19
|
+
jsxName,
|
|
20
|
+
matchesFile,
|
|
21
|
+
matchesModule,
|
|
22
|
+
} from './match.js'
|
|
23
|
+
|
|
24
|
+
const PACKAGE = '@moheng-design/ui'
|
|
25
|
+
|
|
26
|
+
/** ESLint 9 的 meta.schema 必须显式给出;本组规则都不接受选项。 */
|
|
27
|
+
const NO_OPTIONS = []
|
|
28
|
+
|
|
29
|
+
/* ── autofix 的 import 补全 ───────────────────────────────────────────────
|
|
30
|
+
*
|
|
31
|
+
* 只改标签名不补 import,`--fix` 之后 ESLint 报零错、被替换出来的标识符全部未定义
|
|
32
|
+
* —— 报错文案里那句「导入方式:import { Button } from '@moheng-design/ui'」随报错一起消失,
|
|
33
|
+
* §11 的验收标准「让 agent 写一个表单,产出代码通过 eslint 零报错」字面成立、实质架空。
|
|
34
|
+
* 静默的未定义标识符比 §5.3 要防的静默样式丢失更难查:前者连报错都没有。
|
|
35
|
+
*
|
|
36
|
+
* 一条报错的多个 fix 由 ESLint 合并成一段连续改写,因此同一轮里只落地一条;
|
|
37
|
+
* 其余留到下一轮(verifyAndFix 默认 10 轮),补过 import 的组件下一轮不再带
|
|
38
|
+
* import 改写,范围收窄即可与别的改写同轮落地。未收敛的部分仍以报错留在原地,
|
|
39
|
+
* 不会静默丢失。
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/** 组件名在本文件里是否已被别的声明占用。环境全局不算 —— 它们没有 defs。 */
|
|
43
|
+
function nameIsDeclared(sourceCode, node, name) {
|
|
44
|
+
for (let scope = sourceCode.getScope(node); scope; scope = scope.upper) {
|
|
45
|
+
const variable = scope.set.get(name)
|
|
46
|
+
if (variable && variable.defs.length > 0) return true
|
|
47
|
+
}
|
|
48
|
+
return false
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 新增 import 的引号随文件已有的 import;没有 import 时用单引号。 */
|
|
52
|
+
function quoteOf(program) {
|
|
53
|
+
const first = program.body.find((node) => node.type === 'ImportDeclaration')
|
|
54
|
+
return first?.source?.raw?.[0] === '"' ? '"' : "'"
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 为 `component` 补上从 `from` 的具名导入,返回 fix 数组。
|
|
59
|
+
*
|
|
60
|
+
* 返回 `[]` 表示无需补(已导入);返回 `null` 表示补不安全,调用方整条不修只报错。
|
|
61
|
+
*/
|
|
62
|
+
function importFixes(fixer, context, node, component, from) {
|
|
63
|
+
const source = context.sourceCode
|
|
64
|
+
const program = source.ast
|
|
65
|
+
if (program.body.length === 0) return null
|
|
66
|
+
|
|
67
|
+
/* 已从本库导入同名组件 —— 不得重复插入。 */
|
|
68
|
+
if (collectImports(program, from).get(component) === component) return []
|
|
69
|
+
/* 名字被本文件别的声明占用(自写的同名组件、同名变量、改名导入的另一半):
|
|
70
|
+
* 插进去即是重复声明,语法当场就错。此时只报错,把决定权交回 —— 与 §5.3
|
|
71
|
+
* 「拿不准就不改」是同一条取舍。 */
|
|
72
|
+
if (nameIsDeclared(source, node, component)) return null
|
|
73
|
+
|
|
74
|
+
/* 已有一条本库的具名 import:并进去,不另起一行。type-only 声明不算 ——
|
|
75
|
+
* 往里塞值导入会把整条声明的语义搞错。 */
|
|
76
|
+
const named = program.body.find((item) => item.type === 'ImportDeclaration'
|
|
77
|
+
&& item.source.value === from
|
|
78
|
+
&& item.importKind !== 'type'
|
|
79
|
+
&& item.specifiers.some((spec) => spec.type === 'ImportSpecifier'))
|
|
80
|
+
if (named) {
|
|
81
|
+
const specifiers = named.specifiers.filter((spec) => spec.type === 'ImportSpecifier')
|
|
82
|
+
return [fixer.insertTextAfter(specifiers.at(-1), `, ${component}`)]
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const quote = quoteOf(program)
|
|
86
|
+
const declaration = `import { ${component} } from ${quote}${from}${quote}`
|
|
87
|
+
|
|
88
|
+
/* 落位优先级:已有 import 之后 → 指令序言之后 → 首条语句之前。
|
|
89
|
+
* 指令那一档不可省:插到 "use client" 前面,指令序言即告中断,
|
|
90
|
+
* Next.js 的 client component 标记当场失效(§4.4 要求 RSC 环境下正确工作)。 */
|
|
91
|
+
const imports = program.body.filter((item) => item.type === 'ImportDeclaration')
|
|
92
|
+
if (imports.length > 0) return [fixer.insertTextAfter(imports.at(-1), `\n${declaration}`)]
|
|
93
|
+
|
|
94
|
+
const prologue = []
|
|
95
|
+
for (const item of program.body) {
|
|
96
|
+
if (item.type !== 'ExpressionStatement' || typeof item.expression?.value !== 'string') break
|
|
97
|
+
prologue.push(item)
|
|
98
|
+
}
|
|
99
|
+
if (prologue.length > 0) return [fixer.insertTextAfter(prologue.at(-1), `\n\n${declaration}`)]
|
|
100
|
+
return [fixer.insertTextBefore(program.body[0], `${declaration}\n\n`)]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function baseMeta(rule, type) {
|
|
104
|
+
return {
|
|
105
|
+
type,
|
|
106
|
+
docs: {
|
|
107
|
+
description: rule.message,
|
|
108
|
+
recommended: rule.severity === 'error',
|
|
109
|
+
},
|
|
110
|
+
schema: NO_OPTIONS,
|
|
111
|
+
messages: { violation: '{{text}}' },
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/* ── forbid-element ───────────────────────────────────────────────────────
|
|
116
|
+
*
|
|
117
|
+
* §7.2 第 1 类,也是设计系统现有 lint 配置中**唯一缺失**的部分 ——
|
|
118
|
+
* _adherence.oxlintrc.json 的 react/forbid-elements 是空数组。
|
|
119
|
+
*/
|
|
120
|
+
export function forbidElement(rule) {
|
|
121
|
+
const attrsMatch = (node, attributes) =>
|
|
122
|
+
Object.entries(attributes).every(([key, want]) =>
|
|
123
|
+
node.attributes.some((attr) =>
|
|
124
|
+
attr.type === 'JSXAttribute' && attr.name?.name === key && attrStringValue(attr) === want))
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
meta: {
|
|
128
|
+
...baseMeta(rule, 'problem'),
|
|
129
|
+
fixable: rule.autofix?.enabled ? 'code' : undefined,
|
|
130
|
+
},
|
|
131
|
+
create(context) {
|
|
132
|
+
return {
|
|
133
|
+
JSXOpeningElement(node) {
|
|
134
|
+
if (jsxName(node) !== rule.element) return
|
|
135
|
+
if (rule.attributes && !attrsMatch(node, rule.attributes)) return
|
|
136
|
+
/* 兜底规则让位给更具体的兄弟规则:<input type="checkbox"> 只该报
|
|
137
|
+
* no-native-checkbox 一条,不该连 no-native-input 一起报。 */
|
|
138
|
+
if (!rule.attributes && rule.siblings.some((sib) => attrsMatch(node, sib))) return
|
|
139
|
+
|
|
140
|
+
context.report({
|
|
141
|
+
node,
|
|
142
|
+
messageId: 'violation',
|
|
143
|
+
data: { text: rule.message },
|
|
144
|
+
/* §5.3:autofix 必须保守。带 className / style 时只报错不改 ——
|
|
145
|
+
* `<button className="px-4">提交</button>` → `<Button>提交</Button>`
|
|
146
|
+
* 会静默吃掉用户样式,那比 lint 报错难查得多。
|
|
147
|
+
*
|
|
148
|
+
* 改标签名与补 import 是一件事的两半,必须同进同出:只改一半会把
|
|
149
|
+
* 未定义标识符留在代码里,而 ESLint 从此报零错(见 importFixes 的说明)。 */
|
|
150
|
+
fix: rule.autofix?.enabled && !hasStyling(node)
|
|
151
|
+
? (fixer) => {
|
|
152
|
+
const { component, from } = rule.replacement
|
|
153
|
+
const added = importFixes(fixer, context, node, component, from)
|
|
154
|
+
if (added === null) return null
|
|
155
|
+
const fixes = [...added, fixer.replaceText(node.name, component)]
|
|
156
|
+
const parent = node.parent
|
|
157
|
+
if (parent?.type === 'JSXElement' && parent.closingElement) {
|
|
158
|
+
fixes.push(fixer.replaceText(parent.closingElement.name, component))
|
|
159
|
+
}
|
|
160
|
+
return fixes
|
|
161
|
+
}
|
|
162
|
+
: undefined,
|
|
163
|
+
})
|
|
164
|
+
},
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/* ── forbid-import ───────────────────────────────────────────────────────
|
|
171
|
+
*
|
|
172
|
+
* §7.2 第 3 类。两种用途:禁止深引内部路径,以及禁止从 @/components/ui/* 导入
|
|
173
|
+
* —— 后者专门防 agent 顺手执行 npx shadcn add 引入平行的组件实现。
|
|
174
|
+
*/
|
|
175
|
+
export function forbidImport(rule) {
|
|
176
|
+
return {
|
|
177
|
+
meta: baseMeta(rule, 'problem'),
|
|
178
|
+
create(context) {
|
|
179
|
+
if (matchesFile(context.filename, rule.exceptFiles)) return {}
|
|
180
|
+
|
|
181
|
+
const check = (node, source) => {
|
|
182
|
+
if (typeof source !== 'string') return
|
|
183
|
+
if (!matchesModule(source, rule.patterns)) return
|
|
184
|
+
context.report({ node, messageId: 'violation', data: { text: rule.message } })
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
ImportDeclaration: (n) => check(n, n.source.value),
|
|
189
|
+
ExportNamedDeclaration: (n) => n.source && check(n, n.source.value),
|
|
190
|
+
ExportAllDeclaration: (n) => n.source && check(n, n.source.value),
|
|
191
|
+
ImportExpression: (n) => n.source?.type === 'Literal' && check(n, n.source.value),
|
|
192
|
+
CallExpression(n) {
|
|
193
|
+
if (n.callee.type !== 'Identifier' || n.callee.name !== 'require') return
|
|
194
|
+
const arg = n.arguments[0]
|
|
195
|
+
if (arg?.type === 'Literal') check(n, arg.value)
|
|
196
|
+
},
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/* ── forbid-value ────────────────────────────────────────────────────────
|
|
203
|
+
*
|
|
204
|
+
* §7.2 第 2 类的 JS 侧。CSS 侧由 stylelint 承担(§7.2.1)—— ESLint 读不了 .css,
|
|
205
|
+
* 而组件样式全部写在外部 CSS(§1.7),只做 ESLint 等于把约束留在文档里。
|
|
206
|
+
*
|
|
207
|
+
* scope 恒为 internal(schema 强制):用户业务代码里出现色值与 px 是完全正常的,
|
|
208
|
+
* 全量禁止会吵到用户直接关掉整条规则,连带把真正有价值的一起关了。
|
|
209
|
+
*/
|
|
210
|
+
export function forbidValue(rule) {
|
|
211
|
+
return {
|
|
212
|
+
meta: baseMeta(rule, 'problem'),
|
|
213
|
+
create(context) {
|
|
214
|
+
if (matchesFile(context.filename, rule.exceptFiles)) return {}
|
|
215
|
+
/* 编译走 compileValuePattern —— 它剥掉 g / y,否则 test() 会跨节点保留
|
|
216
|
+
* lastIndex,同一文件里的违规每隔一个漏报一次(match.js 有完整说明)。 */
|
|
217
|
+
const re = compileValuePattern(rule)
|
|
218
|
+
const report = (node) => context.report({ node, messageId: 'violation', data: { text: rule.message } })
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
Literal(node) {
|
|
222
|
+
if (typeof node.value !== 'string') return
|
|
223
|
+
/* 导入路径不是样式值 —— `@moheng-design/ui/dist/16px` 这种命中毫无意义 */
|
|
224
|
+
if (node.parent?.type === 'ImportDeclaration' || node.parent?.type === 'ImportExpression') return
|
|
225
|
+
if (re.test(node.value)) report(node)
|
|
226
|
+
},
|
|
227
|
+
TemplateElement(node) {
|
|
228
|
+
if (re.test(node.value.raw)) report(node)
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* ── props-whitelist ─────────────────────────────────────────────────────
|
|
236
|
+
*
|
|
237
|
+
* 事实来源是契约(§5.6),生成器展开。allowed 只含自有 props 与 React 保留项;
|
|
238
|
+
* 继承自 *HTMLAttributes 的原生属性由 nativeBases 表按基类共享放行。
|
|
239
|
+
* 两张表合起来才是规则实际接受的集合 —— 少了后者,`<Button onClick>` 会被误报。
|
|
240
|
+
*/
|
|
241
|
+
export function propsWhitelist(rule, nativeBases) {
|
|
242
|
+
const allowed = new Set(rule.allowed)
|
|
243
|
+
const native = new Set(rule.nativeBase ? nativeBases[rule.nativeBase] ?? [] : [])
|
|
244
|
+
for (const omitted of rule.omitted) native.delete(omitted)
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
meta: baseMeta(rule, 'problem'),
|
|
248
|
+
create(context) {
|
|
249
|
+
let local = new Map()
|
|
250
|
+
return {
|
|
251
|
+
Program(node) {
|
|
252
|
+
local = collectImports(node, PACKAGE)
|
|
253
|
+
},
|
|
254
|
+
JSXOpeningElement(node) {
|
|
255
|
+
const name = jsxName(node)
|
|
256
|
+
if (!name || local.get(name) !== rule.component) return
|
|
257
|
+
for (const attr of node.attributes) {
|
|
258
|
+
if (attr.type !== 'JSXAttribute') continue /* 展开属性判不了,放过 */
|
|
259
|
+
const prop = attr.name.type === 'JSXIdentifier' ? attr.name.name : null
|
|
260
|
+
if (!prop) continue
|
|
261
|
+
if (allowed.has(prop) || native.has(prop)) continue
|
|
262
|
+
/* data-* 是任意扩展点,React 不校验,本规则也不该校验 */
|
|
263
|
+
if (prop.startsWith('data-')) continue
|
|
264
|
+
context.report({ node: attr, messageId: 'violation', data: { text: rule.message } })
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/* ── prop-enum ───────────────────────────────────────────────────────────
|
|
273
|
+
*
|
|
274
|
+
* 只判字面量取值。`variant={x}` 这类表达式判不了,交给 TypeScript ——
|
|
275
|
+
* §7.1 已说明类型层的收益超过 Skill 和 lint 加起来,lint 只补类型看不见的那部分。
|
|
276
|
+
*
|
|
277
|
+
* 取值走 attrLiteralValue:枚举有数值的一类(IconProps.size),字符串与数值
|
|
278
|
+
* 在两侧都归一成字符串后比对。只认字符串时数值枚举整类静默失效,见该函数的说明。
|
|
279
|
+
*/
|
|
280
|
+
export function propEnum(rule) {
|
|
281
|
+
const allowed = new Set(rule.allowed)
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
meta: baseMeta(rule, 'problem'),
|
|
285
|
+
create(context) {
|
|
286
|
+
let local = new Map()
|
|
287
|
+
return {
|
|
288
|
+
Program(node) {
|
|
289
|
+
local = collectImports(node, PACKAGE)
|
|
290
|
+
},
|
|
291
|
+
JSXOpeningElement(node) {
|
|
292
|
+
const name = jsxName(node)
|
|
293
|
+
if (!name || local.get(name) !== rule.component) return
|
|
294
|
+
for (const attr of node.attributes) {
|
|
295
|
+
if (attr.type !== 'JSXAttribute') continue
|
|
296
|
+
if (attr.name?.name !== rule.prop) continue
|
|
297
|
+
const value = attrLiteralValue(attr)
|
|
298
|
+
if (value === null || allowed.has(value)) continue
|
|
299
|
+
context.report({ node: attr, messageId: 'violation', data: { text: rule.message } })
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export const FACTORIES = {
|
|
308
|
+
'forbid-element': forbidElement,
|
|
309
|
+
'forbid-import': forbidImport,
|
|
310
|
+
'forbid-value': forbidValue,
|
|
311
|
+
'props-whitelist': propsWhitelist,
|
|
312
|
+
'prop-enum': propEnum,
|
|
313
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 规则实现共用的匹配基元。
|
|
3
|
+
*
|
|
4
|
+
* 手写文件 —— 生成的是**数据**(generated/plugin-data.js),不是代码。
|
|
5
|
+
* 五类规则各写一个工厂,生成器为每条规则调一次工厂,产出一个具名 ESLint 规则。
|
|
6
|
+
* 这样规则名与 mappings.json 的 id 一一对应、可逐条关闭,而实现只有五份。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* glob → 正则。语法对齐 ESLint no-restricted-imports 的 patterns.group:
|
|
11
|
+
* `*` 不跨越 `/`,`**` 跨越任意层级。
|
|
12
|
+
*/
|
|
13
|
+
export function globToRegExp(pattern) {
|
|
14
|
+
let out = ''
|
|
15
|
+
for (let i = 0; i < pattern.length; i += 1) {
|
|
16
|
+
const ch = pattern[i]
|
|
17
|
+
if (ch === '*') {
|
|
18
|
+
if (pattern[i + 1] === '*') {
|
|
19
|
+
out += '.*'
|
|
20
|
+
i += 1
|
|
21
|
+
if (pattern[i + 1] === '/') i += 1 /* 双星紧跟斜杠时也匹配零层 */
|
|
22
|
+
} else {
|
|
23
|
+
out += '[^/]*'
|
|
24
|
+
}
|
|
25
|
+
} else if (ch === '?') {
|
|
26
|
+
out += '[^/]'
|
|
27
|
+
} else {
|
|
28
|
+
out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return new RegExp(`^${out}$`)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 模块路径是否命中任一 glob。 */
|
|
35
|
+
export function matchesModule(source, patterns) {
|
|
36
|
+
return patterns.some((p) => globToRegExp(p).test(source))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 文件是否命中任一 glob(用于 exceptFiles)。
|
|
41
|
+
*
|
|
42
|
+
* ESLint 给的是绝对路径,而 mappings.json 里写的是 `src/tokens/**\/*.css`
|
|
43
|
+
* 这种仓库内相对形式。按路径**后缀**匹配 —— 绝对路径前缀因人而异,
|
|
44
|
+
* 拿它去比对只会在别人的机器上失效。
|
|
45
|
+
*/
|
|
46
|
+
export function matchesFile(filename, globs) {
|
|
47
|
+
if (!filename || globs.length === 0) return false
|
|
48
|
+
const posix = filename.replace(/\\/g, '/')
|
|
49
|
+
return globs.some((glob) => {
|
|
50
|
+
const re = globToRegExp(glob)
|
|
51
|
+
const parts = posix.split('/')
|
|
52
|
+
for (let i = 0; i < parts.length; i += 1) {
|
|
53
|
+
if (re.test(parts.slice(i).join('/'))) return true
|
|
54
|
+
}
|
|
55
|
+
return false
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 导入绑定表:本地名 → 导出名,兼管命名空间导入的解析。
|
|
61
|
+
*
|
|
62
|
+
* `get()` 额外认 `UI.Button` 这种点号形式 —— 那是 jsxName 对成员表达式的返回值。
|
|
63
|
+
* 命名空间导入不能改名,property 名即导出名,故直接取点号右侧。
|
|
64
|
+
* 非本库命名空间(用户自己的 `<Other.Button>`)一律返回 undefined:
|
|
65
|
+
* 误报一次用户就会把整条规则关掉(§7.4 的顾虑)。
|
|
66
|
+
*/
|
|
67
|
+
class ImportBindings extends Map {
|
|
68
|
+
/** 命名空间导入的本地名,形如 `import * as UI from '@moheng-design/ui'` 里的 UI。 */
|
|
69
|
+
namespaces = new Set()
|
|
70
|
+
|
|
71
|
+
get(name) {
|
|
72
|
+
const dot = name.indexOf('.')
|
|
73
|
+
if (dot === -1) return super.get(name)
|
|
74
|
+
return this.namespaces.has(name.slice(0, dot)) ? name.slice(dot + 1) : undefined
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 收集本文件里从 @moheng-design/ui 导入的组件:本地名 → 导出名。
|
|
80
|
+
*
|
|
81
|
+
* props 白名单与枚举校验都必须先确认「这个 <Card> 确实是本库的 Card」。
|
|
82
|
+
* 不做这一步,用户自己写的同名组件会被误报 —— 而误报一次,
|
|
83
|
+
* 用户就会把整条规则关掉(§7.4 的顾虑)。
|
|
84
|
+
*
|
|
85
|
+
* **命名空间导入必须一并收下。** 只收 ImportSpecifier 时,
|
|
86
|
+
* `import * as UI from '@moheng-design/ui'` 之后写的 `<UI.Button variant="icon" nope="z">`
|
|
87
|
+
* 一条也报不出来 —— 生成类的 props-whitelist 与 prop-enum 全档旁路,
|
|
88
|
+
* 且不报错不告警,正是 §1.4 点名的「以为约束住了、实际没有」。
|
|
89
|
+
* 命名空间的局部名记进 namespaces,由 ImportBindings.get 解析点号形式。
|
|
90
|
+
*/
|
|
91
|
+
export function collectImports(program, packageName) {
|
|
92
|
+
const local = new ImportBindings()
|
|
93
|
+
for (const node of program.body) {
|
|
94
|
+
if (node.type !== 'ImportDeclaration' || node.source.value !== packageName) continue
|
|
95
|
+
for (const spec of node.specifiers) {
|
|
96
|
+
if (spec.type === 'ImportSpecifier' && spec.imported.type === 'Identifier') {
|
|
97
|
+
local.set(spec.local.name, spec.imported.name)
|
|
98
|
+
} else if (spec.type === 'ImportNamespaceSpecifier') {
|
|
99
|
+
local.namespaces.add(spec.local.name)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return local
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 把 forbid-value 的 valuePattern 编译成可反复调用 `test()` 的正则。
|
|
108
|
+
*
|
|
109
|
+
* **必须剥掉 `g` 与 `y`。** schema 的 flags 字段是 `^[gimsuy]*$`,写 `g` 是合法的;
|
|
110
|
+
* 而带 `g` 的正则在 `test()` 之间保留 lastIndex,同一条规则实例在一个文件里
|
|
111
|
+
* 逐个节点比对时会**每隔一个漏掉一次** —— 四处硬编码色值只报两处,且不报错、
|
|
112
|
+
* 不告警,恰恰是 §1.4 点名的「以为约束住了、实际没有」。
|
|
113
|
+
*
|
|
114
|
+
* 两侧共用:ESLint 的 forbidValue 与 stylelint 的同名规则跑的是同一条 valuePattern
|
|
115
|
+
* (§7.2.1 一个来源),编译方式也不得各写一份。
|
|
116
|
+
*/
|
|
117
|
+
export function compileValuePattern(rule) {
|
|
118
|
+
const flags = (rule.flags || '').replace(/[gy]/g, '')
|
|
119
|
+
return new RegExp(rule.valuePattern, flags || undefined)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* JSX 元素名。裸标识符返回其名;`<UI.Button>` 这类成员表达式返回点号形式
|
|
124
|
+
* `UI.Button`,由 collectImports 的绑定表去解析(见 ImportBindings.get)。
|
|
125
|
+
*
|
|
126
|
+
* 点号形式对 forbid-element 无害:那类规则比对的是 `button` / `input` 这种
|
|
127
|
+
* 原生元素名,永远不含点号,`<UI.button>` 因此仍不参与判定 —— 它不是原生元素。
|
|
128
|
+
*
|
|
129
|
+
* 更深的嵌套(`<A.B.C>`)与命名空间标签(`<svg:rect>`)返回 null:
|
|
130
|
+
* 本库不存在二级命名空间,后者也不是组件调用。
|
|
131
|
+
*/
|
|
132
|
+
export function jsxName(node) {
|
|
133
|
+
const { name } = node
|
|
134
|
+
if (name?.type === 'JSXIdentifier') return name.name
|
|
135
|
+
if (name?.type === 'JSXMemberExpression'
|
|
136
|
+
&& name.object?.type === 'JSXIdentifier'
|
|
137
|
+
&& name.property?.type === 'JSXIdentifier') {
|
|
138
|
+
return `${name.object.name}.${name.property.name}`
|
|
139
|
+
}
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** JSX 属性的字面量字符串值,取不到返回 null(表达式值 lint 判不了)。 */
|
|
144
|
+
export function attrStringValue(attr) {
|
|
145
|
+
const { value } = attr
|
|
146
|
+
if (!value) return null
|
|
147
|
+
if (value.type === 'Literal' && typeof value.value === 'string') return value.value
|
|
148
|
+
if (value.type === 'JSXExpressionContainer'
|
|
149
|
+
&& value.expression.type === 'Literal'
|
|
150
|
+
&& typeof value.expression.value === 'string') {
|
|
151
|
+
return value.expression.value
|
|
152
|
+
}
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* JSX 属性的字面量取值,字符串与数值都收,一律归一成字符串;取不到返回 null。
|
|
158
|
+
*
|
|
159
|
+
* prop-enum 用它而不用 attrStringValue:枚举取值有数值的一类(IconProps.size
|
|
160
|
+
* 是 `14 | 16 | 18 | 20 | 24`),而 `size={17}` 在 AST 上是表达式容器包一个
|
|
161
|
+
* 数值 Literal,只认字符串时整类枚举**一条也报不出来**,且不报错不告警 ——
|
|
162
|
+
* 规则装上了、配置也加载得上,跑一遍与规则失效长得一模一样(§1.4)。
|
|
163
|
+
*
|
|
164
|
+
* 归一成字符串是与 build-rules.mjs 的 `allowed: prop.values.map(String)` 配对的:
|
|
165
|
+
* 两侧必须是同一条归一,规则数据里存的是 '14',这里比对的也是 '14'。
|
|
166
|
+
* `size="16"` 这种写对了值、写错了类型的情形不在本条覆盖内 —— 那是 tsc 报的
|
|
167
|
+
* TS2322,§7.1 已判定类型层的收益超过 lint,lint 只补类型看不见的那部分。
|
|
168
|
+
*
|
|
169
|
+
* attrStringValue 保持只认字符串:forbid-element 的 attributes 比对的是
|
|
170
|
+
* `type="checkbox"` 这类字符串属性,把数值收进去只会放宽匹配面。
|
|
171
|
+
*/
|
|
172
|
+
export function attrLiteralValue(attr) {
|
|
173
|
+
const { value } = attr
|
|
174
|
+
if (!value) return null
|
|
175
|
+
const literal = value.type === 'JSXExpressionContainer' ? value.expression : value
|
|
176
|
+
if (literal?.type !== 'Literal') return null
|
|
177
|
+
if (typeof literal.value === 'string') return literal.value
|
|
178
|
+
if (typeof literal.value === 'number') return String(literal.value)
|
|
179
|
+
return null
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 元素上是否带 className 或 style —— autofix 的保守条件(§5.3)。 */
|
|
183
|
+
export function hasStyling(node) {
|
|
184
|
+
return node.attributes.some((attr) => {
|
|
185
|
+
if (attr.type === 'JSXSpreadAttribute') return true /* 展开里可能有,判不了就当有 */
|
|
186
|
+
return attr.name?.name === 'className' || attr.name?.name === 'style'
|
|
187
|
+
})
|
|
188
|
+
}
|