gen-component-page-index.mjs
11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* @file 扫描全库 usingComponents,生成「组件 → 引用方」反向索引 Markdown。
* 边界:仅 json usingComponents;不扫 JS 动态引用、不扫 WXML 标签。
*/
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
export const DEFAULT_ROOT = path.resolve(__dirname, '..')
export const DEFAULT_OUTPUT = 'docs/COMPONENT-PAGE-INDEX.md'
const skipDirs = new Set(['node_modules', 'miniprogram_npm', '.git', 'dist'])
const exts = ['', '.js', '.json', '.wxml', '.wxss', '.sass', '/index.js']
/** 规则与治理文档中点名的高风险组件(路径片段或注册名) */
export const HIGH_RISK_HINTS = [
'Merchant-Seles',
'MerchantSeles',
'Coupon',
'Popup',
'CalendarMonth',
'OrderNoPopup',
'recordingOrderPopup',
]
/**
* 解析 usingComponents 相对路径,返回磁盘上的目标路径(若存在)。
* @param {string} fromJson
* @param {string} spec
* @returns {{ ok: boolean, target?: string }}
*/
export function resolveComponentTarget(fromJson, spec) {
if (!spec.startsWith('.')) return { ok: true }
let target = path.resolve(path.dirname(fromJson), spec)
if (path.extname(target)) {
return { ok: fs.existsSync(target), target }
}
for (const ext of exts) {
const p = target + (ext.startsWith('/') ? ext : ext)
if (fs.existsSync(p)) return { ok: true, target: p }
}
return { ok: false, target }
}
/**
* 将 usingComponents 的 spec 规范化为仓库相对路径(POSIX)。
* @param {string} spec
* @param {string} [resolvedTarget] resolve 后的绝对路径
* @param {string} root
* @returns {{ kind: 'business'|'vant'|'skip', canonical: string }}
*/
export function canonicalizeComponentSpec(spec, resolvedTarget, root) {
if (typeof spec !== 'string' || !spec) {
return { kind: 'skip', canonical: '' }
}
if (spec.startsWith('@vant/')) {
return { kind: 'vant', canonical: spec.replace(/\\/g, '/') }
}
if (spec.startsWith('.')) {
if (!resolvedTarget) return { kind: 'skip', canonical: '' }
const rel = path.relative(root, resolvedTarget).replace(/\\/g, '/')
return { kind: 'business', canonical: stripExtension(rel) }
}
const normalized = spec.replace(/\\/g, '/').replace(/^\//, '')
if (normalized.startsWith('components/') || normalized.startsWith('integration/')) {
return { kind: 'business', canonical: stripExtension(normalized) }
}
return { kind: 'skip', canonical: normalized }
}
/**
* @param {string} p
* @returns {string}
*/
export function stripExtension(p) {
return p.replace(/\.(js|json|wxml|wxss|sass)$/, '')
}
/**
* 从引用方 json 路径推断分包/域。
* @param {string} ownerPath repo 相对路径
* @returns {string}
*/
export function getPackageGroup(ownerPath) {
if (ownerPath === 'app.json') return 'global'
const top = ownerPath.split('/')[0]
const known = new Set([
'tabIndex',
'tabWorkOrder',
'tabRepairOrder',
'tabDate',
'tabMine',
'tabOperating',
'packageEquity',
'packageDynamicForm',
'packageCrowdFunding',
'packageUsedCar',
'packageStudyCenter',
'subvehicleConversion',
'integration',
'components',
'pages',
])
return known.has(top) ? top : 'other'
}
/**
* @param {string} canonical
* @param {string} [aliasName]
* @param {number} refCount
* @returns {boolean}
*/
export function isHighRiskComponent(canonical, aliasName, refCount) {
if (refCount >= 5) return true
const hay = `${canonical}/${aliasName || ''}`
return HIGH_RISK_HINTS.some((hint) => hay.includes(hint))
}
/**
* 遍历仓库内所有 json(跳过 node_modules 等)。
* @param {string} root
* @returns {string[]}
*/
export function walkJsonFiles(root) {
/** @type {string[]} */
const files = []
function walk(dir) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (skipDirs.has(e.name)) continue
const full = path.join(dir, e.name)
if (e.isDirectory()) walk(full)
else if (e.name.endsWith('.json') && !e.name.includes('project')) files.push(full)
}
}
walk(root)
return files
}
/**
* 构建反向索引。
* @param {string} root
* @returns {{ business: Map<string, { owners: Map<string, Set<string>>, aliases: Set<string> }>, vant: Map<string, Set<string>> }}
*/
export function buildComponentPageIndex(root) {
/** @type {Map<string, { owners: Map<string, Set<string>>, aliases: Set<string> }>} */
const business = new Map()
/** @type {Map<string, Set<string>>} */
const vant = new Map()
for (const absFile of walkJsonFiles(root)) {
let json
try {
json = JSON.parse(fs.readFileSync(absFile, 'utf8'))
} catch {
continue
}
const comps = json.usingComponents
if (!comps || typeof comps !== 'object') continue
const ownerRel = path.relative(root, absFile).replace(/\\/g, '/')
const ownerKey = ownerRel === 'app.json' ? 'app.json (global)' : ownerRel
const group = getPackageGroup(ownerRel)
for (const [aliasName, spec] of Object.entries(comps)) {
if (typeof spec !== 'string') continue
const resolved =
spec.startsWith('.') ? resolveComponentTarget(absFile, spec).target : undefined
const { kind, canonical } = canonicalizeComponentSpec(spec, resolved, root)
if (kind === 'skip' || !canonical) continue
if (kind === 'vant') {
if (!vant.has(canonical)) vant.set(canonical, new Set())
vant.get(canonical).add(ownerKey)
continue
}
if (!business.has(canonical)) {
business.set(canonical, { owners: new Map(), aliases: new Set() })
}
const entry = business.get(canonical)
entry.aliases.add(aliasName)
if (!entry.owners.has(group)) entry.owners.set(group, new Set())
entry.owners.get(group).add(ownerKey)
}
}
return { business, vant }
}
/**
* @param {Map<string, { owners: Map<string, Set<string>>, aliases: Set<string> }>} business
* @returns {string}
*/
export function formatBusinessMarkdown(business) {
const lines = []
const sorted = [...business.entries()].sort((a, b) => {
const countA = [...a[1].owners.values()].reduce((n, s) => n + s.size, 0)
const countB = [...b[1].owners.values()].reduce((n, s) => n + s.size, 0)
return countB - countA || a[0].localeCompare(b[0])
})
lines.push('## 业务组件(components / integration)')
lines.push('')
lines.push('| 风险 | 组件路径 | 引用数 | 注册名 | 引用方(按分包) |')
lines.push('|------|----------|--------|--------|------------------|')
for (const [canonical, { owners, aliases }] of sorted) {
const allOwners = [...owners.values()].flatMap((s) => [...s])
const refCount = allOwners.length
const aliasStr = [...aliases].sort().join(', ')
const risk = isHighRiskComponent(canonical, aliasStr, refCount) ? '**高**' : ''
const ownerParts = [...owners.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([group, set]) => {
const list = [...set].sort().join('<br>')
return `**${group}** (${set.size}): ${list}`
})
.join('<br><br>')
lines.push(`| ${risk} | \`${canonical}\` | ${refCount} | ${aliasStr} | ${ownerParts} |`)
}
return lines.join('\n')
}
/**
* @param {Map<string, Set<string>>} vant
* @returns {string}
*/
export function formatVantMarkdown(vant) {
const lines = []
lines.push('## Vant 组件(@vant/weapp)')
lines.push('')
lines.push('| 组件 | 引用数 | 引用方 |')
lines.push('|------|--------|--------|')
const sorted = [...vant.entries()].sort((a, b) => b[1].size - a[1].size || a[0].localeCompare(b[0]))
for (const [canonical, owners] of sorted) {
const list = [...owners].sort().join('<br>')
lines.push(`| \`${canonical}\` | ${owners.size} | ${list} |`)
}
return lines.join('\n')
}
/**
* @param {string} root
* @returns {string}
*/
export function generateMarkdown(root) {
const { business, vant } = buildComponentPageIndex(root)
const businessCount = business.size
const businessRefs = [...business.values()].reduce(
(n, e) => n + [...e.owners.values()].reduce((m, s) => m + s.size, 0),
0,
)
const now = new Date().toISOString().slice(0, 10)
return [
'# 组件 → 页面反向索引(usingComponents)',
'',
'> **生成命令**:`npm run gen:component-index`',
`> **最后生成**:${now} · 业务组件 ${businessCount} 项 · 引用关系 ${businessRefs} 条`,
'> **边界**:仅扫描 json `usingComponents`;不含 JS 动态引用。',
'',
'高风险:引用数 ≥ 5,或命中 Merchant-Seles / Coupon / Popup 等治理名单。',
'',
'详见 [DOMAIN-INDEX.md](./DOMAIN-INDEX.md) 全局组件域。',
'',
formatBusinessMarkdown(business),
'',
formatVantMarkdown(vant),
'',
].join('\n')
}
/**
* @param {string} root
* @param {string} componentQuery
* @returns {string}
*/
export function queryComponent(root, componentQuery) {
const { business, vant } = buildComponentPageIndex(root)
const q = componentQuery.toLowerCase()
const lines = [`# 组件查询: ${componentQuery}`, '']
for (const [canonical, { owners, aliases }] of business) {
const aliasStr = [...aliases].join(', ')
if (!canonical.toLowerCase().includes(q) && !aliasStr.toLowerCase().includes(q)) continue
const allOwners = [...owners.entries()]
.map(([g, s]) => `${g}: ${[...s].sort().join(', ')}`)
.join('\n')
lines.push(`## ${canonical}`)
lines.push(`- 注册名: ${aliasStr}`)
lines.push(`- 引用方:\n${allOwners}`)
lines.push('')
}
for (const [canonical, owners] of vant) {
if (!canonical.toLowerCase().includes(q)) continue
lines.push(`## ${canonical} (vant)`)
lines.push(`- 引用方: ${[...owners].sort().join(', ')}`)
lines.push('')
}
if (lines.length <= 2) lines.push('未找到匹配组件。')
return lines.join('\n')
}
function parseArgs(argv) {
const args = { check: false, component: null, out: DEFAULT_OUTPUT }
for (let i = 2; i < argv.length; i++) {
if (argv[i] === '--check') args.check = true
else if (argv[i] === '--component' && argv[i + 1]) args.component = argv[++i]
else if (argv[i] === '--out' && argv[i + 1]) args.out = argv[++i]
}
return args
}
function main() {
const args = parseArgs(process.argv)
const root = DEFAULT_ROOT
const outAbs = path.resolve(root, args.out)
if (args.component) {
console.log(queryComponent(root, args.component))
return
}
const content = generateMarkdown(root)
if (args.check) {
if (!fs.existsSync(outAbs)) {
console.error(`MISSING ${args.out}; run npm run gen:component-index`)
process.exit(1)
}
const existing = fs.readFileSync(outAbs, 'utf8')
const normalize = (s) =>
s.replace(/^> \*\*最后生成\*\*:.*$/m, '> **最后生成**:<date>')
if (normalize(existing) !== normalize(content)) {
console.error(`STALE ${args.out}; run npm run gen:component-index`)
process.exit(1)
}
console.log(`OK ${args.out}`)
return
}
fs.mkdirSync(path.dirname(outAbs), { recursive: true })
fs.writeFileSync(outAbs, content, 'utf8')
console.log(`WROTE ${path.relative(root, outAbs).replace(/\\/g, '/')}`)
}
const isMain =
process.argv[1] &&
path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
if (isMain) main()