diff --git a/apps/admin/src/features/brand/ComponentTemplatePreview.tsx b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx index 7f3ecd3..e2915f8 100644 --- a/apps/admin/src/features/brand/ComponentTemplatePreview.tsx +++ b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx @@ -3,12 +3,14 @@ import type { RuntimeWorkspace } from "@personal-brand/api-client"; import { Alert } from "antd"; import { resolveTemplateRenderer } from "./component-renderers.jsx"; import type { PreviewSelection, PreviewTarget } from "./preview-selection.js"; +import { TemplatePreviewAssetsContext } from "./preview-assets.js"; import "./ComponentTemplatePreview.css"; type PreviewProps = { workspace: RuntimeWorkspace; page: string; offeringId?: string; + assetFiles?: Record; selection?: PreviewSelection; targets: PreviewTarget[]; onTargetSelected: (selection?: PreviewSelection) => void; @@ -21,6 +23,7 @@ export function ComponentTemplatePreview({ workspace, page, offeringId, + assetFiles, selection, targets, onTargetSelected, @@ -232,7 +235,9 @@ export function ComponentTemplatePreview({ }} >
- + + +
| undefined +>(undefined); diff --git a/apps/admin/src/features/brand/taro-web-components.jsx b/apps/admin/src/features/brand/taro-web-components.jsx index 71b93e3..f32c13f 100644 --- a/apps/admin/src/features/brand/taro-web-components.jsx +++ b/apps/admin/src/features/brand/taro-web-components.jsx @@ -1,4 +1,5 @@ import React from "react"; +import { TemplatePreviewAssetsContext } from "./preview-assets.js"; export const TemplateAssetContext = React.createContext(""); const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", { @@ -99,10 +100,14 @@ export function Checkbox({ value, checked }) { export const Label = element("label"); export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => { const key = React.useContext(TemplateAssetContext); + const assets = React.useContext(TemplatePreviewAssetsContext); return React.createElement("img", { ...props, ref, - src: resolveImageSource(src, key), + src: + assets && typeof src === "string" && src.startsWith("/assets/") + ? assets[src]?.dataUrl + : resolveImageSource(src, key), style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style }, }); }); diff --git a/apps/admin/src/features/template-management/TemplateManagementPage.tsx b/apps/admin/src/features/template-management/TemplateManagementPage.tsx index a0618da..9e68530 100644 --- a/apps/admin/src/features/template-management/TemplateManagementPage.tsx +++ b/apps/admin/src/features/template-management/TemplateManagementPage.tsx @@ -249,8 +249,12 @@ export function TemplateManagementPage() { renderItem={(item) => ( ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}`} + title={`${item.action === "previewed" ? "预览模板" : item.action} · ${item.actor.displayName}`} + description={ + item.action === "previewed" + ? `行业 ${typeof item.metadata?.industry === "string" ? item.metadata.industry : "-"} · ${new Date(item.createdAt).toLocaleString()}` + : `${item.fromStatus ?? "-"} -> ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}` + } /> )} @@ -260,7 +264,12 @@ export function TemplateManagementPage() { {previewVersion ? ( setPreviewVersion(null)} + onClose={() => { + setPreviewVersion(null); + void queryClient.invalidateQueries({ + queryKey: ["admin-template-package-audit", previewVersion.id], + }); + }} /> ) : null}
diff --git a/apps/admin/src/features/template-management/TemplatePackagePreviewModal.tsx b/apps/admin/src/features/template-management/TemplatePackagePreviewModal.tsx index a6b1293..0da0e2e 100644 --- a/apps/admin/src/features/template-management/TemplatePackagePreviewModal.tsx +++ b/apps/admin/src/features/template-management/TemplatePackagePreviewModal.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; -import { Alert, Modal, Select, Typography } from "antd"; +import { Alert, Collapse, List, Modal, Select, Tag, Typography } from "antd"; import type { TemplatePackageVersion } from "@personal-brand/api-client"; import { createApiClient } from "../../lib/api.js"; import { QueryState } from "../../components/QueryState.js"; @@ -76,6 +76,20 @@ export function TemplatePackagePreviewModal({ > {data ? ( <> + {data.preview.diagnostics.map((diagnostic) => ( + + ))} + + 演示数据: + {data.preview.fixtureSource === "previewFixture" + ? "独立预览内容" + : "兼容起始内容"} + {data.industry.name} · Runtime {data.compatibility.runtimeContract} · renderer{" "} {data.compatibility.renderer.key}@{data.compatibility.renderer.version} @@ -103,9 +117,65 @@ export function TemplatePackagePreviewModal({ onChange={setOfferingId} /> ) : null} + item.key === page)?.modules ?? [] + } + locale={{ emptyText: "此页面由 Runtime 提供,不包含模板编辑模块" }} + renderItem={(item) => ( + +
+ {item.title} + + {item.bindings.join("、")} + +
+
+ )} + /> + ), + }, + { + key: "assets", + label: "资源诊断", + children: ( + ( + +
+ {item.label}{" "} + + {item.status === "missing" + ? "内容缺失" + : item.status === "ready" + ? "包内资源已验证" + : "可用性待验证"} + + {item.required ? "必需" : "可选"} · 已配置 {item.populated}/ + {item.total} + + {item.binding} + +
+
+ )} + /> + ), + }, + ]} + /> { - return this.previews.preview(id, query.industry); + const { subject } = await this.access.requireTemplateAdmin(request); + return this.previews.preview( + id, + query.industry, + subject, + request.headers["x-request-id"]?.toString() ?? request.id, + ); } } diff --git a/apps/api/src/modules/admin/admin-template-package.service.ts b/apps/api/src/modules/admin/admin-template-package.service.ts index ca7eb09..3812f6e 100644 --- a/apps/api/src/modules/admin/admin-template-package.service.ts +++ b/apps/api/src/modules/admin/admin-template-package.service.ts @@ -5,6 +5,8 @@ import { PayloadTooLargeException, } from "@nestjs/common"; import { validateTemplatePackageManifest } from "@personal-brand/config"; +import { validateTemplatePreviewFixtures } from "@personal-brand/validation"; +import type { Prisma } from "@prisma/client"; import type { FastifyRequest } from "fastify"; import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; @@ -24,6 +26,8 @@ type Manifest = { version: string; displayName: string; visualTemplateKey?: string; + supportedIndustryTemplates?: string[]; + previewFixture?: Prisma.InputJsonValue; }; type ChecksumFile = { @@ -419,6 +423,16 @@ export class AdminTemplatePackageService { } if (errors.length) throw new BadRequestException(`template.json 不符合模板契约:${errors.join(";")}`); + if (manifest.previewFixture !== undefined) { + const issues = validateTemplatePreviewFixtures( + manifest.previewFixture, + manifest.supportedIndustryTemplates ?? [], + ); + if (issues.length) + throw new BadRequestException( + `previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`, + ); + } if ( checksums.formatVersion !== "1" || checksums.packageKey !== manifest.packageKey || diff --git a/apps/api/src/modules/admin/admin-template-preview-assets.service.ts b/apps/api/src/modules/admin/admin-template-preview-assets.service.ts new file mode 100644 index 0000000..4ef57cd --- /dev/null +++ b/apps/api/src/modules/admin/admin-template-preview-assets.service.ts @@ -0,0 +1,104 @@ +import { ConflictException, Injectable } from "@nestjs/common"; +import { createHash } from "node:crypto"; +import { execFile } from "node:child_process"; +import { readFile, stat } from "node:fs/promises"; +import { promisify } from "node:util"; + +const run = promisify(execFile); +const MAX_IMAGE_BYTES = 2 * 1024 * 1024; +const MAX_PREVIEW_BYTES = 8 * 1024 * 1024; +const digest = (content: Buffer) => createHash("sha256").update(content).digest("hex"); + +function imageMime(content: Buffer): string | undefined { + if (content.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) + return "image/png"; + if (content[0] === 255 && content[1] === 216 && content[2] === 255) return "image/jpeg"; + if (["GIF87a", "GIF89a"].includes(content.subarray(0, 6).toString())) return "image/gif"; + if (content.subarray(0, 4).toString() === "RIFF" && content.subarray(8, 12).toString() === "WEBP") + return "image/webp"; + return undefined; +} + +@Injectable() +export class AdminTemplatePreviewAssetsService { + async read(version: { artifactPath: string; archiveChecksum: string; contentChecksum: string }) { + const files: Record = {}; + const diagnostics: Array<{ code: string; severity: "warning"; message: string }> = []; + try { + // 只读取已通过导入门禁且摘要一致的 archive,不执行源码,也不解压到公开目录。 + if ((await stat(version.artifactPath)).size > 50 * 1024 * 1024) + throw new Error("Archive size"); + if (digest(await readFile(version.artifactPath)) !== version.archiveChecksum) + throw new Error("Archive checksum"); + const { stdout: listing } = await run("tar", ["-tzf", version.artifactPath], { + maxBuffer: 4 * 1024 * 1024, + timeout: 10000, + }); + const root = listing.split("\n")[0]?.split("/")[0]; + if (!root || !/^[a-zA-Z0-9._-]+$/.test(root)) throw new Error("Archive root"); + const readEntry = async (path: string, limit: number) => { + const result = await run("tar", ["-xOzf", version.artifactPath, "--", `${root}/${path}`], { + encoding: "buffer", + maxBuffer: limit, + timeout: 10000, + }); + return result.stdout; + }; + const checksums = JSON.parse( + (await readEntry("checksums.json", 2 * 1024 * 1024)).toString(), + ) as { + contentChecksum: string; + files: Array<{ path: string; bytes: number; sha256: string }>; + }; + if (checksums.contentChecksum !== version.contentChecksum || !Array.isArray(checksums.files)) + throw new Error("Content checksum"); + let totalBytes = 0; + let imageCount = 0; + for (const entry of checksums.files) { + if ( + !/^miniapp\/assets\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_.-]+\.(?:png|jpe?g|webp|gif)$/i.test( + entry.path, + ) + ) + continue; + const key = entry.path.slice("miniapp".length); + if (++imageCount > 128) { + diagnostics.push({ + code: "PREVIEW_ASSET_COUNT", + severity: "warning", + message: "包内图片超过 128 个,请拆分或精简预览资源。", + }); + break; + } + if (entry.bytes > MAX_IMAGE_BYTES || totalBytes + entry.bytes > MAX_PREVIEW_BYTES) { + diagnostics.push({ + code: "PREVIEW_ASSET_LIMIT", + severity: "warning", + message: `资源 ${key} 超出预览体积限制,请缩小图片。`, + }); + continue; + } + const content = await readEntry(entry.path, MAX_IMAGE_BYTES); + if (content.length !== entry.bytes || digest(content) !== entry.sha256) + throw new Error("Asset checksum"); + const mime = imageMime(content); + if (!mime) { + diagnostics.push({ + code: "PREVIEW_ASSET_TYPE", + severity: "warning", + message: `资源 ${key} 不是受支持的图片。`, + }); + continue; + } + totalBytes += content.length; + files[key] = { + sha256: entry.sha256, + dataUrl: `data:${mime};base64,${content.toString("base64")}`, + }; + } + return { files, diagnostics }; + } catch { + throw new ConflictException("模板预览资源不可读取或摘要不一致,请检查已导入的模板包存储"); + } + } +} diff --git a/apps/api/src/modules/admin/admin-template-preview.service.ts b/apps/api/src/modules/admin/admin-template-preview.service.ts index 4e39542..e305601 100644 --- a/apps/api/src/modules/admin/admin-template-preview.service.ts +++ b/apps/api/src/modules/admin/admin-template-preview.service.ts @@ -7,11 +7,16 @@ import { getVisualTemplateManifest, validateTemplatePackageManifest, } from "@personal-brand/config"; -import type { TemplatePackageManifest, TemplateSampleContent } from "@personal-brand/config"; -import { validateFieldSnapshot } from "@personal-brand/validation"; +import type { + TemplatePackageManifest, + TemplatePreviewFixture, + TemplateSampleContent, +} from "@personal-brand/config"; +import { validateFieldSnapshot, validateTemplatePreviewFixture } from "@personal-brand/validation"; import type { BrandReleaseSnapshot } from "../../brand-release.service.js"; import { PrismaService } from "../../prisma.service.js"; import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js"; +import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js"; function record(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) @@ -45,6 +50,11 @@ function hasPreviewStructure(manifest: Record): boolean { ) && records(manifest.navigation) && manifest.navigation.every((tab) => strings(tab, ["key", "label", "page"])) && + records(manifest.assetSlots) && + manifest.assetSlots.every( + (slot) => + strings(slot, ["key", "label", "binding", "target"]) && typeof slot.required === "boolean", + ) && records(record(manifest.admin).sections) && (record(manifest.admin).sections as Record[]).every( (section) => strings(section, ["key", "target"]) && fields(section.fields), @@ -60,8 +70,11 @@ function hasPreviewStructure(manifest: Record): boolean { @Injectable() export class AdminTemplatePreviewService { - constructor(private readonly prisma: PrismaService) {} - async preview(id: string, industry: string) { + constructor( + private readonly prisma: PrismaService, + private readonly assets: AdminTemplatePreviewAssetsService, + ) {} + async preview(id: string, industry: string, actorId: string, requestId?: string) { const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } }); if (!version) throw new BadRequestException("模板版本不存在"); if (version.status === "retired") throw new ConflictException("已撤回的模板版本不能创建新预览"); @@ -119,12 +132,28 @@ export class AdminTemplatePreviewService { ) { blockers.push("模板依赖的 capability 与所选行业不兼容"); } + if (blockers.length) throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`); - const sample = record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined; + const fixtureDeclared = rawManifest.previewFixture !== undefined; + const fixture = record(rawManifest.previewFixture)[industry] as + TemplatePreviewFixture | undefined; + if (fixtureDeclared) { + const issues = validateTemplatePreviewFixture(fixture); + if (issues.length) + throw new BadRequestException( + `模板 previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`, + ); + } + // 一旦包声明独立 fixture,缺失或无效时禁止偷偷回退到 bootstrap sample。 + const sample = fixtureDeclared + ? fixture!.content + : (record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined); const missingSampleSlots = this.missingSampleSlots(manifest, sample); if (missingSampleSlots.length) blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`); if (sample?.templateKey !== industry) blockers.push("sample 所属行业与所选行业不一致"); + if (sample && !industryTemplate!.capabilities.some((key) => key === sample.capabilityKey)) + blockers.push("preview sample 的咨询 capability 与所选行业不兼容"); if (!Array.isArray(sample?.fields) || validateFieldSnapshot(sample.fields).length) blockers.push("sample 咨询字段不符合表单契约"); if ( @@ -151,11 +180,38 @@ export class AdminTemplatePreviewService { ) ) blockers.push("sample 信任记录不符合模板声明"); + for (const declaration of manifest.trustContentTypes ?? []) { + if ( + declaration.required && + !array(sample?.trustContent).some((item) => record(item).type === declaration.type) + ) + blockers.push(`preview sample 缺少必需信任内容:${declaration.type}`); + } if (blockers.length) { throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`); } - const workspace = this.buildSampleWorkspace(version.id, manifest, industryTemplate!, sample!); + const resources = await this.assets.read(version); + const workspace = this.buildSampleWorkspace( + version.id, + manifest, + industryTemplate!, + sample!, + fixture?.brand, + ); + await this.prisma.templatePackageAuditLog.create({ + data: { + templatePackageVersionId: version.id, + actorId, + action: "previewed", + ...(requestId ? { requestId } : {}), + metadata: { + industry, + contentChecksum: version.contentChecksum, + fixtureSource: fixtureDeclared ? "previewFixture" : "legacy-sampleContent", + }, + }, + }); return { template: { id: version.id, @@ -185,6 +241,78 @@ export class AdminTemplatePreviewService { requiredCapabilities, missingSampleSlots: [], }, + preview: { + assetFiles: resources.files, + fixtureSource: fixtureDeclared + ? ("previewFixture" as const) + : ("legacy-sampleContent" as const), + safety: { + submissions: "disabled" as const, + customerRecords: "disabled" as const, + contactActions: "disabled" as const, + }, + diagnostics: [ + ...resources.diagnostics, + ...(fixtureDeclared + ? [] + : [ + { + code: "LEGACY_PREVIEW_SAMPLE", + severity: "warning" as const, + message: "该版本尚未提供独立预览数据,当前兼容使用品牌起始内容。", + }, + ]), + ], + pages: Object.keys(manifest.entrypoints).map((page) => ({ + key: page, + modules: manifest.admin.sections + .filter((section) => section.page === page) + .map((section) => ({ + key: section.key, + title: section.title, + bindings: section.fields.map((field) => field.binding), + })), + })), + assets: manifest.assetSlots.map((slot) => { + const resolve = (source: Record, path: string[]) => + path.reduce((value, key) => record(value)[key], source); + const sources = + slot.target === "brand" + ? [record(workspace.brand)] + : slot.target === "offering" + ? sample!.offerings + : sample!.trustContent; + const path = slot.binding.split(".").slice(1); + const values = sources.map((source) => resolve(record(source), path)); + const populated = values.filter( + (value) => typeof value === "string" && value.trim().length > 0, + ).length; + const verified = values.filter( + (value) => typeof value === "string" && Object.hasOwn(resources.files, value), + ).length; + return { + key: slot.key, + label: slot.label, + binding: slot.binding, + required: slot.required, + populated, + total: sources.length, + status: + populated !== sources.length || + !sources.length || + values.some( + (value) => + typeof value === "string" && + value.startsWith("/assets/") && + !Object.hasOwn(resources.files, value), + ) + ? ("missing" as const) + : verified === sources.length + ? ("ready" as const) + : ("unverified" as const), + }; + }), + }, workspace, }; } @@ -225,21 +353,22 @@ export class AdminTemplatePreviewService { manifest: TemplatePackageManifest, industryTemplate: NonNullable>, sample: TemplateSampleContent, + identity?: TemplatePreviewFixture["brand"], ) { const brandConfig = record(sample.brandConfig); const visualTemplateKey = manifest.visualTemplateKey; const brand = { id: `template-preview:${versionId}`, slug: `template-preview-${manifest.packageKey}`, - name: `${manifest.displayName}示例品牌`, + name: identity?.name ?? `${manifest.displayName}示例品牌`, templateKey: industryTemplate.key, - tagline: `${industryTemplate.name}模板示例`, - description: "这是模板预览数据,不属于任何真实品牌。", - avatarUrl: null, - coverUrl: null, - hours: "示例营业时间", - address: "示例服务范围", - deliveryNote: "预览模式不会提交咨询或创建客户记录。", + tagline: identity?.tagline ?? `${industryTemplate.name}模板示例`, + description: identity?.description ?? "这是模板预览数据,不属于任何真实品牌。", + avatarUrl: identity?.avatarUrl ?? null, + coverUrl: identity?.coverUrl ?? null, + hours: identity?.hours ?? "示例营业时间", + address: identity?.address ?? "示例服务范围", + deliveryNote: identity?.deliveryNote ?? "预览模式不会提交咨询或创建客户记录。", contactPhone: null, contactWechat: null, config: { ...brandConfig, visualTemplateKey }, diff --git a/apps/api/src/modules/admin/admin.module.ts b/apps/api/src/modules/admin/admin.module.ts index b2f2cc7..dcede38 100644 --- a/apps/api/src/modules/admin/admin.module.ts +++ b/apps/api/src/modules/admin/admin.module.ts @@ -17,6 +17,7 @@ import { AdminTemplatePackageController } from "./admin-template-package.control import { AdminTemplatePackageService } from "./admin-template-package.service.js"; import { AdminTemplatePreviewService } from "./admin-template-preview.service.js"; +import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js"; @Module({ imports: [InfrastructureModule, BookingModule], @@ -38,6 +39,7 @@ import { AdminTemplatePreviewService } from "./admin-template-preview.service.js AdminUploadService, AdminTemplatePackageService, AdminTemplatePreviewService, + AdminTemplatePreviewAssetsService, ], }) export class AdminModule {} diff --git a/apps/api/test/http.integration.test.js b/apps/api/test/http.integration.test.js index 607ca78..8b5e49f 100644 --- a/apps/api/test/http.integration.test.js +++ b/apps/api/test/http.integration.test.js @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, readdirSync } from "node:fs"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { after, before, test } from "node:test"; @@ -41,22 +41,50 @@ function multipartArchive(archive) { }; } -function createTemplateArchive(template = "acheng-campus-food") { +function createTemplateArchive(template = "acheng-campus-food", mutateManifest) { const output = mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-pack-")); - execFileSync( - process.execPath, - [ - path.resolve(process.cwd(), "../../scripts/template-pack.cjs"), - "--template", - template, - "--out", - output, - ], - { cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" }, - ); - const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz")); - assert.ok(filename); - return readFileSync(path.join(output, filename)); + try { + execFileSync( + process.execPath, + [ + path.resolve(process.cwd(), "../../scripts/template-pack.cjs"), + "--template", + template, + "--out", + output, + ], + { cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" }, + ); + const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz")); + assert.ok(filename); + if (mutateManifest) { + const packageName = filename.slice(0, -7); + const directory = path.join(output, packageName); + const manifestPath = path.join(directory, "template.json"); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + mutateManifest(manifest); + const content = Buffer.from(JSON.stringify(manifest)); + writeFileSync(manifestPath, content); + const checksumPath = path.join(directory, "checksums.json"); + const checksums = JSON.parse(readFileSync(checksumPath, "utf8")); + const entry = checksums.files.find((item) => item.path === "template.json"); + entry.bytes = content.length; + entry.sha256 = createHash("sha256").update(content).digest("hex"); + const canonicalEntries = checksums.files.map((item) => ({ + bytes: item.bytes, + path: item.path, + sha256: item.sha256, + })); + checksums.contentChecksum = createHash("sha256") + .update(JSON.stringify(canonicalEntries)) + .digest("hex"); + writeFileSync(checksumPath, JSON.stringify(checksums)); + execFileSync("tar", ["-czf", path.join(output, filename), "-C", output, packageName]); + } + return readFileSync(path.join(output, filename)); + } finally { + rmSync(output, { recursive: true, force: true }); + } } test("模板目录只允许平台模板管理员访问,并支持安全、幂等导入", async () => { @@ -190,6 +218,19 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品 }); assert.equal(login.statusCode, 201); const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` }; + const invalidArchive = createTemplateArchive("atelier-solopreneur", (manifest) => { + manifest.previewFixture.personal.safety.submissions = "enabled"; + }); + const invalidMultipart = multipartArchive(invalidArchive); + const versionCount = await prisma.templatePackageVersion.count(); + const rejectedImport = await request("/admin/templates/import", { + method: "POST", + headers: { ...headers, ...invalidMultipart.headers }, + rawPayload: invalidMultipart.payload, + }); + assert.equal(rejectedImport.statusCode, 400, rejectedImport.body); + assert.match(JSON.parse(rejectedImport.body).error.message, /previewFixture/); + assert.equal(await prisma.templatePackageVersion.count(), versionCount); const archive = createTemplateArchive("atelier-solopreneur"); const multipart = multipartArchive(archive); const imported = await request("/admin/templates/import", { @@ -213,7 +254,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品 ]); const before = await businessCounts(); const preview = await request(`/admin/templates/${versionId}/preview?industry=personal`, { - headers, + headers: { ...headers, "x-request-id": "independent-template-preview" }, }); assert.equal(preview.statusCode, 200, preview.body); const body = JSON.parse(preview.body); @@ -226,11 +267,85 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品 assert.equal(body.workspace.brand.config.visualTemplateKey, "atelier-solopreneur"); assert.equal(body.template.pages.includes("profile"), true); assert.equal(body.template.pages.includes("inquiry"), true); + assert.equal(body.preview.fixtureSource, "previewFixture"); + assert.equal(body.workspace.brand.name, "独立工坊 · 演示品牌"); + assert.equal(body.workspace.brand.founder, "林予 · 示例主理人"); + assert.equal(body.workspace.brand.contactPhone, null); + assert.equal(body.preview.safety.submissions, "disabled"); + assert.ok(body.preview.pages.find((page) => page.key === "home").modules.length > 0); + assert.ok( + body.preview.assets.some( + (asset) => asset.binding === "brand.avatarUrl" && asset.status === "missing", + ), + ); + assert.ok( + body.preview.assets.some( + (asset) => asset.binding === "offering.coverUrl" && asset.status === "ready", + ), + ); + assert.match( + body.preview.assetFiles["/assets/cases/campus.jpg"].dataUrl, + /^data:image\/jpeg;base64,/, + ); + assert.match(body.preview.assetFiles["/assets/cases/campus.jpg"].sha256, /^[a-f0-9]{64}$/); + const previewAudit = await request(`/admin/templates/${versionId}/audit`, { headers }); + assert.equal(previewAudit.statusCode, 200); + const event = JSON.parse(previewAudit.body).find((entry) => entry.action === "previewed"); + assert.equal(event.requestId, "independent-template-preview"); + assert.deepEqual(event.metadata, { + industry: "personal", + contentChecksum: body.template.contentChecksum, + fixtureSource: "previewFixture", + }); + assert.ok(event.actor.id); const stored = await prisma.templatePackageVersion.findUniqueOrThrow({ where: { id: versionId }, }); const failures = [ - [{ ...stored.manifestSnapshot, sampleContent: {} }, /缺少必需数据/], + [{ ...stored.manifestSnapshot, previewFixture: {} }, /previewFixture/], + [{ ...stored.manifestSnapshot, previewFixture: { personal: null } }, /previewFixture/], + [ + { + ...stored.manifestSnapshot, + previewFixture: { + personal: { + ...stored.manifestSnapshot.previewFixture.personal, + safety: { submissions: "enabled" }, + }, + }, + }, + /previewFixture/, + ], + [ + { + ...stored.manifestSnapshot, + previewFixture: { + personal: { + ...stored.manifestSnapshot.previewFixture.personal, + brand: { + ...stored.manifestSnapshot.previewFixture.personal.brand, + contactPhone: "13800000000", + }, + }, + }, + }, + /previewFixture/, + ], + [ + { + ...stored.manifestSnapshot, + previewFixture: { + personal: { + ...stored.manifestSnapshot.previewFixture.personal, + content: { + ...stored.manifestSnapshot.previewFixture.personal.content, + templateKey: "food", + }, + }, + }, + }, + /所属行业/, + ], [{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/], [{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /renderer/], [{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/], @@ -241,6 +356,41 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品 [{ ...stored.manifestSnapshot, admin: { sections: [{ fields: [null] }] } }, /契约/], ]; try { + await prisma.templatePackageVersion.update({ + where: { id: versionId }, + data: { archiveChecksum: "0".repeat(64) }, + }); + const corrupt = await request(`/admin/templates/${versionId}/preview?industry=personal`, { + headers, + }); + assert.equal(corrupt.statusCode, 409, corrupt.body); + assert.match(JSON.parse(corrupt.body).error.message, /摘要不一致/); + await prisma.templatePackageVersion.update({ + where: { id: versionId }, + data: { archiveChecksum: stored.archiveChecksum }, + }); + // 独立演示内容不依赖 bootstrap;旧包则显式标明兼容来源。 + await prisma.templatePackageVersion.update({ + where: { id: versionId }, + data: { manifestSnapshot: { ...stored.manifestSnapshot, sampleContent: {} } }, + }); + const independent = await request(`/admin/templates/${versionId}/preview?industry=personal`, { + headers, + }); + assert.equal(independent.statusCode, 200, independent.body); + assert.equal(JSON.parse(independent.body).workspace.brand.founder, "林予 · 示例主理人"); + const legacyManifest = { ...stored.manifestSnapshot }; + delete legacyManifest.previewFixture; + await prisma.templatePackageVersion.update({ + where: { id: versionId }, + data: { manifestSnapshot: legacyManifest }, + }); + const legacy = await request(`/admin/templates/${versionId}/preview?industry=personal`, { + headers, + }); + assert.equal(legacy.statusCode, 200, legacy.body); + assert.equal(JSON.parse(legacy.body).preview.fixtureSource, "legacy-sampleContent"); + assert.equal(JSON.parse(legacy.body).preview.diagnostics[0].code, "LEGACY_PREVIEW_SAMPLE"); for (const [manifestSnapshot, reason] of failures) { await prisma.templatePackageVersion.update({ where: { id: versionId }, @@ -255,7 +405,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品 } finally { await prisma.templatePackageVersion.update({ where: { id: versionId }, - data: { manifestSnapshot: stored.manifestSnapshot }, + data: { manifestSnapshot: stored.manifestSnapshot, archiveChecksum: stored.archiveChecksum }, }); } const noIndustry = await request(`/admin/templates/${versionId}/preview`, { headers }); diff --git a/apps/api/test/template-preview-assets.test.ts b/apps/api/test/template-preview-assets.test.ts new file mode 100644 index 0000000..773cd6f --- /dev/null +++ b/apps/api/test/template-preview-assets.test.ts @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import "reflect-metadata"; +import { ConflictException } from "@nestjs/common"; +import { AdminTemplatePreviewAssetsService } from "../src/modules/admin/admin-template-preview-assets.service.js"; + +const digest = (value: Buffer | string) => createHash("sha256").update(value).digest("hex"); + +function archiveFixture(corruptImage = false) { + const root = mkdtempSync(path.join(os.tmpdir(), "template-preview-assets-")); + const directory = path.join(root, "fixture"); + mkdirSync(path.join(directory, "miniapp/assets"), { recursive: true }); + const png = readFileSync( + "../../packages/template-atelier-solopreneur/miniapp/assets/tab/home.png", + ); + const contents: Record = { + "miniapp/assets/icon.png": png, + "miniapp/assets/bad.jpg": Buffer.from("This is not an image"), + "miniapp/assets/large.png": Buffer.alloc(2 * 1024 * 1024 + 1), + "miniapp/assets/script.svg": Buffer.from(""), + }; + const files = Object.entries(contents).map(([file, content]) => { + writeFileSync(path.join(directory, file), content); + return { + bytes: content.length, + path: file, + sha256: corruptImage ? "0".repeat(64) : digest(content), + }; + }); + const contentChecksum = digest(JSON.stringify(files)); + writeFileSync(path.join(directory, "checksums.json"), JSON.stringify({ contentChecksum, files })); + const artifactPath = path.join(root, "fixture.tar.gz"); + execFileSync("tar", ["-czf", artifactPath, "-C", root, "fixture"]); + return { + root, + version: { artifactPath, contentChecksum, archiveChecksum: digest(readFileSync(artifactPath)) }, + }; +} + +test("preview resources verify raster content and diagnose invalid or oversized assets", async () => { + const fixture = archiveFixture(); + try { + const result = await new AdminTemplatePreviewAssetsService().read(fixture.version); + assert.deepEqual(Object.keys(result.files), ["/assets/icon.png"]); + assert.match(result.files["/assets/icon.png"]!.dataUrl, /^data:image\/png;base64,/); + assert.deepEqual( + result.diagnostics.map((item) => item.code), + ["PREVIEW_ASSET_TYPE", "PREVIEW_ASSET_LIMIT"], + ); + } finally { + rmSync(fixture.root, { recursive: true, force: true }); + } +}); + +test("preview resources reject image checksum drift and unavailable archives", async () => { + const fixture = archiveFixture(true); + try { + const service = new AdminTemplatePreviewAssetsService(); + await assert.rejects(service.read(fixture.version), ConflictException); + await assert.rejects( + service.read({ ...fixture.version, artifactPath: path.join(fixture.root, "missing.tar.gz") }), + ConflictException, + ); + } finally { + rmSync(fixture.root, { recursive: true, force: true }); + } +}); diff --git a/apps/taro/test/browser/template-management.spec.ts b/apps/taro/test/browser/template-management.spec.ts index 7f920f3..7ad29a9 100644 --- a/apps/taro/test/browser/template-management.spec.ts +++ b/apps/taro/test/browser/template-management.spec.ts @@ -30,11 +30,25 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的 ` import 'reflect-metadata'; import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js'; + import { AdminTemplatePreviewAssetsService } from './dist/modules/admin/admin-template-preview-assets.service.js'; + import { execFileSync } from 'node:child_process'; + import { createHash } from 'node:crypto'; + import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; + import os from 'node:os'; + import path from 'node:path'; let input = ''; for await (const chunk of process.stdin) input += chunk; const version = JSON.parse(input); - const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version } }); - process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal'))); + const temporary = mkdtempSync(path.join(os.tmpdir(), 'template-preview-browser-')); + try { + execFileSync(process.execPath, ['../../scripts/template-pack.cjs', '--template', version.packageKey, '--out', temporary], { stdio: 'ignore' }); + const archive = readdirSync(temporary).find((file) => file.endsWith('.tar.gz')); + version.artifactPath = path.join(temporary, archive); + version.archiveChecksum = createHash('sha256').update(readFileSync(version.artifactPath)).digest('hex'); + version.contentChecksum = JSON.parse(readFileSync(path.join(temporary, archive.slice(0, -7), 'checksums.json'), 'utf8')).contentChecksum; + const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version }, templatePackageAuditLog: { create: async () => ({}) } }, new AdminTemplatePreviewAssetsService()); + process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal', 'browser-fixture-admin'))); + } finally { rmSync(temporary, { recursive: true, force: true }); } `, ], { cwd: path.resolve("../api"), input: JSON.stringify(version), encoding: "utf8" }, @@ -70,8 +84,12 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的 await expect(modal.getByText("预览测试失败,请重试")).toBeVisible(); await modal.getByRole("button", { name: /重试/ }).click(); await expect(modal.locator(".atelier-founder-name")).toHaveText( - manifest.sampleContent.personal.brandConfig.founder, + manifest.previewFixture.personal.content.brandConfig.founder, ); + await expect(modal.getByText("演示数据:独立预览内容")).toBeVisible(); + await modal.getByText("资源诊断", { exact: true }).click(); + await expect(modal.getByText("内容缺失", { exact: true }).first()).toBeVisible(); + await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible(); const choosePage = async (label: string) => { await modal.getByLabel("预览页面").click(); await page.locator(".ant-select-item-option-content").getByText(label, { exact: true }).click(); @@ -80,8 +98,13 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的 await expect(modal.locator(".component-template-preview")).toContainText("我的咨询记录"); await choosePage("业务详情"); await expect(modal.locator(".component-template-preview")).toContainText( - manifest.sampleContent.personal.offerings[0].name, + manifest.previewFixture.personal.content.offerings[0].name, ); + const caseImage = modal.locator('.component-template-preview img[src^="data:image/"]').first(); + await expect(caseImage).toBeVisible(); + await expect + .poll(() => caseImage.evaluate((image: HTMLImageElement) => image.naturalWidth)) + .toBeGreaterThan(0); await choosePage("咨询表单"); await expect(modal.locator(".inquiry-form")).toBeVisible(); await expect(modal.locator(".inquiry-form button").last()).toBeDisabled(); diff --git a/config/template-build.json b/config/template-build.json index e6cd850..495f3d4 100644 --- a/config/template-build.json +++ b/config/template-build.json @@ -14,7 +14,7 @@ { "packageKey": "atelier-solopreneur", "packageName": "@personal-brand/template-atelier-solopreneur", - "version": "1.1.0" + "version": "1.2.0" } ] } diff --git a/docs/adr/0029-template-management-and-distribution.md b/docs/adr/0029-template-management-and-distribution.md index 0d0b951..541975f 100644 --- a/docs/adr/0029-template-management-and-distribution.md +++ b/docs/adr/0029-template-management-and-distribution.md @@ -118,3 +118,9 @@ template:doctor、manifest 静态校验、mock 请求和页面能打开只能证 - 补充 [ADR 0028:按当前视觉模板显式导入示例](0028-template-selected-sample-import.md):将 sample preview、bootstrap import、来源和升级规则统一到模板管理生命周期; - 取代旧注册表中“手工列出所有可用模板即可完成注册”的隐含假设;docs/template-registry.md 只保留当前盘点和迁移入口; - 不删除或否定 [ADR 0010:模板示例内容注册表](0010-template-sample-content-registry.md) 的历史背景,但其中与“全局注册表或 seed 作为模板事实来源”冲突的部分以本 ADR 和模板数据流规则为准。 + +## Phase 3 实现补充(2026-10-16) + +独立演示内容使用 `previewFixture.`,与既有 `sampleContent`(品牌起始内容)分别维护。契约校验复用 `packages/validation` 的 Zod;导出和线上导入共用规则。旧包兼容使用 sample 时必须给出显式诊断;声明 fixture 后缺失或无效则阻断,不能静默回退。 + +第一步包内预览图片采用受权限保护的预览响应内嵌 data URL,与版本 checksum 和 Runtime 同时交付。服务核对已导入 archive、内容及逐图片摘要,只接受 raster 格式,不执行或公开解压包内代码。限制为单图 2 MiB、总计 8 MiB、128 张;超限或外链返回诊断。该方案优先保证精确版本和权限隔离,代价是响应体积与重复读取;后续可迁移为同 checksum 的短期资源 URL/CDN,不改变模板内容契约。它不替代尚未完成的 sandbox/origin/CSP 门禁。 diff --git a/docs/template-management-delivery-plan.md b/docs/template-management-delivery-plan.md index 873ce51..e2be5e6 100644 --- a/docs/template-management-delivery-plan.md +++ b/docs/template-management-delivery-plan.md @@ -2,7 +2,7 @@ > 任务 ID:TMP-PLATFORM-001 > -> 状态:实施中,Phase 0/1/2 已完成,Phase 3 已接入版本预览 API 和管理页,完整 fixture、资源诊断与隔离预览仍待验收 +> 状态:实施中,Phase 0/1/2 已完成,Phase 3 已接入版本预览、独立 fixture 和包内图片校验,隔离上下文与完整矩阵仍待验收 > > 唯一任务入口:本文档 > @@ -402,7 +402,7 @@ Phase 2 当前进度(2026-10-16): 退出门禁:预览不创建品牌和业务数据;不同版本、行业和资源组合不会串数据;页面失败时保留上传和选择上下文;真实 Runtime 和预览数据映射有测试。 -Phase 3 当前实现(2026-10-16): +Phase 3 初版实现(提交 `6edde5a`,2026-10-16): - 增加 `GET /admin/templates/:id/preview?industry=`,只允许平台模板管理员;DTO 校验查询,服务读取数据库版本的 `manifestSnapshot.sampleContent`,不读取当前品牌内容,不创建品牌或业务记录。 - `imported` 和 `published` 可预览;`retired` 和其他不可用状态返回 `409`。不存在的版本、非法行业组合、Runtime/renderer/capability/sample 校验失败返回 `400`,沿用统一错误 envelope。 @@ -413,7 +413,19 @@ Phase 3 当前实现(2026-10-16): - 预览入口增加嵌套声明结构门禁;集成测试覆盖 `dataSlots`、`navigation`、`templateFields`、`trustContentTypes` 和 Admin section 的畸形输入,返回可操作的 `400` 错误。 - 本轮验证:API HTTP integration `52/52`、upload `2/2`、API unit `49/49`、Client `6/6`、Admin unit `6/6`、Playwright 预览交互 `1/1`;全仓 typecheck、Admin production build、变更范围 lint、format、`template:check` 通过。`template:doctor` 未解决项为 `0`,模板完成度仍为 `unverified`。Playwright 运行前需构建 API/config 并启动 Admin:`ADMIN_PORT=3016 pnpm --filter @personal-brand/admin dev`,随后在 `apps/taro` 运行 `pnpm exec playwright test test/browser/template-management.spec.ts`。 - 咨询按钮改动另行完成 atelier 的 `weapp` 和 `h5` 构建,参数为 `TEMPLATE_KEY=atelier-solopreneur API_BASE_URL=https://wechat.app.que01.top/api WEAPP_APP_ID=wxd75d946d6978d183 pnpm --filter @personal-brand/taro build:`;产物包含对应 AppID/API 地址并通过 masking 检查。本轮不作为微信真机视觉验收。 -- 本阶段尚未完成:独立 `previewFixture` 与 bootstrap sample 的拆分、包内完整身份和媒体 fixture、按 checksum 提供导入资源、逐资源缺失诊断、画布内 CTA 导航、预览审计、短期 session/origin/CSP 隔离、跨模板/行业/版本矩阵及最终视觉验收。因此以上阶段清单仍保留未完成状态。 +- 初版剩余项(以下续进展为准):独立 `previewFixture` 与 bootstrap sample 的拆分、包内完整身份和媒体 fixture、按 checksum 提供导入资源、逐资源缺失诊断、画布内 CTA 导航、预览审计、短期 session/origin/CSP 隔离、跨模板/行业/版本矩阵及最终视觉验收。因此以上阶段清单仍保留未完成状态。 + +Phase 3 独立 fixture 与资源进展(2026-10-16): + +- 新增 `previewFixture.`:`schemaVersion: "1"`、身份白名单 `brand`、独立 `content` 和固定禁用策略 `safety`;使用 `packages/validation` 的同一 Zod 规则校验本地包和线上导入,不引入新校验体系。声明 fixture 的包必须覆盖全部兼容行业;无效声明不能回退到 `sampleContent`。 +- atelier 升为 `1.2.0`,保持旧版本不可变;预览主理人和品牌身份单独声明,`sampleContent` 仍只用于品牌起始内容,不修改 seed 或自动安装到现有品牌。尚未迁移的旧包走明确标注的兼容路径。 +- 管理页展示当前页面的 Admin 模块声明顺序、字段 binding、资源配置数量和缺失状态。这是声明诊断,不代表已经验证 renderer 的实际视觉顺序或全部字段消费。 +- 预览读取已导入 archive,核对 archive/content checksum 及逐图片 SHA-256,校验实际图片格式后以内嵌 data URL 提供给画布;不执行源码、不解压到公共目录、不回退到当前部署的同名图片。每图最多 2 MiB、总图片最多 8 MiB、最多 128 张,超出限额返回明确诊断;外链图片仍为待验证。 +- 同一预览响应同时包含版本 checksum、Runtime 和图片映射,切换版本/行业不会复用另一份图片;当前实现尚不包含可公开访问的资源 URL、远程资源探测或 CDN 缓存。 +- 本轮不涉及编辑 binding 或 renderer 布局变更;真实品牌编辑/保存/发布闭环及微信视觉验收仍按模板完成度规则独立验收。 +- 预览成功会写平台模板审计:操作者、版本 checksum、行业、fixture 来源及 requestId;不记录演示内容、不创建业务数据,关闭预览后刷新审计缓存。 +- 自动化新增独立 fixture 与 bootstrap 解耦、无效安全策略导入拒绝、敏感身份字段拒绝、兼容来源标识、archive 漂移阻断及图片类型/体积/摘要故障回归。API HTTP integration `52/52`、upload `2/2`、API unit `51/51`、Client/Admin unit 各 `6/6`、真实包图片浏览器交互 `1/1` 通过;typecheck、Admin production build、变更范围 lint 和 `template:check` 通过。 +- 仍待推进:预览上下文与 origin/CSP 隔离、画布内 CTA 导航、跨模板/行业/版本完整矩阵和最终视觉验收。前述初版实现记录中的 fixture 与包内资源缺口由本段更新,其余阶段门禁不变。 ### Phase 4:品牌安装、bootstrap 和发布 diff --git a/docs/template-registry.md b/docs/template-registry.md index eff1f34..9c0ad0d 100644 --- a/docs/template-registry.md +++ b/docs/template-registry.md @@ -16,7 +16,7 @@ - acheng-campus-food@1.0.0:餐饮场景,使用 food 行业能力。 - linjing-editorial@1.0.0:林境建筑画册,可用于 doors 和 personal 组合。 -- atelier-solopreneur@1.1.0:独立工坊方向,适配 personal 行业。 +- atelier-solopreneur@1.2.0:独立工坊方向,适配 personal 行业。 以上是仓库盘点,不表示三个包都已经通过线上导入、预览、品牌安装和微信上传验收。生成目录当前位于 packages/config/src/generated-template-packages.ts,后续必须由导出和 conformance 流程生成并校验。 diff --git a/packages/api-client/src/resources/template.ts b/packages/api-client/src/resources/template.ts index 7168ee7..e959170 100644 --- a/packages/api-client/src/resources/template.ts +++ b/packages/api-client/src/resources/template.ts @@ -133,6 +133,25 @@ export interface TemplatePackagePreview { missingSampleSlots: string[]; }; workspace: RuntimeWorkspace; + preview: { + assetFiles: Record; + fixtureSource: "previewFixture" | "legacy-sampleContent"; + safety: { submissions: "disabled"; customerRecords: "disabled"; contactActions: "disabled" }; + diagnostics: Array<{ code: string; severity: "warning"; message: string }>; + pages: Array<{ + key: string; + modules: Array<{ key: string; title: string; bindings: string[] }>; + }>; + assets: Array<{ + key: string; + label: string; + binding: string; + required: boolean; + populated: number; + total: number; + status: "missing" | "unverified" | "ready"; + }>; + }; } export interface TemplatePackageList { diff --git a/packages/config/src/generated-template-packages.ts b/packages/config/src/generated-template-packages.ts index 0635867..4720b30 100644 --- a/packages/config/src/generated-template-packages.ts +++ b/packages/config/src/generated-template-packages.ts @@ -1516,7 +1516,7 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[ }, { packageKey: "atelier-solopreneur", - version: "1.1.0", + version: "1.2.0", displayName: "独立工坊 · 品牌小程序", defaultBrandSlug: "atelier-studio", runtimeContract: "1.0", @@ -3352,6 +3352,462 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[ }, }, pages: ["pages/index/index", "pages/services/index", "pages/bookings/index"], + previewFixture: { + personal: { + schemaVersion: "1", + brand: { + name: "独立工坊 · 演示品牌", + tagline: "把专业经验变成值得信任的个人品牌", + description: + "为独立主理人提供品牌定位、产品设计与小程序开发支持。这些内容仅用于演示模板。", + hours: "工作日 10:00–18:00", + address: "远程协作 · 全国", + deliveryNote: "演示内容不接受真实咨询。", + }, + content: { + templateKey: "personal", + inquiryFormName: "品牌小程序需求意向单", + offerings: [ + { + kind: "service", + name: "校园餐饮品牌", + summary: "敏捷菜单 + 品牌展示 + 咨询承接", + categoryKey: "portfolio", + coverUrl: "/assets/cases/campus.jpg", + priceText: "按需求确认范围与报价", + config: { + spaceType: "餐饮品牌展示与咨询承接", + series: "试点架构原型", + keywords: ["模板演示", "可持续运营", "后台配置"], + details: { + background: + "校园餐饮品牌需要让访客快速了解餐品、营业安排与预订方式。本案例是用于验证系统结构的试点模板,不代表真实客户项目。", + designConcept: + "以品牌介绍建立第一印象,通过菜单与服务说明帮助访客了解供给,再通过咨询表单承接具体需求。", + crafts: [ + "品牌介绍与餐品内容由后台维护", + "草稿预览与发布分离,确认后更新公开内容", + "咨询表单收集需求,支持后续人工跟进", + ], + materialsList: [ + { + name: "品牌展示", + spec: "首页、主理人介绍与信任内容", + }, + { + name: "餐品管理", + spec: "列表、详情与封面配置", + }, + { + name: "需求承接", + spec: "咨询表单与跟进记录", + }, + ], + }, + }, + }, + { + kind: "service", + name: "个人编辑型品牌", + summary: "案例沉淀 + 专业表达 + 合作咨询", + categoryKey: "portfolio", + coverUrl: "/assets/cases/editorial.jpg", + priceText: "按需求确认范围与报价", + config: { + spaceType: "个人品牌作品展示与合作咨询", + series: "试点架构原型", + keywords: ["模板演示", "可持续运营", "后台配置"], + details: { + background: + "个人品牌需要将定位、代表作品与合作方式组织成清晰的了解路径。本案例展示编辑型模板的结构,不构成客户合作背书。", + designConcept: + "围绕专业表达与作品沉淀组织页面,让访客先了解品牌与工作方式,再浏览案例细节并提出合作需求。", + crafts: [ + "个人定位、作品与流程可持续更新", + "案例详情展示背景、构建思路与交付要点", + "通过咨询入口衔接后续需求沟通", + ], + materialsList: [ + { + name: "专业表达", + spec: "定位、简介与品牌理念", + }, + { + name: "作品沉淀", + spec: "案例列表、详情与图片", + }, + { + name: "合作沟通", + spec: "合作说明、咨询表单与跟进记录", + }, + ], + }, + }, + }, + ], + trustContent: [ + { + type: "credential", + title: "系统基础与合作边界", + content: + "当前已实现两套试点模板、网页内容管理、草稿预览与发布、咨询承接能力。具体交付页面、上线材料、费用、排期与后续支持范围,需要在需求沟通后确认。", + }, + ], + fields: [ + { + key: "name", + label: "称呼 / 品牌名称", + type: "text", + required: true, + }, + { + key: "industry", + label: "你的主营领域", + type: "radio", + required: true, + options: [ + { + label: "独立设计 / 建筑", + value: "独立设计 / 建筑", + }, + { + label: "摄影 / 视觉艺术", + value: "摄影 / 视觉艺术", + }, + { + label: "独立商业咨询", + value: "独立商业咨询", + }, + { + label: "教练 / 身心疗愈", + value: "教练 / 身心疗愈", + }, + { + label: "个人 IP / 创作者", + value: "个人 IP / 创作者", + }, + { + label: "精品品牌 / 实体", + value: "精品品牌 / 实体", + }, + { + label: "其他", + value: "其他", + }, + ], + }, + { + key: "needs", + label: "目前主要诉求与现状", + type: "textarea", + required: true, + }, + { + key: "timeline", + label: "预期启动排期", + type: "radio", + required: false, + options: [ + { + label: "本月内", + value: "本月内", + }, + { + label: "下月起", + value: "下月起", + }, + { + label: "先期评估", + value: "先期评估", + }, + ], + }, + { + key: "contact", + label: "联系方式(微信 / 电话)", + type: "text", + required: true, + }, + ], + capabilityKey: "inquiry", + brandConfig: { + visualPresentation: { + home: { + eyebrow: "独立开发者 · 品牌小程序构建", + title: "把个人品牌做成\n可持续运营的小程序", + subtitle: + "不只是做一个展示页面,而是为你搭建专业展示、内容运营与长期承接咨询的小程序系统。", + primaryAction: "预约咨询 / 聊聊需求", + secondaryAction: "查看服务架构", + featuresTitle: "差异化构建逻辑", + featuresEnglish: "Bespoke System", + casesTitle: "试点架构原型", + casesSubtitle: "验证模板 · 点击进入结构解析", + caseAction: "查看详情架构 →", + audienceTitle: "专属服务群体", + audienceEnglish: "Target Creators", + ctaTitle: "开启你的品牌小程序", + ctaSubtitle: "从策略梳理到上线的一站式交付", + ctaAction: "立即沟通", + }, + offerings: { + eyebrow: "完整独立交付 · 匠心构建", + title: "全链路服务与透明协作", + subtitle: "站在产品与长期运营的角度设计,专注交付可持续更新的个人品牌数字资产。", + deliverablesTitle: "交付体系", + deliverablesEnglish: "7 Deliverables", + processTitle: "协作流程", + processEnglish: "5 Phases · 节点透明可溯", + proofTitle: "信任基石", + proofEnglish: "Why bespoke", + ctaTitle: "对流程有疑问?直接聊聊", + ctaSubtitle: "一起梳理当前的品牌数字化需求,评估适合的结构与启动时间。", + ctaAction: "预约需求沟通", + }, + profile: { + eyebrow: "个人中心 · 状态与沟通", + title: "我的", + subtitle: "查看咨询记录、发起新咨询,或直接联系主理人。", + inquiryAction: "新增咨询", + timeHint: "约 3 分钟", + wechatLabel: "微信直聊", + copyAction: "复制微信", + contactHint: "尚未配置微信号,可先填写意向单", + promise: "先梳理可行性与时间节点,再确认合作范围", + recordsAction: "查看咨询记录 →", + faqTitle: "常见疑问解答", + faqSubtitle: "把透明与确定性放在第一位,说明合作的常见顾虑与流程。", + footerQuote: "Bespoke digital architecture for clear minds.", + footerNote: "用心打磨每一处体验 · 期待与你的灵感交汇", + recordsTitle: "我的咨询记录", + recordsDescription: "查看提交过的意向和主理人回复状态。", + }, + inquiry: { + eyebrow: "Atelier Note · 品牌意向梳理", + title: "品牌意向梳理 · 3 分钟完成", + subtitle: "用于需求梳理与排期评估,请填写当前业务、目标用户与主要诉求。", + submitLabel: "提交意向 · 预约沟通", + privacyTitle: "信息使用说明", + privacyNote: + "你提交的信息仅用于本次需求评估与后续联系。请勿填写密码、证件号码等敏感信息。", + followupHint: "提交后可在咨询记录中查看状态,具体响应时间以主理人确认为准。", + note: "填写的信息仅用于需求沟通与排期评估。", + }, + success: { + eyebrow: "已提交", + title: "意向已送达工坊", + intro: "已收到你的需求清单,将结合业务情况评估可行性,并通过你留下的联系方式沟通。", + recordsAction: "查看咨询记录", + homeAction: "返回首页", + }, + records: { + title: "我的品牌咨询", + createAction: "填写新需求", + emptyTitle: "还没有咨询记录", + emptyDescription: "提交品牌需求后,可以在这里查看后续跟进状态。", + emptyAction: "填写品牌需求", + }, + detail: { + priceLabel: "合作方式", + spaceLabel: "适用场景", + backgroundTitle: "案例与业务背景", + conceptTitle: "构建思路", + craftsTitle: "交付要点", + materialsTitle: "能力构成", + inquiryAction: "聊聊类似需求", + inquiryHint: "具体范围与报价在需求确认后提供。", + }, + }, + atelier: { + badges: [ + { + title: "完整可交付小程序", + }, + { + title: "支持后台随时更新", + }, + { + title: "支持长期演进", + }, + ], + features: [ + { + tag: "敏捷控制台", + title: "不是静态页面,而是可持续更新的系统", + description: + "拥有独立管理后台,案例作品、核心业务与介绍随时增删修改,让日常更新回归内容本身。", + }, + { + tag: "信任转化", + title: "先梳理定位与信任结构", + description: + "优先厘清客户的了解路径与业务背书,从第一屏价值表达,到高意向咨询的承接。", + }, + { + tag: "陪伴演进", + title: "交付之后,支持长期迭代", + description: "从上线协助到阶段性功能扩展,让品牌载体伴随业务持续成长。", + }, + ], + audiences: [ + { + symbol: "◎", + title: "摄影师", + description: "样片沉淀", + }, + { + symbol: "◇", + title: "咨询顾问", + description: "信任转化", + }, + { + symbol: "✎", + title: "独立设计", + description: "作品展呈", + }, + { + symbol: "↗", + title: "教练疗愈", + description: "需求预约", + }, + { + symbol: "▤", + title: "IP 创作者", + description: "私域载体", + }, + { + symbol: "⌂", + title: "小微实体", + description: "产品看板", + }, + ], + deliverables: [ + { + title: "品牌定位梳理", + tag: "清晰聚焦", + description: "提炼核心专长与目标客户画像,明确小程序核心诉求与转化路径。", + }, + { + title: "页面结构设计", + tag: "信任动线", + description: "梳理信息架构与信任动线,建立递进式了解路径。", + }, + { + title: "小程序视觉设计", + tag: "克制美学", + description: "结合微信使用习惯设计界面,用精致排版强化专业辨识度。", + }, + { + title: "内容字段规划", + tag: "结构资产", + description: "规范案例、服务与常见问题字段,让内容持续沉淀。", + }, + { + title: "后台管理配置", + tag: "自主维护", + description: "通过网页后台修改内容、上传图片,保存为草稿,确认后发布。", + }, + { + title: "发布上线协助", + tag: "上线协作", + description: "协助准备微信主体与类目材料、配置和提审,审核结果以微信平台为准。", + }, + { + title: "后续运营支持", + tag: "长期支持", + description: "提供操作说明与迭代建议,具体支持范围在合作时确认。", + }, + ], + process: [ + { + title: "需求沟通", + description: "交流专业背景、获客渠道与核心需求,评估可行性与排期。", + }, + { + title: "品牌结构梳理", + description: "提炼品牌关键词与信息架构,统一页面目标。", + }, + { + title: "界面设计确认", + description: "确认原型、视觉、排版与交互细节。", + }, + { + title: "内容配置与上线", + description: "录入案例与服务资料,联调、提审并协助发布。", + }, + { + title: "长期演进迭代", + description: "根据反馈完善内容,按约定范围迭代功能。", + }, + ], + proofs: [ + { + title: "已有系统基础", + description: "两套试点模板验证展示、配置与咨询链路。", + }, + { + title: "支持后台管理", + description: "内容由品牌自行维护,草稿确认后再发布。", + }, + { + title: "模块化扩展", + description: "复用稳定的系统能力,按需求扩展页面与服务。", + }, + { + title: "定位先于视觉", + description: "先说明你是谁、为谁服务、为什么值得信任。", + }, + { + title: "直接沟通与持续支持", + description: "独立主理人直接对接,合作边界与后续支持提前确认。", + }, + ], + faqs: [ + { + title: "还没整理好品牌文案,可以开始吗?", + description: + "可以先沟通。第一阶段一起梳理定位、核心业务与已有素材,再确定需要补齐的内容。", + }, + { + title: "后续内容可以自己修改吗?", + description: + "可以通过网页管理后台维护简介、案例、服务与表单。保存先形成草稿,确认并发布后,公开小程序才更新。", + }, + { + title: "可以先做轻量版本验证吗?", + description: + "可以。优先用展示、服务介绍与意向咨询等核心页面验证需求,再依据反馈扩展。", + }, + { + title: "设计和上线怎么配合?", + description: + "需求对齐、结构梳理、视觉确认、内容配置与上线分阶段推进。微信认证与审核由平台决定,所需材料和分工提前确认。", + }, + ], + identity: { + status: "当前可接新项目", + experience: "10 年", + tags: [ + { + title: "大屏可视化", + }, + { + title: "小程序", + }, + ], + }, + }, + founder: "林予 · 示例主理人", + title: "产品设计 / 全栈开发", + }, + }, + safety: { + submissions: "disabled", + customerRecords: "disabled", + contactActions: "disabled", + }, + }, + }, visualTemplateKey: "atelier-solopreneur", }, { @@ -4904,4 +5360,4 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[ }, ]; export const generatedTemplatePackageRegistryHash = - "6a2736b95fc446c4a9c8a106d8d4726f393992fefcfe9a8a27e8509fdca8c5a9"; + "409bf2553c819c916ba1036eed103cae7b707f88b7b396fd566dc77c02b1ec03"; diff --git a/packages/config/src/template-package-manifest.ts b/packages/config/src/template-package-manifest.ts index cc233f2..77f65cc 100644 --- a/packages/config/src/template-package-manifest.ts +++ b/packages/config/src/template-package-manifest.ts @@ -3,6 +3,26 @@ import type { CapabilityKey } from "./template-keys.js"; import type { VisualTemplateKey } from "./template-keys.js"; import type { TemplateSampleContent } from "./template-sample-content.js"; +export interface TemplatePreviewFixture { + schemaVersion: "1"; + brand: { + name: string; + tagline: string; + description: string; + avatarUrl?: string; + coverUrl?: string; + hours?: string; + address?: string; + deliveryNote?: string; + }; + content: TemplateSampleContent; + safety: { + submissions: "disabled"; + customerRecords: "disabled"; + contactActions: "disabled"; + }; +} + export interface TemplatePackageManifest { packageKey: string; version: string; @@ -127,4 +147,5 @@ export interface TemplatePackageManifest { }[]; overrides?: readonly string[]; sampleContent?: Partial>; + previewFixture?: Partial>; } diff --git a/packages/config/src/visual-templates.ts b/packages/config/src/visual-templates.ts index 85072f8..7ef1805 100644 --- a/packages/config/src/visual-templates.ts +++ b/packages/config/src/visual-templates.ts @@ -40,7 +40,7 @@ export const visualTemplates: Record; + previewFixture?: Record; }; export function validateTemplatePackageManifest(value: unknown): string[] { const errors: string[] = []; if (!value || typeof value !== "object") return ["manifest must be an object"]; const manifest = value as Partial; + if (manifest.previewFixture !== undefined) { + for (const issue of validateTemplatePreviewFixtures( + manifest.previewFixture, + manifest.supportedIndustryTemplates ?? [], + )) + errors.push(`previewFixture.${issue.path}: ${issue.message}`); + } if (!manifest.packageKey?.trim()) errors.push("packageKey is required"); if (!manifest.version?.trim()) errors.push("version is required"); if (manifest.runtimeContract !== TEMPLATE_RUNTIME_CONTRACT) diff --git a/packages/template-contract/test/manifest.test.mjs b/packages/template-contract/test/manifest.test.mjs index 33233ee..48690bb 100644 --- a/packages/template-contract/test/manifest.test.mjs +++ b/packages/template-contract/test/manifest.test.mjs @@ -8,6 +8,45 @@ import { runtimeContractForBinding } from "../../types/src/runtime-content-contr const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +test("independent preview fixtures validate safety and industry without changing bootstrap content", () => { + const manifest = JSON.parse( + fs.readFileSync(path.join(packageRoot, "template-atelier-solopreneur/template.json"), "utf8"), + ); + assert.deepEqual(validateTemplatePackageManifest(manifest), []); + assert.notEqual( + manifest.previewFixture.personal.content.brandConfig.founder, + manifest.sampleContent.personal.brandConfig.founder, + ); + for (const mutate of [ + (value) => { + value.previewFixture.personal.safety.submissions = "enabled"; + }, + (value) => { + value.previewFixture.personal.brand.contactPhone = "13800000000"; + }, + (value) => { + value.previewFixture.personal.content.fields = [null]; + }, + (value) => { + value.previewFixture.personal.content.templateKey = "food"; + }, + (value) => { + value.previewFixture = []; + }, + (value) => { + value.previewFixture.personal = null; + }, + ]) { + const invalid = structuredClone(manifest); + mutate(invalid); + assert.ok( + validateTemplatePackageManifest(invalid).some((message) => + message.startsWith("previewFixture"), + ), + ); + } +}); + for (const key of ["acheng-campus-food", "linjing-editorial"]) { test(`${key} declares valid admin content and asset requirements`, () => { const manifestPath = path.join(packageRoot, `template-${key}`, "template.json"); diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts index 0a27e3f..aa3c8a1 100644 --- a/packages/validation/src/index.ts +++ b/packages/validation/src/index.ts @@ -106,3 +106,90 @@ export function validateFieldSnapshot(value: unknown): ValidationIssue[] { export function validateOfferingConfig(value: unknown): ValidationIssue[] { return value === undefined || value === null ? [] : issues(offeringConfigSchema.safeParse(value)); } + +// 预览身份采用白名单,联系信息由预览运行时固定为空,不允许导入真实联系人。 +export const templatePreviewFixtureSchema = z + .object({ + schemaVersion: z.literal("1"), + brand: z + .object({ + name: z.string().trim().min(1), + tagline: z.string(), + description: z.string(), + avatarUrl: z.string().optional(), + coverUrl: z.string().optional(), + hours: z.string().optional(), + address: z.string().optional(), + deliveryNote: z.string().optional(), + }) + .strict(), + content: z + .object({ + templateKey: z.string().min(1), + brandConfig: z.record(z.unknown()).optional(), + inquiryFormName: z.string().trim().min(1), + capabilityKey: z.string().min(1), + offerings: z.array( + z + .object({ + kind: z.enum(["service", "product", "package", "subscription"]), + name: z.string().trim().min(1), + summary: z.string(), + categoryKey: z.string().min(1), + coverUrl: z.string().optional(), + priceText: z.string().optional(), + config: z.record(z.unknown()).optional(), + }) + .strict(), + ), + trustContent: z.array( + z + .object({ + type: z.string().min(1), + title: z.string(), + content: z.string(), + summary: z.string().optional(), + config: z.record(z.unknown()).optional(), + }) + .strict(), + ), + fields: fieldSnapshotSchema, + }) + .strict(), + safety: z + .object({ + submissions: z.literal("disabled"), + customerRecords: z.literal("disabled"), + contactActions: z.literal("disabled"), + }) + .strict(), + }) + .strict(); + +export function validateTemplatePreviewFixture(value: unknown): ValidationIssue[] { + return issues(templatePreviewFixtureSchema.safeParse(value)); +} + +export function validateTemplatePreviewFixtures( + value: unknown, + industries: readonly string[], +): ValidationIssue[] { + if (!value || typeof value !== "object" || Array.isArray(value)) + return [{ path: "", message: "must be an industry map" }]; + const fixtures = value as Record; + const result: ValidationIssue[] = []; + for (const industry of new Set([...industries, ...Object.keys(fixtures)])) { + if (!industries.includes(industry)) + result.push({ path: industry, message: "is not a supported industry template" }); + const fixture = templatePreviewFixtureSchema.safeParse(fixtures[industry]); + result.push( + ...issues(fixture).map((issue) => ({ + path: `${industry}.${issue.path}`, + message: issue.message, + })), + ); + if (fixture.success && fixture.data.content.templateKey !== industry) + result.push({ path: `${industry}.content.templateKey`, message: "must match its key" }); + } + return result; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 56c270c..0f75031 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -288,7 +288,11 @@ importers: specifier: workspace:* version: link:../template-contract - packages/template-contract: {} + packages/template-contract: + dependencies: + '@personal-brand/validation': + specifier: workspace:^ + version: link:../validation packages/template-linjing-editorial: dependencies: diff --git a/scripts/template-conformance.test.mjs b/scripts/template-conformance.test.mjs index 5187dab..bb35d22 100644 --- a/scripts/template-conformance.test.mjs +++ b/scripts/template-conformance.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; +import { readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; @@ -9,8 +10,20 @@ const script = path.join(root, "scripts/template-conformance.cjs"); test("template:conformance automatically discovers all template packages", () => { const output = execFileSync(process.execPath, [script], { cwd: root, encoding: "utf8" }); - assert.match(output, /Conformance passed: acheng-campus-food@1\.0\.0/); - assert.match(output, /Conformance passed: atelier-solopreneur@1\.1\.0/); - assert.match(output, /Conformance passed: linjing-editorial@1\.0\.0/); - assert.match(output, /Template conformance passed: 3 package\(s\)\./); + const manifests = readdirSync(path.join(root, "packages")) + .filter((name) => name.startsWith("template-")) + .flatMap((name) => { + try { + return [ + JSON.parse(readFileSync(path.join(root, "packages", name, "template.json"), "utf8")), + ]; + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } + }); + assert.ok(manifests.length > 0); + for (const manifest of manifests) + assert.ok(output.includes(`Conformance passed: ${manifest.packageKey}@${manifest.version} (`)); + assert.ok(output.includes(`Template conformance passed: ${manifests.length} package(s).`)); }); diff --git a/scripts/template-pack.test.mjs b/scripts/template-pack.test.mjs index 15a6a46..1cde2b4 100644 --- a/scripts/template-pack.test.mjs +++ b/scripts/template-pack.test.mjs @@ -1,17 +1,24 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const script = path.join(root, "scripts/template-pack.cjs"); -const templatePackages = [ - ["acheng-campus-food", "1.0.0"], - ["atelier-solopreneur", "1.1.0"], - ["linjing-editorial", "1.0.0"], -]; +const templatePackages = readdirSync(path.join(root, "packages")) + .filter( + (name) => + name.startsWith("template-") && + existsSync(path.join(root, "packages", name, "template.json")), + ) + .map((name) => { + const manifest = JSON.parse( + readFileSync(path.join(root, "packages", name, "template.json"), "utf8"), + ); + return [manifest.packageKey, manifest.version]; + }); for (const [packageKey, version] of templatePackages) { test(`${packageKey} produces a stable package directory and archive`, () => {