check-subpackage-size.mjs 5.97 KB
/**
 * @file 分包原始源码体积防回涨门禁。开发者工具产物仍是上传限制的最终依据,
 * 本脚本用于在提交前尽早发现业务包重新逼近上限。
 */
import { readFile, readdir, stat } from 'node:fs/promises'
import path from 'node:path'
import { pathToFileURL } from 'node:url'

const DEFAULT_IGNORES = new Set([
	'.git', 'docs', 'tests', 'node_modules', 'miniprogram_npm', 'outputs'
])

/** 微信侧推荐的单包源码上界;超过它不等于上传失败,但必须显式登记在下方债务清单里。 */
export const RECOMMENDED_SOURCE_LIMIT = 1_800_000

/**
 * 各分包的防回涨上界。2026-11-07 并入 monorepo 时实测:packageEquity / tabWorkOrder /
 * packageDynamicForm 三个包已越过原推荐线(源工程同文件同字节,属存量债,非迁移造成),
 * 因此按当天实测值锁死——只允许下降,要涨必须先瘦身或显式改这里。
 */
export const SUBPACKAGE_LIMITS = Object.freeze({
	packageEquity: 2_020_410,
	// 主包减重后的分包组件与 QR 生成副本约 153 KB;仍保留约 64 KB 原始源码防回涨空间。
	packageEquityAI: 550_000,
	tabWorkOrder: 1_820_092,
	packageDynamicForm: 1_818_158
})

/** 超过 RECOMMENDED_SOURCE_LIMIT 的分包;新增要在此登记,消化完必须移除。 */
export const SUBPACKAGE_OVER_RECOMMENDED = Object.freeze([
	'packageEquity',
	'tabWorkOrder',
	'packageDynamicForm'
])

function toPosix(value) {
	return value.split(path.sep).join('/')
}

function isExplicitlyIgnored(relativePath, isDirectory, explicitIgnores) {
	return explicitIgnores.some(ignore => {
		if (ignore.type === 'file') return !isDirectory && relativePath === ignore.value
		return relativePath === ignore.value || relativePath.startsWith(`${ignore.value}/`)
	})
}

async function measureDirectory(packageRoot, current, ignoredSegments, explicitIgnores) {
	let bytes = 0
	for (const entry of await readdir(current, { withFileTypes: true })) {
		if (ignoredSegments.has(entry.name)) continue
		const absolutePath = path.join(current, entry.name)
		const relativePath = toPosix(path.relative(packageRoot, absolutePath))
		if (isExplicitlyIgnored(relativePath, entry.isDirectory(), explicitIgnores)) continue
		if (entry.isDirectory()) {
			bytes += await measureDirectory(
				packageRoot,
				absolutePath,
				ignoredSegments,
				explicitIgnores
			)
		} else if (entry.isFile()) {
			bytes += (await stat(absolutePath)).size
		}
	}
	return bytes
}

/**
 * 统计会参与业务包构建的原始文件字节数。
 * @param {string} packageRoot 分包目录
 * @param {Iterable<string>} [ignoreRules] 需要忽略的目录名
 * @param {Array<{value: string, type: 'file'|'folder'}>} [explicitIgnores] 相对分包根的显式排除项
 * @returns {Promise<number>} 原始源码字节数
 */
export async function measurePackageBytes(
	packageRoot,
	ignoreRules = DEFAULT_IGNORES,
	explicitIgnores = []
) {
	const absoluteRoot = path.resolve(packageRoot)
	let rootStat
	try {
		rootStat = await stat(absoluteRoot)
	} catch (error) {
		if (error?.code === 'ENOENT') {
			throw new Error(`Package root is missing: ${absoluteRoot}`)
		}
		throw error
	}
	if (!rootStat.isDirectory()) throw new Error(`Package root is not a directory: ${absoluteRoot}`)
	return measureDirectory(
		absoluteRoot,
		absoluteRoot,
		new Set(ignoreRules),
		explicitIgnores
	)
}

async function readPackageExplicitIgnores(projectRoot, packageName) {
	let config
	try {
		config = JSON.parse(await readFile(path.join(projectRoot, 'project.config.json'), 'utf8'))
	} catch (error) {
		if (error?.code === 'ENOENT') return []
		throw error
	}
	const prefix = `${packageName}/`
	return (config.packOptions?.ignore || [])
		.filter(item => item?.value?.startsWith(prefix))
		.map(item => ({
			value: item.value.slice(prefix.length).replace(/\\/g, '/').replace(/\/$/, ''),
			type: item.type
		}))
}

/**
 * 按 project.config.json 的显式上传排除规则统计分包源码上界。
 * `ignoreUploadUnusedFiles` 的编译期剔除不计入,结果因此仍比最终上传包更保守。
 * @param {string} projectRoot 项目根目录
 * @param {string} packageName 分包 root
 * @returns {Promise<number>} 上传前原始源码字节上界
 */
export async function measurePackageUploadBytes(projectRoot, packageName) {
	const absoluteRoot = path.resolve(projectRoot)
	const explicitIgnores = await readPackageExplicitIgnores(absoluteRoot, packageName)
	return measurePackageBytes(
		path.join(absoluteRoot, packageName),
		DEFAULT_IGNORES,
		explicitIgnores
	)
}

/**
 * 对一组分包执行原始源码阈值检查。
 * @param {string} projectRoot 项目根目录
 * @param {Record<string, number>} limits 分包 root 到最大字节数的映射
 * @returns {Promise<Array<{root: string, bytes: number, limit: number, passed: boolean, overRecommended: boolean}>>} 检查结果
 */
export async function checkPackageSizeLimits(projectRoot, limits) {
	const results = []
	for (const [root, limit] of Object.entries(limits)) {
		const bytes = await measurePackageUploadBytes(projectRoot, root)
		results.push({
			root,
			bytes,
			limit,
			passed: bytes <= limit,
			overRecommended: bytes > RECOMMENDED_SOURCE_LIMIT
		})
	}
	return results
}

async function runCli() {
	const results = await checkPackageSizeLimits(process.cwd(), SUBPACKAGE_LIMITS)
	for (const result of results) {
		console.log(
			`${result.root}=${result.bytes} limit=${result.limit} status=${result.passed ? 'PASS' : 'FAIL'}` +
				`${result.overRecommended ? ` over-recommended(>${RECOMMENDED_SOURCE_LIMIT})` : ''}`
		)
	}
	const failures = results.filter(result => !result.passed)
	console.log(`SUBPACKAGE_SIZE_FAILURES=${failures.length}`)
	console.log(
		`SUBPACKAGE_OVER_RECOMMENDED=${results
			.filter(result => result.overRecommended)
			.map(result => result.root)
			.join(',')}`
	)
	if (failures.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
	})
}