From a97cc860cf07cf6216fc5471982648d62d5b1fbd Mon Sep 17 00:00:00 2001 From: que01 Date: Sun, 27 Sep 2026 06:55:56 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=A1=A5=E9=BD=90=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E6=89=A9=E5=B1=95=E6=80=A7=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E4=B8=8E=E6=BC=94=E7=BB=83=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增第二行业演练模板 drill-consultant,验证新增行业无需修改编译器和运行��� - 补充 override 冲突与显式覆盖测试,产物校验覆盖 wxss - 修复 --template-dir 模板被误判引用其他模板组件的问题 - 修复运行时排除规则误删 TDesign 深层 src 目录,增加 miniprogram_npm 完整性回归 - 模板目录校验统一复用 template-contract,新增 template:check 并接入 pnpm check - tabBar 配色归属模板包,清理编译器过期排除项和旧 fixture - ADR 0015 明确对 0005/0008/0009 的替换范围 Co-Authored-By: Claude Opus 5.5 (1M context) --- .../SUBTASKS.csv | 2 +- .../miniapp/test/fixtures/doors-industry.json | 19 ----- apps/miniapp/test/fixtures/linjing-door.json | 24 ------ apps/miniapp/test/validate-fixture.cjs | 48 +---------- .../0015-template-build-time-composition.md | 10 ++- docs/template-runtime-progress.md | 3 +- package.json | 3 +- .../miniapp/app.json | 6 ++ packages/template-compiler/src/cli.mjs | 36 +++----- packages/template-compiler/test/cli.test.mjs | 85 ++++++++++++++++++- .../template-drill-consultant/README.md | 5 ++ .../templates/drill-card/drill-card.js | 13 +++ .../templates/drill-card/drill-card.json | 3 + .../templates/drill-card/drill-card.wxml | 5 ++ .../templates/drill-card/drill-card.wxss | 18 ++++ .../miniapp/pages/index/index.js | 23 +++++ .../miniapp/pages/index/index.json | 6 ++ .../miniapp/pages/index/index.wxml | 22 +++++ .../miniapp/pages/index/index.wxss | 24 ++++++ .../miniapp/pages/profile/index.js | 16 ++++ .../miniapp/pages/profile/index.json | 7 ++ .../miniapp/pages/profile/index.wxml | 10 +++ .../miniapp/pages/profile/index.wxss | 9 ++ .../miniapp/pages/services/index.js | 13 +++ .../miniapp/pages/services/index.json | 7 ++ .../miniapp/pages/services/index.wxml | 13 +++ .../miniapp/pages/services/index.wxss | 3 + .../template-drill-consultant/template.json | 58 +++++++++++++ packages/template-contract/README.md | 4 +- .../miniapp/app.json | 8 ++ scripts/validate-template-packages.cjs | 73 ++++++++-------- 31 files changed, 418 insertions(+), 158 deletions(-) delete mode 100644 apps/miniapp/test/fixtures/doors-industry.json delete mode 100644 apps/miniapp/test/fixtures/linjing-door.json create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/README.md create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.js create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.json create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxml create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxss create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.js create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.json create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxml create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxss create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.js create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.json create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxml create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxss create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.js create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.json create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxml create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxss create mode 100644 packages/template-compiler/test/fixtures/template-drill-consultant/template.json create mode 100644 packages/template-linjing-editorial/miniapp/app.json diff --git a/.codex-tasks/template-build-time-composition/SUBTASKS.csv b/.codex-tasks/template-build-time-composition/SUBTASKS.csv index c1cb501..e653a36 100644 --- a/.codex-tasks/template-build-time-composition/SUBTASKS.csv +++ b/.codex-tasks/template-build-time-composition/SUBTASKS.csv @@ -3,4 +3,4 @@ id,title,status,depends_on,validation,notes 2,清理运行时模板代码与资源,DONE,1,rg -n 'acheng|linjing|pageRenderer|templateKey ===' apps/miniapp,运行时生产目录无模板专属代码 3,迁移 booking 能力包,DONE,1,node packages/template-compiler/src/cli.mjs --template acheng-campus-food, 4,完善两个模板包页面与资产,DONE,1;2,node packages/template-compiler/src/cli.mjs --template linjing-editorial,林境页面和 tab 资源已迁移并编译通过 -5,补齐测试、演练模板和文档,IN_PROGRESS,1;2;3;4,pnpm check,编译器测试、模板校验、fixture、lint、typecheck 通过;format 全仓受既有 settings 文件阻塞 +5,补齐测试、演练模板和文档,DONE,1;2;3;4,pnpm check,Claude 补齐 drill-consultant 演练模板、override 冲突测试、统一校验和 template:check;pnpm check 全部通过 diff --git a/apps/miniapp/test/fixtures/doors-industry.json b/apps/miniapp/test/fixtures/doors-industry.json deleted file mode 100644 index bcae965..0000000 --- a/apps/miniapp/test/fixtures/doors-industry.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "templateKey": "doors", - "version": "1.0.0", - "pages": ["home", "offerings", "detail", "inquiry", "success", "records", "profile"], - "layout": { "home": ["brand-hero", "founder-card", "trust-proof", "offering-list"] }, - "requiredModules": [ - "brand-hero", - "founder-card", - "trust-proof", - "offering-list", - "offering-detail", - "inquiry-form", - "records", - "profile", - "success-summary" - ], - "requiredCapabilities": ["offerings", "inquiry"], - "visualAnchors": { "home": ["brand-hero", "founder-card", "trust-proof", "offering-list"] } -} diff --git a/apps/miniapp/test/fixtures/linjing-door.json b/apps/miniapp/test/fixtures/linjing-door.json deleted file mode 100644 index b563faa..0000000 --- a/apps/miniapp/test/fixtures/linjing-door.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "templateKey": "linjing-door", - "version": "1.0.0", - "pages": ["home", "offerings", "detail", "inquiry", "success", "records", "profile"], - "layout": { - "home": ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"] - }, - "requiredModules": [ - "brand-hero", - "founder-card", - "trust-proof", - "trust-manifesto", - "offering-list", - "offering-detail", - "inquiry-form", - "records", - "profile", - "success-summary" - ], - "requiredCapabilities": ["offerings", "inquiry"], - "visualAnchors": { - "home": ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"] - } -} diff --git a/apps/miniapp/test/validate-fixture.cjs b/apps/miniapp/test/validate-fixture.cjs index 78f9607..f607ae8 100644 --- a/apps/miniapp/test/validate-fixture.cjs +++ b/apps/miniapp/test/validate-fixture.cjs @@ -1,11 +1,8 @@ const fs = require("node:fs"); const path = require("node:path"); -const os = require("node:os"); -const { execFileSync } = require("node:child_process"); const root = path.resolve(__dirname, ".."); const requestSource = fs.readFileSync(path.join(root, "utils/request.js"), "utf8"); const configSource = fs.readFileSync(path.join(root, "utils/config.js"), "utf8"); -const runtimeRequestSource = fs.readFileSync(path.join(root, "utils/request.js"), "utf8"); if ( !requestSource.includes('path.startsWith("/public/")') || !requestSource.includes("brandSlug") || @@ -15,8 +12,8 @@ if ( process.exit(1); } if ( - !runtimeRequestSource.includes('path.startsWith("/customer/session/wechat")') || - !runtimeRequestSource.includes('"customerToken:" + config.brandSlug') + !requestSource.includes('path.startsWith("/customer/session/wechat")') || + !requestSource.includes('"customerToken:" + config.brandSlug') ) { console.error("miniapp: customer sessions must be brand-scoped"); process.exit(1); @@ -41,10 +38,7 @@ for (const term of ["林境门", "亲自主理量房", "拒绝流水线拼装", process.exit(1); } } -const fixtureFiles = ["linjing-door.json", "doors-industry.json"]; -const fixtures = fixtureFiles.map((file) => - JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures", file), "utf8")), -); +// 各模板的页面完整性由 template-contract 与 test:visual-fixture(自动发现全部模板并编译)负责。 const doorsContent = JSON.parse( fs.readFileSync(path.join(__dirname, "fixtures", "doors-content.json"), "utf8"), ); @@ -60,42 +54,6 @@ if (!doorsContent.offerings.every((item) => item.kind === "product" || item.kind console.error("doors: offerings must use shared product or service kinds"); process.exit(1); } -for (const fixture of fixtures) { - const pageMap = { - home: "pages/index/index", - offerings: "pages/services/index", - detail: "pages/offering/detail", - inquiry: "pages/inquiry/index", - success: "pages/inquiry-success/index", - records: "pages/records/index", - profile: "pages/bookings/index", - }; - const templateKey = fixture.templateKey.startsWith("acheng") - ? "acheng-campus-food" - : "linjing-editorial"; - const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-fixture-")); - execFileSync( - process.execPath, - [ - path.resolve(root, "../../packages/template-compiler/src/cli.mjs"), - "--template", - templateKey, - "--out", - output, - ], - { stdio: "ignore" }, - ); - const missingPages = fixture.pages.filter( - (key) => !fs.existsSync(path.join(output, `${pageMap[key]}.json`)), - ); - if (missingPages.length) { - console.error(`${fixture.templateKey}: missing page manifests: ${missingPages.join(", ")}`); - process.exit(1); - } - console.log( - `Fixture ${fixture.templateKey}@${fixture.version} passed: ${fixture.pages.length} pages.`, - ); -} console.log( `Content fixture doors passed: ${doorsContent.offerings.length} offerings, ${doorsContent.trustContent.length} trust entries, ${doorsContent.inquiryFields.length} inquiry fields.`, ); diff --git a/docs/adr/0015-template-build-time-composition.md b/docs/adr/0015-template-build-time-composition.md index ed19b5e..bcb6621 100644 --- a/docs/adr/0015-template-build-time-composition.md +++ b/docs/adr/0015-template-build-time-composition.md @@ -22,10 +22,18 @@ - 运行时下载 WXML/JS 模板:微信小程序安全和编译模型不支持,放弃。 - 每个模板独立复制完整小程序:公共能力重复、修复无法统一,放弃。 +## 与既有 ADR 的关系 + +本决定只替换"小程序如何选择和渲染模板",不改变业务数据、能力和兼容性声明: + +- **ADR 0005**:替换第 3 节中"小程序只消费 Runtime Workspace 的 `modules`/`theme` 并按模块渲染"以及 Phase 2 的"模块顺序、可见性和模块变体"。Runtime Workspace 仍是品牌、Offering、表单、能力的数据契约,但页面结构由模板包在构建时决定。第 4 节 Capability Plugin 保持,并新增小程序页面以 `packages/capability-*` 形式交付。 +- **ADR 0008**:替换迁移计划第 3 步"Miniapp 页面按页面 schema 和模块 registry 渲染"。模块 registry 已退役,模板包直接提供页面和组件;manifest 的数据槽位、资源槽位和安装边界保持。 +- **ADR 0009**:`supportedIndustryTemplates` 兼容声明保持有效。其中"实际切换"只影响后台记录和 Runtime Workspace,不会改变已构建的小程序。 + ## 后果 新增模板只需新增 package 和 manifest,不需要改 compiler 或 runtime。模板包需要自行提供 manifest 声明的页面四件套和 tab 资源,编译测试会阻止缺页、缺图标、组件引用或 `require` 路径错误。后台视觉模板切换不会直接改变已构建小程序,后台切换历史和回滚属于后续治理任务。 ## 迁移计划 -先完成阿成、林境两个模板和 `booking` capability 的迁移,再增加第二行业演练模板。每个新增模板必须通过 compiler 产物校验、模板契约校验和小程序 fixture 检查后才能进入目录 registry。 +阿成、林境两个模板和 `booking` capability 已迁移。`packages/template-compiler/test/fixtures/template-drill-consultant` 是第二行业演练模板,只用模板包自有页面和运行时通用组件,作为"新增行业不改 compiler/runtime"的回归门禁。每个新增模板必须通过 `pnpm template:check`(契约校验、compiler 产物校验、全部模板自动发现编译)后才能进入目录 registry。 diff --git a/docs/template-runtime-progress.md b/docs/template-runtime-progress.md index 7e814dc..ef51812 100644 --- a/docs/template-runtime-progress.md +++ b/docs/template-runtime-progress.md @@ -12,7 +12,8 @@ - [x] 阿成、林境页面与 tab 资源已迁入独立模板包,Runtime 不再携带行业页面和模板组件。 - [x] `booking` 下单页面已迁入 `packages/capability-booking`。 - [x] 编译产物校验覆盖页面文件、组件引用、`require`、tab 图标、品牌参数和能力依赖错误。 -- [ ] 增加第二行业最小演练模板并接入视觉截图回归。 +- [x] 增加第二行业最小演练模板(`packages/template-compiler/test/fixtures/template-drill-consultant`),并由 `pnpm template:check` 门禁。 +- [ ] 接入视觉截图回归。 ## 阶段状态 diff --git a/package.json b/package.json index 801dca2..c567e0e 100644 --- a/package.json +++ b/package.json @@ -13,13 +13,14 @@ "typecheck": "turbo run typecheck", "format": "prettier --write .", "format:check": "prettier --check .", - "check": "pnpm format:check && pnpm lint && pnpm typecheck", + "check": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check", "db:migrate": "pnpm --filter @personal-brand/api db:migrate", "db:seed": "pnpm --filter @personal-brand/api db:seed", "test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts", "validate:templates": "node scripts/validate-template-packages.cjs && pnpm --filter @personal-brand/template-contract test", "generate:template-catalog": "node scripts/generate-template-catalog.cjs --write", "template:dev": "node packages/template-compiler/src/cli.mjs --template", + "template:check": "pnpm validate:templates && pnpm test:template-compiler && pnpm --filter @personal-brand/miniapp test:visual-fixture", "validate:template-release": "node scripts/validate-template-release.cjs", "test:template-compiler": "pnpm --filter @personal-brand/template-compiler test", "clean": "turbo run clean && rimraf node_modules .turbo" diff --git a/packages/template-acheng-campus-food/miniapp/app.json b/packages/template-acheng-campus-food/miniapp/app.json index 9f44320..bfd85db 100644 --- a/packages/template-acheng-campus-food/miniapp/app.json +++ b/packages/template-acheng-campus-food/miniapp/app.json @@ -4,5 +4,11 @@ "navigationBarTitleText": "阿成校园餐", "navigationBarBackgroundColor": "#FFF8F0", "navigationBarTextStyle": "black" + }, + "tabBar": { + "color": "#8b8178", + "selectedColor": "#3b2118", + "backgroundColor": "#ffffff", + "borderStyle": "white" } } diff --git a/packages/template-compiler/src/cli.mjs b/packages/template-compiler/src/cli.mjs index 3cb9e2f..f676d24 100644 --- a/packages/template-compiler/src/cli.mjs +++ b/packages/template-compiler/src/cli.mjs @@ -29,18 +29,9 @@ const RUNTIME_EXCLUDES = new Set([ "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"]; +const PAGE_EXTENSIONS = [".js", ".json", ".wxml", ".wxss"]; class CompileError extends Error {} @@ -56,15 +47,12 @@ 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(entry.name) || - [...exclude].some((value) => entryPath === value || entryPath.startsWith(value + "/")) - ) - continue; + 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)); @@ -202,6 +190,7 @@ function buildAppJson(manifest, templateDirectory, capabilities) { 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, @@ -212,8 +201,8 @@ function buildAppJson(manifest, templateDirectory, capabilities) { ...(templateApp.window || {}), }, tabBar: { - color: tabBarStyle.color || "#8b8178", - selectedColor: tabBarStyle.selectedColor || "#3b2118", + color: tabBarStyle.color || "#7a7a7a", + selectedColor: tabBarStyle.selectedColor || "#1a1a1a", backgroundColor: tabBarStyle.backgroundColor || "#ffffff", borderStyle: tabBarStyle.borderStyle || "white", list: manifest.navigation.map((item) => ({ @@ -276,12 +265,15 @@ function writeGeneratedFiles(output, manifest, params, appJson, capabilities) { ); } -function otherTemplateComponentNames(currentDirectory) { +// 按 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); - if (path.resolve(directory) === path.resolve(currentDirectory)) continue; + 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); @@ -306,7 +298,7 @@ function resolveRequire(output, fromFile, reference) { } /** 校验产物可以被微信开发者工具直接打开:页面、组件、require、图标和模板隔离。 */ -function validateOutput(output, appJson, templateDirectory) { +function validateOutput(output, appJson, packageKey) { const errors = []; const warnings = []; for (const page of appJson.pages) { @@ -322,7 +314,7 @@ function validateOutput(output, appJson, templateDirectory) { } } const hasNpm = fs.existsSync(path.join(output, "miniprogram_npm")); - const forbiddenComponents = otherTemplateComponentNames(templateDirectory); + const forbiddenComponents = otherTemplateComponentNames(packageKey); const sourceFiles = listFiles(output, new Set(["miniprogram_npm"])).filter((file) => /\.(js|json|wxml)$/.test(file), ); @@ -393,7 +385,7 @@ export function compileTemplate(options) { ); const appJson = buildAppJson(manifest, templateDirectory, capabilities); writeGeneratedFiles(output, manifest, params, appJson, capabilities); - const { errors, warnings } = validateOutput(output, appJson, templateDirectory); + 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 }; } diff --git a/packages/template-compiler/test/cli.test.mjs b/packages/template-compiler/test/cli.test.mjs index 596c04a..38c8784 100644 --- a/packages/template-compiler/test/cli.test.mjs +++ b/packages/template-compiler/test/cli.test.mjs @@ -45,6 +45,14 @@ test("compiler generates an isolated Acheng runtime manifest", () => { assert.equal(fs.existsSync(path.join(output, "pages/stall-service/index.wxml")), true); assert.equal(fs.existsSync(path.join(output, "pages/booking/index.wxml")), true); assert.equal(fs.existsSync(path.join(output, "assets/tab/booking.png")), true); + // 运行时的 npm 构建产物必须完整复制,不能被按名称排除的 src/test/dist 误伤。 + const runtimeNpm = path.join(workspaceRoot, "apps/miniapp/miniprogram_npm"); + if (fs.existsSync(runtimeNpm)) { + for (const file of fs.readdirSync(runtimeNpm, { recursive: true })) { + if (fs.statSync(path.join(runtimeNpm, file)).isFile()) + assert.equal(fs.existsSync(path.join(output, "miniprogram_npm", file)), true, file); + } + } }); test("compiler generates the Linjing navigation contract", () => { @@ -108,13 +116,82 @@ test("compiler rejects production builds without deployment parameters", () => { ); }); -test("compiler rejects unknown capabilities before copying layers", () => { - const templateDirectory = fs.mkdtempSync( - path.join(os.tmpdir(), "personal-brand-template-package-"), +test("a second-industry template compiles without compiler or runtime changes", () => { + const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-")); + execFileSync( + process.execPath, + [ + compiler, + "--template-dir", + path.join(packageRoot, "test/fixtures/template-drill-consultant"), + "--out", + output, + ], + { cwd: workspaceRoot, stdio: "inherit" }, ); - fs.cpSync(path.join(workspaceRoot, "packages/template-linjing-editorial"), templateDirectory, { + const app = JSON.parse(fs.readFileSync(path.join(output, "app.json"), "utf8")); + assertPageBundle(output, app); + assert.equal(app.pages[0], "pages/index/index"); + for (const page of ["pages/offering/detail", "pages/inquiry/index", "pages/records/index"]) + assert.equal(app.pages.includes(page), true, page); + assert.deepEqual( + app.tabBar.list.map((item) => item.pagePath), + ["pages/index/index", "pages/services/index", "pages/profile/index"], + ); + assert.equal(fs.existsSync(path.join(output, "pages/booking")), false); + assert.deepEqual(fs.readdirSync(path.join(output, "components/templates")), ["drill-card"]); + assert.match(fs.readFileSync(path.join(output, "runtime-config.js"), "utf8"), /drill-consultant/); +}); + +function copyTemplate(key) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-package-")); + fs.cpSync(path.join(workspaceRoot, `packages/template-${key}`), directory, { recursive: true }); + return directory; +} + +test("compiler rejects template files that shadow runtime files without overrides", () => { + const templateDirectory = copyTemplate("linjing-editorial"); + fs.cpSync( + path.join(workspaceRoot, "apps/miniapp/pages/records"), + path.join(templateDirectory, "miniapp/pages/records"), + { recursive: true }, + ); + const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-")); + assert.throws( + () => + execFileSync( + process.execPath, + [compiler, "--template-dir", templateDirectory, "--out", output], + { cwd: workspaceRoot, stdio: "pipe" }, + ), + /conflicts with runtime at pages\/records\/index\.(js|json|wxml|wxss); declare it in overrides/, + ); +}); + +test("compiler lets a template replace a runtime page declared in overrides", () => { + const templateDirectory = copyTemplate("linjing-editorial"); + const pageDirectory = path.join(templateDirectory, "miniapp/pages/records"); + fs.cpSync(path.join(workspaceRoot, "apps/miniapp/pages/records"), pageDirectory, { recursive: true, }); + fs.appendFileSync(path.join(pageDirectory, "index.wxml"), "\n"); + const manifestPath = path.join(templateDirectory, "template.json"); + const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + manifest.overrides = [...(manifest.overrides || []), "pages/records"]; + fs.writeFileSync(manifestPath, JSON.stringify(manifest)); + const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-")); + execFileSync(process.execPath, [compiler, "--template-dir", templateDirectory, "--out", output], { + cwd: workspaceRoot, + stdio: "pipe", + }); + assert.match( + fs.readFileSync(path.join(output, "pages/records/index.wxml"), "utf8"), + /template override/, + ); +}); + +test("compiler rejects unknown capabilities before copying layers", () => { + const templateDirectory = copyTemplate("linjing-editorial"); const manifestPath = path.join(templateDirectory, "template.json"); const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); manifest.requiredCapabilities.push("missing"); diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/README.md b/packages/template-compiler/test/fixtures/template-drill-consultant/README.md new file mode 100644 index 0000000..ac54caf --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/README.md @@ -0,0 +1,5 @@ +# 第二行业演练模板 + +编译器扩展性的回归门禁。它是一个最小的咨询师模板:只包含模板包自己的页面和组件,数据访问、详情、咨询、记录等页面全部来自运行时。 + +`packages/template-compiler/test/cli.test.mjs` 会编译它。如果为了让它通过而必须修改编译器或 `apps/miniapp`,说明新增行业仍然需要改平台代码,应先修正平台边界。 diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.js b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.js new file mode 100644 index 0000000..7da0e66 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.js @@ -0,0 +1,13 @@ +Component({ + properties: { + itemId: { type: String, value: "" }, + title: { type: String, value: "" }, + desc: { type: String, value: "" }, + meta: { type: String, value: "" }, + }, + methods: { + open() { + if (this.data.itemId) this.triggerEvent("open", { id: this.data.itemId }); + }, + }, +}); diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.json b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.json new file mode 100644 index 0000000..467ce29 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.json @@ -0,0 +1,3 @@ +{ + "component": true +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxml b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxml new file mode 100644 index 0000000..ac8f5a1 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxml @@ -0,0 +1,5 @@ + + {{title}} + {{desc}} + {{meta}} + diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxss b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxss new file mode 100644 index 0000000..b9f626f --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/components/templates/drill-card/drill-card.wxss @@ -0,0 +1,18 @@ +.drill-card { + margin: 24rpx 32rpx; + padding: 32rpx; + border-radius: 16rpx; + background: #ffffff; +} + +.drill-card__title { + font-size: 32rpx; + font-weight: 600; +} + +.drill-card__desc, +.drill-card__meta { + margin-top: 12rpx; + font-size: 26rpx; + color: #666666; +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.js b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.js new file mode 100644 index 0000000..2404351 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.js @@ -0,0 +1,23 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); + +Page({ + data: { brand: {}, offerings: [], error: "" }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => { + const brand = workspace.brand || {}; + this.setData({ brand, offerings: (workspace.offerings || []).slice(0, 3) }); + wx.setNavigationBarTitle({ title: brand.name || "个人品牌" }); + }) + .catch((error) => this.setData({ error: error.message })); + }, + open(event) { + wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id }); + }, + goServices() { + wx.switchTab({ url: "/pages/services/index" }); + }, + inquire() { + wx.navigateTo({ url: "/pages/inquiry/index" }); + }, +}); diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.json b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.json new file mode 100644 index 0000000..c1385c3 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.json @@ -0,0 +1,6 @@ +{ + "usingComponents": { + "drill-card": "/components/templates/drill-card/drill-card", + "brand-button": "/components/ui/brand-button/brand-button" + } +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxml b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxml new file mode 100644 index 0000000..494a791 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxml @@ -0,0 +1,22 @@ + + {{error}} + + + {{brand.name}} + {{brand.tagline || brand.description}} + + + + 查看全部服务 + 预约咨询 + + + diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxss b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxss new file mode 100644 index 0000000..1e23120 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/index/index.wxss @@ -0,0 +1,24 @@ +.drill-hero { + padding: 64rpx 32rpx 32rpx; +} + +.drill-hero__name { + font-size: 44rpx; + font-weight: 700; +} + +.drill-hero__tagline { + margin-top: 16rpx; + font-size: 28rpx; + color: #666666; +} + +.drill-actions { + padding: 32rpx; +} + +.drill-link { + margin-bottom: 24rpx; + font-size: 28rpx; + text-align: center; +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.js b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.js new file mode 100644 index 0000000..0695349 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.js @@ -0,0 +1,16 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); + +Page({ + data: { brand: {}, error: "" }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => this.setData({ brand: workspace.brand || {} })) + .catch((error) => this.setData({ error: error.message })); + }, + openRecords() { + wx.navigateTo({ url: "/pages/records/index" }); + }, + inquire() { + wx.navigateTo({ url: "/pages/inquiry/index" }); + }, +}); diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.json b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.json new file mode 100644 index 0000000..22d466e --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.json @@ -0,0 +1,7 @@ +{ + "navigationBarTitleText": "关于我", + "usingComponents": { + "drill-card": "/components/templates/drill-card/drill-card", + "brand-button": "/components/ui/brand-button/brand-button" + } +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxml b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxml new file mode 100644 index 0000000..4b5da36 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxml @@ -0,0 +1,10 @@ + + {{error}} + + + + 我的咨询记录 + 预约咨询 + + + diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxss b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxss new file mode 100644 index 0000000..454d9da --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/profile/index.wxss @@ -0,0 +1,9 @@ +.drill-actions { + padding: 32rpx; +} + +.drill-link { + margin-bottom: 24rpx; + font-size: 28rpx; + text-align: center; +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.js b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.js new file mode 100644 index 0000000..ce12ebc --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.js @@ -0,0 +1,13 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); + +Page({ + data: { offerings: [], error: "" }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => this.setData({ offerings: workspace.offerings || [] })) + .catch((error) => this.setData({ error: error.message })); + }, + open(event) { + wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id }); + }, +}); diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.json b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.json new file mode 100644 index 0000000..759573f --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.json @@ -0,0 +1,7 @@ +{ + "navigationBarTitleText": "服务", + "usingComponents": { + "drill-card": "/components/templates/drill-card/drill-card", + "brand-empty": "/components/ui/brand-empty/brand-empty" + } +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxml b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxml new file mode 100644 index 0000000..0900c76 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxml @@ -0,0 +1,13 @@ + + {{error}} + + + diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxss b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxss new file mode 100644 index 0000000..ea705e2 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/miniapp/pages/services/index.wxss @@ -0,0 +1,3 @@ +.page { + padding-bottom: 32rpx; +} diff --git a/packages/template-compiler/test/fixtures/template-drill-consultant/template.json b/packages/template-compiler/test/fixtures/template-drill-consultant/template.json new file mode 100644 index 0000000..9782ab0 --- /dev/null +++ b/packages/template-compiler/test/fixtures/template-drill-consultant/template.json @@ -0,0 +1,58 @@ +{ + "packageKey": "drill-consultant", + "version": "0.1.0", + "displayName": "咨询师演练模板", + "defaultBrandSlug": "drill-consultant", + "runtimeContract": "1.0", + "supportedIndustryTemplates": ["consulting"], + "entrypoints": { + "home": "pages/index/index", + "offerings": "pages/services/index", + "detail": "pages/offering/detail", + "inquiry": "pages/inquiry/index", + "success": "pages/inquiry-success/index", + "records": "pages/records/index", + "profile": "pages/profile/index" + }, + "navigation": [ + { "key": "home", "label": "首页", "page": "home" }, + { "key": "offerings", "label": "服务", "page": "offerings" }, + { "key": "profile", "label": "关于我", "page": "profile" } + ], + "requiredCapabilities": ["offerings", "inquiry"], + "pages": ["pages/index/index", "pages/services/index", "pages/profile/index"], + "dataSlots": [ + { + "key": "brand.identity", + "source": "brand", + "required": true, + "description": "顾问姓名、定位和联系方式" + }, + { + "key": "offering.list", + "source": "offering", + "required": true, + "description": "咨询服务项目" + } + ], + "assetSlots": [], + "admin": { + "sections": [ + { + "key": "identity", + "title": "顾问介绍", + "description": "客户在首页看到的姓名和定位", + "target": "brand", + "fields": [ + { + "key": "name", + "binding": "brand.name", + "label": "姓名", + "input": "text", + "required": true + } + ] + } + ] + } +} diff --git a/packages/template-contract/README.md b/packages/template-contract/README.md index eee3cf4..a876ea1 100644 --- a/packages/template-contract/README.md +++ b/packages/template-contract/README.md @@ -8,6 +8,8 @@ 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`。 +5. 执行 `pnpm generate:template-catalog --write` 和 `pnpm template:check`。 + +最小可编译模板可参考 `packages/template-compiler/test/fixtures/template-drill-consultant`。 使用 `pnpm template:dev --brand ` 生成微信开发者工具项目。生产构建还必须提供 `--appid` 和 HTTPS `--api`。模板在构建时选择,运行时不会下载或解释模板代码。 diff --git a/packages/template-linjing-editorial/miniapp/app.json b/packages/template-linjing-editorial/miniapp/app.json new file mode 100644 index 0000000..b320163 --- /dev/null +++ b/packages/template-linjing-editorial/miniapp/app.json @@ -0,0 +1,8 @@ +{ + "tabBar": { + "color": "#8b8178", + "selectedColor": "#3b2118", + "backgroundColor": "#ffffff", + "borderStyle": "white" + } +} diff --git a/scripts/validate-template-packages.cjs b/scripts/validate-template-packages.cjs index 69a5a01..e3f2cbc 100644 --- a/scripts/validate-template-packages.cjs +++ b/scripts/validate-template-packages.cjs @@ -1,11 +1,11 @@ const fs = require("node:fs"); const path = require("node:path"); +const { pathToFileURL } = require("node:url"); const root = path.resolve(__dirname, ".."); require(path.join(root, "scripts/generate-template-catalog.cjs")); const workspacePackageRoot = path.join(root, "packages"); -const requiredPages = ["home", "offerings", "detail", "inquiry", "success", "records", "profile"]; -const errors = []; +const contractEntry = path.join(workspacePackageRoot, "template-contract/src/index.ts"); const workspaceTemplates = fs .readdirSync(workspacePackageRoot, { withFileTypes: true }) .filter( @@ -15,44 +15,39 @@ const workspaceTemplates = fs fs.existsSync(path.join(workspacePackageRoot, entry.name, "template.json")), ); -for (const entry of workspaceTemplates) { - const packageDir = path.join(workspacePackageRoot, entry.name); - const manifestPath = path.join(packageDir, "template.json"); - let manifest; - try { - manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - } catch (error) { - errors.push(`${entry.name}: invalid template.json (${error.message})`); - continue; - } - if (![entry.name, entry.name.replace(/^template-/, "")].includes(manifest.packageKey)) - errors.push(`${entry.name}: packageKey must match directory name or template key`); - if (!manifest.version) errors.push(`${entry.name}: version is required`); - if (manifest.runtimeContract !== "1.0") errors.push(`${entry.name}: unsupported runtimeContract`); - if (!manifest.displayName) errors.push(`${entry.name}: displayName is required`); - if (!Array.isArray(manifest.navigation) || !manifest.navigation.length) - errors.push(`${entry.name}: navigation is required`); - if (!Array.isArray(manifest.dataSlots) || !manifest.dataSlots.length) - errors.push(`${entry.name}: dataSlots is required`); - if (!Array.isArray(manifest.assetSlots)) - errors.push(`${entry.name}: assetSlots must be an array`); - if (!manifest.admin || !Array.isArray(manifest.admin.sections) || !manifest.admin.sections.length) - errors.push(`${entry.name}: admin.sections is required`); - if (!Array.isArray(manifest.pages) || !manifest.pages.length) - errors.push(`${entry.name}: pages is required`); - for (const page of requiredPages) - if (typeof manifest.entrypoints?.[page] !== "string") - errors.push(`${entry.name}: entrypoints.${page} is required`); - for (const item of manifest.navigation || []) { - for (const asset of [item.iconPath, item.selectedIconPath]) { - if (asset && !fs.existsSync(path.join(packageDir, "miniapp", asset))) - errors.push(`${entry.name}: navigation asset is missing: ${asset}`); +async function main() { + // manifest 规则只在 template-contract 中维护;这里只补充依赖文件系统的检查。 + const { validateTemplatePackageManifest } = await import(pathToFileURL(contractEntry).href); + const errors = []; + for (const entry of workspaceTemplates) { + const packageDir = path.join(workspacePackageRoot, entry.name); + let manifest; + try { + manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "template.json"), "utf8")); + } catch (error) { + errors.push(`${entry.name}: invalid template.json (${error.message})`); + continue; + } + for (const error of validateTemplatePackageManifest(manifest)) + errors.push(`${entry.name}: ${error}`); + if (![entry.name, entry.name.replace(/^template-/, "")].includes(manifest.packageKey)) + errors.push(`${entry.name}: packageKey must match directory name or template key`); + for (const page of manifest.pages || []) { + if (!fs.existsSync(path.join(packageDir, "miniapp", page + ".js"))) + errors.push(`${entry.name}: declared page is missing: ${page}`); + } + for (const item of manifest.navigation || []) { + for (const asset of [item.iconPath, item.selectedIconPath]) { + if (asset && !fs.existsSync(path.join(packageDir, "miniapp", asset))) + errors.push(`${entry.name}: navigation asset is missing: ${asset}`); + } } } + if (errors.length) { + console.error(errors.join("\n")); + process.exit(1); + } + console.log(`Workspace template packages validated: ${workspaceTemplates.length}`); } -if (errors.length) { - console.error(errors.join("\n")); - process.exit(1); -} -console.log(`Workspace template packages validated: ${workspaceTemplates.length}`); +main();