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

+9
View File
@@ -0,0 +1,9 @@
# booking 能力包
为需要"选择数量 + 自取/配送"下单流程的模板提供小程序页面。模板在 `template.json` 的
`requiredCapabilities` 中声明 `booking` 后,`template:dev` 会把 `miniapp/` 叠加进产物。
- `miniapp/pages/booking`:下单页,提交到 `POST /customer/bookings`。
- `miniapp/utils/booking-templates.js`:下单页文案。
当前后端仍使用核心 `Booking` 模型;把它迁移为独立 capability 是后续任务。
@@ -0,0 +1,7 @@
{
"key": "booking",
"version": "1.0.0",
"runtimeContract": "1.0",
"description": "带数量、自取/配送的下单能力,提交到 /customer/bookings。",
"pages": ["pages/booking/index"]
}
@@ -0,0 +1,92 @@
const { request, customerRequest, customerTokenKey } = require("../../utils/request");
const { getTemplate } = require("../../utils/booking-templates");
Page({
data: {
service: {},
form: {},
offeringId: "",
quantity: 1,
fulfillment: "pickup",
submitting: false,
template: getTemplate("personal"),
},
onLoad(query) {
Promise.all([request("/public/offerings"), request("/public/brand")])
.then(([services, brand]) => {
const list = Array.isArray(services) ? services : [];
const service =
list.find((item) => item.id === query.offeringId || item.id === query.serviceId) ||
list.find((item) => item.priceAmount !== null) ||
{};
this.setData({
service,
offeringId: service.id || "",
template: getTemplate(brand.templateKey),
});
})
.catch(() => wx.showToast({ title: "服务加载失败", icon: "none" }));
},
input(event) {
this.setData({ ["form." + event.currentTarget.dataset.key]: event.detail.value });
},
chooseFulfillment(event) {
this.setData({ fulfillment: event.currentTarget.dataset.value });
},
increase() {
if (this.data.quantity < 50) this.setData({ quantity: this.data.quantity + 1 });
},
decrease() {
if (this.data.quantity > 1) this.setData({ quantity: this.data.quantity - 1 });
},
submit() {
const form = this.data.form;
if (!this.data.offeringId) return wx.showToast({ title: "请先选择服务", icon: "none" });
if (!form.customerName || !form.wechatId)
return wx.showToast({ title: "请填写称呼和联系方式", icon: "none" });
if (this.data.fulfillment === "delivery" && !form.deliveryAddress)
return wx.showToast({ title: "请填写" + this.data.template.locationLabel, icon: "none" });
this.setData({ submitting: true });
const send = () =>
customerRequest("/customer/bookings", {
method: "POST",
data: {
requestType: this.data.template.requestType,
customerName: form.customerName,
wechatId: form.wechatId,
contactPreference: "wechat",
fulfillmentType: this.data.fulfillment,
deliveryAddress: form.deliveryAddress,
requestedTime: form.requestedTime,
note: form.note,
items: [{ offeringId: this.data.offeringId, quantity: this.data.quantity }],
},
})
.then(() => {
this.setData({ submitting: false });
wx.showToast({ title: "预约已提交" });
setTimeout(() => wx.navigateTo({ url: "/pages/bookings/index" }), 500);
})
.catch((error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.message || "提交失败", icon: "none" });
});
const token = wx.getStorageSync(customerTokenKey());
if (token) return send();
wx.login({
success: (login) =>
request("/customer/session/wechat", { method: "POST", data: { code: login.code } })
.then((result) => {
wx.setStorageSync(customerTokenKey(), result.token);
send();
})
.catch((error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.message || "微信登录失败", icon: "none" });
}),
fail: (error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.errMsg || "微信登录失败", icon: "none" });
},
});
},
});
@@ -0,0 +1,10 @@
{
"navigationBarTitleText": "提交需求",
"navigationBarBackgroundColor": "#FBF7F1",
"navigationBarTextStyle": "black",
"usingComponents": {
"brand-button": "/components/ui/brand-button/brand-button",
"brand-field": "/components/ui/brand-field/brand-field",
"brand-card": "/components/ui/brand-card/brand-card"
}
}
@@ -0,0 +1,7 @@
<view class="page">
<view class="product"><view class="product-image"><image wx:if="{{service.coverUrl}}" src="{{service.coverUrl}}" mode="aspectFill"/><view wx:else class="dish-placeholder"></view></view><view class="product-copy"><text class="name">{{service.name || '选择服务'}}</text><text class="price">{{service.priceText || '沟通报价'}}</text></view><text class="available">{{template.available}}</text></view>
<view class="quantity"><text>数量</text><view class="stepper"><button bindtap="decrease">−</button><text>{{quantity}} 份</text><button bindtap="increase">+</button></view></view>
<view class="fulfillment"><text class="field-title">{{template.modeLabel}}</text><view class="choices"><button class="choice {{fulfillment === 'pickup' ? 'active' : ''}}" data-value="pickup" bindtap="chooseFulfillment">{{template.modeA}}</button><button class="choice {{fulfillment === 'delivery' ? 'active' : ''}}" data-value="delivery" bindtap="chooseFulfillment">{{template.modeB}}</button></view></view>
<brand-card><view class="form"><brand-field label="怎么称呼" placeholder="请输入你的称呼" required value="{{form.customerName}}" bind:change="input" data-key="customerName"/><brand-field label="联系方式" placeholder="手机号或微信号" required value="{{form.wechatId}}" bind:change="input" data-key="wechatId"/><brand-field label="期望时间" placeholder="例如:下周三 14:00" value="{{form.requestedTime}}" bind:change="input" data-key="requestedTime"/><brand-field wx:if="{{fulfillment === 'delivery'}}" label="{{template.locationLabel}}" placeholder="{{template.locationPlaceholder}}" value="{{form.deliveryAddress}}" bind:change="input" data-key="deliveryAddress"/><brand-field label="{{template.requestType === 'package' ? '备注' : '需求说明'}}" placeholder="{{template.notePlaceholder}}" type="textarea" value="{{form.note}}" bind:change="input" data-key="note"/></view></brand-card>
<view class="notice">● {{template.submitNotice}}</view><brand-button loading="{{submitting}}" disabled="{{submitting}}" bind:tap="submit">{{submitting ? '提交中...' : template.submitLabel}}</brand-button>
</view>
@@ -0,0 +1,138 @@
.page {
min-height: 100vh;
padding: 24rpx 32rpx 60rpx;
background: #fbf7f1;
color: #2b2b2b;
}
.product {
display: flex;
align-items: center;
gap: 20rpx;
padding: 20rpx;
background: #f4ebd9;
border-radius: 16rpx;
}
.product-image {
width: 220rpx;
height: 180rpx;
overflow: hidden;
border-radius: 12rpx;
flex: none;
}
.product-image image,
.dish-placeholder {
width: 100%;
height: 100%;
display: block;
background: #c79555;
}
.product-copy {
flex: 1;
}
.name {
display: block;
font-size: 34rpx;
font-weight: 700;
}
.price {
display: block;
margin-top: 18rpx;
color: #b54a2c;
font-size: 38rpx;
}
.available {
color: #7a4a2b;
font-size: 26rpx;
white-space: nowrap;
align-self: flex-start;
margin-top: 14rpx;
}
.quantity,
.fulfillment {
margin-top: 20rpx;
padding: 28rpx;
background: #f4ebd9;
border-radius: 16rpx;
font-size: 32rpx;
}
.stepper {
float: right;
display: flex;
align-items: center;
gap: 18rpx;
}
.stepper button {
width: 56rpx;
height: 56rpx;
line-height: 52rpx;
padding: 0;
border-radius: 50%;
background: #fff;
color: #b54a2c;
}
.field-title {
font-weight: 700;
}
.choices {
display: flex;
gap: 16rpx;
margin-top: 18rpx;
}
.choice {
flex: 1;
border-radius: 12rpx;
background: #7a4a2b;
color: #fff;
}
.choice.active {
background: #b54a2c;
}
.form {
margin-top: 20rpx;
background: #fff;
border-radius: 16rpx;
padding: 8rpx 28rpx;
}
.form label {
display: flex;
justify-content: space-between;
gap: 20rpx;
padding: 28rpx 0;
border-bottom: 1rpx solid #eee;
font-size: 30rpx;
}
.form input,
.form textarea {
flex: 1;
text-align: right;
}
.form textarea {
min-height: 100rpx;
}
.notice {
margin: 20rpx 0;
padding: 24rpx;
background: #f4ebd9;
border-radius: 16rpx;
color: #7a4a2b;
}
.submit {
background: #b54a2c;
color: #fff;
border-radius: 12rpx;
font-size: 34rpx;
}
.stepper button {
display: flex;
width: 64rpx;
height: 64rpx;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: 16rpx;
background: #fff;
color: #b54a2c;
font-size: 40rpx;
line-height: 1;
}
@@ -0,0 +1,78 @@
const TEMPLATES = {
food: {
modeLabels: { pickup: "自取", delivery: "配送" },
contactLabel: "联系摊主",
cancelLabel: "取消预约",
cancelNote: "取消后请及时告知摊主,避免食材浪费。",
hero: "今天吃什么",
heroSub: "现做家常饭",
about: "品牌简介",
description: "个人经营的家常小灶,套餐现做,也可预约小型聚餐和私厨定制。",
primary: "预约套餐",
secondary: "咨询私厨",
timeLabel: "营业时间",
time: "11:00—20:00",
addressLabel: "摊位地址",
address: "校园路社区便民点 12 号",
noteLabel: "配送说明",
note: "满 30 元周边配送,也可自取",
serviceSub: "今日可订",
first: "普通套餐",
firstSub: "日常家常饭",
second: "私厨服务",
secondSub: "聚餐定制",
available: "今日可订",
unavailable: "暂不可订",
empty: "暂无可订服务",
bookingTitle: "预约套餐",
requestType: "package",
modeLabel: "取餐方式",
modeA: "自取",
modeB: "配送",
locationLabel: "配送地址",
locationPlaceholder: "请输入配送地址",
notePlaceholder: "口味、餐具或其他说明",
submitNotice: "提交后由摊主人工确认,确认后再安排制作。",
submitLabel: "提交预约",
},
personal: {
modeLabels: { pickup: "线上沟通", delivery: "线下沟通" },
contactLabel: "联系品牌方",
cancelLabel: "取消申请",
cancelNote: "如需调整,请尽早联系品牌方。",
hero: "个人品牌",
heroSub: "把专业能力,变成值得信赖的体验",
about: "关于我",
description: "这里展示你的专业背景、工作方式与品牌理念。",
primary: "查看服务",
secondary: "发起咨询",
timeLabel: "服务时间",
time: "工作日 10:00—18:00",
addressLabel: "所在位置",
address: "线上 / 线下均可沟通",
noteLabel: "合作说明",
note: "提交需求后,我会尽快与你联系",
serviceSub: "可咨询",
first: "标准服务",
firstSub: "清晰的服务方案",
second: "定制合作",
secondSub: "按需求沟通",
available: "可咨询",
unavailable: "暂不可用",
empty: "暂无可咨询服务",
bookingTitle: "合作咨询",
requestType: "inquiry",
modeLabel: "沟通方式",
modeA: "线上沟通",
modeB: "线下沟通",
locationLabel: "沟通方式或地点",
locationPlaceholder: "请输入会议方式、地点或链接",
notePlaceholder: "请介绍你的需求、预算或期待结果",
submitNotice: "提交后品牌方会与你确认需求、时间和合作方式。",
submitLabel: "提交需求",
},
};
function getTemplate(key) {
return TEMPLATES[key] || TEMPLATES.personal;
}
module.exports = { getTemplate, TEMPLATES };
+6
View File
@@ -0,0 +1,6 @@
{
"name": "@personal-brand/capability-booking",
"version": "1.0.0",
"private": true,
"description": "下单能力的小程序页面,由声明 booking 能力的模板在编译时引入。"
}
@@ -341,28 +341,16 @@ export const generatedTemplatePackageRegistry = [
"capabilityKey": "booking"
}
},
"renderers": {
"home": "acheng-home",
"offerings": "acheng-offerings",
"profile": "acheng-profile"
},
"runtimeOwnedPages": [
"detail",
"inquiry",
"success",
"records"
"pages": [
"pages/index/index",
"pages/services/index",
"pages/stall-service/index",
"pages/bookings/index"
],
"ownedPaths": [
"components/templates/acheng-home",
"components/templates/acheng-offerings",
"components/templates/acheng-profile",
"pages/index",
"pages/services",
"pages/bookings",
"overrides": [
"pages/inquiry",
"pages/stall-service",
"pages/offering",
"pages/inquiry-success",
"pages/offering",
"pages/records"
],
"visualTemplateKey": "acheng-campus-food"
@@ -866,24 +854,13 @@ export const generatedTemplatePackageRegistry = [
"capabilityKey": "inquiry"
}
},
"renderers": {
"home": "linjing-home",
"offerings": "linjing-offerings",
"profile": "linjing-profile"
},
"runtimeOwnedPages": [
"detail",
"inquiry",
"success",
"records"
],
"ownedPaths": [
"components/templates/linjing-home",
"components/templates/linjing-offerings",
"components/templates/linjing-profile"
"pages": [
"pages/index/index",
"pages/services/index",
"pages/bookings/index"
],
"visualTemplateKey": "linjing-editorial"
}
];
export const generatedTemplatePackageRegistryHash =
"6d56212ec96d9b7b99a9e12aa278ca0927dc5e4472ec6ece3098a7d99842897b";
"254f31edcf4073091691fc5f88fced2b5857c60aec3d1175a5f1e44b9e45acd0";
@@ -310,23 +310,11 @@
"capabilityKey": "booking"
}
},
"renderers": {
"home": "acheng-home",
"offerings": "acheng-offerings",
"profile": "acheng-profile"
},
"runtimeOwnedPages": ["detail", "inquiry", "success", "records"],
"ownedPaths": [
"components/templates/acheng-home",
"components/templates/acheng-offerings",
"components/templates/acheng-profile",
"pages/index",
"pages/services",
"pages/bookings",
"pages/inquiry",
"pages/stall-service",
"pages/offering",
"pages/inquiry-success",
"pages/records"
]
"pages": [
"pages/index/index",
"pages/services/index",
"pages/stall-service/index",
"pages/bookings/index"
],
"overrides": ["pages/inquiry", "pages/inquiry-success", "pages/offering", "pages/records"]
}
+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();
+54 -48
View File
@@ -10,6 +10,13 @@ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "
const workspaceRoot = path.resolve(packageRoot, "../..");
const compiler = path.join(packageRoot, "src/cli.mjs");
function assertPageBundle(output, app) {
for (const page of app.pages) {
for (const extension of [".js", ".json", ".wxml", ".wxss"])
assert.equal(fs.existsSync(path.join(output, page + extension)), true, `${page}${extension}`);
}
}
test("compiler generates an isolated Acheng runtime manifest", () => {
const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-"));
execFileSync(process.execPath, [compiler, "--template", "acheng-campus-food", "--out", output], {
@@ -20,58 +27,24 @@ test("compiler generates an isolated Acheng runtime manifest", () => {
const runtime = JSON.parse(fs.readFileSync(path.join(output, "template.runtime.json"), "utf8"));
assert.equal(app.window.navigationBarTitleText, "阿成校园餐");
assert.equal(runtime.packageKey, "acheng-campus-food");
assert.equal(runtime.renderers.home, "acheng-home");
assert.match(fs.readFileSync(path.join(output, "app.js"), "utf8"), /default-brand/);
assert.equal(runtime.entrypoints.home, "pages/index/index");
assert.match(fs.readFileSync(path.join(output, "runtime-config.js"), "utf8"), /default-brand/);
assert.equal(runtime.navigation.length, 5);
assert.equal(runtime.navigation[2].page, "service");
assert.equal(
JSON.parse(fs.readFileSync(path.join(output, "app.json"), "utf8")).tabBar.list.length,
5,
);
assertPageBundle(output, app);
assert.equal(fs.existsSync(path.join(output, "components/runtime-tab-bar")), false);
assert.equal(
fs
.readFileSync(path.join(output, "pages/index/index.wxml"), "utf8")
.includes("runtime-tab-bar"),
false,
);
assert.equal(fs.existsSync(path.join(output, "components/templates/linjing-home")), false);
assert.equal(
fs.existsSync(path.join(output, "components/templates/acheng-home/acheng-home.wxml")),
false,
);
assert.equal(fs.existsSync(path.join(output, "components/template-pages/home/home.wxml")), true);
assert.equal(fs.existsSync(path.join(output, "components/templates")), false);
assert.match(
fs.readFileSync(path.join(output, "pages/index/index.wxml"), "utf8"),
/<template-home/,
);
assert.doesNotMatch(
fs.readFileSync(path.join(output, "pages/index/index.wxml"), "utf8"),
/acheng-home/,
);
assert.equal(
fs.readFileSync(path.join(output, "pages/index/index.wxml"), "utf8").trim().length > 20,
true,
);
assert.doesNotMatch(
fs.readFileSync(path.join(output, "pages/index/index.wxml"), "utf8"),
/pageRenderer ===/,
);
assert.equal(fs.existsSync(path.join(output, "pages/stall-service/index.wxml")), true);
assert.match(
fs.readFileSync(path.join(output, "pages/services/index.wxml"), "utf8"),
/<template-offerings/,
);
assert.match(
fs.readFileSync(path.join(output, "pages/bookings/index.wxml"), "utf8"),
/<template-profile/,
);
assert.equal(
fs
.readFileSync(path.join(output, "pages/inquiry/index.wxml"), "utf8")
.includes("runtime-tab-bar"),
false,
);
assert.equal(fs.existsSync(path.join(output, "pages/booking/index.wxml")), true);
assert.equal(fs.existsSync(path.join(output, "assets/tab/booking.png")), true);
});
test("compiler generates the Linjing navigation contract", () => {
@@ -82,9 +55,10 @@ test("compiler generates the Linjing navigation contract", () => {
});
const runtime = JSON.parse(fs.readFileSync(path.join(output, "template.runtime.json"), "utf8"));
assert.equal(runtime.packageKey, "linjing-editorial");
assert.equal(runtime.renderers.home, "linjing-home");
assert.equal(runtime.renderers.offerings, "linjing-offerings");
assert.match(fs.readFileSync(path.join(output, "app.js"), "utf8"), /linjing-doors/);
assert.equal(runtime.entrypoints.home, "pages/index/index");
assert.match(fs.readFileSync(path.join(output, "runtime-config.js"), "utf8"), /linjing-doors/);
const app = JSON.parse(fs.readFileSync(path.join(output, "app.json"), "utf8"));
assertPageBundle(output, app);
assert.equal(runtime.navigation.length, 3);
assert.equal(runtime.navigation[0].iconPath, "assets/tab/home.png");
assert.equal(
@@ -94,7 +68,7 @@ test("compiler generates the Linjing navigation contract", () => {
assert.equal(fs.existsSync(path.join(output, "assets/tab/works.png")), true);
assert.equal(
fs.existsSync(path.join(output, "components/templates/linjing-home/linjing-home.wxml")),
false,
true,
);
assert.equal(fs.existsSync(path.join(output, "pages/stall-service")), false);
assert.equal(fs.existsSync(path.join(output, "pages/booking")), false);
@@ -102,10 +76,7 @@ test("compiler generates the Linjing navigation contract", () => {
fs.readFileSync(path.join(output, "app.json"), "utf8"),
/stall-service|booking\/index/,
);
assert.match(
fs.readFileSync(path.join(output, "pages/services/index.wxml"), "utf8"),
/<template-offerings/,
);
assert.equal(fs.existsSync(path.join(output, "pages/services/index.wxml")), true);
});
test("release manifest pins every workspace template version", () => {
@@ -124,3 +95,38 @@ test("release manifest pins every workspace template version", () => {
assert.equal(manifest.runtimeContract, releaseConfig.runtimeContract);
}
});
test("compiler rejects production builds without deployment parameters", () => {
assert.throws(
() =>
execFileSync(
process.execPath,
[compiler, "--template", "linjing-editorial", "--env", "prod"],
{ cwd: workspaceRoot },
),
/Production build requires --brand, --appid, --api/,
);
});
test("compiler rejects unknown capabilities before copying layers", () => {
const templateDirectory = fs.mkdtempSync(
path.join(os.tmpdir(), "personal-brand-template-package-"),
);
fs.cpSync(path.join(workspaceRoot, "packages/template-linjing-editorial"), templateDirectory, {
recursive: true,
});
const manifestPath = path.join(templateDirectory, "template.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
manifest.requiredCapabilities.push("missing");
fs.writeFileSync(manifestPath, JSON.stringify(manifest));
const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-"));
assert.throws(
() =>
execFileSync(
process.execPath,
[compiler, "--template-dir", templateDirectory, "--out", output],
{ cwd: workspaceRoot },
),
/requires unknown capability: missing/,
);
});
+10
View File
@@ -1,3 +1,13 @@
# Template Contract
模板包是构建期输入。模板必须声明 runtime contract、页面入口、导航、行业兼容性和能力依赖;不得在模板包中实现数据库访问、鉴权或业务状态机。
## 新增模板
1. 在 `packages/template-<key>/` 创建 `template.json` 和 `miniapp/`。
2. 在 manifest 中声明 `entrypoints`、`pages`、`navigation`、`requiredCapabilities`、数据槽位、媒体槽位和面向管理员的 `admin.sections`。
3. 将模板自己的页面、组件、tab 图标和 `miniapp/app.json` 放入模板包。页面必须提供 `.js`、`.json`、`.wxml`、`.wxss` 四个文件。
4. 如果需要替换运行时或能力包页面,必须在 `overrides` 中声明目录;未声明的同路径文件会被 compiler 拒绝。
5. 执行 `pnpm generate:template-catalog --write`、`pnpm validate:templates` 和 `pnpm test:template-compiler`。
使用 `pnpm template:dev <key> --brand <slug>` 生成微信开发者工具项目。生产构建还必须提供 `--appid` 和 HTTPS `--api`。模板在构建时选择,运行时不会下载或解释模板代码。
+65 -12
View File
@@ -3,9 +3,13 @@ export const TEMPLATE_RUNTIME_CONTRACT = "1.0" as const;
export type TemplatePageKey =
"home" | "offerings" | "detail" | "inquiry" | "success" | "records" | "profile" | (string & {});
export type TemplateRenderers = Partial<Record<"home" | "offerings" | "profile", string>>;
/** 运行时(apps/miniapp)提供的核心能力,不需要能力包。 */
export const CORE_CAPABILITIES = ["offerings", "inquiry"] as const;
export type TemplateRuntimeOwnedPage = "detail" | "inquiry" | "success" | "records";
/** 小程序页面路径,例如 `pages/index/index`,不带扩展名。 */
const PAGE_PATH_PATTERN = /^pages\/[a-z0-9-]+(\/[a-z0-9-]+)*$/;
/** 叠加路径:页面目录或组件目录,例如 `pages/inquiry`、`components/templates/acheng-home`。 */
const LAYER_PATH_PATTERN = /^(pages|components)\/[a-z0-9-]+(\/[a-z0-9-]+)*$/;
/**
* 模板向平台声明的内容来源。它只描述稳定的业务事实,不描述页面结构或 renderer。
@@ -83,9 +87,12 @@ export type TemplatePackageManifest = {
selectedIconPath?: string;
}>;
requiredCapabilities: string[];
renderers?: TemplateRenderers;
runtimeOwnedPages?: TemplateRuntimeOwnedPage[];
ownedPaths?: string[];
/** 模板包自己提供的页面;编译器据此生成 app.json。 */
pages: string[];
/** 模板替换运行时或能力包中的页面/组件目录;未声明的同名文件视为冲突。 */
overrides?: string[];
/** 开发时的默认品牌;构建参数 `--brand` 优先。 */
defaultBrandSlug?: string;
dataSlots: TemplateDataSlot[];
assetSlots: TemplateAssetSlot[];
admin: TemplateAdminManifest;
@@ -139,13 +146,25 @@ export function validateTemplatePackageManifest(value: unknown): string[] {
}
}
}
if (manifest.ownedPaths !== undefined && !Array.isArray(manifest.ownedPaths))
errors.push("ownedPaths must be an array when provided");
if (
manifest.renderers !== undefined &&
(typeof manifest.renderers !== "object" || Array.isArray(manifest.renderers))
)
errors.push("renderers must be an object when provided");
if (!Array.isArray(manifest.requiredCapabilities))
errors.push("requiredCapabilities must be an array");
if (!Array.isArray(manifest.pages) || !manifest.pages.length)
errors.push("pages must not be empty");
else if (manifest.pages.some((page) => typeof page !== "string" || !PAGE_PATH_PATTERN.test(page)))
errors.push("pages must contain mini program page paths such as pages/index/index");
if (manifest.overrides !== undefined) {
if (
!Array.isArray(manifest.overrides) ||
manifest.overrides.some((item) => typeof item !== "string" || !LAYER_PATH_PATTERN.test(item))
)
errors.push("overrides must contain pages/... or components/... directories");
}
for (const item of manifest.navigation ?? []) {
if (!item?.key?.trim() || !item.label?.trim())
errors.push("navigation items require key and label");
if (typeof item?.page !== "string" || typeof manifest.entrypoints?.[item.page] !== "string")
errors.push(`navigation page is not a declared entrypoint: ${String(item?.key)}`);
}
for (const page of [
"home",
"offerings",
@@ -158,6 +177,10 @@ export function validateTemplatePackageManifest(value: unknown): string[] {
if (!manifest.entrypoints || typeof manifest.entrypoints[page] !== "string")
errors.push(`entrypoints.${page} is required`);
}
for (const [key, page] of Object.entries(manifest.entrypoints ?? {})) {
if (typeof page !== "string" || !PAGE_PATH_PATTERN.test(page))
errors.push(`entrypoints.${key} must be a mini program page path`);
}
if (manifest.sampleContent !== undefined) {
for (const [industryKey, sample] of Object.entries(manifest.sampleContent)) {
if (!manifest.supportedIndustryTemplates?.includes(industryKey))
@@ -180,3 +203,33 @@ export function validateTemplatePackageManifest(value: unknown): string[] {
}
return errors;
}
/**
* 能力包清单(packages/capability-<key>/capability.json)。
* 能力包为需要独立业务流程的能力提供小程序页面,由模板的 requiredCapabilities 引入。
*/
export type CapabilityPackageManifest = {
key: string;
version: string;
runtimeContract: typeof TEMPLATE_RUNTIME_CONTRACT;
description: string;
pages: string[];
};
export function validateCapabilityPackageManifest(value: unknown): string[] {
const errors: string[] = [];
if (!value || typeof value !== "object") return ["capability manifest must be an object"];
const manifest = value as Partial<CapabilityPackageManifest>;
if (!manifest.key?.trim()) errors.push("key is required");
if ((CORE_CAPABILITIES as readonly string[]).includes(manifest.key ?? ""))
errors.push(`${manifest.key} is a core capability provided by the runtime`);
if (!manifest.version?.trim()) errors.push("version is required");
if (manifest.runtimeContract !== TEMPLATE_RUNTIME_CONTRACT)
errors.push(`runtimeContract must be ${TEMPLATE_RUNTIME_CONTRACT}`);
if (!manifest.description?.trim()) errors.push("description is required");
if (!Array.isArray(manifest.pages) || !manifest.pages.length)
errors.push("pages must not be empty");
else if (manifest.pages.some((page) => typeof page !== "string" || !PAGE_PATH_PATTERN.test(page)))
errors.push("pages must contain mini program page paths");
return errors;
}
@@ -0,0 +1,37 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
const { customerRequest, customerTokenKey } = require("../../utils/request");
Page({
data: { brand: {}, records: [], error: "" },
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) => this.setData({ brand: workspace.brand || {} }))
.catch((error) => this.setData({ error: error.message }));
},
onShow() {
this.loadRecords();
},
loadRecords() {
if (!wx.getStorageSync(customerTokenKey())) return this.setData({ records: [] });
customerRequest("/customer/inquiry-submissions")
.then((records) => this.setData({ records: Array.isArray(records) ? records : [] }))
.catch(() => this.setData({ records: [] }));
},
call() {
wx.makePhoneCall({
phoneNumber: (this.data.brand.phone || this.data.brand.contactPhone || "").replace(
/[^0-9-]/g,
"",
),
});
},
copyWechat() {
wx.setClipboardData({
data: this.data.brand.wechat || this.data.brand.contactWechat || "",
success: () => wx.showToast({ title: "微信号已复制", icon: "none" }),
});
},
recordsPage() {
wx.navigateTo({ url: "/pages/records/index" });
},
});
@@ -0,0 +1,8 @@
{
"navigationBarTitleText": "主理人与我",
"navigationBarBackgroundColor": "#FBF7F1",
"navigationBarTextStyle": "black",
"usingComponents": {
"linjing-profile": "/components/templates/linjing-profile/linjing-profile"
}
}
@@ -0,0 +1,4 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<linjing-profile wx:else brand="{{brand}}" presentation="{{brand.visualPresentation.profile}}" records-count="{{records.length}}" bind:call="call" bind:copy="copyWechat" bind:records="recordsPage" />
</view>
@@ -0,0 +1 @@
/* 页面样式由林境模板组件提供。 */
@@ -0,0 +1,41 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
Page({
data: {
brand: {},
trustContent: {},
offerings: [],
hero: { image: "", eyebrow: "", title: "", slogan: "", cta: "" },
error: "",
},
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) => {
const brand = workspace.brand || {};
const offerings = workspace.offerings || [];
const configuredHero =
brand.homeHero && typeof brand.homeHero === "object" ? brand.homeHero : {};
this.setData({
brand,
trustContent: workspace.trustPresentation || {},
offerings,
hero: {
...this.data.hero,
image: brand.heroImage || "",
eyebrow: brand.tagline || brand.name,
title: (offerings[0] && offerings[0].name) || brand.name,
slogan: brand.description || "",
...configuredHero,
},
});
wx.setNavigationBarTitle({ title: brand.name || "个人品牌" });
})
.catch((error) => this.setData({ error: error.message }));
},
selectOffering(event) {
wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id });
},
goWorks() {
wx.switchTab({ url: "/pages/services/index" });
},
});
@@ -0,0 +1,6 @@
{
"navigationBarTitleText": "品牌首页",
"usingComponents": {
"linjing-home": "/components/templates/linjing-home/linjing-home"
}
}
@@ -0,0 +1,4 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<linjing-home wx:else brand="{{brand}}" presentation="{{brand.visualPresentation.home}}" hero="{{hero}}" trust-content="{{trustContent}}" offerings="{{offerings}}" bind:select="selectOffering" bind:works="goWorks" />
</view>
@@ -0,0 +1 @@
/* 页面样式由林境模板组件提供。 */
@@ -0,0 +1,22 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
Page({
data: { brand: {}, presentation: {}, offerings: [], error: "" },
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) =>
this.setData({
brand: workspace.brand || {},
presentation: workspace.brand?.visualPresentation?.offerings || {},
offerings: workspace.offerings || [],
}),
)
.catch((error) => this.setData({ error: error.message }));
},
open(event) {
wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id });
},
inquire() {
wx.navigateTo({ url: "/pages/inquiry/index" });
},
});
@@ -0,0 +1,8 @@
{
"navigationBarTitleText": "案例与体系",
"navigationBarBackgroundColor": "#FBF7F1",
"navigationBarTextStyle": "black",
"usingComponents": {
"linjing-offerings": "/components/templates/linjing-offerings/linjing-offerings"
}
}
@@ -0,0 +1,4 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<linjing-offerings wx:else brand="{{brand}}" presentation="{{presentation}}" offerings="{{offerings}}" bind:open="open" bind:more="inquire" />
</view>
@@ -0,0 +1 @@
/* 页面样式由林境模板组件提供。 */
@@ -413,15 +413,5 @@
"capabilityKey": "inquiry"
}
},
"renderers": {
"home": "linjing-home",
"offerings": "linjing-offerings",
"profile": "linjing-profile"
},
"runtimeOwnedPages": ["detail", "inquiry", "success", "records"],
"ownedPaths": [
"components/templates/linjing-home",
"components/templates/linjing-offerings",
"components/templates/linjing-profile"
]
"pages": ["pages/index/index", "pages/services/index", "pages/bookings/index"]
}