196 lines
7.2 KiB
JavaScript
196 lines
7.2 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
import { isDeepStrictEqual } from "node:util";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { createRequire } from "node:module";
|
|
|
|
const CONTRACT_KEYS = new Set([
|
|
"templateDefinition",
|
|
"visualTemplateDefinition",
|
|
"visualTemplateManifest",
|
|
"templatePackageManifest",
|
|
"installation",
|
|
"templateKey",
|
|
]);
|
|
const VOLATILE_KEYS = new Set(["generatedAt"]);
|
|
|
|
/** null 与缺失键都表示“没有值”,比较前统一剔除,避免旧快照缺列被误判为内容变更。 */
|
|
function normalizeNullish(value) {
|
|
if (Array.isArray(value)) return value.map(normalizeNullish);
|
|
if (value && typeof value === "object") {
|
|
const result = {};
|
|
for (const [key, item] of Object.entries(value)) {
|
|
if (item === null || item === undefined) continue;
|
|
result[key] = normalizeNullish(item);
|
|
}
|
|
return result;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function isPlainObject(value) {
|
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
|
|
/** 返回递归差异路径,用于判断内容差异是否全部属于显式允许的遗留字段删除。 */
|
|
export function diffPaths(published, current, prefix = "") {
|
|
if (isPlainObject(published) && isPlainObject(current)) {
|
|
const keys = new Set([...Object.keys(published), ...Object.keys(current)]);
|
|
return [...keys].flatMap((key) =>
|
|
diffPaths(published[key], current[key], prefix ? prefix + "." + key : key),
|
|
);
|
|
}
|
|
return isDeepStrictEqual(published, current) ? [] : [{ path: prefix }];
|
|
}
|
|
|
|
/**
|
|
* 只允许自动重发“模板契约字段变化、品牌内容未变”的发布快照。
|
|
* 一旦草稿内容与已发布快照不同,必须由管理员显式审查后发布,避免误发草稿。
|
|
* allowedRemovedKeys 只能放行“旧值存在、新值缺失”的遗留字段删除,不能放行赋值变化。
|
|
*/
|
|
export function classifyContractRefresh(published, current, options = {}) {
|
|
if (!published || !current) throw new Error("发布快照不能为空");
|
|
const allowedRemovedKeys = new Set(options.allowedRemovedKeys ?? []);
|
|
const normalizedPublished = normalizeNullish(published);
|
|
const normalizedCurrent = normalizeNullish(current);
|
|
const keys = new Set([...Object.keys(normalizedPublished), ...Object.keys(normalizedCurrent)]);
|
|
const changedKeys = [...keys]
|
|
.filter((key) => !VOLATILE_KEYS.has(key))
|
|
.filter((key) => !isDeepStrictEqual(normalizedPublished[key], normalizedCurrent[key]));
|
|
const blockingKeys = [];
|
|
const allowedChanges = [];
|
|
for (const key of changedKeys) {
|
|
if (CONTRACT_KEYS.has(key)) continue;
|
|
const changes = diffPaths(normalizedPublished[key], normalizedCurrent[key], key);
|
|
const blocking = changes.filter(
|
|
(change) =>
|
|
!(allowedRemovedKeys.has(change.path) && isRemovedAtPath(normalizedCurrent, change.path)),
|
|
);
|
|
if (blocking.length) blockingKeys.push(key);
|
|
else allowedChanges.push(...changes.map((change) => change.path));
|
|
}
|
|
const status = blockingKeys.length
|
|
? "content-diverged"
|
|
: changedKeys.length
|
|
? "contract-stale"
|
|
: "current";
|
|
return { status, changedKeys, blockingKeys, allowedChanges };
|
|
}
|
|
|
|
function isRemovedAtPath(root, dotPath) {
|
|
let node = root;
|
|
const parts = dotPath.split(".");
|
|
for (const part of parts.slice(0, -1)) {
|
|
if (!isPlainObject(node) || !Object.hasOwn(node, part)) return false;
|
|
node = node[part];
|
|
}
|
|
return isPlainObject(node) && !Object.hasOwn(node, parts.at(-1));
|
|
}
|
|
|
|
async function loadServices() {
|
|
const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url));
|
|
const { PrismaService } = await import("../apps/api/dist/prisma.service.js");
|
|
const { BrandReleaseService } = await import("../apps/api/dist/brand-release.service.js");
|
|
const { BrandReleaseApiService } = await import("../apps/api/dist/brand-release-api.service.js");
|
|
// 触发运行时依赖解析,避免发布脚本在错误的工作目录下才失败。
|
|
apiRequire("@prisma/client");
|
|
const prisma = new PrismaService();
|
|
const snapshots = new BrandReleaseService(prisma);
|
|
return {
|
|
prisma,
|
|
snapshots,
|
|
releases: new BrandReleaseApiService(prisma, snapshots),
|
|
};
|
|
}
|
|
|
|
function parseArgs(argv) {
|
|
const options = { apply: false, allowedRemovedKeys: [] };
|
|
for (const arg of argv) {
|
|
if (arg === "--apply") options.apply = true;
|
|
else if (arg.startsWith("--allow-removed-key=")) {
|
|
const key = arg.slice("--allow-removed-key=".length);
|
|
if (!key) throw new Error("--allow-removed-key 需要字段路径");
|
|
options.allowedRemovedKeys.push(key);
|
|
} else throw new Error(`未知参数:${arg}`);
|
|
}
|
|
return options;
|
|
}
|
|
|
|
async function main() {
|
|
const options = parseArgs(process.argv.slice(2));
|
|
const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin";
|
|
const note =
|
|
process.env.TEMPLATE_CONTRACT_REPUBLISH_NOTE ?? "模板契约迁移:刷新已发布页面方案兼容性";
|
|
const { prisma, snapshots, releases } = await loadServices();
|
|
try {
|
|
const actor = await prisma.adminUser.findFirst({
|
|
where: { username: actorUsername, isEnabled: true },
|
|
select: { id: true },
|
|
});
|
|
if (!actor) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`);
|
|
const brands = await prisma.brandProfile.findMany({
|
|
select: { id: true, slug: true },
|
|
orderBy: { slug: "asc" },
|
|
});
|
|
const results = [];
|
|
for (const brand of brands) {
|
|
const release = await prisma.brandRelease.findFirst({
|
|
where: { brandId: brand.id, status: "published" },
|
|
orderBy: { version: "desc" },
|
|
select: { version: true, snapshot: true },
|
|
});
|
|
if (!release) {
|
|
results.push({ slug: brand.slug, status: "unpublished" });
|
|
continue;
|
|
}
|
|
const current = await snapshots.buildSnapshot(brand.id);
|
|
const classification = classifyContractRefresh(release.snapshot, current, options);
|
|
const result = {
|
|
slug: brand.slug,
|
|
releaseVersion: release.version,
|
|
...classification,
|
|
};
|
|
results.push(result);
|
|
if (!options.apply || classification.status !== "contract-stale") continue;
|
|
const readiness = await releases.readiness(brand.id);
|
|
if (!readiness.ready) {
|
|
result.status = "not-ready";
|
|
result.blockingKeys = readiness.checks
|
|
.filter((check) => !check.passed)
|
|
.map((check) => check.key);
|
|
continue;
|
|
}
|
|
const published = await releases.publish(brand.id, actor.id, note);
|
|
result.status = "republished";
|
|
result.newReleaseVersion = published.version;
|
|
}
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
apply: options.apply,
|
|
actor: actorUsername,
|
|
allowedRemovedKeys: options.allowedRemovedKeys,
|
|
results,
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
);
|
|
if (
|
|
options.apply &&
|
|
results.some((item) => ["content-diverged", "not-ready"].includes(item.status))
|
|
)
|
|
process.exitCode = 1;
|
|
} finally {
|
|
await prisma.$disconnect();
|
|
}
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
main().catch((error) => {
|
|
console.error(error instanceof Error ? error.message : String(error));
|
|
process.exitCode = 1;
|
|
});
|
|
}
|