194 lines
5.8 KiB
JavaScript
194 lines
5.8 KiB
JavaScript
/**
|
||
* 静态路由表一致性校验(`npm run check:pages`)
|
||
*
|
||
* 校验三件事:
|
||
* 1. `PAGE_REGISTRY[].path` 必须真实存在于 `src/pages.json`(含 subPackages)
|
||
* 2. `PAGE_REGISTRY[].key` 不能重复
|
||
* 3. `pages.json` 里已注册但没有登记进 `PAGE_REGISTRY` 的页面 → 告警(不阻断)
|
||
*
|
||
* 为什么需要:小程序页面必须在 `pages.json` **编译期**注册,
|
||
* 一旦静态路由表与 `pages.json` 漂移,用户点入口就会跳转失败(且只在真机上才暴露)。
|
||
*
|
||
* 注意:本脚本用正则从 `src/router/pages.ts` 提取条目(Node 无法直接 import .ts),
|
||
* 因此 `PAGE_REGISTRY` 的条目请保持「一个字面量对象 + 单引号」的写法,
|
||
* 注释掉的示例条目(整行 `//` 开头)会被自动忽略。
|
||
*/
|
||
|
||
import { readFileSync } from 'node:fs'
|
||
import { fileURLToPath } from 'node:url'
|
||
import { join } from 'node:path'
|
||
|
||
const ROOT = fileURLToPath(new URL('..', import.meta.url))
|
||
const PAGES_JSON = join(ROOT, 'src/pages.json')
|
||
const REGISTRY_TS = join(ROOT, 'src/router/pages.ts')
|
||
|
||
/**
|
||
* 去掉 JSON 里的 `//` 与块注释
|
||
* 按字符状态机处理(尊重字符串字面量),避免把 `"http://..."` 里的 `//` 当注释切掉
|
||
*/
|
||
function stripJsonComments(text) {
|
||
let out = ''
|
||
let inString = false
|
||
let inLine = false
|
||
let inBlock = false
|
||
|
||
for (let i = 0; i < text.length; i++) {
|
||
const c = text[i]
|
||
const next = text[i + 1]
|
||
|
||
if (inLine) {
|
||
if (c === '\n') {
|
||
inLine = false
|
||
out += c
|
||
}
|
||
continue
|
||
}
|
||
if (inBlock) {
|
||
if (c === '*' && next === '/') {
|
||
inBlock = false
|
||
i++
|
||
}
|
||
continue
|
||
}
|
||
if (inString) {
|
||
out += c
|
||
if (c === '\\') {
|
||
out += next ?? ''
|
||
i++
|
||
} else if (c === '"') {
|
||
inString = false
|
||
}
|
||
continue
|
||
}
|
||
if (c === '"') {
|
||
inString = true
|
||
out += c
|
||
} else if (c === '/' && next === '/') {
|
||
inLine = true
|
||
i++
|
||
} else if (c === '/' && next === '*') {
|
||
inBlock = true
|
||
i++
|
||
} else {
|
||
out += c
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
/** 收集 pages.json 中所有已注册的页面物理路径 */
|
||
function collectRegisteredPaths(pagesJson) {
|
||
const registered = new Set()
|
||
for (const page of pagesJson.pages ?? []) {
|
||
if (page?.path) registered.add(page.path)
|
||
}
|
||
// 分包字段官方写法是 subPackages(写成 subpackages 无效,这里只为兼容提示)
|
||
const subPackages = pagesJson.subPackages ?? pagesJson.subpackages ?? []
|
||
for (const sub of subPackages) {
|
||
const root = String(sub?.root ?? '').replace(/\/$/, '')
|
||
for (const page of sub?.pages ?? []) {
|
||
if (page?.path) registered.add(`${root}/${page.path}`)
|
||
}
|
||
}
|
||
return registered
|
||
}
|
||
|
||
/** 从 src/router/pages.ts 里提取 PAGE_REGISTRY 的字面量条目 */
|
||
function collectRegistryEntries(source) {
|
||
// 整行注释(含被注释掉的示例条目)先剔除,否则会被当成真条目
|
||
const code = source
|
||
.split(/\r?\n/)
|
||
.filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line))
|
||
.join('\n')
|
||
|
||
const start = code.indexOf('PAGE_REGISTRY')
|
||
if (start === -1) return null
|
||
|
||
const open = code.indexOf('[', start)
|
||
if (open === -1) return null
|
||
|
||
// 数组以「行首的 ]」结束
|
||
const close = code.indexOf('\n]', open)
|
||
const block = close === -1 ? code.slice(open) : code.slice(open, close)
|
||
|
||
const entries = []
|
||
for (const match of block.matchAll(/\{([^{}]*)\}/g)) {
|
||
const body = match[1]
|
||
const key = /key:\s*'([^']+)'/.exec(body)?.[1]
|
||
const path = /path:\s*'([^']+)'/.exec(body)?.[1]
|
||
if (key && path) entries.push({ key, path })
|
||
}
|
||
return entries
|
||
}
|
||
|
||
const errors = []
|
||
const warnings = []
|
||
|
||
// ── 读取 pages.json ──
|
||
let pagesJson
|
||
try {
|
||
pagesJson = JSON.parse(stripJsonComments(readFileSync(PAGES_JSON, 'utf8')))
|
||
} catch (err) {
|
||
console.error(`✖ 解析 src/pages.json 失败:${err.message}`)
|
||
process.exit(1)
|
||
}
|
||
const registered = collectRegisteredPaths(pagesJson)
|
||
|
||
// ── 读取 PAGE_REGISTRY ──
|
||
let source
|
||
try {
|
||
source = readFileSync(REGISTRY_TS, 'utf8')
|
||
} catch (err) {
|
||
console.error(`✖ 读取 src/router/pages.ts 失败:${err.message}`)
|
||
process.exit(1)
|
||
}
|
||
const entries = collectRegistryEntries(source)
|
||
|
||
if (!entries || entries.length === 0) {
|
||
console.error(
|
||
'✖ 未能从 src/router/pages.ts 解析出任何 PAGE_REGISTRY 条目。\n' +
|
||
' 请确认条目仍是「字面量对象 + 单引号」写法(key: \'...\' / path: \'...\')。'
|
||
)
|
||
process.exit(1)
|
||
}
|
||
|
||
// ── 校验 1:path 必须已在 pages.json 注册 ──
|
||
for (const entry of entries) {
|
||
if (!registered.has(entry.path)) {
|
||
errors.push(
|
||
`PAGE_REGISTRY 的 "${entry.key}" 指向 "${entry.path}",但 src/pages.json 中未注册该页面`
|
||
)
|
||
}
|
||
}
|
||
|
||
// ── 校验 2:key 不能重复 ──
|
||
const seen = new Map()
|
||
for (const entry of entries) {
|
||
if (seen.has(entry.key)) {
|
||
errors.push(`PAGE_REGISTRY 中存在重复的 key:"${entry.key}"`)
|
||
}
|
||
seen.set(entry.key, entry)
|
||
}
|
||
|
||
// ── 校验 3:pages.json 有、但没登记进 PAGE_REGISTRY(仅告警) ──
|
||
const registeredPaths = new Set(entries.map((entry) => entry.path))
|
||
for (const path of registered) {
|
||
if (!registeredPaths.has(path)) {
|
||
warnings.push(`src/pages.json 已注册 "${path}",但 PAGE_REGISTRY 未登记(无法被菜单映射/按 auth 渲染)`)
|
||
}
|
||
}
|
||
|
||
// ── 输出 ──
|
||
for (const warn of warnings) console.warn(`⚠ ${warn}`)
|
||
for (const error of errors) console.error(`✖ ${error}`)
|
||
|
||
if (errors.length > 0) {
|
||
console.error(`\n✖ 静态路由表校验失败:${errors.length} 个错误,${warnings.length} 个告警`)
|
||
process.exit(1)
|
||
}
|
||
|
||
console.log(
|
||
`✔ 静态路由表校验通过:PAGE_REGISTRY ${entries.length} 条,` +
|
||
`pages.json 已注册 ${registered.size} 个页面,${warnings.length} 个告警`
|
||
)
|