audit-mp-antipatterns.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/env node
  2. /**
  3. * 小程序模板/脚本反模式审计(AGENTS.md「ANTI-PATTERNS」中可机器判定的部分)
  4. *
  5. * 分级:
  6. * ERROR — 确定会在微信小程序端出错/违反硬规范,必须修
  7. * 1) 模板可选链 `?.`
  8. * 2) `:key` 使用运算符表达式
  9. * 3) CSS 选择器含中文
  10. * 4) `uni.getSystemInfoSync()`
  11. * 5) `transition: all`
  12. * 6) `v-for` 缺 `:key`(支持跨行)
  13. * 7) 日期用 `toLocaleString` / `toLocaleDateString` / `toLocaleTimeString` 格式化
  14. * 8) `v-for` 的 `:key` 是方法调用,且作用域内事件/v-model 传条目变量
  15. * → uni-app 把 `:key` 表达式当作「找回条目」的属性路径,方法调用会让
  16. * 运行时 `find(v => v['getXxx(item)'] === value)` 恒失败,handler 收到
  17. * `undefined`(`Cannot read properties of undefined (reading 'id')`)。
  18. * `:key` 必须是条目真实属性(`item.id`)或循环索引别名(`idx`)。
  19. * WARN — 需人工确认
  20. * 9) `new Date(<非字面量>)`:iOS 解析空格分隔/Java 格式会失败,应改 `parseDate()`
  21. * (`new Date()` 与 `new Date(Date 对象)` 不计入)
  22. * 10) `:class` / `:style` 内带参方法调用:uni-app 渲染函数下可用,
  23. * 但 AGENTS.md 列为禁用项,仅提示(WXML 原生表达式不支持)
  24. *
  25. * 用法: node scripts/audit-mp-antipatterns.js [--json] [--error-only]
  26. * 退出码: 0 无 ERROR / 1 存在 ERROR
  27. */
  28. const fs = require('fs')
  29. const path = require('path')
  30. const ROOT = path.resolve(__dirname, '..')
  31. const SKIP_DIRS = new Set(['node_modules', 'dist', 'unpackage', '.git', 'dist_bak_1792213156', '.tmp_equiv'])
  32. const SKIP_FILES = new Set(['components/mp-html/node/node.vue'])
  33. const JSON_OUT = process.argv.includes('--json')
  34. const ERROR_ONLY = process.argv.includes('--error-only')
  35. function collect(dir, out = []) {
  36. for (const name of fs.readdirSync(dir)) {
  37. if (SKIP_DIRS.has(name)) continue
  38. const p = path.join(dir, name)
  39. const st = fs.statSync(p)
  40. if (st.isDirectory()) collect(p, out)
  41. else if (name.endsWith('.vue')) out.push(p)
  42. }
  43. return out
  44. }
  45. const findings = []
  46. function add(level, kind, file, line, text) {
  47. findings.push({ level, kind, file, line, text: String(text).trim().slice(0, 140) })
  48. }
  49. // ---------- 规则 8 辅助:模板标签树解析 ----------
  50. function escRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }
  51. // 顶层逗号切分(跨越括号/引号的内容视为内部)
  52. function splitTop(str) {
  53. const out = []
  54. let depth = 0, cur = '', q = null
  55. for (const ch of str) {
  56. if (q) { cur += ch; if (ch === q) q = null; continue }
  57. if (ch === '"' || ch === "'") { q = ch; cur += ch; continue }
  58. if ('([{'.includes(ch)) depth++
  59. else if (')]}'.includes(ch)) depth--
  60. if (ch === ',' && depth === 0) { out.push(cur.trim()); cur = ''; continue }
  61. cur += ch
  62. }
  63. if (cur.trim()) out.push(cur.trim())
  64. return out
  65. }
  66. function parseAttrs(raw) {
  67. const attrs = {}
  68. const re = /([:@]?[A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
  69. let m
  70. while ((m = re.exec(raw))) {
  71. const name = m[1]
  72. const val = m[2] !== undefined ? m[2] : m[3]
  73. if (!(name in attrs)) attrs[name] = val
  74. }
  75. return attrs
  76. }
  77. // v-for="(item, idx) in list" 或 v-for="item in list"
  78. function parseVFor(expr) {
  79. if (!expr) return null
  80. const m = String(expr).trim().match(/^\s*(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s+(?:in|of)\s+/)
  81. if (!m) return null
  82. const vars = (m[1] != null ? m[1] : m[2]).split(',').map(s => s.trim()).filter(Boolean)
  83. if (!vars.length) return null
  84. return { item: vars[0], index: vars[1] || null }
  85. }
  86. // :key 是否为方法调用表达式(含 item.getId() 这类挂在条目上的方法调用)
  87. function isMethodCallKey(expr) {
  88. return /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*\s*\(/.test((expr || '').trim())
  89. }
  90. // 括号配平且调用括号延伸到末尾时才返回参数字符串,否则 null(保守不判)
  91. function callInner(expr) {
  92. const t = String(expr).trim()
  93. const i = t.indexOf('(')
  94. if (i < 0) return null
  95. let depth = 0
  96. for (let k = i; k < t.length; k++) {
  97. if (t[k] === '(') depth++
  98. else if (t[k] === ')') { depth--; if (depth === 0) return k === t.length - 1 ? t.slice(i + 1, k) : null }
  99. }
  100. return null
  101. }
  102. // arg 是否是 alias 的裸引用或成员引用(含括号则编译器会预计算内联,安全)
  103. function refAlias(arg, aliases) {
  104. for (const a of aliases) {
  105. if (arg === a) return a
  106. if (!arg.includes('(') && new RegExp('^' + escRe(a) + '(?:\\.[A-Za-z_$][\\w$]*|\\[[^\\]]*\\])+$').test(arg)) return a
  107. }
  108. return null
  109. }
  110. // 在元素子树内找「事件/v-model 传条目别名」的绑定
  111. function scanScoped(el, aliases, hits) {
  112. for (const child of el.children) {
  113. const inner = parseVFor(child.attrs['v-for'])
  114. const childAliases = inner ? aliases.concat([inner.item]) : aliases
  115. for (const [name, val] of Object.entries(child.attrs)) {
  116. if (name === 'v-model') {
  117. if (refAlias(val, childAliases)) hits.push({ line: child.line, via: 'v-model="' + val + '"' })
  118. } else if (name.charAt(0) === '@' || name.indexOf('v-on:') === 0) {
  119. const ia = callInner(val)
  120. if (ia !== null && splitTop(ia).some(a => refAlias(a, childAliases))) hits.push({ line: child.line, via: name + '="' + val + '"' })
  121. }
  122. }
  123. scanScoped(child, childAliases, hits)
  124. }
  125. }
  126. // 解析模板为标签树(line 为源文件绝对行号)
  127. function parseTree(tplBody, tplOffset, src) {
  128. const clean = tplBody.replace(/<!--[\s\S]*?-->/g, m => m.replace(/[^\n]/g, ' '))
  129. const tagRe = /<(\/)?([A-Za-z][\w-]*)((?:"[^"]*"|'[^']*'|[^'">])*)(\/)?>/g
  130. const roots = []
  131. const stack = []
  132. let m
  133. while ((m = tagRe.exec(clean))) {
  134. const closing = !!m[1]
  135. const tag = m[2]
  136. const attrsRaw = m[3] || ''
  137. const selfClose = !!m[4]
  138. const line = src.slice(0, tplOffset + m.index).split('\n').length
  139. if (closing) {
  140. for (let i = stack.length - 1; i >= 0; i--) {
  141. if (stack[i].tag === tag) { stack.length = i; break }
  142. }
  143. continue
  144. }
  145. const el = { tag, raw: m[0], attrs: parseAttrs(attrsRaw), children: [], line }
  146. const parent = stack[stack.length - 1]
  147. if (parent) parent.children.push(el); else roots.push(el)
  148. if (!selfClose) stack.push(el)
  149. }
  150. return roots
  151. }
  152. for (const abs of collect(ROOT)) {
  153. const rel = path.relative(ROOT, abs).split(path.sep).join('/')
  154. if (SKIP_FILES.has(rel)) continue
  155. const src = fs.readFileSync(abs, 'utf8')
  156. const lines = src.split(/\r?\n/)
  157. const tplMatch = src.match(/^<template[^>]*>/m)
  158. const tplStart = tplMatch ? src.indexOf(tplMatch[0]) : -1
  159. const tplEnd = tplStart === -1 ? -1 : src.indexOf('\n</template>', tplStart)
  160. let offset = 0
  161. for (let i = 0; i < lines.length; i++) {
  162. const l = lines[i]
  163. const pos = offset
  164. const inTpl = tplStart !== -1 && pos > tplStart && pos < tplEnd
  165. offset += l.length + 1
  166. if (inTpl && /\?\./.test(l)) add('ERROR', '模板可选链 ?.', rel, i + 1, l)
  167. if (inTpl && /:key="[^"]*(\|\||&&|\+|\?)/.test(l)) add('ERROR', ':key 运算符表达式', rel, i + 1, l)
  168. if (/uni\.getSystemInfoSync\s*\(/.test(l)) add('ERROR', 'getSystemInfoSync 弃用', rel, i + 1, l)
  169. if (/transition\s*:\s*all\b/.test(l)) add('ERROR', 'transition: all', rel, i + 1, l)
  170. // toLocale* 仅针对日期;数字千分位(toLocaleString)不算违规
  171. const localeHit = l.match(/(new\s+Date\s*\([^)]*\)|[A-Za-z_$][\w$.]*)\s*\.\s*toLocale(Date|Time)?String\s*\(/)
  172. if (localeHit) {
  173. const receiver = localeHit[1]
  174. if (/Date|date|time|Time|day|Day|created|updated/.test(receiver)) {
  175. add('ERROR', 'toLocale* 日期格式化', rel, i + 1, l)
  176. }
  177. }
  178. if (inTpl && /:(class|style)="[^"]*\w+\([^)]*\)/.test(l)) add('WARN', ':class/:style 方法调用', rel, i + 1, l)
  179. // new Date(<非字面量>):排除无参、数字字面量与多参数字构造(多参为合法且 iOS 安全)
  180. const dm = l.match(/new\s+Date\s*\(\s*([^)]*?)\s*\)/)
  181. if (dm && dm[1] && !dm[1].includes(',') && !/^['"`\d]/.test(dm[1]) && !/^[A-Za-z_$][\w$.]*\s*[-+*/]/.test(dm[1])) {
  182. add('WARN', 'new Date(非字面量)', rel, i + 1, l)
  183. }
  184. }
  185. // v-for 缺 :key(允许属性跨行,检查标签范围)
  186. for (const tag of src.matchAll(/<[a-zA-Z][\w-]*(\s[^>]*?)?>/g)) {
  187. const body = tag[0]
  188. if (!/\bv-for=/.test(body)) continue
  189. if (/:key=|v-bind:key=/.test(body)) continue
  190. const line = src.slice(0, tag.index).split('\n').length
  191. add('ERROR', 'v-for 缺 :key', rel, line, body.replace(/\s+/g, ' '))
  192. }
  193. // v-for 的 :key 是方法调用 → uni-app 会把该表达式当作「找回条目」的属性路径,
  194. // 运行时 find(v => v['getXxx(item)'] === value) 恒失败 → handler 收到 undefined
  195. if (tplStart !== -1 && tplEnd !== -1) {
  196. const tplOffset = tplStart + tplMatch[0].length
  197. const roots = parseTree(src.slice(tplOffset, tplEnd), tplOffset, src)
  198. const walk = (els) => {
  199. for (const el of els) {
  200. const vf = parseVFor(el.attrs['v-for'])
  201. const keyExpr = el.attrs[':key'] || el.attrs['v-bind:key']
  202. if (vf && keyExpr && isMethodCallKey(keyExpr)) {
  203. const hits = []
  204. for (const [name, val] of Object.entries(el.attrs)) {
  205. if (name === 'v-model') {
  206. if (refAlias(val, [vf.item])) hits.push({ line: el.line, via: 'v-model="' + val + '"' })
  207. } else if (name.charAt(0) === '@' || name.indexOf('v-on:') === 0) {
  208. const ia = callInner(val)
  209. if (ia !== null && splitTop(ia).some(a => refAlias(a, [vf.item]))) hits.push({ line: el.line, via: name + '="' + val + '"' })
  210. }
  211. }
  212. scanScoped(el, [vf.item], hits)
  213. if (hits.length) {
  214. add('ERROR', ':key 方法调用 → 事件参数 undefined', rel, el.line,
  215. ':key="' + keyExpr + '"(v-for=' + el.attrs['v-for'] + ');作用域内 ' + hits.length +
  216. ' 处事件/v-model 传条目变量 → ' + hits[0].via)
  217. }
  218. }
  219. walk(el.children)
  220. }
  221. }
  222. walk(roots)
  223. }
  224. // CSS 选择器含中文(排除注释行)
  225. for (const m of src.matchAll(/^<style[^>]*>([\s\S]*?)^<\/style>/gm)) {
  226. const base = src.slice(0, m.index).split('\n').length
  227. m[1].split(/\r?\n/).forEach((l, i) => {
  228. if (/^\s*(\/\/|\/\*|\*)/.test(l)) return
  229. if (/^[^{}\n]*[\u4e00-\u9fa5][^{}\n]*\{/.test(l)) add('ERROR', 'CSS 选择器含中文', rel, base + i, l)
  230. })
  231. }
  232. }
  233. const shown = ERROR_ONLY ? findings.filter(f => f.level === 'ERROR') : findings
  234. if (JSON_OUT) {
  235. console.log(JSON.stringify(shown, null, 2))
  236. } else {
  237. const kinds = [...new Set(findings.map(f => f.kind))]
  238. for (const kind of kinds) {
  239. const list = findings.filter(f => f.kind === kind)
  240. const level = list[0].level
  241. if (ERROR_ONLY && level !== 'ERROR') continue
  242. console.log('[' + level + '] ' + kind + ': ' + list.length)
  243. for (const f of list.slice(0, 6)) console.log(' ' + f.file + ':' + f.line + ' ' + f.text)
  244. if (list.length > 6) console.log(' ... 另有 ' + (list.length - 6) + ' 处')
  245. }
  246. const errors = findings.filter(f => f.level === 'ERROR').length
  247. const warns = findings.length - errors
  248. console.log('')
  249. console.log('ERROR ' + errors + ' 处 / WARN ' + warns + ' 处')
  250. }
  251. process.exit(findings.some(f => f.level === 'ERROR') ? 1 : 0)