refactor: 重构模板叠加式编译产物

This commit is contained in:
que01 committed 2026-09-26 11:21:29 +08:00
1 parent c46297b13b
commit 25d1fe983c
93 files changed
+870 -2467

No files matched your search

+407 -283
View File
@@ -1,306 +1,257 @@
#!/usr/bin/env node
// 叠加式模板编译器:运行时(apps/miniapp)→ 能力包 → 模板包,再注入品牌构建参数。
// 编译器只负责拼装和校验,不改写任何页面源码。
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
CORE_CAPABILITIES,
validateCapabilityPackageManifest,
validateTemplatePackageManifest,
} from "../../template-contract/src/index.ts";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
const packagesRoot = path.join(root, "packages");
const generatedRoot = path.join(root, "apps/miniapp-generated");
export const workspaceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
const packagesRoot = path.join(workspaceRoot, "packages");
const runtimeRoot = path.join(workspaceRoot, "apps/miniapp");
function usage() {
console.log("Usage: template-compiler --template <package-key> [--out <directory>]");
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",
"assets",
"pages/booking",
"utils/templates.js",
"components/templates",
"components/runtime-tab-bar",
"pages/index",
"pages/services",
"pages/bookings",
"pages/stall-service",
]);
const LAYER_EXCLUDES = new Set(["node_modules", ".turbo", "dist", ".gitkeep", "app.json"]);
const PAGE_EXTENSIONS = [".js", ".json", ".wxml"];
class CompileError extends Error {}
function fail(message) {
throw new CompileError(message);
}
function validateManifest(manifest) {
const requiredPages = ["home", "offerings", "detail", "inquiry", "success", "records", "profile"];
if (!manifest.packageKey || !manifest.version || !manifest.displayName)
throw new Error("template.json requires packageKey, version and displayName");
if (manifest.runtimeContract !== "1.0") throw new Error("Only runtimeContract 1.0 is supported");
for (const page of requiredPages) {
if (typeof manifest.entrypoints?.[page] !== "string")
throw new Error(`template.json missing entrypoint: ${page}`);
}
if (!Array.isArray(manifest.navigation) || !manifest.navigation.length)
throw new Error("template.json navigation must not be empty");
if (!Array.isArray(manifest.dataSlots) || !manifest.dataSlots.length)
throw new Error("template.json dataSlots must not be empty");
if (!Array.isArray(manifest.assetSlots))
throw new Error("template.json assetSlots must be an array");
if (!manifest.admin || !Array.isArray(manifest.admin.sections) || !manifest.admin.sections.length)
throw new Error("template.json admin.sections must not be empty");
for (const section of manifest.admin.sections) {
if (!section.key || !section.title || !section.description || !Array.isArray(section.fields))
throw new Error("template.json admin sections require key, title, description and fields");
for (const field of section.fields) {
if (!field.key || !field.binding || !field.label || !field.input)
throw new Error("template.json admin fields require key, binding, label and input");
}
}
if (
manifest.renderers !== undefined &&
(typeof manifest.renderers !== "object" || Array.isArray(manifest.renderers))
)
throw new Error("template.json renderers must be an object");
for (const page of ["home", "offerings", "profile"]) {
if (typeof manifest.renderers?.[page] !== "string" || !manifest.renderers[page]) {
throw new Error(`template.json requires a dedicated renderer for visual page: ${page}`);
}
}
if (
manifest.runtimeOwnedPages !== undefined &&
(!Array.isArray(manifest.runtimeOwnedPages) ||
manifest.runtimeOwnedPages.some(
(page) => !["detail", "inquiry", "success", "records"].includes(page),
))
)
throw new Error("template.json runtimeOwnedPages contains an unsupported page");
for (const item of manifest.navigation) {
if (!item || typeof item.key !== "string" || typeof item.label !== "string")
throw new Error("template.json navigation items require key and label");
if (typeof item.page !== "string" || typeof manifest.entrypoints?.[item.page] !== "string")
throw new Error(`template.json navigation page is not a declared entrypoint: ${item.key}`);
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function validateEntrypoints(output, manifest) {
for (const [key, relativePath] of Object.entries(manifest.entrypoints || {})) {
const pagePath = path.join(output, relativePath);
for (const extension of [".js", ".json", ".wxml", ".wxss"]) {
if (!fs.existsSync(`${pagePath}${extension}`)) {
throw new Error(`Template entrypoint ${key} is missing ${relativePath}${extension}`);
}
}
}
function toPosix(relativePath) {
return relativePath.split(path.sep).join("/");
}
function validateGeneratedIsolation(output) {
const forbidden = [
"components/templates",
"runtime-tab-bar",
"acheng-",
"linjing-",
"templateKey ===",
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(entry.name) ||
[...exclude].some((value) => entryPath === value || entryPath.startsWith(value + "/"))
)
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 visit = (directory) => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const filePath = path.join(directory, entry.name);
if (entry.isDirectory()) visit(filePath);
else if (/\.(wxml|json|js|wxss)$/.test(entry.name)) {
const source = fs.readFileSync(filePath, "utf8");
for (const token of forbidden) {
if (source.includes(token))
throw new Error(`Generated output contains forbidden token ${token}: ${filePath}`);
}
}
}
};
visit(path.join(output, "pages"));
const found = candidates.find((candidate) =>
fs.existsSync(path.join(candidate, "template.json")),
);
if (!found) fail(`Template package not found: ${options.template}`);
return found;
}
function copyDirectory(source, target) {
fs.mkdirSync(target, { recursive: true });
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
if (["node_modules", ".turbo", "dist"].includes(entry.name)) continue;
const from = path.join(source, entry.name);
const to = path.join(target, entry.name);
if (entry.isDirectory()) copyDirectory(from, to);
else fs.copyFileSync(from, to);
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 removeOwnedPaths(rootDirectory, ownedPaths = []) {
for (const relativePath of ownedPaths) {
fs.rmSync(path.join(rootDirectory, relativePath), { recursive: true, force: true });
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://");
}
}
function removeRuntimeTabBar(output) {
const pagesDirectory = path.join(output, "pages");
if (!fs.existsSync(pagesDirectory)) return;
const visit = (directory) => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const filePath = path.join(directory, entry.name);
if (entry.isDirectory()) visit(filePath);
else if (entry.name.endsWith(".wxml")) {
const source = fs.readFileSync(filePath, "utf8");
const cleaned = source.replace(/<runtime-tab-bar\b[^>]*\/\s*>/g, "");
if (cleaned !== source) fs.writeFileSync(filePath, cleaned);
} else if (entry.name.endsWith(".json")) {
const json = JSON.parse(fs.readFileSync(filePath, "utf8"));
if (json.usingComponents?.["runtime-tab-bar"]) {
delete json.usingComponents["runtime-tab-bar"];
fs.writeFileSync(filePath, JSON.stringify(json, null, 2) + "\n");
}
}
}
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,
};
visit(pagesDirectory);
fs.rmSync(path.join(output, "components/runtime-tab-bar"), { recursive: true, force: true });
}
function pruneUndeclaredPages(output, manifest) {
const appJsonPath = path.join(output, "app.json");
const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf8"));
const allowed = new Set([
...manifest.navigation.map((item) => manifest.entrypoints[item.page]),
...(manifest.runtimeOwnedPages || []).map((page) => manifest.entrypoints[page]),
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 page of appJson.pages || []) {
if (allowed.has(page)) continue;
fs.rmSync(path.join(output, path.dirname(page)), { recursive: true, force: true });
}
appJson.pages = (appJson.pages || []).filter((page) => allowed.has(page));
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2) + "\n");
const appJsPath = path.join(output, "app.js");
if (fs.existsSync(appJsPath) && manifest.defaultBrandSlug) {
const appJs = fs
.readFileSync(appJsPath, "utf8")
.replace(
/const DEFAULT_BRAND_SLUG = "[^"]*";/,
`const DEFAULT_BRAND_SLUG = ${JSON.stringify(manifest.defaultBrandSlug)};`,
);
fs.writeFileSync(appJsPath, appJs);
for (const [key, page] of Object.entries(manifest.entrypoints)) {
if (!pages.includes(page)) fail(`entrypoints.${key} (${page}) is not provided by any layer`);
}
const tabBarStyle = templateApp.tabBar || {};
return {
...runtimeApp,
pages,
window: {
...runtimeApp.window,
navigationBarTitleText: manifest.displayName,
...(templateApp.window || {}),
},
tabBar: {
color: tabBarStyle.color || "#8b8178",
selectedColor: tabBarStyle.selectedColor || "#3b2118",
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 materializeRendererAliases(output, packageDirectory, manifest) {
const rendererRoot = path.join(packageDirectory, "miniapp/components/templates");
const pagePaths = {
home: "pages/index/index",
offerings: "pages/services/index",
profile: "pages/bookings/index",
};
for (const page of Object.keys(pagePaths)) {
const renderer = manifest.renderers?.[page];
const source = path.join(rendererRoot, renderer);
if (!fs.existsSync(source)) {
throw new Error(`Template renderer source is missing: ${renderer}`);
}
const aliasDirectory = path.join(output, "components/template-pages", page);
fs.mkdirSync(aliasDirectory, { recursive: true });
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
if (!entry.isFile()) continue;
fs.copyFileSync(
path.join(source, entry.name),
path.join(aliasDirectory, `${page}${path.extname(entry.name)}`),
);
}
const pageDirectory = path.join(output, pagePaths[page]);
const jsonPath = `${pageDirectory}.json`;
const wxmlPath = `${pageDirectory}.wxml`;
const pageJson = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
pageJson.usingComponents = pageJson.usingComponents || {};
for (const key of Object.keys(pageJson.usingComponents)) {
if (/-home$|-offerings$|-profile$/.test(key)) delete pageJson.usingComponents[key];
}
pageJson.usingComponents[`template-${page}`] = `/components/template-pages/${page}/${page}`;
fs.writeFileSync(jsonPath, JSON.stringify(pageJson, null, 2) + "\n");
const rendererPattern = new RegExp(`<([a-z0-9-]+)-${page}\\b`, "g");
const originalWxml = fs.readFileSync(wxmlPath, "utf8");
const wxml =
page === "offerings"
? `<view class="page"><template-${page} brand="{{brand}}" presentation="{{presentation}}" offerings="{{offerings}}" bind:open="open" bind:more="inquire" /></view>`
: originalWxml.replace(rendererPattern, `<template-${page}`);
fs.writeFileSync(wxmlPath, wxml);
}
}
function freezeRendererConditions(output, manifest) {
const rendererByPage = manifest.renderers || {};
const pagePaths = {
home: "pages/index/index.wxml",
offerings: "pages/services/index.wxml",
profile: "pages/bookings/index.wxml",
};
for (const [page, relativePath] of Object.entries(pagePaths)) {
const filePath = path.join(output, relativePath);
if (!fs.existsSync(filePath)) continue;
const selected = rendererByPage[page] || "";
const source = fs.readFileSync(filePath, "utf8");
const frozen = source.replace(
/wx:(if|elif)="\{\{pageRenderer === '([^']+)'\}\}"/g,
(_match, branch, renderer) => `wx:${branch}="{{${renderer === selected}}}"`,
);
const selectedAlias =
page === "offerings"
? frozen.replace(
'<template-offerings wx:if="{{false}}"',
'<template-offerings wx:if="{{true}}"',
)
: frozen;
fs.writeFileSync(filePath, selectedAlias);
}
}
function main() {
const args = process.argv.slice(2);
const templateIndex = args.indexOf("--template");
if (templateIndex < 0 || !args[templateIndex + 1]) return usage();
const packageKey = args[templateIndex + 1];
const outputIndex = args.indexOf("--out");
const output = path.resolve(outputIndex >= 0 ? args[outputIndex + 1] : generatedRoot);
const packageDirectory = fs.existsSync(path.join(packagesRoot, packageKey))
? path.join(packagesRoot, packageKey)
: path.join(packagesRoot, `template-${packageKey}`);
const manifestPath = path.join(packageDirectory, "template.json");
if (!fs.existsSync(manifestPath)) throw new Error(`Template package not found: ${packageKey}`);
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
if (manifest.packageKey !== packageKey)
throw new Error("template.json packageKey does not match requested template");
validateManifest(manifest);
fs.rmSync(output, { recursive: true, force: true });
const shell = path.join(root, "apps/miniapp");
if (!fs.existsSync(shell)) throw new Error("Mini Program shell is missing: apps/miniapp");
copyDirectory(shell, output);
// 迁移期间保留 shell 的模板目录,直到模板包提供对应页面的完整覆盖。
// ownedPaths 只记录最终所有权,不在不完整迁移时删除可用 renderer。
const source = path.join(packageDirectory, "miniapp");
if (!fs.existsSync(source))
throw new Error(`Template package has no miniapp directory: ${packageKey}`);
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
if (entry.name === "app.json") continue;
const from = path.join(source, entry.name);
const to = path.join(output, entry.name);
if (entry.isDirectory()) copyDirectory(from, to);
else fs.copyFileSync(from, to);
}
materializeRendererAliases(output, packageDirectory, manifest);
freezeRendererConditions(output, manifest);
removeRuntimeTabBar(output);
pruneUndeclaredPages(output, manifest);
validateEntrypoints(output, manifest);
for (const relativePath of manifest.ownedPaths || []) {
if (!fs.existsSync(path.join(output, relativePath)))
throw new Error(`Template package did not provide owned path: ${relativePath}`);
}
for (const renderer of Object.values(manifest.renderers || {})) {
const rendererPath = path.join(output, "components/templates", renderer, `${renderer}.wxml`);
if (!fs.existsSync(rendererPath)) throw new Error(`Template renderer is missing: ${renderer}`);
}
fs.rmSync(path.join(output, "components/templates"), { recursive: true, force: true });
validateGeneratedIsolation(output);
const appJsonPath = path.join(output, "app.json");
const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf8"));
appJson.window = {
...appJson.window,
navigationBarTitleText: manifest.displayName,
};
appJson.tabBar = {
color: "#8b8178",
selectedColor: "#3b2118",
backgroundColor: "#ffffff",
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 } : {}),
})),
};
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2) + "\n");
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, "template.manifest.json"),
JSON.stringify(manifest, null, 2) + "\n",
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,
};
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"),
@@ -309,18 +260,191 @@ function main() {
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,
requiredCapabilities: manifest.requiredCapabilities,
renderers: manifest.renderers || {},
runtimeOwnedPages: manifest.runtimeOwnedPages || [],
ownedPaths: manifest.ownedPaths || [],
},
null,
2,
) + "\n",
);
console.log(`Generated ${packageKey}@${manifest.version} -> ${path.relative(root, output)}`);
}
main();
function otherTemplateComponentNames(currentDirectory) {
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);
if (path.resolve(directory) === path.resolve(currentDirectory)) 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, templateDirectory) {
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 forbiddenComponents = otherTemplateComponentNames(templateDirectory);
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`);
}
}
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),
);
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, templateDirectory);
if (errors.length) fail(`Generated mini program is invalid:\n ${errors.join("\n ")}`);
return { output, manifest, params, warnings };
}
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 <template> [--brand <slug>] [--appid <id>] [--api <url>] [--env dev|prod] [--out <dir>]";
try {
const options = parseArgs(process.argv.slice(2));
if (!options.template && !options.templateDir) {
console.log(usage);
process.exitCode = 1;
return;
}
const result = compileTemplate(options);
for (const warning of result.warnings) console.warn(`warning: ${warning}`);
console.log(
`Generated ${result.manifest.packageKey}@${result.manifest.version} for ${result.params.brandSlug} (${result.params.env}) -> ${path.relative(workspaceRoot, result.output) || result.output}`,
);
} catch (error) {
if (!(error instanceof CompileError)) throw error;
console.error(error.message);
process.exitCode = 1;
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href)
main();