election-game/backend/packages/protocol/test/avatar.test.ts

270 lines
13 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.

import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { ART_OUT, CATALOG_OUT, buildAvatarCatalog } from "../scripts/build-avatar-catalog.ts";
import {
AVATAR_CATALOG,
AvatarSpecSchema,
CustomCandidate,
checkAvatar,
cleanAvatar,
lintCatalog,
onSale,
parseAvatarLoose,
shopShelf,
shopWeek,
slotItems,
stampAvatarVersion,
wearItem,
wearSlots,
type AvatarSpecData,
} from "../src/index.ts";
import { convertSvgArt, SvgArtError } from "../src/avatar/svg.ts";
/** 改版前(寫死選項那一版)存下來的頭像:每個舊選項都要照樣合法、清洗後一個字都不變 */
const legacy: AvatarSpecData = {
skin: "#f6d3b7",
hair: "bobSide",
hairColor: "#2f2520",
outfit: "blouse",
suit: "#5a2d34",
shirt: "#f3e6d8",
tie: "#2c5aa0",
glasses: true,
beard: false,
bg: "#efe0e6",
face: "heart",
faceW: 0.95,
faceH: 1.06,
ears: "small",
brows: "thin",
browAngle: -0.3,
eyes: "narrow",
glassesStyle: "halfRim",
glassesColor: "#a8874f",
nose: "small",
mouth: "teeth",
lines: 1,
part: "right",
mustache: false,
};
const OLD_OPTIONS = {
hair: ["short", "side", "buzz", "bob", "long", "bun", "curly", "bald", "receding", "slick", "bobSide", "shortBob", "perm", "crew", "volume"],
outfit: ["suit", "blouse", "vest", "polo"],
face: ["oval", "round", "long", "square", "heart"],
ears: ["small", "normal", "big"],
brows: ["thin", "normal", "thick"],
eyes: ["round", "narrow", "dot", "smile"],
glassesStyle: ["metal", "rimless", "black", "round", "halfRim"],
nose: ["small", "normal", "big"],
mouth: ["smile", "grin", "closed", "teeth"],
} as const;
describe("頭像資料:舊存檔照樣過", () => {
it("改版前的完整頭像:格式合法、目錄檢查沒問題、清洗後是同一個物件", () => {
const parsed = AvatarSpecSchema.parse(legacy);
expect(parsed).toEqual(legacy);
expect(checkAvatar(parsed)).toEqual([]);
expect(cleanAvatar(parsed).spec).toBe(parsed);
});
it("每一個舊選項都在目錄裡(代號沿用)", () => {
for (const [field, values] of Object.entries(OLD_OPTIONS)) {
for (const v of values) {
const spec = { ...legacy, [field]: v };
expect(checkAvatar(AvatarSpecSchema.parse(spec)), `${field}=${v}`).toEqual([]);
}
}
});
it("只有必填欄位的最舊存檔也合法;自創角色照樣能開局", () => {
const minimal = { skin: "#eebd98", hair: "short", hairColor: "#1f1b18", outfit: "suit", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: false, beard: false, bg: "#dfe8f0" };
expect(cleanAvatar(AvatarSpecSchema.parse(minimal)).notes).toEqual([]);
const custom = CustomCandidate.parse({ name: "測試人", party: null, background: "律師", stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: legacy, replace: null });
expect(custom.avatar).toEqual(legacy);
});
it("新欄位(畫風、新部位、換色)也合法", () => {
const spec = AvatarSpecSchema.parse({ ...legacy, v: 2, style: "chibi", wear: { hat: "hat-campaign-cap", sash: "sash-red" }, tint: { "hat.main": "#c0392b" } });
expect(checkAvatar(spec)).toEqual([]);
expect(cleanAvatar(spec).spec).toBe(spec);
});
});
describe("頭像資料:看不懂的代號換預設、格式壞掉才擋", () => {
it("看不懂的髮型、服裝換成預設值;看不懂的五官拿掉(畫的時候用預設)", () => {
const spec = AvatarSpecSchema.parse({ ...legacy, hair: "mohawk-2099", outfit: "spacesuit", eyes: "laser", glassesStyle: "monocle" });
const { spec: out, notes } = cleanAvatar(spec);
expect(out.hair).toBe("short");
expect(out.outfit).toBe("suit");
expect(out.eyes).toBeUndefined();
expect(out.glassesStyle).toBeUndefined();
expect(notes.length).toBe(4);
expect(checkAvatar(out)).toEqual([]);
});
it("看不懂的部件、部位、畫風拿掉;穿錯部位的拿掉;沒穿的部件的換色也拿掉", () => {
const spec = AvatarSpecSchema.parse({
...legacy,
style: "oil-painting",
wear: { hat: "hat-from-the-future", pet: "pet-cat", sash: "hat-campaign-cap", outer: "outer-campaign-vest" },
tint: { "hat.main": "#123456", "outer.main": "#654321", "outer.glitter": "#ffffff" },
});
const { spec: out } = cleanAvatar(spec);
expect(out.style).toBeUndefined();
expect(out.wear).toEqual({ outer: "outer-campaign-vest" });
expect(out.tint).toEqual({ "outer.main": "#654321" });
});
it("格式壞掉才回錯誤:代號有怪字元、穿太多件、顏色不是 #RRGGBB", () => {
expect(AvatarSpecSchema.safeParse({ ...legacy, hair: "<script>" }).success).toBe(false);
expect(AvatarSpecSchema.safeParse({ ...legacy, wear: Object.fromEntries(Array.from({ length: 13 }, (_, i) => [`s${i}`, "x"])) }).success).toBe(false);
expect(AvatarSpecSchema.safeParse({ ...legacy, tint: { "hat.main": "red" } }).success).toBe(false);
expect(AvatarSpecSchema.safeParse({ ...legacy, hair: "a".repeat(41) }).success).toBe(false);
});
it("瀏覽器存檔壞掉:壞欄位丟掉或換預設,不會當機", () => {
const broken = { ...legacy, skin: 42, faceW: 9, hair: "mohawk", wear: "not-an-object", extra: { deep: true } };
const out = parseAvatarLoose(broken)!;
expect(out.skin).toBe("#eebd98");
expect(out.faceW).toBeUndefined();
expect(out.hair).toBe("short");
expect(out.wear).toBeUndefined();
expect(AvatarSpecSchema.safeParse(out).success).toBe(true);
expect(parseAvatarLoose("hello")).toBeNull();
expect(parseAvatarLoose(null)).toBeNull();
});
it("有新部位或畫風才標第 2 版,舊頭像不動", () => {
expect(stampAvatarVersion(legacy)).toBe(legacy);
expect(stampAvatarVersion({ ...legacy, wear: { hat: "hat-campaign-cap" } }).v).toBe(2);
});
});
describe("真實政治人物的頭像", () => {
it("不能穿 realPersonOk:false 的部件,也不放商店部件", () => {
const spec = AvatarSpecSchema.parse({ ...legacy, wear: { hat: "hat-victory-band", held: "held-megaphone", outer: "outer-campaign-vest", sash: "sash-red", mask: "mask-number" } });
const issues = checkAvatar(spec, { realPerson: true });
expect(issues.map((i) => i.field).sort()).toEqual(["wear.hat", "wear.held", "wear.mask"]);
expect(issues.every((i) => i.problem === "notForRealPerson")).toBe(true);
const { spec: out } = cleanAvatar(spec, { realPerson: true });
expect(out.wear).toEqual({ outer: "outer-campaign-vest", sash: "sash-red" });
// 自創角色照穿
expect(checkAvatar(spec)).toEqual([]);
});
it("真人能穿的只有正式類:競選背心、彩帶、胸花、競選鴨舌帽、口罩,而且都不是商店部件", () => {
const ok = AVATAR_CATALOG.items.filter((i) => !i.art.startsWith("builtin:") && i.realPersonOk);
expect(new Set(ok.map((i) => i.slot))).toEqual(new Set(["outer", "sash", "chest", "hat", "mask"]));
expect(ok.map((i) => i.id).sort()).toEqual(["chest-corsage", "hat-campaign-cap", "mask-plain", "outer-campaign-vest", "sash-gold", "sash-red", "sash-thanks"]);
expect(ok.every((i) => i.get.type !== "shop")).toBe(true);
});
});
describe("部件目錄", () => {
it("目錄規則都通過;產生的檔和原始檔一致(改了 JSON 或 SVG 要跑 pnpm avatar:build)", () => {
expect(lintCatalog(AVATAR_CATALOG)).toEqual([]);
const built = buildAvatarCatalog();
expect(readFileSync(CATALOG_OUT, "utf-8")).toBe(built.catalog);
expect(readFileSync(ART_OUT, "utf-8")).toBe(built.art);
});
it("第一批新部件約 24 件;每個新部位至少 1 件免費;名稱不用「凍蒜」", () => {
const fresh = AVATAR_CATALOG.items.filter((i) => !i.art.startsWith("builtin:"));
expect(fresh.length).toBeGreaterThanOrEqual(24);
for (const s of wearSlots()) expect(slotItems(s.id).some((i) => i.get.type === "free"), s.id).toBe(true);
expect(fresh.some((i) => i.name.includes("凍蒜"))).toBe(false);
expect(wearItem("hat-victory-band")?.name).toBe("必勝頭帶");
});
it("目錄的部件代號只增不減(代號永不刪除、永不改名)", () => {
const ids = new Set(AVATAR_CATALOG.items.map((i) => `${i.slot}:${i.id}`));
for (const [field, values] of Object.entries(OLD_OPTIONS)) {
const slot = AVATAR_CATALOG.slots.find((s) => s.field === field)!;
for (const v of values) expect(ids.has(`${slot.id}:${v}`), `${slot.id}:${v}`).toBe(true);
}
const firstBatch = [
"hat-campaign-cap", "hat-victory-band", "hat-bamboo", "hat-helmet", "hat-bucket", "mask-plain", "mask-number",
"outer-campaign-vest", "outer-volunteer-vest", "outer-hivis", "outer-raincoat", "sash-red", "sash-thanks", "sash-gold",
"chest-corsage", "chest-name-tag", "held-megaphone", "held-flag", "held-tissue", "held-fan", "held-mic", "held-thermos",
"frame-gazette", "frame-billboard", "frame-newspaper", "frame-gold", "frame-neon",
];
for (const id of firstBatch) expect(wearItem(id), id).toBeDefined();
});
});
describe("部件 SVG 檢查", () => {
const ok = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 220"><path d="M10 10 L190 10 L100 200 Z" fill="#FF00FF"/></svg>';
const bad = (inner: string) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 220">${inner}</svg>`;
it("合規定的圖轉成形狀資料,魔術色轉小寫", () => {
const art = convertSvgArt(ok);
expect(art.front).toEqual([{ t: "path", a: { d: "M10 10 L190 10 L100 200 Z", fill: "#ff00ff" } }]);
});
it("分前後兩層", () => {
const art = convertSvgArt(bad('<g id="back"><circle cx="100" cy="100" r="10" fill="#000"/></g><g id="front"><rect x="1" y="1" width="5" height="5" fill="#fff"/></g>'));
expect(art.back?.[0]?.c?.[0]?.t).toBe("circle");
expect(art.front[0]?.c?.[0]?.t).toBe("rect");
});
it.each([
["script", bad("<script>alert(1)</script>")],
["事件屬性", bad('<path d="M0 0 L10 10" onload="alert(1)"/>')],
["外部連結", bad('<image href="https://example.com/x.png" width="10" height="10"/>')],
["use 連結", bad('<use href="#a"/>')],
["style", bad("<style>*{}</style>")],
["style 屬性", bad('<path d="M0 0 L10 10" style="fill:red"/>')],
["url() 填色", bad('<path d="M0 0 L10 10" fill="url(#g)"/>')],
["文字", bad("<g>凍蒜</g>")],
["超出畫布", bad('<circle cx="190" cy="100" r="30" fill="#000"/>')],
["transform 移出畫布", bad('<rect x="0" y="0" width="10" height="10" transform="translate(250 0)" fill="#000"/>')],
["顏色名稱", bad('<path d="M0 0 L10 10" fill="red"/>')],
["DOCTYPE", `<!DOCTYPE svg [<!ENTITY x "y">]>${ok}`],
["viewBox 不對", ok.replace("0 0 200 220", "0 0 400 400")],
["foreignObject", bad("<foreignObject></foreignObject>")],
])("擋掉:%s", (_name, src) => {
expect(() => convertSvgArt(src)).toThrow(SvgArtError);
});
});
describe("服裝店每週上架", () => {
const monday = new Date("2026-10-26T00:00:00+08:00");
it("台灣時間星期一換週;同一週所有人看到一樣", () => {
expect(shopWeek(new Date("2026-10-25T23:59:00+08:00"))).toBe(shopWeek(monday) - 1);
expect(shopShelf(monday).weekly.map((i) => i.id)).toEqual(shopShelf(new Date("2026-11-01T20:00:00+08:00")).weekly.map((i) => i.id));
});
it("每週 6 件;基本款常駐;本週和常駐不重複", () => {
const s = shopShelf(monday);
expect(s.weekly).toHaveLength(6);
expect(s.always.map((i) => i.id).sort()).toEqual(["hat-bucket", "held-tissue", "mask-number", "outer-volunteer-vest"]);
expect(s.weekly.some((i) => s.always.includes(i))).toBe(false);
});
it("每件輪替的部件一年內一定會再上架", () => {
const rotating = AVATAR_CATALOG.items.filter((i) => i.get.type === "shop" && i.get.shelf === "rotate" && !i.available);
const last = new Map<string, number>();
let maxGap = 0;
const w0 = shopWeek(monday);
for (let w = w0; w < w0 + 156; w++) {
for (const it of shopShelf(new Date(+monday + (w - w0) * 7 * 86_400_000)).weekly) {
const prev = last.get(it.id);
if (prev !== undefined) maxGap = Math.max(maxGap, w - prev);
last.set(it.id, w);
}
}
for (const it of rotating) expect(last.has(it.id), it.id).toBe(true);
expect(maxGap).toBeLessThanOrEqual(52);
});
it("限定品只在每年選舉季(11、12 月)上架,隔年同一個時候回來", () => {
const neon = wearItem("frame-neon")!;
expect(onSale(neon, "2026-11-15")).toBe(true);
expect(onSale(neon, "2027-01-02")).toBe(false);
expect(onSale(neon, "2027-12-01")).toBe(true);
expect(shopShelf(new Date("2026-11-16T12:00:00+08:00")).limited.map((i) => i.id)).toEqual(["frame-neon"]);
expect(shopShelf(new Date("2027-03-16T12:00:00+08:00")).limited).toEqual([]);
});
});