| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273 |
- #!/usr/bin/env node
- /**
- * 小程序模板/脚本反模式审计(AGENTS.md「ANTI-PATTERNS」中可机器判定的部分)
- *
- * 分级:
- * ERROR — 确定会在微信小程序端出错/违反硬规范,必须修
- * 1) 模板可选链 `?.`
- * 2) `:key` 使用运算符表达式
- * 3) CSS 选择器含中文
- * 4) `uni.getSystemInfoSync()`
- * 5) `transition: all`
- * 6) `v-for` 缺 `:key`(支持跨行)
- * 7) 日期用 `toLocaleString` / `toLocaleDateString` / `toLocaleTimeString` 格式化
- * 8) `v-for` 的 `:key` 是方法调用,且作用域内事件/v-model 传条目变量
- * → uni-app 把 `:key` 表达式当作「找回条目」的属性路径,方法调用会让
- * 运行时 `find(v => v['getXxx(item)'] === value)` 恒失败,handler 收到
- * `undefined`(`Cannot read properties of undefined (reading 'id')`)。
- * `:key` 必须是条目真实属性(`item.id`)或循环索引别名(`idx`)。
- * WARN — 需人工确认
- * 9) `new Date(<非字面量>)`:iOS 解析空格分隔/Java 格式会失败,应改 `parseDate()`
- * (`new Date()` 与 `new Date(Date 对象)` 不计入)
- * 10) `:class` / `:style` 内带参方法调用:uni-app 渲染函数下可用,
- * 但 AGENTS.md 列为禁用项,仅提示(WXML 原生表达式不支持)
- *
- * 用法: node scripts/audit-mp-antipatterns.js [--json] [--error-only]
- * 退出码: 0 无 ERROR / 1 存在 ERROR
- */
- const fs = require('fs')
- const path = require('path')
- const ROOT = path.resolve(__dirname, '..')
- const SKIP_DIRS = new Set(['node_modules', 'dist', 'unpackage', '.git', 'dist_bak_1792213156', '.tmp_equiv'])
- const SKIP_FILES = new Set(['components/mp-html/node/node.vue'])
- const JSON_OUT = process.argv.includes('--json')
- const ERROR_ONLY = process.argv.includes('--error-only')
- function collect(dir, out = []) {
- for (const name of fs.readdirSync(dir)) {
- if (SKIP_DIRS.has(name)) continue
- const p = path.join(dir, name)
- const st = fs.statSync(p)
- if (st.isDirectory()) collect(p, out)
- else if (name.endsWith('.vue')) out.push(p)
- }
- return out
- }
- const findings = []
- function add(level, kind, file, line, text) {
- findings.push({ level, kind, file, line, text: String(text).trim().slice(0, 140) })
- }
- // ---------- 规则 8 辅助:模板标签树解析 ----------
- function escRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }
- // 顶层逗号切分(跨越括号/引号的内容视为内部)
- function splitTop(str) {
- const out = []
- let depth = 0, cur = '', q = null
- for (const ch of str) {
- if (q) { cur += ch; if (ch === q) q = null; continue }
- if (ch === '"' || ch === "'") { q = ch; cur += ch; continue }
- if ('([{'.includes(ch)) depth++
- else if (')]}'.includes(ch)) depth--
- if (ch === ',' && depth === 0) { out.push(cur.trim()); cur = ''; continue }
- cur += ch
- }
- if (cur.trim()) out.push(cur.trim())
- return out
- }
- function parseAttrs(raw) {
- const attrs = {}
- const re = /([:@]?[A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
- let m
- while ((m = re.exec(raw))) {
- const name = m[1]
- const val = m[2] !== undefined ? m[2] : m[3]
- if (!(name in attrs)) attrs[name] = val
- }
- return attrs
- }
- // v-for="(item, idx) in list" 或 v-for="item in list"
- function parseVFor(expr) {
- if (!expr) return null
- const m = String(expr).trim().match(/^\s*(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s+(?:in|of)\s+/)
- if (!m) return null
- const vars = (m[1] != null ? m[1] : m[2]).split(',').map(s => s.trim()).filter(Boolean)
- if (!vars.length) return null
- return { item: vars[0], index: vars[1] || null }
- }
- // :key 是否为方法调用表达式(含 item.getId() 这类挂在条目上的方法调用)
- function isMethodCallKey(expr) {
- return /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*\s*\(/.test((expr || '').trim())
- }
- // 括号配平且调用括号延伸到末尾时才返回参数字符串,否则 null(保守不判)
- function callInner(expr) {
- const t = String(expr).trim()
- const i = t.indexOf('(')
- if (i < 0) return null
- let depth = 0
- for (let k = i; k < t.length; k++) {
- if (t[k] === '(') depth++
- else if (t[k] === ')') { depth--; if (depth === 0) return k === t.length - 1 ? t.slice(i + 1, k) : null }
- }
- return null
- }
- // arg 是否是 alias 的裸引用或成员引用(含括号则编译器会预计算内联,安全)
- function refAlias(arg, aliases) {
- for (const a of aliases) {
- if (arg === a) return a
- if (!arg.includes('(') && new RegExp('^' + escRe(a) + '(?:\\.[A-Za-z_$][\\w$]*|\\[[^\\]]*\\])+$').test(arg)) return a
- }
- return null
- }
- // 在元素子树内找「事件/v-model 传条目别名」的绑定
- function scanScoped(el, aliases, hits) {
- for (const child of el.children) {
- const inner = parseVFor(child.attrs['v-for'])
- const childAliases = inner ? aliases.concat([inner.item]) : aliases
- for (const [name, val] of Object.entries(child.attrs)) {
- if (name === 'v-model') {
- if (refAlias(val, childAliases)) hits.push({ line: child.line, via: 'v-model="' + val + '"' })
- } else if (name.charAt(0) === '@' || name.indexOf('v-on:') === 0) {
- const ia = callInner(val)
- if (ia !== null && splitTop(ia).some(a => refAlias(a, childAliases))) hits.push({ line: child.line, via: name + '="' + val + '"' })
- }
- }
- scanScoped(child, childAliases, hits)
- }
- }
- // 解析模板为标签树(line 为源文件绝对行号)
- function parseTree(tplBody, tplOffset, src) {
- const clean = tplBody.replace(/<!--[\s\S]*?-->/g, m => m.replace(/[^\n]/g, ' '))
- const tagRe = /<(\/)?([A-Za-z][\w-]*)((?:"[^"]*"|'[^']*'|[^'">])*)(\/)?>/g
- const roots = []
- const stack = []
- let m
- while ((m = tagRe.exec(clean))) {
- const closing = !!m[1]
- const tag = m[2]
- const attrsRaw = m[3] || ''
- const selfClose = !!m[4]
- const line = src.slice(0, tplOffset + m.index).split('\n').length
- if (closing) {
- for (let i = stack.length - 1; i >= 0; i--) {
- if (stack[i].tag === tag) { stack.length = i; break }
- }
- continue
- }
- const el = { tag, raw: m[0], attrs: parseAttrs(attrsRaw), children: [], line }
- const parent = stack[stack.length - 1]
- if (parent) parent.children.push(el); else roots.push(el)
- if (!selfClose) stack.push(el)
- }
- return roots
- }
- for (const abs of collect(ROOT)) {
- const rel = path.relative(ROOT, abs).split(path.sep).join('/')
- if (SKIP_FILES.has(rel)) continue
- const src = fs.readFileSync(abs, 'utf8')
- const lines = src.split(/\r?\n/)
- const tplMatch = src.match(/^<template[^>]*>/m)
- const tplStart = tplMatch ? src.indexOf(tplMatch[0]) : -1
- const tplEnd = tplStart === -1 ? -1 : src.indexOf('\n</template>', tplStart)
- let offset = 0
- for (let i = 0; i < lines.length; i++) {
- const l = lines[i]
- const pos = offset
- const inTpl = tplStart !== -1 && pos > tplStart && pos < tplEnd
- offset += l.length + 1
- if (inTpl && /\?\./.test(l)) add('ERROR', '模板可选链 ?.', rel, i + 1, l)
- if (inTpl && /:key="[^"]*(\|\||&&|\+|\?)/.test(l)) add('ERROR', ':key 运算符表达式', rel, i + 1, l)
- if (/uni\.getSystemInfoSync\s*\(/.test(l)) add('ERROR', 'getSystemInfoSync 弃用', rel, i + 1, l)
- if (/transition\s*:\s*all\b/.test(l)) add('ERROR', 'transition: all', rel, i + 1, l)
- // toLocale* 仅针对日期;数字千分位(toLocaleString)不算违规
- const localeHit = l.match(/(new\s+Date\s*\([^)]*\)|[A-Za-z_$][\w$.]*)\s*\.\s*toLocale(Date|Time)?String\s*\(/)
- if (localeHit) {
- const receiver = localeHit[1]
- if (/Date|date|time|Time|day|Day|created|updated/.test(receiver)) {
- add('ERROR', 'toLocale* 日期格式化', rel, i + 1, l)
- }
- }
- if (inTpl && /:(class|style)="[^"]*\w+\([^)]*\)/.test(l)) add('WARN', ':class/:style 方法调用', rel, i + 1, l)
- // new Date(<非字面量>):排除无参、数字字面量与多参数字构造(多参为合法且 iOS 安全)
- const dm = l.match(/new\s+Date\s*\(\s*([^)]*?)\s*\)/)
- if (dm && dm[1] && !dm[1].includes(',') && !/^['"`\d]/.test(dm[1]) && !/^[A-Za-z_$][\w$.]*\s*[-+*/]/.test(dm[1])) {
- add('WARN', 'new Date(非字面量)', rel, i + 1, l)
- }
- }
- // v-for 缺 :key(允许属性跨行,检查标签范围)
- for (const tag of src.matchAll(/<[a-zA-Z][\w-]*(\s[^>]*?)?>/g)) {
- const body = tag[0]
- if (!/\bv-for=/.test(body)) continue
- if (/:key=|v-bind:key=/.test(body)) continue
- const line = src.slice(0, tag.index).split('\n').length
- add('ERROR', 'v-for 缺 :key', rel, line, body.replace(/\s+/g, ' '))
- }
- // v-for 的 :key 是方法调用 → uni-app 会把该表达式当作「找回条目」的属性路径,
- // 运行时 find(v => v['getXxx(item)'] === value) 恒失败 → handler 收到 undefined
- if (tplStart !== -1 && tplEnd !== -1) {
- const tplOffset = tplStart + tplMatch[0].length
- const roots = parseTree(src.slice(tplOffset, tplEnd), tplOffset, src)
- const walk = (els) => {
- for (const el of els) {
- const vf = parseVFor(el.attrs['v-for'])
- const keyExpr = el.attrs[':key'] || el.attrs['v-bind:key']
- if (vf && keyExpr && isMethodCallKey(keyExpr)) {
- const hits = []
- for (const [name, val] of Object.entries(el.attrs)) {
- if (name === 'v-model') {
- if (refAlias(val, [vf.item])) hits.push({ line: el.line, via: 'v-model="' + val + '"' })
- } else if (name.charAt(0) === '@' || name.indexOf('v-on:') === 0) {
- const ia = callInner(val)
- if (ia !== null && splitTop(ia).some(a => refAlias(a, [vf.item]))) hits.push({ line: el.line, via: name + '="' + val + '"' })
- }
- }
- scanScoped(el, [vf.item], hits)
- if (hits.length) {
- add('ERROR', ':key 方法调用 → 事件参数 undefined', rel, el.line,
- ':key="' + keyExpr + '"(v-for=' + el.attrs['v-for'] + ');作用域内 ' + hits.length +
- ' 处事件/v-model 传条目变量 → ' + hits[0].via)
- }
- }
- walk(el.children)
- }
- }
- walk(roots)
- }
- // CSS 选择器含中文(排除注释行)
- for (const m of src.matchAll(/^<style[^>]*>([\s\S]*?)^<\/style>/gm)) {
- const base = src.slice(0, m.index).split('\n').length
- m[1].split(/\r?\n/).forEach((l, i) => {
- if (/^\s*(\/\/|\/\*|\*)/.test(l)) return
- if (/^[^{}\n]*[\u4e00-\u9fa5][^{}\n]*\{/.test(l)) add('ERROR', 'CSS 选择器含中文', rel, base + i, l)
- })
- }
- }
- const shown = ERROR_ONLY ? findings.filter(f => f.level === 'ERROR') : findings
- if (JSON_OUT) {
- console.log(JSON.stringify(shown, null, 2))
- } else {
- const kinds = [...new Set(findings.map(f => f.kind))]
- for (const kind of kinds) {
- const list = findings.filter(f => f.kind === kind)
- const level = list[0].level
- if (ERROR_ONLY && level !== 'ERROR') continue
- console.log('[' + level + '] ' + kind + ': ' + list.length)
- for (const f of list.slice(0, 6)) console.log(' ' + f.file + ':' + f.line + ' ' + f.text)
- if (list.length > 6) console.log(' ... 另有 ' + (list.length - 6) + ' 处')
- }
- const errors = findings.filter(f => f.level === 'ERROR').length
- const warns = findings.length - errors
- console.log('')
- console.log('ERROR ' + errors + ' 处 / WARN ' + warns + ' 处')
- }
- process.exit(findings.some(f => f.level === 'ERROR') ? 1 : 0)
|