import { existsSync } from "node:fs"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { SCENARIOS } from "@election2026/content"; import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader"; import { RogueView, ScenarioListItem, ScenarioSummary } from "@election2026/protocol"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { FastifyInstance } from "fastify"; import { buildApp } from "../src/app.ts"; const scenario = SCENARIOS[0]; const built = existsSync(join(DEFAULT_PACKS_ROOT, scenario.packId, "manifest.json")); describe.skipIf(!built)("API", () => { let app: FastifyInstance; beforeAll(async () => { app = await buildApp({ maxRuns: 5 }); }); afterAll(() => app.close()); const createRun = (body: unknown) => app.inject({ method: "POST", url: "/api/rogue/runs", payload: body as object }); it("列出劇本", async () => { const res = await app.inject("/api/scenarios"); expect(res.statusCode).toBe(200); const list = res.json(); expect(list.map((s: unknown) => ScenarioSummary.safeParse(s).success)).toEqual(list.map(() => true)); }); it("劇本清單版:只留畫面用到的欄位,和完整版一一對應", async () => { const full = (await app.inject("/api/scenarios")).json() as { id: string; candidates: { id: string }[] }[]; const res = await app.inject("/api/scenarios/list"); expect(res.statusCode).toBe(200); const list = res.json() as unknown[]; expect(list.map((s) => ScenarioListItem.safeParse(s).success)).toEqual(full.map(() => true)); expect(list.map((s) => (s as { id: string }).id)).toEqual(full.map((s) => s.id)); expect(list[0]).not.toHaveProperty("sources"); expect(res.body.length).toBeLessThan(JSON.stringify(full).length / 2); }); it("劇本摘要附上錢的出處", async () => { const [s] = (await app.inject("/api/scenarios")).json(); expect(s.spendingCap).toBe(81_679_000); expect(s.sources.length).toBeGreaterThan(0); expect(s.candidates.every((c: { realFinance: unknown }) => c.realFinance !== null)).toBe(true); }); it("地圖:資料包的拓撲", async () => { const res = await app.inject(`/api/packs/${scenario.packId}/topology`); expect(res.statusCode).toBe(200); expect(res.json().type).toBe("Topology"); expect((await app.inject("/api/packs/nope/topology")).statusCode).toBe(404); }); it("經典模式的 API 已經拿掉", async () => { expect((await app.inject({ method: "POST", url: "/api/matches", payload: {} })).statusCode).toBe(404); }); it("選戰卡牌:開局、出牌、結束這週、選下一站;不合法的出牌回 400", async () => { const even = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor-even")!; const res = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: even.id, candidateId: even.candidates[0]!.id, seed: 5 } }); expect(res.statusCode).toBe(201); const { runId, view } = res.json() as { runId: string; view: unknown }; const v = RogueView.parse(view); expect(v.week).toBe(1); expect(v.hand).toHaveLength(5); expect(v.towns.length).toBeGreaterThan(10); expect(v.towns.some((t) => t.traits.length > 0)).toBe(true); // 相鄰的區由地圖拓撲算出:桃園區和龜山區相鄰 expect(v.towns.find((t) => t.name === "桃園區")!.neighbors).toContain(v.towns.find((t) => t.name === "龜山區")!.code); const card = v.hand.find((c) => c.target === "town" && !c.blocked)!; const best = [...v.previews[card.uid]!].sort((a, b) => b.votes - a.votes)[0]!; const played = await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/play`, payload: { uid: card.uid, target: best.target } }); expect(played.statusCode).toBe(200); const after = RogueView.parse(played.json()); expect(after.hand).toHaveLength(4); expect(after.log.reduce((a, e) => a + e.votes, 0)).toBeCloseTo(best.votes, -1); const bad = await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/play`, payload: { uid: "nope", target: null } }); expect(bad.statusCode).toBe(400); // 第 1 週是開跑記者會(政見支票,docs/27);還有體力時不能趕場 expect(after.scene).toMatchObject({ kind: "press", title: "開跑記者會" }); expect(after.overtime?.blocked).toBe("體力用完才能趕場"); const early = await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/overtime`, payload: {} }); expect(early.statusCode).toBe(409); const ended = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).json()); expect(ended.phase).toBe("route"); expect(ended.route!.length).toBe(3); const next = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: "skip" } })).json()); expect(next.week).toBe(2); // 記者堵麥不擋出牌:出牌階段就有事件,結束這週前要回答 expect(next.phase).toBe("plan"); expect(next.scene!.kind).toBe("press"); expect((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).statusCode).toBe(409); expect((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: 9 } })).statusCode).toBe(409); // 下一站:門上直接攤開的牌,選門+選牌一次完成 const answered = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: 0 } })).json()); expect(answered.scene).toBeNull(); const week2 = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).json()); const door = week2.route!.findIndex((r) => r.preview && (r.preview.kind === "card" || r.preview.kind === "advisor")); expect(door).toBeGreaterThanOrEqual(0); const week3 = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: door, option: 0 } })).json()); expect(week3.week).toBe(3); expect((await app.inject("/api/rogue/runs/00000000-0000-0000-0000-000000000000")).statusCode).toBe(404); }); it("選戰卡牌:新手教學、圖鑑、逆風難度與勢均力敵", async () => { const tut = await app.inject({ method: "POST", url: "/api/rogue/tutorial" }); expect(tut.statusCode).toBe(201); const t = RogueView.parse((tut.json() as { view: unknown }).view); expect(t.options.tutorial).toBe(true); expect(t.totalWeeks).toBe(3); expect(t.towns).toHaveLength(3); const cat = (await app.inject("/api/rogue/catalog")).json() as { cards: unknown[]; advisors: unknown[]; feats: unknown[]; ascension: string[] }; expect(cat.cards.length).toBeGreaterThan(40); expect(cat.advisors.length).toBeGreaterThanOrEqual(30); expect(cat.ascension).toHaveLength(11); const real = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor")!; const hard = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: real.id, candidateId: real.candidates[0]!.id, seed: 1, ascension: 3, even: true } }); expect(hard.statusCode).toBe(201); expect(RogueView.parse((hard.json() as { view: unknown }).view).options.ascension).toBe(3); }); it("選戰卡牌:帶政策島、能力、政策開局;每日一戰不帶;格式不對回 400", async () => { const real = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor")!; const base = { scenarioId: real.id, candidateId: real.candidates[0]!.id, seed: 7 }; const meta = { perks: [{ id: "vault", level: 1 }], abilities: { eloquence: 1, organization: 0, media: 0, finance: 0, integrity: 0 }, policies: [{ name: "長輩安心卡", target: "old", method: "subsidy", funding: "invest" }], }; const plain = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: base })).json().view); const boosted = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, ...meta } })).json().view); expect(boosted.money - plain.money).toBe(150); expect(boosted.hand.some((c) => c.name === "長輩安心卡")).toBe(true); const daily = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, ...meta, daily: "2026-10-26" } })).json().view); expect(daily.hand.some((c) => c.name === "長輩安心卡")).toBe(false); const tooLong = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, policies: [{ ...meta.policies[0], name: "一".repeat(21) }] } }); expect(tooLong.statusCode).toBe(400); const badAbility = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, abilities: { ...meta.abilities, finance: 9 } } }); expect(badAbility.statusCode).toBe(400); const cat = (await app.inject("/api/rogue/catalog")).json() as { buildings: unknown[] }; expect(cat.buildings).toHaveLength(12); }); it("選戰卡牌:存檔之後換一台伺服器也讀得到", async () => { const dir = await mkdtemp(join(tmpdir(), "rogue-save-")); const first = await buildApp({ rogueSaveDir: dir }); const { runId } = (await first.inject({ method: "POST", url: "/api/rogue/tutorial" })).json() as { runId: string }; await first.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` }); await first.close(); // 等寫檔完成 for (let k = 0; k < 20 && !existsSync(join(dir, `${runId}.json`)); k++) await new Promise((r) => setTimeout(r, 25)); const second = await buildApp({ rogueSaveDir: dir }); const res = await second.inject(`/api/rogue/runs/${runId}`); expect(res.statusCode).toBe(200); expect(RogueView.parse(res.json()).phase).toBe("route"); await second.close(); await rm(dir, { recursive: true, force: true }); }); const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" }; const custom = (over: Record = {}) => ({ name: "林小桃", party: null, background: "網紅", stats: { fame: 6, eloquence: 5, strategy: 4, wealth: 5, network: 5 }, avatar, replace: null, ...over, }); it("政治生涯:自創角色以新候選人加入,或取代同黨的候選人;帶過來的幕僚和牌", async () => { const add = await createRun({ scenarioId: "local2022-10018", candidateId: "custom", custom: custom(), even: true, career: { stage: 2 } }); expect(add.statusCode).toBe(201); const a = RogueView.parse((add.json() as { view: unknown }).view); expect(a.you.id).toBe("custom"); expect(a.you.name).toBe("林小桃"); expect(a.options.career).toEqual({ stage: 2, total: 5 }); const rep = await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom({ party: "民主進步黨", replace: "cheng-yun-peng" }), carry: { advisors: ["chief"], cards: [{ id: "rally", up: true }], money: 150 }, }); expect(rep.statusCode).toBe(201); const r = RogueView.parse((rep.json() as { view: unknown }).view); expect(r.rival.name).not.toBe("鄭運鵬"); expect(r.advisors.map((x) => x.id)).toEqual(["chief"]); expect(r.hand.some((c) => c.id === "rally" && c.up)).toBe(true); const leg = await createRun({ scenarioId: "leg2024-63000-01-even", candidateId: "custom", custom: custom() }); expect(leg.statusCode).toBe(201); }); it("政治生涯的地方選舉:里長(真實的里、虛構的對手)、議員(那個里的議員選區,贏過最後一席就當選)", async () => { const kao = { id: "local2022-64000", candidates: [{ id: "64000-1" }] }; const viewOf = async (body: unknown) => { const res = await createRun(body); expect(res.statusCode).toBe(201); return { ...RogueView.parse((res.json() as { view: unknown }).view), runId: (res.json() as { runId: string }).runId }; }; const village = await viewOf({ scenarioId: kao.id, candidateId: "custom", custom: custom(), seed: 4, career: { stage: 1 }, local: { kind: "village", village: null } }); expect(village.office).toBe("里長"); expect(village.towns).toHaveLength(3); expect(village.totalWeeks).toBe(5); expect(village.packId).toBe(""); // 對手是遊戲自己的人物(不是真實候選人) expect(village.rival.id).toBe("rival"); expect(village.rival.party).toBeNull(); const code = village.scenarioId.replace("village:", ""); expect(code).toMatch(/^64000\d{6}$/); const council = await viewOf({ scenarioId: kao.id, candidateId: "custom", custom: custom(), seed: 4, career: { stage: 2 }, local: { kind: "council", village: code } }); expect(council.office).toBe("議員"); expect(council.seats).toBeGreaterThan(1); expect(council.threshold).toBeGreaterThan(0); expect(council.towns.length).toBeGreaterThanOrEqual(3); const area = (await app.inject(`/api/rogue/runs/${council.runId}/area`)).json() as { villages: string[]; groups: Record | null }; expect(area.villages).toContain(code); // 地方選舉一定要用自創角色 const real = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: kao.id, candidateId: kao.candidates[0]!.id, local: { kind: "village", village: null } } }); expect(real.statusCode).toBe(400); const nowhere = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: kao.id, candidateId: "custom", custom: custom(), local: { kind: "council", village: "63000110001" } } }); expect(nowhere.statusCode).toBe(400); }); it("政治生涯:點數超過上限、用真實人物的名字、帶狀態牌都會被拒絕", async () => { expect((await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom({ stats: { fame: 10, eloquence: 10, strategy: 10, wealth: 0, network: 0 } }) })).statusCode).toBe(400); const res = await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom({ name: "蔣萬安" }) }); expect(res.statusCode).toBe(400); expect(res.json().error).toContain("真實人物"); expect((await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom(), carry: { advisors: [], cards: [{ id: "favor", up: false }] } })).statusCode).toBe(400); }); it("超過容量時淘汰最久沒動的一局(沒有存檔目錄時)", async () => { const ids: string[] = []; for (let i = 0; i < 6; i++) ids.push(((await app.inject({ method: "POST", url: "/api/rogue/tutorial" })).json() as { runId: string }).runId); expect((await app.inject(`/api/rogue/runs/${ids[0]}`)).statusCode).toBe(404); expect((await app.inject(`/api/rogue/runs/${ids[5]}`)).statusCode).toBe(200); }); }); describe("流量限制", () => { it("超過每分鐘上限回 429", async () => { const app = await buildApp({ rateLimit: 2 }); const codes = []; for (let i = 0; i < 3; i++) codes.push((await app.inject("/api/health")).statusCode); expect(codes).toEqual([200, 200, 429]); await app.close(); }); });