fix: 收口发布包完整性与模板契约迁移

This commit is contained in:
que01 committed 2026-10-20 17:59:11 +08:00
1 parent 38e9d59864
commit 16fd827634
7 files changed
+812 -26

No files matched your search

@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-20T09:00:52.740+00:00",
"generatedAt": "2026-10-20T09:58:15.011Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
@@ -256,5 +256,5 @@
}
}
},
"sourceTreeHash": "2e0f2c24ab52790d4684385a4e40a42a156202ae14fbf690b74c3bcce7084699"
"sourceTreeHash": "a1dbfac7dbf6897814276ca0188c78808c587253307fa6f865761645bf054cdb"
}
+2
View File
@@ -381,6 +381,8 @@ try {
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
await pruneBackups(path.join(root, "shared/backups"));
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
const seedDirectory = path.join(process.env.LOCAL_MEDIA_ROOT, "seed");
await copyMissingFiles(path.join(release, "seed-media"), seedDirectory);
+479
View File
@@ -0,0 +1,479 @@
#!/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;
});
}
+99
View File
@@ -0,0 +1,99 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildTemplateContractPlan } from "./prepare-template-contract.mjs";
function manifest(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
visualTemplateKey: packageKey,
runtimeContract: "1.0",
supportedIndustryTemplates: [industry],
previewFixture: { [industry]: { schemaVersion: "1" } },
};
}
function catalogEntry(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
displayName: packageKey,
contentChecksum: "a".repeat(64),
validationReport: { errors: [] },
manifest: manifest(packageKey, industry, version),
archiveChecksum: "b".repeat(64),
archivePath: `template-artifacts/${packageKey}/${version}/${"b".repeat(64)}.tar.gz`,
};
}
test("template contract plan resolves legacy installations and imports missing packages", () => {
const existing = catalogEntry("atelier-solopreneur", "personal", "1.3.2");
const defaultBrand = catalogEntry("acheng-campus-food", "food", "1.0.3");
const plan = buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [existing, defaultBrand] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "atelier-studio",
templateKey: "personal",
brandVisualTemplateKey: "atelier-solopreneur",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: null,
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
{
brandId: "brand-2",
slug: "default-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [],
},
],
});
assert.deepEqual(
plan.catalogImports.map((entry) => `${entry.packageKey}@${entry.version}`),
["atelier-solopreneur@1.3.2", "acheng-campus-food@1.0.3"],
);
assert.equal(plan.installations.length, 2);
assert.equal(plan.installations[0].installationId, "installation-1");
assert.equal(plan.installations[0].packageVersionId, null);
assert.equal(plan.installations[0].catalogImport, true);
assert.equal(plan.installations[1].installationId, null);
assert.equal(plan.installations[1].slug, "default-brand");
});
test("template contract plan rejects conflicting legacy package declarations", () => {
assert.throws(
() =>
buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "conflicting-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: "linjing-editorial",
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
],
}),
/模板包声明冲突/,
);
});
+60
View File
@@ -54,6 +54,66 @@ export async function checkPackage(directory) {
if (content.byteLength !== file.bytes || digest !== file.sha256)
throw new Error("Release checksum mismatch: " + file.path);
}
const workspacePackages = new Map();
for (const relative of actual.filter(
(file) => file === "package.json" || file.endsWith("/package.json"),
)) {
const workspacePackage = JSON.parse(await readFile(path.join(directory, relative), "utf8"));
if (typeof workspacePackage.name !== "string" || !workspacePackage.name)
throw new Error("Workspace package has no name: " + relative);
workspacePackages.set(workspacePackage.name, {
directory: path.posix.dirname(relative),
manifest: workspacePackage,
});
}
for (const [name, workspacePackage] of workspacePackages) {
for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
for (const [dependency, range] of Object.entries(workspacePackage.manifest[section] ?? {})) {
if (typeof range !== "string" || !range.startsWith("workspace:")) continue;
const target = workspacePackages.get(dependency);
if (!target) {
throw new Error(
`Release is missing workspace dependency ${dependency} required by ${name}`,
);
}
if (target.directory === ".") {
throw new Error(`Workspace dependency ${dependency} cannot be the release root package`);
}
}
}
}
if (actual.includes("template-catalog.json")) {
const catalog = JSON.parse(
await readFile(path.join(directory, "template-catalog.json"), "utf8"),
);
if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages))
throw new Error("Invalid template catalog");
const keys = new Set();
for (const entry of catalog.packages) {
if (
typeof entry.packageKey !== "string" ||
typeof entry.version !== "string" ||
typeof entry.archiveChecksum !== "string" ||
typeof entry.archivePath !== "string"
)
throw new Error("Invalid template catalog entry");
if (keys.has(entry.packageKey))
throw new Error("Duplicate template package in catalog: " + entry.packageKey);
keys.add(entry.packageKey);
if (
path.isAbsolute(entry.archivePath) ||
entry.archivePath.split("/").includes("..") ||
!actual.includes(entry.archivePath)
)
throw new Error("Template archive is missing from release: " + entry.packageKey);
const digest = createHash("sha256")
.update(await readFile(path.join(directory, entry.archivePath)))
.digest("hex");
if (digest !== entry.archiveChecksum)
throw new Error("Template archive checksum mismatch: " + entry.packageKey);
}
}
return manifest;
}
+85
View File
@@ -65,6 +65,7 @@ test("release package checker rejects files missing from the manifest", async ()
test("release package checker rejects patched dependencies missing from the package", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({
name: "fixture-release",
pnpm: {
patchedDependencies: {
"example-package@1.0.0": "patches/example-package.patch",
@@ -78,3 +79,87 @@ test("release package checker rejects patched dependencies missing from the pack
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker accepts a complete workspace dependency closure", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({ name: "fixture-release" }),
"packages/api/package.json": JSON.stringify({
name: "@fixture/api",
dependencies: { "@fixture/contract": "workspace:^" },
}),
"packages/contract/package.json": JSON.stringify({
name: "@fixture/contract",
}),
});
try {
await checkPackage(directory);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker rejects a missing workspace dependency", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({ name: "fixture-release" }),
"packages/api/package.json": JSON.stringify({
name: "@fixture/api",
dependencies: { "@fixture/contract": "workspace:^" },
}),
});
try {
await assert.rejects(
checkPackage(directory),
/missing workspace dependency @fixture\/contract/,
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker accepts a valid template catalog", async () => {
const archive = Buffer.from("template archive");
const archiveChecksum = createHash("sha256").update(archive).digest("hex");
const archivePath = `template-artifacts/example/1.0.0/${archiveChecksum}.tar.gz`;
const directory = await createPackage({
[archivePath]: archive,
"template-catalog.json": JSON.stringify({
formatVersion: "1",
packages: [
{
packageKey: "example",
version: "1.0.0",
archiveChecksum,
archivePath,
},
],
}),
});
try {
await checkPackage(directory);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker rejects a template archive with a mismatched checksum", async () => {
const archivePath = "template-artifacts/example/1.0.0/archive.tar.gz";
const directory = await createPackage({
[archivePath]: "template archive",
"template-catalog.json": JSON.stringify({
formatVersion: "1",
packages: [
{
packageKey: "example",
version: "1.0.0",
archiveChecksum: "0".repeat(64),
archivePath,
},
],
}),
});
try {
await assert.rejects(checkPackage(directory), /template archive checksum mismatch/i);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
+85 -24
View File
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
@@ -71,9 +71,13 @@ async function copyWorkspace(workspace) {
const target = path.join(output, workspace);
await mkdir(target, { recursive: true });
await cp(path.join(source, "package.json"), path.join(target, "package.json"));
await cp(path.join(source, "src"), path.join(target, "src"), { recursive: true });
await cp(path.join(source, "dist"), path.join(target, "dist"), { recursive: true });
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
for (const directory of ["src", "dist"]) {
if (!existsSync(path.join(source, directory))) continue;
await cp(path.join(source, directory), path.join(target, directory), { recursive: true });
}
if (existsSync(path.join(source, "tsconfig.json"))) {
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
}
if (workspace === "apps/api") {
await cp(path.join(source, "prisma/schema.prisma"), path.join(target, "prisma/schema.prisma"));
await cp(path.join(source, "prisma/migrations"), path.join(target, "prisma/migrations"), {
@@ -92,15 +96,80 @@ async function copyTaroWorkspace() {
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
}
async function copyTemplatePackage(directoryName) {
const source = path.join(root, "packages", directoryName);
const target = path.join(output, "packages", directoryName);
await mkdir(target, { recursive: true });
await cp(path.join(source, "package.json"), path.join(target, "package.json"));
await cp(path.join(source, "template.json"), path.join(target, "template.json"));
await cp(path.join(source, "miniapp"), path.join(target, "miniapp"), { recursive: true });
await cp(path.join(source, "taro"), path.join(target, "taro"), { recursive: true });
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
function sha256File(file) {
return readFile(file).then((content) => createHash("sha256").update(content).digest("hex"));
}
async function discoverTemplatePackages() {
const packages = [];
for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true })) {
const templateDirectory = path.join(root, "packages", entry.name);
if (
entry.isDirectory() &&
entry.name.startsWith("template-") &&
existsSync(path.join(templateDirectory, "template.json")) &&
existsSync(path.join(templateDirectory, "taro/index.tsx"))
) {
packages.push({
directoryName: entry.name,
manifest: JSON.parse(await readFile(path.join(templateDirectory, "template.json"), "utf8")),
});
}
}
return packages.sort((left, right) =>
left.manifest.packageKey.localeCompare(right.manifest.packageKey),
);
}
async function buildTemplateCatalog() {
const packedRoot = path.join(root, "dist/template-packages");
await rm(packedRoot, { recursive: true, force: true });
const packages = [];
for (const template of await discoverTemplatePackages()) {
const { packageKey, version } = template.manifest;
if (typeof packageKey !== "string" || typeof version !== "string")
throw new Error("Template manifest must declare packageKey and version");
run("node", ["scripts/template-pack.cjs", "--template", packageKey, "--out", packedRoot]);
const packedDirectory = path.join(packedRoot, `${packageKey}-${version}`);
const checksums = JSON.parse(
await readFile(path.join(packedDirectory, "checksums.json"), "utf8"),
);
const archiveSource = packedDirectory + ".tar.gz";
const archiveChecksum = await sha256File(archiveSource);
const archivePath = path.posix.join(
"template-artifacts",
packageKey,
version,
archiveChecksum + ".tar.gz",
);
const archiveTarget = path.join(output, archivePath);
await mkdir(path.dirname(archiveTarget), { recursive: true });
await cp(archiveSource, archiveTarget);
const target = path.join(output, "packages", template.directoryName);
await cp(packedDirectory, target, { recursive: true });
packages.push({
packageKey,
version,
displayName: template.manifest.displayName,
supportedIndustryTemplates: template.manifest.supportedIndustryTemplates,
manifest: template.manifest,
validationReport: {
formatVersion: "1",
errors: [],
fileCount: checksums.files.length,
extractedBytes: checksums.files.reduce((total, file) => total + file.bytes, 0),
files: checksums.files,
},
contentChecksum: checksums.contentChecksum,
archiveChecksum,
archivePath,
});
}
await writeFile(
path.join(output, "template-catalog.json"),
JSON.stringify({ formatVersion: "1", packages }, null, 2) + "\n",
);
return packages;
}
async function main() {
@@ -123,6 +192,7 @@ async function main() {
for (const workspace of [
"apps/api",
"packages/config",
"packages/template-contract",
"packages/types",
"packages/validation",
]) {
@@ -130,17 +200,8 @@ async function main() {
}
await copyTaroWorkspace();
await cp(adminDist, path.join(output, "apps/admin/dist"), { recursive: true });
for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true })) {
const templateDirectory = path.join(root, "packages", entry.name);
if (
entry.isDirectory() &&
entry.name.startsWith("template-") &&
existsSync(path.join(templateDirectory, "template.json")) &&
existsSync(path.join(templateDirectory, "taro/index.tsx"))
) {
await copyTemplatePackage(entry.name);
}
}
const templateCatalog = await buildTemplateCatalog();
if (!templateCatalog.length) throw new Error("Release contains no template package");
await cp(path.join(root, "apps/api/prisma/assets"), path.join(output, "seed-media"), {
recursive: true,
});