#!/usr/bin/env node import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile } from "node:fs/promises"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; const CONTRACT_MIGRATION = "20261018120000_enforce_single_template_contract"; const source = path.resolve(process.argv[2] ?? "."); const apply = process.argv.includes("--apply"); const catalogPath = path.join(source, "template-catalog.json"); const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url)); const { PrismaClient } = apiRequire("@prisma/client"); function object(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : null; } function nonEmpty(value) { return typeof value === "string" && value.trim() ? value.trim() : null; } function sha256(content) { return createHash("sha256").update(content).digest("hex"); } function supportsIndustry(version, industry) { const manifest = object(version.manifestSnapshot) ?? object(version.manifest) ?? {}; const fixture = object(object(manifest.previewFixture)?.[industry]); return ( version.status === "published" && manifest.packageKey === version.packageKey && manifest.visualTemplateKey === version.packageKey && manifest.version === version.version && manifest.runtimeContract === "1.0" && Array.isArray(manifest.supportedIndustryTemplates) && manifest.supportedIndustryTemplates.includes(industry) && fixture !== null ); } function versionShape(version) { return { id: version.id, packageKey: version.packageKey, version: version.version, status: version.status, contentChecksum: version.contentChecksum, manifestSnapshot: version.manifestSnapshot ?? version.manifest, }; } /** * 只规划旧数据到单一模板契约的转换。运行时不得复用此逻辑做兜底。 */ export function buildTemplateContractPlan({ brands, versions, catalog }) { const catalogPackages = catalog.packages ?? []; const normalizedVersions = versions.map(versionShape); const imports = new Map(); const installations = []; for (const brand of brands) { if (!Array.isArray(brand.installations) || brand.installations.length > 1) throw new Error(`品牌 ${brand.slug} 存在多条模板安装记录,必须人工处理`); const installation = brand.installations?.[0] ?? null; const declarations = [ ["installation.visualTemplateKey", nonEmpty(installation?.visualTemplateKey)], ["brand.config.visualTemplateKey", nonEmpty(brand.brandVisualTemplateKey)], [ "installation.configSnapshot.visualTemplateKey", nonEmpty(installation?.snapshotVisualTemplateKey), ], ["installation.configSnapshot.packageKey", nonEmpty(installation?.snapshotPackageKey)], ].filter(([, value]) => value); const declaredKeys = [...new Set(declarations.map(([, value]) => value))]; if (declaredKeys.length > 1) throw new Error(`品牌 ${brand.slug} 的模板包声明冲突:${declaredKeys.join("、")}`); let selected; const linkedId = nonEmpty(installation?.templatePackageVersionId); if (linkedId) { selected = normalizedVersions.find((version) => version.id === linkedId); if (!selected || !supportsIndustry(selected, brand.templateKey)) throw new Error(`品牌 ${brand.slug} 已关联的模板包版本不符合契约`); if (declaredKeys[0] && declaredKeys[0] !== selected.packageKey) throw new Error(`品牌 ${brand.slug} 的模板包声明与已关联版本冲突`); } else { const packageKey = declaredKeys[0]; if (!packageKey) throw new Error(`品牌 ${brand.slug} 没有可审计的旧模板包声明`); const candidates = normalizedVersions.filter( (version) => version.packageKey === packageKey && supportsIndustry(version, brand.templateKey), ); if (candidates.length > 1) throw new Error(`品牌 ${brand.slug} 匹配到多个已发布模板包版本,必须人工处理`); if (candidates.length === 1) { selected = candidates[0]; } else { const bundled = catalogPackages.filter( (entry) => entry.packageKey === packageKey && supportsIndustry( { packageKey: entry.packageKey, version: entry.version, status: "published", manifestSnapshot: entry.manifest, }, brand.templateKey, ), ); if (bundled.length !== 1) throw new Error( `品牌 ${brand.slug} 在发布包中匹配到 ${bundled.length} 个可用模板包,必须人工处理`, ); selected = bundled[0]; imports.set(`${selected.packageKey}@${selected.version}`, selected); } } installations.push({ brandId: brand.brandId, slug: brand.slug, installationId: installation?.id ?? null, templateKey: brand.templateKey, packageKey: selected.packageKey, version: selected.version, packageVersionId: selected.id ?? null, catalogImport: !selected.id, contentChecksum: selected.contentChecksum, configSnapshot: selected.manifestSnapshot ?? selected.manifest, }); } return { catalogImports: [...imports.values()], installations, }; } async function loadInputs(prisma) { const columns = await prisma.$queryRawUnsafe(` SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name IN ('BrandTemplateInstallation', 'TemplatePackageVersion') AND column_name IN ('visualTemplateKey', 'templatePackageVersionId') `); const installationVisual = columns.some( (column) => column.table_name === "BrandTemplateInstallation" && column.column_name === "visualTemplateKey", ); const versionVisual = columns.some( (column) => column.table_name === "TemplatePackageVersion" && column.column_name === "visualTemplateKey", ); if (!installationVisual && !versionVisual) return { alreadyApplied: true }; const tables = await prisma.$queryRawUnsafe(` SELECT to_regclass('"TemplatePackage"')::text AS package_table, to_regclass('"TemplatePackageVersion"')::text AS version_table, to_regclass('"TemplatePackageAuditLog"')::text AS audit_table `); if (!tables[0]?.package_table || !tables[0]?.version_table || !tables[0]?.audit_table) throw new Error("模板包目录表尚未创建,请先让 Prisma 应用目录类 migration"); const brands = await prisma.$queryRawUnsafe(` SELECT brand.id AS "brandId", brand.slug, brand."templateKey", brand.config->>'visualTemplateKey' AS "brandVisualTemplateKey", installation.id AS "installationId", installation."templatePackageVersionId", installation."visualTemplateKey" AS "installationVisualTemplateKey", installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey", installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey" FROM "BrandProfile" brand LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand.id ORDER BY brand.slug, installation.id `); const grouped = new Map(); for (const row of brands) { const entry = grouped.get(row.brandId) ?? { brandId: row.brandId, slug: row.slug, templateKey: row.templateKey, brandVisualTemplateKey: row.brandVisualTemplateKey, installations: [], }; if (row.installationId) { entry.installations.push({ id: row.installationId, templatePackageVersionId: row.templatePackageVersionId, visualTemplateKey: row.installationVisualTemplateKey, snapshotVisualTemplateKey: row.snapshotVisualTemplateKey, snapshotPackageKey: row.snapshotPackageKey, }); } grouped.set(row.brandId, entry); } const versions = await prisma.$queryRawUnsafe(` SELECT id, "packageKey", version, status, "contentChecksum", "manifestSnapshot" FROM "TemplatePackageVersion" ORDER BY "packageKey", version `); const catalog = JSON.parse(await readFile(catalogPath, "utf8")); if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages)) throw new Error("发布包模板目录格式无效"); return { alreadyApplied: false, brands: [...grouped.values()], versions, catalog }; } async function ensureArtifact(root, entry) { const sourceArchive = path.join(source, entry.archivePath); const content = await readFile(sourceArchive); if (sha256(content) !== entry.archiveChecksum) throw new Error(`发布包模板归档校验失败:${entry.packageKey}@${entry.version}`); const target = path.join( root, "shared/template-artifacts", entry.packageKey, entry.version, entry.archiveChecksum + ".tar.gz", ); await mkdir(path.dirname(target), { recursive: true }); try { const existing = await readFile(target); if (sha256(existing) === entry.archiveChecksum) return target; } catch {} await copyFile(sourceArchive, target); return target; } async function runApply(prisma, plan, deployRoot, actorId) { const imported = new Map(); await prisma.$transaction(async (tx) => { for (const entry of plan.catalogImports) { const artifactPath = await ensureArtifact(deployRoot, entry); const existingRows = await tx.$queryRawUnsafe( `SELECT id, status, "contentChecksum", "manifestSnapshot" FROM "TemplatePackageVersion" WHERE "packageKey" = $1 AND version = $2`, entry.packageKey, entry.version, ); let version = existingRows[0]; if (version) { if (version.contentChecksum !== entry.contentChecksum) throw new Error(`已存在不同内容的模板包版本:${entry.packageKey}@${entry.version}`); if (version.status === "imported") { await tx.$executeRawUnsafe( `UPDATE "TemplatePackageVersion" SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP WHERE id = $1`, version.id, ); await tx.$executeRawUnsafe( `INSERT INTO "TemplatePackageAuditLog" ("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata) VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`, randomUUID(), version.id, actorId, JSON.stringify({ source: "legacy-template-contract-migration" }), ); } else if (version.status !== "published") { throw new Error( `模板包版本 ${entry.packageKey}@${entry.version} 状态为 ${version.status},不能用于旧数据迁移`, ); } } else { await tx.$executeRawUnsafe( `INSERT INTO "TemplatePackage" (id, "packageKey", "createdAt", "updatedAt") VALUES ($1, $2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) ON CONFLICT ("packageKey") DO NOTHING`, randomUUID(), entry.packageKey, ); const packageRows = await tx.$queryRawUnsafe( `SELECT id FROM "TemplatePackage" WHERE "packageKey" = $1`, entry.packageKey, ); const templatePackageId = packageRows[0]?.id; if (!templatePackageId) throw new Error(`无法创建模板包:${entry.packageKey}`); const versionId = randomUUID(); await tx.$executeRawUnsafe( `INSERT INTO "TemplatePackageVersion" ( id, "templatePackageId", "packageKey", version, "displayName", "visualTemplateKey", status, "manifestSnapshot", "validationReport", "contentChecksum", "archiveChecksum", "artifactPath", "importedById", "importedAt", "createdAt", "updatedAt" ) VALUES ( $1, $2, $3, $4, $5, $3, 'imported', $6::jsonb, $7::jsonb, $8, $9, $10, $11, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP )`, versionId, templatePackageId, entry.packageKey, entry.version, entry.displayName, JSON.stringify(entry.manifest), JSON.stringify(entry.validationReport), entry.contentChecksum, entry.archiveChecksum, artifactPath, actorId, ); await tx.$executeRawUnsafe( `INSERT INTO "TemplatePackageAuditLog" ("id", "templatePackageVersionId", "actorId", action, "toStatus", metadata) VALUES ($1, $2, $3, 'imported', 'imported', $4::jsonb)`, randomUUID(), versionId, actorId, JSON.stringify({ source: "legacy-template-contract-migration", contentChecksum: entry.contentChecksum, archiveChecksum: entry.archiveChecksum, }), ); await tx.$executeRawUnsafe( `UPDATE "TemplatePackageVersion" SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP WHERE id = $1`, versionId, ); await tx.$executeRawUnsafe( `INSERT INTO "TemplatePackageAuditLog" ("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata) VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`, randomUUID(), versionId, actorId, JSON.stringify({ source: "legacy-template-contract-migration" }), ); version = { id: versionId, status: "published", contentChecksum: entry.contentChecksum, }; } imported.set(`${entry.packageKey}@${entry.version}`, version.id); } for (const installation of plan.installations) { const packageVersionId = installation.packageVersionId ?? imported.get(`${installation.packageKey}@${installation.version}`); if (!packageVersionId) throw new Error(`模板包版本未导入:${installation.packageKey}@${installation.version}`); if (installation.installationId) { await tx.$executeRawUnsafe( `UPDATE "BrandTemplateInstallation" SET "templateKey" = $2, "templateVersion" = $3, "templatePackageVersionId" = $4, "contentChecksum" = $5, "configSnapshot" = $6::jsonb, "visualTemplateKey" = $7, "updatedAt" = CURRENT_TIMESTAMP WHERE id = $1`, installation.installationId, installation.templateKey, installation.version, packageVersionId, installation.contentChecksum, JSON.stringify(installation.configSnapshot), installation.packageKey, ); } else { await tx.$executeRawUnsafe( `INSERT INTO "BrandTemplateInstallation" ( id, "brandId", "templateKey", "templateVersion", "templatePackageVersionId", "contentChecksum", "configSnapshot", "previousSnapshots", "visualTemplateKey", "installedAt", "updatedAt" ) VALUES ( $1, $2, $3, $4, $5, $6, $7::jsonb, '[]'::jsonb, $8, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP )`, randomUUID(), installation.brandId, installation.templateKey, installation.version, packageVersionId, installation.contentChecksum, JSON.stringify(installation.configSnapshot), installation.packageKey, ); } } }); } async function resolveFailedMigration(root) { const result = spawnSync( "pnpm", [ "--filter", "@personal-brand/api", "exec", "prisma", "migrate", "resolve", "--rolled-back", CONTRACT_MIGRATION, ], { cwd: root, stdio: "inherit", env: process.env }, ); if (result.status !== 0) throw new Error("无法将失败的模板契约 migration 标记为 rolled-back"); } async function main() { const deployRoot = process.env.DEPLOY_ROOT; if (!deployRoot || !path.isAbsolute(deployRoot)) throw new Error("DEPLOY_ROOT must be an absolute path"); const prisma = new PrismaClient(); try { const inputs = await loadInputs(prisma); if (inputs.alreadyApplied) { console.log("template contract migration already applied; no legacy data to prepare"); return 0; } const plan = buildTemplateContractPlan(inputs); console.log( JSON.stringify( { apply, catalogImports: plan.catalogImports.map((entry) => ({ packageKey: entry.packageKey, version: entry.version, contentChecksum: entry.contentChecksum, })), installations: plan.installations.map((entry) => ({ slug: entry.slug, templateKey: entry.templateKey, packageKey: entry.packageKey, version: entry.version, action: entry.installationId ? "update" : "create", })), }, null, 2, ), ); if (!apply) return 0; const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin"; const actors = await prisma.$queryRawUnsafe( `SELECT id FROM "AdminUser" WHERE username = $1 AND "isEnabled" = true`, actorUsername, ); if (!actors[0]) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`); await runApply(prisma, plan, deployRoot, actors[0].id); const failed = await prisma.$queryRawUnsafe( `SELECT 1 FROM _prisma_migrations WHERE migration_name = $1 AND finished_at IS NULL AND rolled_back_at IS NULL`, CONTRACT_MIGRATION, ); if (failed.length) await resolveFailedMigration(source); console.log("legacy template contract data prepared"); return 0; } finally { await prisma.$disconnect(); } } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { main() .then((code) => { process.exitCode = code; }) .catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); }