Files
persionalBrand/packages/template-contract/test/editability.test.mjs

343 lines
13 KiB
JavaScript

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
const packagesRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const runtimeRoot = path.resolve(packagesRoot, "../apps/miniapp");
const adminTrustEditor = fs.readFileSync(
path.resolve(
packagesRoot,
"../apps/admin/src/features/trust-content/components/TrustContentEditorModal.tsx",
),
"utf8",
);
for (const field of ["title", "summary", "content"]) {
assert.ok(
adminTrustEditor.includes(`selectedTypeMeta?.adminFields.${field}`),
`Admin trust editor must render the manifest label for ${field}`,
);
}
function sourceFile(templateRoot, relativePath, extension) {
const local = path.join(templateRoot, "miniapp", `${relativePath}.${extension}`);
const runtime = path.join(runtimeRoot, `${relativePath}.${extension}`);
return fs.existsSync(local) ? local : fs.existsSync(runtime) ? runtime : null;
}
function renderedFields(templateRoot, entrypoint) {
const seen = new Set();
const fields = new Set();
const heroFields = new Set();
const profileFields = new Set();
const trustFields = new Set();
const trustItemTypes = new Set();
const brandFields = new Set();
let rendersAllTrustItems = false;
function visit(relativePath) {
if (seen.has(relativePath)) return;
seen.add(relativePath);
for (const extension of ["wxml", "js"]) {
const source = sourceFile(templateRoot, relativePath, extension);
if (!source) continue;
const content = fs.readFileSync(source, "utf8");
for (const match of content.matchAll(/(?<![.\w])presentation\.([A-Za-z][A-Za-z0-9]*)/g)) {
fields.add(match[1]);
}
for (const match of content.matchAll(/(?<![.\w])brand\.([A-Za-z][A-Za-z0-9]*)/g)) {
brandFields.add(match[1]);
}
for (const match of content.matchAll(/(?<![.\w])hero\.([A-Za-z][A-Za-z0-9]*)/g)) {
heroFields.add(match[1]);
}
for (const match of content.matchAll(/brand\.profilePresentation\.([A-Za-z][A-Za-z0-9]*)/g)) {
profileFields.add(match[1]);
}
for (const match of content.matchAll(/trustContent\.([A-Za-z][A-Za-z0-9]*)/g)) {
trustFields.add(match[1]);
}
for (const match of content.matchAll(
/selectSlot\(items,\s*["']([A-Za-z][A-Za-z0-9_-]*)["']\)/g,
)) {
trustItemTypes.add(match[1]);
}
if (/trustItems/.test(content)) {
for (const match of content.matchAll(
/item\.type\s*===\s*["']([A-Za-z][A-Za-z0-9_-]*)["']/g,
)) {
trustItemTypes.add(match[1]);
}
if (/wx:for="{{trustItems}}"/.test(content) && !/item\.type\s*===/.test(content)) {
rendersAllTrustItems = true;
}
}
}
const componentConfig = sourceFile(templateRoot, relativePath, "json");
if (!componentConfig) return;
const config = JSON.parse(fs.readFileSync(componentConfig, "utf8"));
for (const component of Object.values(config.usingComponents ?? {})) {
if (typeof component === "string" && component.startsWith("/components/")) {
visit(component.slice(1));
}
}
}
visit(entrypoint);
return {
fields,
heroFields,
profileFields,
trustFields,
trustItemTypes,
brandFields,
rendersAllTrustItems,
seen,
};
}
const sharedOfferingBindings = [
"offering.config.categoryKey",
"offering.config.detailHero",
"offering.config.area",
"offering.config.series",
"offering.config.spaceType",
"offering.config.keywords",
"offering.config.details.background",
"offering.config.details.designConcept",
"offering.config.details.crafts",
"offering.config.details.materialsList",
];
const offeringRuntimeBindings = {
"offering.config.categoryKey": "item.presentation.categoryLabel",
"offering.config.detailHero": "item.detailHero",
"offering.config.area": "item.area",
"offering.config.series": "item.series",
"offering.config.spaceType": "item.spaceType",
"offering.config.keywords": "item.keywords",
"offering.config.details.background": "item.details.background",
"offering.config.details.designConcept": "item.details.designConcept",
"offering.config.details.crafts": "item.details.crafts",
"offering.config.details.materialsList": "item.details.materialsList",
};
for (const directory of fs
.readdirSync(packagesRoot)
.filter((name) => name.startsWith("template-"))) {
const templateRoot = path.join(packagesRoot, directory);
const manifestPath = path.join(templateRoot, "template.json");
if (!fs.existsSync(manifestPath)) continue;
test(`${directory} exposes rendered content through Admin bindings`, () => {
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
for (const declaration of manifest.trustContentTypes ?? []) {
for (const field of ["title", "summary", "content"]) {
assert.ok(
declaration.adminFields?.[field]?.trim(),
`${manifest.packageKey}: trust type ${declaration.type} has no Admin label for ${field}`,
);
}
}
for (const sample of Object.values(manifest.sampleContent ?? {})) {
for (const item of sample.trustContent ?? []) {
assert.ok(
manifest.trustContentTypes?.some((type) => type.type === item.type),
`${manifest.packageKey}: sample trust type ${item.type} has no declared editor or renderer`,
);
}
}
for (const section of manifest.admin.sections) {
assert.ok(
manifest.entrypoints[section.page],
`${manifest.packageKey}: ${section.key} points to an unknown Mini Program page`,
);
}
const bindings = new Set(
manifest.admin.sections.flatMap((section) => section.fields.map((field) => field.binding)),
);
for (const [pageKey, entrypoint] of Object.entries(manifest.entrypoints)) {
const {
fields,
heroFields,
profileFields,
trustFields,
trustItemTypes,
brandFields,
rendersAllTrustItems,
seen,
} = renderedFields(templateRoot, entrypoint);
const pageBindings = new Set(
manifest.admin.sections
.filter((section) => section.page === pageKey)
.flatMap((section) => section.fields.map((field) => field.binding)),
);
for (const field of fields) {
const binding = `brand.config.visualPresentation.${pageKey}.${field}`;
assert.ok(
bindings.has(binding),
`${manifest.packageKey}: ${pageKey}.${field} has no Admin field`,
);
assert.ok(
pageBindings.has(binding),
`${manifest.packageKey}: ${pageKey}.${field} Admin field is assigned to another page`,
);
}
for (const field of heroFields) {
const binding =
field === "image" ? "brand.config.heroImage" : `brand.config.homeHero.${field}`;
assert.ok(
pageBindings.has(binding),
`${manifest.packageKey}: ${pageKey} hero.${field} has no Admin field`,
);
}
for (const declaration of manifest.admin.sections.filter((item) => item.page === pageKey)) {
for (const field of declaration.fields) {
const binding = field.binding;
if (binding === "brand.avatarUrl")
assert.ok(
brandFields.has("avatarUrl"),
`${manifest.packageKey}: avatar has no renderer`,
);
if (binding === "brand.description")
assert.ok(
brandFields.has("slogan") || brandFields.has("description"),
`${manifest.packageKey}: description has no renderer`,
);
if (binding === "brand.contactPhone")
assert.ok(
brandFields.has("phone") || brandFields.has("contactPhone"),
`${manifest.packageKey}: phone has no renderer`,
);
if (binding === "brand.contactWechat")
assert.ok(
brandFields.has("wechat") || brandFields.has("contactWechat"),
`${manifest.packageKey}: WeChat has no renderer`,
);
if (binding === "brand.address")
assert.ok(
brandFields.has("studioAddress") || brandFields.has("address"),
`${manifest.packageKey}: address has no renderer`,
);
}
}
for (const field of profileFields) {
assert.ok(
pageBindings.has(`brand.config.profilePresentation.${field}`),
`${manifest.packageKey}: profilePresentation.${field} has no Admin field`,
);
}
for (const field of trustFields) {
if (field === "bio") {
assert.ok(
manifest.trustContentTypes?.some((type) => type.type === "credential"),
`${manifest.packageKey}: biography has no editable trust content type`,
);
continue;
}
assert.ok(
manifest.trustContentTypes?.some(
(type) =>
type.pages?.includes(pageKey) &&
type.configFields?.some(
(configField) => configField.binding === `trust.config.${field}`,
),
),
`${manifest.packageKey}: trustContent.${field} has no Admin field`,
);
}
for (const type of trustItemTypes) {
const declaration = manifest.trustContentTypes?.find((item) => item.type === type);
assert.ok(
declaration,
`${manifest.packageKey}: renderer uses undeclared trust type ${type}`,
);
assert.ok(
declaration.pages?.includes(pageKey),
`${manifest.packageKey}: renderer uses trust type ${type} on ${pageKey} but the page is not declared`,
);
}
for (const declaration of manifest.trustContentTypes ?? []) {
if (!declaration.pages?.includes(pageKey)) continue;
assert.ok(
rendersAllTrustItems || trustItemTypes.has(declaration.type),
`${manifest.packageKey}: trust type ${declaration.type} claims ${pageKey}, but that renderer does not display it`,
);
}
const pageSource = [...seen]
.flatMap((relativePath) =>
["js", "wxml"]
.map((extension) => sourceFile(templateRoot, relativePath, extension))
.filter(Boolean)
.map((file) => fs.readFileSync(file, "utf8")),
)
.join("\n");
for (const declaration of manifest.trustContentTypes ?? []) {
if (!declaration.pages?.includes(pageKey)) continue;
for (const field of declaration.configFields ?? []) {
assert.ok(
pageSource.includes(`.${field.key}`) ||
declaration.pages.some((destination) => {
const destinationFiles = renderedFields(
templateRoot,
manifest.entrypoints[destination],
).seen;
return [...destinationFiles].some((file) =>
["js", "wxml"].some((extension) => {
const source = sourceFile(templateRoot, file, extension);
return source && fs.readFileSync(source, "utf8").includes(`.${field.key}`);
}),
);
}),
`${manifest.packageKey}: ${declaration.type}.${field.key} is editable but is not consumed on ${pageKey}`,
);
}
}
if (pageKey === Object.keys(manifest.entrypoints)[0]) {
for (const declaration of manifest.trustContentTypes ?? []) {
assert.ok(
declaration.pages?.length,
`${manifest.packageKey}: trust type ${declaration.type} must declare its Mini Program destination`,
);
}
}
if (pageKey === "home") {
for (const field of manifest.templateFields ?? []) {
const source = `templateData.${field.key}`;
const entryFiles = [...seen].flatMap((relativePath) =>
["js", "wxml"]
.map((extension) => sourceFile(templateRoot, relativePath, extension))
.filter(Boolean),
);
assert.ok(
entryFiles.some((file) =>
new RegExp(`templateData(?:\\?\\.)?${field.key}`).test(fs.readFileSync(file, "utf8")),
),
`${manifest.packageKey}: template field ${field.key} is declared but never rendered`,
);
}
}
if (seen.has("components/modules/offering-detail/offering-detail")) {
for (const binding of sharedOfferingBindings) {
assert.ok(
pageBindings.has(binding),
`${manifest.packageKey}: missing ${binding} on detail page`,
);
}
const detailSources = [...seen].flatMap((relativePath) =>
["wxml", "js"]
.map((extension) => sourceFile(templateRoot, relativePath, extension))
.filter(Boolean)
.map((file) => fs.readFileSync(file, "utf8")),
);
const detailSource = detailSources.join("\n");
for (const [binding, runtimePath] of Object.entries(offeringRuntimeBindings)) {
if (!pageBindings.has(binding)) continue;
assert.ok(
detailSource.includes(runtimePath),
`${manifest.packageKey}: ${binding} is editable but ${runtimePath} is not rendered on ${pageKey}`,
);
}
}
}
});
}