check-subpackage-boundaries.mjs 6.74 KB
/**
 * @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
	})
}