election-game/backend/packages/protocol/scripts/build-avatar-catalog.ts

80 lines
4.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 頭像部件目錄的建置工具(docs/24):檢查 data/avatar-catalog.json 和 art/avatar 底下的 SVG,
* 轉成前後端共用的 src/avatar/catalog.generated.ts(目錄)和 src/avatar/art.generated.ts(部件圖,只有形狀和顏色)。
* 執行:pnpm avatar:build(在 backend/ 底下),或 node scripts/build-avatar-catalog.ts。
* 加 --check 只檢查、不寫檔(產生的檔和原始檔對不上就失敗)。
*/
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, relative } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { AvatarCatalogSchema, lintCatalog } from "../src/avatar/schema.ts";
import { convertSvgArt, type PartArt } from "../src/avatar/svg.ts";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
export const CATALOG_FILE = join(ROOT, "data", "avatar-catalog.json");
export const ART_DIR = join(ROOT, "art", "avatar");
export const CATALOG_OUT = join(ROOT, "src", "avatar", "catalog.generated.ts");
export const ART_OUT = join(ROOT, "src", "avatar", "art.generated.ts");
const HEADER = "// 這個檔是 scripts/build-avatar-catalog.ts 產生的,不要手改:改 data/avatar-catalog.json 或 art/avatar/*.svg 之後跑 pnpm avatar:build\n";
function listSvgs(dir: string): string[] {
if (!existsSync(dir)) return [];
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? listSvgs(join(dir, e.name)) : e.name.endsWith(".svg") ? [join(dir, e.name)] : []));
}
/** 讀原始檔、檢查、轉換;回傳要寫的兩個檔的內容。有問題就丟錯(訊息列出全部問題) */
export function buildAvatarCatalog(): { catalog: string; art: string; items: number; parts: number } {
const raw: unknown = JSON.parse(readFileSync(CATALOG_FILE, "utf-8"));
const parsed = AvatarCatalogSchema.safeParse(raw);
if (!parsed.success) throw new Error(`avatar-catalog.json 格式不對:\n${parsed.error.issues.map((i) => `- ${i.path.join(".")}: ${i.message}`).join("\n")}`);
const catalog = parsed.data;
const problems = lintCatalog(catalog);
const art: Record<string, PartArt> = {};
for (const item of catalog.items) {
if (item.art.startsWith("builtin:")) continue;
const file = join(ART_DIR, item.art);
if (!existsSync(file)) {
problems.push(`${item.id}:找不到部件圖 art/avatar/${item.art}`);
continue;
}
try {
art[item.art] = convertSvgArt(readFileSync(file, "utf-8"), item.art);
} catch (e) {
problems.push((e as Error).message);
}
}
const used = new Set(catalog.items.map((i) => i.art));
for (const f of listSvgs(ART_DIR)) {
const rel = relative(ART_DIR, f).split("\\").join("/");
if (!used.has(rel)) problems.push(`art/avatar/${rel} 沒有任何部件用到(要嘛加進目錄,要嘛刪掉)`);
}
if (problems.length) throw new Error(`頭像部件目錄有問題:\n${problems.map((p) => `- ${p}`).join("\n")}`);
const catalogTs = `${HEADER}import type { AvatarCatalog } from "./schema.ts";\n\nexport const AVATAR_CATALOG: AvatarCatalog = ${JSON.stringify(catalog, null, 1)};\n`;
const artTs = `${HEADER}import type { PartArt } from "./svg.ts";\n\nexport const AVATAR_ART: Readonly<Record<string, PartArt>> = ${JSON.stringify(art)};\n`;
return { catalog: catalogTs, art: artTs, items: catalog.items.length, parts: Object.keys(art).length };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try {
const out = buildAvatarCatalog();
if (process.argv.includes("--check")) {
const stale = [
[CATALOG_OUT, out.catalog],
[ART_OUT, out.art],
].filter(([file, text]) => !existsSync(file!) || readFileSync(file!, "utf-8") !== text);
if (stale.length) throw new Error(`產生的檔和原始檔對不上,請跑 pnpm avatar:build:${stale.map(([f]) => relative(ROOT, f!)).join("、")}`);
process.stdout.write(`頭像部件目錄檢查通過:${out.items} 件部件、${out.parts} 張部件圖\n`);
} else {
writeFileSync(CATALOG_OUT, out.catalog);
writeFileSync(ART_OUT, out.art);
process.stdout.write(`已產生頭像部件目錄:${out.items} 件部件、${out.parts} 張部件圖\n`);
}
} catch (e) {
process.stderr.write(`${(e as Error).message}\n`);
process.exit(1);
}
}