load-mini-program-source.mjs 3.36 KB
/**
 * @file 以依赖注入方式加载小程序页面或 ES 模块,仅用于迁移行为特征测试。
 */
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { parse } from '@babel/parser'
import generatorModule from '@babel/generator'

const generate = generatorModule.default || generatorModule
const projectRoot = path.resolve(process.cwd())

async function transformSource(relativePath) {
	const absolutePath = path.resolve(projectRoot, relativePath)
	const relativeToRoot = path.relative(projectRoot, absolutePath)
	if (
		relativeToRoot === '..' ||
		relativeToRoot.startsWith(`..${path.sep}`) ||
		path.isAbsolute(relativeToRoot)
	) {
		throw new Error(`Source must stay inside project: ${relativePath}`)
	}
	const source = await readFile(absolutePath, 'utf8')
	const ast = parse(source, { sourceType: 'module' })
	const exportNames = []
	const body = []
	for (const node of ast.program.body) {
		if (node.type === 'ImportDeclaration') continue
		if (node.type === 'ExportNamedDeclaration') {
			if (node.declaration) {
				body.push(node.declaration)
				if (node.declaration.type === 'VariableDeclaration') {
					for (const declaration of node.declaration.declarations) {
						if (declaration.id.type === 'Identifier') exportNames.push(declaration.id.name)
					}
				} else if (node.declaration.id?.name) {
					exportNames.push(node.declaration.id.name)
				}
			}
			for (const specifier of node.specifiers || []) {
				exportNames.push(specifier.local.name)
			}
			continue
		}
		if (node.type === 'ExportDefaultDeclaration') {
			body.push({
				type: 'VariableDeclaration',
				kind: 'const',
				declarations: [{
					type: 'VariableDeclarator',
					id: { type: 'Identifier', name: '__defaultExport' },
					init: node.declaration
				}]
			})
			exportNames.push('__defaultExport')
			continue
		}
		body.push(node)
	}
	ast.program.body = body
	return { code: generate(ast).code, exportNames }
}

/**
 * 加载模块的命名导出,import 依赖由调用方显式注入。
 * @param {string} relativePath 仓库内模块路径
 * @param {Record<string, unknown>} [dependencies] 顶层依赖
 * @returns {Promise<Record<string, unknown>>} 模块导出
 */
export async function loadSourceExports(relativePath, dependencies = {}) {
	const { code, exportNames } = await transformSource(relativePath)
	const names = Object.keys(dependencies)
	const values = Object.values(dependencies)
	const resultExpression = exportNames
		.map(name => `${JSON.stringify(name)}: ${name}`)
		.join(',')
	return new Function(...names, `${code}\nreturn {${resultExpression}};`)(...values)
}

/**
 * 捕获 Page/Component 注册对象,便于直接验证页面编排行为。
 * @param {string} relativePath 仓库内页面脚本
 * @param {Record<string, unknown>} [dependencies] 页面顶层依赖
 * @param {'Page'|'Component'} [registerName] 注册函数名
 * @returns {Promise<object>} 页面或组件定义
 */
export async function loadMiniProgramDefinition(
	relativePath,
	dependencies = {},
	registerName = 'Page'
) {
	const { code } = await transformSource(relativePath)
	let definition
	const register = value => {
		definition = value
	}
	const injected = { ...dependencies, [registerName]: register }
	new Function(...Object.keys(injected), code)(...Object.values(injected))
	if (!definition) throw new Error(`${registerName} was not registered: ${relativePath}`)
	return definition
}