check-subpackage-boundaries.mjs
6.74 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
/**
* @file 微信小程序静态分包边界扫描器。普通分包可引用主包和自身,
* 但禁止主包同步引用分包、分包同步引用兄弟分包。
*/
import { readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
const MAIN_PACKAGE = '__main__'
const SOURCE_EXTENSIONS = new Set([
'.js', '.mjs', '.cjs', '.wxs', '.json', '.wxml', '.wxss', '.sass', '.scss'
])
const IGNORED_SEGMENTS = new Set([
'.git', 'docs', 'tests', 'node_modules', 'miniprogram_npm', 'outputs'
])
function toPosix(value) {
return value.split(path.sep).join('/')
}
function normalizeRoot(value) {
return String(value || '').replace(/^\/+|\/+$/g, '')
}
function packageForPath(relativePath, packageRoots) {
const normalized = toPosix(relativePath).replace(/^\.\//, '')
for (const root of packageRoots) {
if (normalized === root || normalized.startsWith(`${root}/`)) return root
}
return MAIN_PACKAGE
}
async function walkFiles(root, current = root, files = []) {
const entries = await readdir(current, { withFileTypes: true })
for (const entry of entries) {
if (IGNORED_SEGMENTS.has(entry.name)) continue
const absolutePath = path.join(current, entry.name)
if (entry.isDirectory()) {
await walkFiles(root, absolutePath, files)
} else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {
files.push(absolutePath)
}
}
return files
}
function extractJavaScriptSpecifiers(source) {
const values = []
const patterns = [
/(?:import|export)\s+(?:[^'"\r\n]*?\s+from\s+)?['"]([^'"]+)['"]/g,
/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g
]
for (const pattern of patterns) {
for (const match of source.matchAll(pattern)) values.push(match[1])
}
return values
}
function extractJsonSpecifiers(source) {
try {
const parsed = JSON.parse(source)
return Object.values(parsed.usingComponents || {}).filter(value => typeof value === 'string')
} catch {
return []
}
}
function extractMarkupSpecifiers(source) {
const values = []
for (const match of source.matchAll(/<(?:import|include|wxs)\b[^>]*?\bsrc\s*=\s*['"]([^'"]+)['"]/gi)) {
values.push(match[1])
}
return values
}
function extractStyleSpecifiers(source) {
return [...source.matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]/gi)]
.map(match => match[1])
}
function extractSpecifiers(extension, source) {
if (['.js', '.mjs', '.cjs', '.wxs'].includes(extension)) {
return extractJavaScriptSpecifiers(source)
}
if (extension === '.json') return extractJsonSpecifiers(source)
if (extension === '.wxml') return extractMarkupSpecifiers(source)
if (['.wxss', '.sass', '.scss'].includes(extension)) {
return extractStyleSpecifiers(source)
}
return []
}
function resolveSpecifier(projectRoot, importer, specifier) {
if (
!specifier ||
specifier.startsWith('plugin://') ||
specifier.startsWith('wx://') ||
specifier.startsWith('@')
) return null
if (specifier.startsWith('~/')) {
return path.resolve(projectRoot, specifier.slice(2))
}
if (specifier.startsWith('/')) {
return path.resolve(projectRoot, specifier.slice(1))
}
if (specifier.startsWith('.')) {
return path.resolve(path.dirname(importer), specifier)
}
return null
}
function issueKey(issue) {
return `${issue.importer}|${issue.specifier}|${issue.kind}`
}
/**
* 扫描同步静态依赖是否越过微信小程序分包边界。
* @param {string} projectRoot 项目绝对或相对根目录
* @param {object} appConfig 已解析的 app.json
* @param {{roots?: string[], allowlist?: string[]}} [options] 需扫描的 importer 包及已登记例外
* @returns {Promise<Array<{importer: string, specifier: string, importerPackage: string, targetPackage: string, kind: string}>>} 边界问题
*/
export async function checkSubpackageBoundaries(
projectRoot,
appConfig,
options = {}
) {
const absoluteRoot = path.resolve(projectRoot)
const configuredPackages = appConfig.subPackages || appConfig.subpackages || []
const packageRoots = configuredPackages
.map(item => normalizeRoot(item.root))
.filter(Boolean)
.sort((left, right) => right.length - left.length)
const selectedRoots = new Set(
(options.roots?.length ? options.roots : [MAIN_PACKAGE, ...packageRoots])
.map(normalizeRoot)
)
const unknownRoots = [...selectedRoots].filter(
root => root !== MAIN_PACKAGE && !packageRoots.includes(root)
)
if (unknownRoots.length) {
throw new Error(`Subpackage root is not registered: ${unknownRoots.join(', ')}`)
}
const allowlist = new Set(options.allowlist || [])
const files = (await walkFiles(absoluteRoot)).sort()
const issues = []
for (const importer of files) {
const importerRelative = toPosix(path.relative(absoluteRoot, importer))
const importerPackage = packageForPath(importerRelative, packageRoots)
if (!selectedRoots.has(importerPackage)) continue
const source = await readFile(importer, 'utf8')
for (const specifier of new Set(extractSpecifiers(path.extname(importer), source))) {
const target = resolveSpecifier(absoluteRoot, importer, specifier)
if (!target) continue
const relativeTarget = path.relative(absoluteRoot, target)
if (
relativeTarget === '..' ||
relativeTarget.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativeTarget)
) continue
const targetPackage = packageForPath(relativeTarget, packageRoots)
let kind = ''
if (importerPackage === MAIN_PACKAGE && targetPackage !== MAIN_PACKAGE) {
kind = 'main-to-subpackage'
} else if (
importerPackage !== MAIN_PACKAGE &&
targetPackage !== MAIN_PACKAGE &&
importerPackage !== targetPackage
) {
kind = 'subpackage-to-subpackage'
}
if (!kind) continue
const issue = {
importer: importerRelative,
specifier,
importerPackage,
targetPackage,
kind
}
if (!allowlist.has(issueKey(issue))) issues.push(issue)
}
}
return issues.sort((left, right) => issueKey(left).localeCompare(issueKey(right)))
}
function parseRoots(argv) {
const index = argv.indexOf('--roots')
if (index === -1 || !argv[index + 1]) return undefined
return argv[index + 1].split(',').map(normalizeRoot).filter(Boolean)
}
async function runCli() {
const projectRoot = process.cwd()
const appConfig = JSON.parse(await readFile(path.join(projectRoot, 'app.json'), 'utf8'))
const roots = parseRoots(process.argv.slice(2))
const issues = await checkSubpackageBoundaries(projectRoot, appConfig, { roots })
for (const issue of issues) {
console.error(
`${issue.importer} -> ${issue.specifier} (${issue.importerPackage} -> ${issue.targetPackage})`
)
}
console.log(`BOUNDARY_ISSUES=${issues.length}`)
if (issues.length) process.exitCode = 1
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
runCli().catch(error => {
console.error(error.message)
process.exitCode = 1
})
}