Files
persionalBrand/apps/api/test/template-contract-migration.integration.mjs
T
que01 3017e3eb49 fix: 收口依赖兼容与会话撤销
为 miniprogram-ci 和 Jimp 依赖增加兼容 patch 与 smoke test;修复平台模板管理员路由漏配;收紧模板契约校验;为 admin/customer 增加 token 撤销和集中会话存储;同步品牌切换角色、doctor source hash、多屏宽截图证据和 CI 构建门禁。
2026-10-18 23:43:25 +08:00

209 lines
8.0 KiB
JavaScript

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { cpSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { PrismaClient } from "@prisma/client";
const apiRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const migrationsRoot = path.join(apiRoot, "prisma/migrations");
const targetMigration = "20261018120000_enforce_single_template_contract";
function run(args, env) {
const result = spawnSync("pnpm", args, { cwd: apiRoot, env, encoding: "utf8" });
if (result.status !== 0) {
throw new Error(`${args.join(" ")} failed:\n${result.stdout}\n${result.stderr}`);
}
}
function assertDefined(value, message) {
assert.ok(value, message);
return value;
}
async function main() {
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) throw new Error("DATABASE_URL is required for migration integration tests");
const schema = `pb_contract_migration_${randomUUID().replaceAll("-", "")}`;
const testUrl = new URL(databaseUrl);
testUrl.searchParams.set("schema", schema);
const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString() };
const tempRoot = mkdtempSync(path.join(os.tmpdir(), "pb-contract-migration-"));
const tempPrisma = path.join(tempRoot, "prisma");
const tempMigrations = path.join(tempPrisma, "migrations");
const schemaPath = path.join(tempPrisma, "schema.prisma");
const fixturePath = path.join(tempRoot, "legacy-fixture.sql");
const admin = new PrismaClient();
let createdSchema = false;
try {
const schemaSource = readFileSync(path.join(apiRoot, "prisma/schema.prisma"), "utf8");
const migrationDirs = readdirSync(migrationsRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
const { mkdirSync, copyFileSync } = await import("node:fs");
mkdirSync(tempMigrations, { recursive: true });
writeFileSync(schemaPath, schemaSource);
copyFileSync(
path.join(migrationsRoot, "migration_lock.toml"),
path.join(tempMigrations, "migration_lock.toml"),
);
for (const migration of migrationDirs) {
cpSync(path.join(migrationsRoot, migration), path.join(tempMigrations, migration), {
recursive: true,
});
}
run(["exec", "prisma", "migrate", "deploy", "--schema", schemaPath], testEnvironment);
const database = new PrismaClient({ datasourceUrl: testUrl.toString() });
try {
const actorId = randomUUID();
const brandId = randomUUID();
const packageId = randomUUID();
const packageVersionId = randomUUID();
const historicalPackageId = randomUUID();
const historicalVersionId = randomUUID();
const packageKey = "explicit-food-package";
const manifest = {
packageKey,
version: "2.4.0",
visualTemplateKey: packageKey,
runtimeContract: "1.0",
supportedIndustryTemplates: ["food"],
previewFixture: { food: { schemaVersion: "1" } },
};
const legacySnapshot = { packageKey: "old-invalid-package", version: "1.0.0" };
const checksum = "a".repeat(64);
await database.adminUser.create({
data: {
id: actorId,
username: `migration-${randomUUID()}`,
passwordHash: "unused",
displayName: "Migration Fixture",
},
});
await database.brandProfile.create({
data: {
id: brandId,
slug: `migration-${randomUUID()}`,
name: "Migration Fixture Brand",
templateKey: "food",
config: { visualTemplateKey: packageKey },
},
});
await database.templatePackage.create({ data: { id: packageId, packageKey } });
await database.templatePackageVersion.create({
data: {
id: packageVersionId,
templatePackageId: packageId,
packageKey,
version: "2.4.0",
displayName: "Current Food Package",
status: "published",
manifestSnapshot: manifest,
validationReport: { errors: [] },
contentChecksum: checksum,
archiveChecksum: "b".repeat(64),
artifactPath: "/fixture/current.tar.gz",
importedById: actorId,
},
});
await database.templatePackage.create({
data: { id: historicalPackageId, packageKey: "old-invalid-package" },
});
await database.templatePackageVersion.create({
data: {
id: historicalVersionId,
templatePackageId: historicalPackageId,
packageKey: "old-invalid-package",
version: "1.0.0",
displayName: "Invalid Historical Package",
status: "retired",
manifestSnapshot: legacySnapshot,
validationReport: { errors: [] },
contentChecksum: "c".repeat(64),
archiveChecksum: "d".repeat(64),
artifactPath: "/fixture/historical.tar.gz",
importedById: actorId,
},
});
await database.$executeRaw`
INSERT INTO "BrandTemplateInstallation" (
"id", "brandId", "templateKey", "templateVersion", "installedAt", "updatedAt",
"configSnapshot", "previousSnapshots", "contentChecksum", "templatePackageVersionId",
"visualTemplateKey"
) VALUES (
${randomUUID()}, ${brandId}, 'food', '1.0.0', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,
'{}'::jsonb, '[]'::jsonb, NULL, NULL, NULL
)
`;
const migrationSql = readFileSync(
path.join(migrationsRoot, targetMigration, "migration.sql"),
"utf8",
);
writeFileSync(fixturePath, migrationSql);
run(
["exec", "prisma", "db", "execute", "--schema", schemaPath, "--file", fixturePath],
testEnvironment,
);
const installation = assertDefined(
await database.$queryRaw`
SELECT "templatePackageVersionId", "templateVersion", "contentChecksum", "configSnapshot"
FROM "BrandTemplateInstallation" WHERE "brandId" = ${brandId}
`.then((rows) => rows[0]),
"Migration should preserve and resolve the existing installation",
);
assert.equal(installation.templatePackageVersionId, packageVersionId);
assert.equal(installation.templateVersion, "2.4.0");
assert.equal(installation.contentChecksum, checksum);
assert.equal(installation.configSnapshot.packageKey, packageKey);
const brandConfig = await database.$queryRaw`
SELECT "config" FROM "BrandProfile" WHERE "id" = ${brandId}
`;
assert.equal(Object.hasOwn(brandConfig[0].config, "visualTemplateKey"), false);
const historical = await database.templatePackageVersion.findUniqueOrThrow({
where: { id: historicalVersionId },
select: { manifestSnapshot: true, status: true },
});
assert.deepEqual(historical.manifestSnapshot, legacySnapshot);
assert.equal(historical.status, "retired");
const redundantColumns = await database.$queryRaw`
SELECT column_name FROM information_schema.columns
WHERE table_schema = current_schema()
AND ((table_name = 'TemplatePackageVersion' AND column_name = 'visualTemplateKey')
OR (table_name = 'BrandTemplateInstallation' AND column_name = 'visualTemplateKey'))
`;
assert.deepEqual(redundantColumns, []);
} finally {
await database.$disconnect();
}
console.log("Template contract migration populated-data rehearsal passed");
} finally {
if (createdSchema) await admin.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`);
await admin.$disconnect();
rmSync(tempRoot, { recursive: true, force: true });
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});