Files
persionalBrand/apps/api/scripts/template-contract-migration-audit.mjs
T

197 lines
6.9 KiB
JavaScript

import { pathToFileURL } from "node:url";
import { PrismaClient } from "@prisma/client";
function object(value) {
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}
function packageMetadataMatches(version, industry) {
const manifest = object(version.manifestSnapshot);
const fixture = object(manifest.previewFixture)[industry];
return (
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 &&
typeof fixture === "object" &&
!Array.isArray(fixture)
);
}
function packageMetadataIsConsistent(version) {
const manifest = object(version.manifestSnapshot);
const fixtures = object(manifest.previewFixture);
return (
manifest.packageKey === version.packageKey &&
manifest.visualTemplateKey === version.packageKey &&
manifest.version === version.version &&
manifest.runtimeContract === "1.0" &&
Array.isArray(manifest.supportedIndustryTemplates) &&
manifest.supportedIndustryTemplates.length > 0 &&
manifest.supportedIndustryTemplates.every((industry) => {
const fixture = fixtures[industry];
return fixture !== null && typeof fixture === "object" && !Array.isArray(fixture);
})
);
}
export function buildTemplateContractMigrationReport({ brands, versions }) {
const grouped = new Map();
for (const row of brands) {
const entries = grouped.get(row.brandId) ?? [];
entries.push(row);
grouped.set(row.brandId, entries);
}
const brandReports = [...grouped.values()].map((entries) => {
const row = entries[0];
const installations = entries.filter((entry) => entry.installationId);
const base = {
brandId: row.brandId,
slug: row.slug,
industry: row.industry,
installationCount: installations.length,
mappingSource: null,
packageKey: null,
candidates: [],
blockers: [],
};
if (installations.length !== 1) {
base.blockers.push(
installations.length === 0 ? "installation_missing" : "multiple_installations",
);
return base;
}
const installation = installations[0];
const declarations = [
["installation.visualTemplateKey", installation.installationVisualTemplateKey],
["brand.config.visualTemplateKey", row.brandVisualTemplateKey],
["installation.configSnapshot.visualTemplateKey", installation.snapshotVisualTemplateKey],
["installation.configSnapshot.packageKey", installation.snapshotPackageKey],
].filter(([, value]) => typeof value === "string" && value.trim());
const declaredKeys = [...new Set(declarations.map(([, value]) => value))];
if (declaredKeys.length > 1) {
base.blockers.push("legacy_package_declarations_conflict");
return base;
}
const explicitPackageKey = declaredKeys[0] ?? null;
base.mappingSource = declarations[0]?.[0] ?? null;
base.packageKey = explicitPackageKey;
if (!installation.installationPackageVersionId && !explicitPackageKey) {
base.blockers.push("explicit_package_declaration_missing");
return base;
}
const matches = installation.installationPackageVersionId
? versions.filter((version) => version.id === installation.installationPackageVersionId)
: versions.filter(
(version) =>
version.packageKey === explicitPackageKey &&
packageMetadataMatches(version, row.industry),
);
base.candidates = matches.map((version) => ({
id: version.id,
packageKey: version.packageKey,
version: version.version,
status: version.status,
}));
if (installation.installationPackageVersionId) {
const [version] = matches;
if (
!version ||
version.status !== "published" ||
!packageMetadataMatches(version, row.industry) ||
(explicitPackageKey && explicitPackageKey !== version.packageKey)
) {
base.blockers.push("linked_package_version_invalid");
}
return base;
}
const published = matches.filter((version) => version.status === "published");
if (published.length === 1) return base;
if (published.length > 1) base.blockers.push("published_package_version_ambiguous");
else if (matches.length) base.blockers.push("matching_package_version_not_published");
else base.blockers.push("matching_contract_package_version_missing");
return base;
});
const invalidHistoricalVersions = versions
.filter((version) => !packageMetadataIsConsistent(version))
.map((version) => ({
packageKey: version.packageKey,
version: version.version,
status: version.status,
storedVisualTemplateKey: version.visualTemplateKey ?? null,
hasPreviewFixture: Boolean(object(version.manifestSnapshot).previewFixture),
}));
const blocked = brandReports.filter((brand) => brand.blockers.length);
return {
schemaVersion: 1,
readOnly: true,
ready: blocked.length === 0,
summary: {
brandCount: brandReports.length,
readyCount: brandReports.length - blocked.length,
blockedCount: blocked.length,
historicalInvalidVersionCount: invalidHistoricalVersions.length,
},
brands: brandReports,
invalidHistoricalVersions,
};
}
async function main() {
const prisma = new PrismaClient();
try {
const [brands, versions] = await Promise.all([
prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
brand."templateKey" AS "industry",
brand."config"->>'visualTemplateKey' AS "brandVisualTemplateKey",
installation."id" AS "installationId",
installation."visualTemplateKey" AS "installationVisualTemplateKey",
installation."templatePackageVersionId" AS "installationPackageVersionId",
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"
`,
prisma.$queryRaw`
SELECT
"id",
"packageKey",
"version",
"status",
"visualTemplateKey",
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`,
]);
process.stdout.write(
`${JSON.stringify(buildTemplateContractMigrationReport({ brands, versions }), null, 2)}\n`,
);
} finally {
await prisma.$disconnect();
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}