#!/usr/bin/env node // 叠加式模板编译器:运行时(apps/miniapp)→ 能力包 → 模板包,再注入品牌构建参数。 // 编译器只负责拼装和校验,不改写任何页面源码。 import fs from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { CORE_CAPABILITIES, validateCapabilityPackageManifest, validateTemplatePackageManifest, } from "../../template-contract/src/index.ts"; export const workspaceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); const packagesRoot = path.join(workspaceRoot, "packages"); const runtimeRoot = path.join(workspaceRoot, "apps/miniapp"); const DEV_API_BASE_URL = "http://localhost:3001"; const DEV_BRAND_SLUG = "default-brand"; // 运行时目录中不属于小程序产物的内容,以及由编译器生成的文件。 const RUNTIME_EXCLUDES = new Set([ "node_modules", "test", "src", "dist", ".turbo", "package.json", "tsconfig.json", "project.private.config.json", "app.json", "project.config.json", "runtime-config.js", ]); const LAYER_EXCLUDES = new Set(["node_modules", ".turbo", "dist", ".gitkeep", "app.json"]); const PAGE_EXTENSIONS = [".js", ".json", ".wxml", ".wxss"]; class CompileError extends Error {} function fail(message) { throw new CompileError(message); } function readJson(filePath) { return JSON.parse(fs.readFileSync(filePath, "utf8")); } function toPosix(relativePath) { return relativePath.split(path.sep).join("/"); } /** exclude 中的条目是相对层根目录的路径,只匹配该路径本身,不匹配深层同名目录(如 TDesign 的 common/src)。 */ function listFiles(directory, exclude, base = directory) { const files = []; for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { const entryPath = toPosix(path.relative(base, path.join(directory, entry.name))); if (exclude.has(entryPath)) continue; if (entry.name === ".gitkeep") continue; const filePath = path.join(directory, entry.name); if (entry.isDirectory()) files.push(...listFiles(filePath, exclude, base)); else files.push(toPosix(path.relative(base, filePath))); } return files; } function underPrefix(relativePath, prefix) { return relativePath === prefix || relativePath.startsWith(prefix + "/"); } function resolveTemplateDirectory(options) { if (options.templateDir) return path.resolve(options.templateDir); const candidates = [ path.join(packagesRoot, `template-${options.template}`), path.join(packagesRoot, options.template), ]; const found = candidates.find((candidate) => fs.existsSync(path.join(candidate, "template.json")), ); if (!found) fail(`Template package not found: ${options.template}`); return found; } function loadTemplate(options) { const directory = resolveTemplateDirectory(options); const manifest = readJson(path.join(directory, "template.json")); if (options.template && manifest.packageKey !== options.template) fail(`template.json packageKey ${manifest.packageKey} does not match ${options.template}`); const errors = validateTemplatePackageManifest(manifest); if (errors.length) fail(`Invalid template ${manifest.packageKey}:\n ${errors.join("\n ")}`); if (!fs.existsSync(path.join(directory, "miniapp"))) fail(`Template package has no miniapp directory: ${manifest.packageKey}`); return { directory, manifest }; } function loadCapabilities(manifest, capabilitiesRoot) { const capabilities = []; for (const key of manifest.requiredCapabilities) { if (CORE_CAPABILITIES.includes(key)) continue; const directory = path.join(capabilitiesRoot, `capability-${key}`); const manifestPath = path.join(directory, "capability.json"); if (!fs.existsSync(manifestPath)) fail(`Template ${manifest.packageKey} requires unknown capability: ${key}`); const capability = readJson(manifestPath); const errors = validateCapabilityPackageManifest(capability); if (capability.key !== key) errors.push(`capability.json key must be ${key}`); if (errors.length) fail(`Invalid capability ${key}:\n ${errors.join("\n ")}`); capabilities.push({ key, directory, manifest: capability }); } return capabilities; } function resolveParams(options, manifest) { const env = options.env || "dev"; if (!["dev", "prod"].includes(env)) fail(`--env must be dev or prod, got ${env}`); if (env === "prod") { const missing = ["brand", "appid", "api"].filter((key) => !options[key]); if (missing.length) fail(`Production build requires ${missing.map((key) => "--" + key).join(", ")}`); if (!options.api.startsWith("https://")) fail("Production --api must use https://"); } const runtimeProject = readJson(path.join(runtimeRoot, "project.config.json")); return { env, brandSlug: options.brand || manifest.defaultBrandSlug || DEV_BRAND_SLUG, appid: options.appid || runtimeProject.appid, apiBaseUrl: options.api || DEV_API_BASE_URL, }; } function prepareOutput(output) { const resolved = path.resolve(output); if ( resolved === path.parse(resolved).root || resolved === workspaceRoot || workspaceRoot.startsWith(resolved + path.sep) ) fail(`Refusing to use output directory: ${resolved}`); if (fs.existsSync(resolved)) { const entries = fs.readdirSync(resolved); if (entries.length && !entries.includes("template.runtime.json")) fail(`Output directory is not empty and was not generated by the compiler: ${resolved}`); fs.rmSync(resolved, { recursive: true, force: true }); } fs.mkdirSync(resolved, { recursive: true }); return resolved; } /** 按层复制文件;除模板显式 override 的目录外,任何同名文件都视为冲突。 */ function createLayerWriter(output) { const owners = new Map(); return { owners, copy(sourceDirectory, layer, exclude) { for (const relativePath of listFiles(sourceDirectory, exclude)) { if (owners.has(relativePath)) fail( `${layer} conflicts with ${owners.get(relativePath)} at ${relativePath}; declare it in overrides`, ); const target = path.join(output, relativePath); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(path.join(sourceDirectory, relativePath), target); owners.set(relativePath, layer); } }, release(prefix, layer) { const released = [...owners.keys()].filter((relativePath) => underPrefix(relativePath, prefix), ); if (!released.length) fail(`${layer} overrides ${prefix}, but no lower layer provides it`); for (const relativePath of released) { fs.rmSync(path.join(output, relativePath), { force: true }); owners.delete(relativePath); } }, }; } function unique(values) { return [...new Set(values)]; } function buildAppJson(manifest, templateDirectory, capabilities) { const runtimeApp = readJson(path.join(runtimeRoot, "app.json")); const templateAppPath = path.join(templateDirectory, "miniapp/app.json"); const templateApp = fs.existsSync(templateAppPath) ? readJson(templateAppPath) : {}; const pages = unique([ manifest.entrypoints.home, ...manifest.pages, ...(runtimeApp.pages || []), ...capabilities.flatMap((capability) => capability.manifest.pages), ]); for (const [key, page] of Object.entries(manifest.entrypoints)) { if (!pages.includes(page)) fail(`entrypoints.${key} (${page}) is not provided by any layer`); } // 颜色属于模板视觉,由模板的 miniapp/app.json 提供;这里只兜底中性色。 const tabBarStyle = templateApp.tabBar || {}; return { ...runtimeApp, pages, window: { ...runtimeApp.window, navigationBarTitleText: manifest.displayName, ...(templateApp.window || {}), }, tabBar: { color: tabBarStyle.color || "#7a7a7a", selectedColor: tabBarStyle.selectedColor || "#1a1a1a", backgroundColor: tabBarStyle.backgroundColor || "#ffffff", borderStyle: tabBarStyle.borderStyle || "white", list: manifest.navigation.map((item) => ({ pagePath: manifest.entrypoints[item.page], text: item.label, ...(item.iconPath ? { iconPath: item.iconPath } : {}), ...(item.selectedIconPath ? { selectedIconPath: item.selectedIconPath } : {}), })), }, }; } function writeGeneratedFiles(output, manifest, params, appJson, capabilities) { fs.writeFileSync(path.join(output, "app.json"), JSON.stringify(appJson, null, 2) + "\n"); const project = readJson(path.join(runtimeRoot, "project.config.json")); fs.writeFileSync( path.join(output, "project.config.json"), JSON.stringify( { ...project, appid: params.appid, projectname: `${params.brandSlug}-${manifest.packageKey}`, }, null, 2, ) + "\n", ); const runtimeConfig = { env: params.env, apiBaseUrl: params.apiBaseUrl, brandSlug: params.brandSlug, templateKey: manifest.packageKey, templateVersion: manifest.version, runtimeContract: manifest.runtimeContract, tabPages: appJson.tabBar.list.map((item) => item.pagePath), }; fs.writeFileSync( path.join(output, "runtime-config.js"), `// 由 template-compiler 生成,请勿手动修改。\nmodule.exports = ${JSON.stringify(runtimeConfig, null, 2)};\n`, ); fs.writeFileSync( path.join(output, "template.runtime.json"), JSON.stringify( { packageKey: manifest.packageKey, version: manifest.version, runtimeContract: manifest.runtimeContract, brandSlug: params.brandSlug, env: params.env, capabilities: capabilities.map((capability) => ({ key: capability.key, version: capability.manifest.version, })), pages: appJson.pages, entrypoints: manifest.entrypoints, navigation: manifest.navigation, }, null, 2, ) + "\n", ); } // 按 packageKey 识别当前模板,--template-dir 指向 packages/ 之外的副本时同样成立。 function otherTemplateComponentNames(currentPackageKey) { const names = new Set(); for (const entry of fs.readdirSync(packagesRoot, { withFileTypes: true })) { if (!entry.isDirectory() || !entry.name.startsWith("template-")) continue; const directory = path.join(packagesRoot, entry.name); const manifestPath = path.join(directory, "template.json"); if (!fs.existsSync(manifestPath) || readJson(manifestPath).packageKey === currentPackageKey) continue; const componentRoot = path.join(directory, "miniapp/components/templates"); if (!fs.existsSync(componentRoot)) continue; for (const component of fs.readdirSync(componentRoot)) names.add(component); } return names; } function resolveComponent(output, fromFile, reference) { const base = reference.startsWith("/") ? path.join(output, reference) : reference.startsWith(".") ? path.resolve(path.dirname(path.join(output, fromFile)), reference) : path.join(output, "miniprogram_npm", reference); return [".json", ".js", ".wxml"].every((extension) => fs.existsSync(base + extension)); } function resolveRequire(output, fromFile, reference) { const base = path.resolve(path.dirname(path.join(output, fromFile)), reference); return [base, base + ".js", path.join(base, "index.js")].some( (candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile(), ); } /** 校验产物可以被微信开发者工具直接打开:页面、组件、require、图标和模板隔离。 */ function validateOutput(output, appJson, packageKey) { const errors = []; const warnings = []; for (const page of appJson.pages) { for (const extension of PAGE_EXTENSIONS) { if (!fs.existsSync(path.join(output, page + extension))) errors.push(`page ${page} is missing ${extension}`); } } for (const item of appJson.tabBar.list) { for (const icon of [item.iconPath, item.selectedIconPath]) { if (icon && !fs.existsSync(path.join(output, icon))) errors.push(`tabBar icon is missing: ${icon}`); } } const hasNpm = fs.existsSync(path.join(output, "miniprogram_npm")); const tabPages = new Set(appJson.tabBar.list.map((item) => item.pagePath)); const forbiddenComponents = otherTemplateComponentNames(packageKey); const sourceFiles = listFiles(output, new Set(["miniprogram_npm"])).filter((file) => /\.(js|json|wxml)$/.test(file), ); for (const file of sourceFiles) { const source = fs.readFileSync(path.join(output, file), "utf8"); if (file.endsWith(".json") && (file.startsWith("pages/") || file.startsWith("components/"))) { const usingComponents = JSON.parse(source).usingComponents || {}; for (const [name, reference] of Object.entries(usingComponents)) { if (reference.startsWith("/miniprogram_npm/") && !hasNpm) { warnings.push(`${file}: ${name} needs miniprogram_npm (build npm in apps/miniapp first)`); continue; } if (reference.startsWith("plugin://")) continue; if (!resolveComponent(output, file, reference)) errors.push(`${file}: component ${name} cannot be resolved (${reference})`); } } if (file.endsWith(".js")) { for (const match of source.matchAll(/require\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)/g)) { if (!resolveRequire(output, file, match[1])) errors.push(`${file}: require("${match[1]}") cannot be resolved`); } // 微信不允许 navigateTo/redirectTo 到 tabBar 页,switchTab 也不能带参数;失败时页面毫无反应。 for (const match of source.matchAll( /wx\.(navigateTo|redirectTo|switchTab)\(\s*\{\s*url:\s*["'`]\/?([^"'`?]+)(\?)?/g, )) { const [, method, target, hasQuery] = match; if (method !== "switchTab" && tabPages.has(target)) errors.push(`${file}: wx.${method} cannot open tabBar page ${target}; use openPage()`); if (method === "switchTab" && hasQuery) errors.push(`${file}: wx.switchTab cannot pass a query to ${target}; use openPage()`); } } if (file.startsWith("pages/") || file.startsWith("components/")) { for (const token of ["pageRenderer", "templateKey ==="]) { if (source.includes(token)) errors.push(`${file}: contains template branch token ${token}`); } for (const component of forbiddenComponents) { if (source.includes(component)) errors.push(`${file}: references another template's ${component}`); } } } return { errors, warnings }; } /** * 编译一个模板为完整的小程序目录。 * @param {{ template?: string, templateDir?: string, brand?: string, appid?: string, api?: string, * env?: "dev" | "prod", out?: string, capabilitiesRoot?: string }} options */ export function compileTemplate(options) { const { directory: templateDirectory, manifest } = loadTemplate(options); const capabilities = loadCapabilities(manifest, options.capabilitiesRoot || packagesRoot); const params = resolveParams(options, manifest); const output = prepareOutput( options.out || path.join(workspaceRoot, "dist/miniapp", params.brandSlug), ); try { const writer = createLayerWriter(output); writer.copy(runtimeRoot, "runtime", RUNTIME_EXCLUDES); for (const capability of capabilities) { writer.copy( path.join(capability.directory, "miniapp"), `capability:${capability.key}`, LAYER_EXCLUDES, ); for (const page of capability.manifest.pages) { if (!fs.existsSync(path.join(output, page + ".js"))) fail(`capability ${capability.key} declares ${page} but does not provide it`); } } for (const prefix of manifest.overrides || []) writer.release(prefix, `template:${manifest.packageKey}`); writer.copy( path.join(templateDirectory, "miniapp"), `template:${manifest.packageKey}`, LAYER_EXCLUDES, ); const appJson = buildAppJson(manifest, templateDirectory, capabilities); writeGeneratedFiles(output, manifest, params, appJson, capabilities); const { errors, warnings } = validateOutput(output, appJson, manifest.packageKey); if (errors.length) fail(`Generated mini program is invalid:\n ${errors.join("\n ")}`); return { output, manifest, params, warnings }; } catch (error) { fs.rmSync(output, { recursive: true, force: true }); throw error; } } function parseArgs(argv) { const options = {}; const names = { "--template": "template", "--template-dir": "templateDir", "--brand": "brand", "--appid": "appid", "--api": "api", "--env": "env", "--out": "out", }; for (let index = 0; index < argv.length; index += 1) { const argument = argv[index]; if (!names[argument]) { if (!options.template && !argument.startsWith("--")) options.template = argument; else fail(`Unknown argument: ${argument}`); continue; } const value = argv[index + 1]; if (!value || value.startsWith("--")) fail(`${argument} requires a value`); options[names[argument]] = value; index += 1; } return options; } function main() { const usage = "Usage: template:dev