76 lines
3.1 KiB
TypeScript
76 lines
3.1 KiB
TypeScript
import { existsSync, readFileSync } from 'node:fs'
|
||
import { dirname, join, resolve } from 'node:path'
|
||
|
||
const ROOT = process.cwd()
|
||
const SRC = join(ROOT, 'src')
|
||
const EXTENSIONS = ['', '.ts', '.tsx', '.vue', '.js', '.json']
|
||
const INDEX_CANDIDATES = ['/index.ts', '/index.tsx', '/index.vue', '/index.js']
|
||
|
||
/**
|
||
* 读取工程内源码文件(相对工程根)。
|
||
*
|
||
* 行尾一律归一成 LF:仓库 `core.autocrlf=true`,新检出的工作树是 CRLF 而源码 blob 是 LF,
|
||
* 而本仓多数判据是 `[\s\S]{0,N}` 这类**有界窗口**(例如 company-tab-wiring 里 catch→this.error→throw
|
||
* 那记 420 字符的钉子)。每个换行多背一个 `\r` 就把窗口预算吃掉一截——实测同一份 `src/stores/company-tab.ts`
|
||
* (内容逐字节等价,主树 LF 3565 B / 新检出 CRLF 3629 B)在干净检出树上会多红一条与本任务无关的用例。
|
||
* 归一之后判据只取决于内容,不取决于在哪台机器、哪个 worktree 里跑。
|
||
*/
|
||
export function readSource(rel: string, includeVueStyles = false): string {
|
||
const source = readFileSync(join(ROOT, rel), 'utf8').replace(/\r\n/g, '\n')
|
||
if (!includeVueStyles) return source
|
||
const styles = [...source.matchAll(/<style\b[^>]*\bsrc="(\.\/[^"\n]+\.css)"[^>]*>/g)]
|
||
.map(([, path]) => readSource(join(dirname(rel), path)))
|
||
return [source, ...styles].join('\n')
|
||
}
|
||
|
||
/** 统计非重叠子串出现次数(幂等、只读)。 */
|
||
export function occurrences(text: string, token: string): number {
|
||
if (!token) return 0
|
||
let count = 0
|
||
let index = text.indexOf(token)
|
||
while (index !== -1) {
|
||
count += 1
|
||
index = text.indexOf(token, index + token.length)
|
||
}
|
||
return count
|
||
}
|
||
|
||
/** 从源码里抓出所有 @/ 别名 import 说明符(含 import type)。 */
|
||
export function aliasImports(source: string): string[] {
|
||
const specs = new Set<string>()
|
||
const re = /(?:import\s+type\s+)?[^'"]*from\s*['"](@\/[^'"]+)['"]/g
|
||
let match: RegExpExecArray | null
|
||
while ((match = re.exec(source))) specs.add(match[1])
|
||
// 处理动态 import('@/...') 与直接裸 @/ 引用
|
||
const dyn = /(?:import|import\s*\(\s*)['"](@\/[^'"]+)['"]/g
|
||
while ((match = dyn.exec(source))) specs.add(match[1])
|
||
return [...specs]
|
||
}
|
||
|
||
/** 把 import 说明符解析为存在的模块文件;解析不到返回 null(含可操作路径)。 */
|
||
export function resolveModuleSpec(spec: string, fromRel: string): string | null {
|
||
let base: string
|
||
if (spec.startsWith('@/')) {
|
||
base = join(SRC, spec.slice(2))
|
||
} else {
|
||
base = resolve(dirname(join(ROOT, fromRel)), spec)
|
||
}
|
||
for (const ext of EXTENSIONS) {
|
||
if (existsSync(base + ext)) return base + ext
|
||
}
|
||
for (const idx of INDEX_CANDIDATES) {
|
||
if (existsSync(base + idx)) return base + idx
|
||
}
|
||
return null
|
||
}
|
||
|
||
/** 校验一个源文件的所有 @/ import 都能解析;返回缺失清单(空 = 全部可解析)。 */
|
||
export function missingImports(rel: string): string[] {
|
||
const source = readSource(rel)
|
||
const missing: string[] = []
|
||
for (const spec of aliasImports(source)) {
|
||
if (!resolveModuleSpec(spec, rel)) missing.push(`${rel} 无法解析 import: ${spec}`)
|
||
}
|
||
return missing
|
||
}
|