Files
wikideck/tests/modes-api.test.ts
T
claudeandClaude Opus 5.5 a2c2166bcc Modes: follow engine core f3b6097 (trend arrows, timeouts, deckSize)
Live/trending presets freeze the engine's trend arrow from cached live data;
the host turn timer uses the ruleset's turnSeconds and applies the engine's
timeout action (logged, replayable AFK forfeits). Non-draft modes whose rules
make starter decks illegal are rejected at startup. HOSTING.md updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:04:12 -05:00

192 lines
12 KiB
TypeScript

// End to end over HTTP with the real engine: publish, discover, host all three example modes.
import test from 'node:test';
import assert from 'node:assert/strict';
import express from 'express';
import type { AddressInfo } from 'node:net';
import { gameRouter } from '../server/game/index.ts';
import { previewPool } from '../server/game/engine-binding.ts';
import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts';
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { ModeListSchema } from '../shared/game/modes.ts';
async function serve(env: NodeJS.ProcessEnv, enrichment?: any) {
const app = express();
app.use(express.json({ limit: '68kb' }));
app.use('/api/game', await gameRouter({ dataDir: null, env, enrichment }));
app.use((err: Error, _q: express.Request, res: express.Response, _n: express.NextFunction) => res.status(400).json({ error: err.message }));
const server = app.listen(0, '127.0.0.1');
await new Promise(r => server.once('listening', r));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
return { base, close: () => new Promise(r => server.close(r)) };
}
const call = async (base: string, path: string, body?: unknown, token?: string) => {
const res = await fetch(base + path, { method: body === undefined ? 'GET' : 'POST',
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body) });
return { status: res.status, json: await res.json() as any };
};
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
async function playToEnd(base: string, lobby: string, tokens: string[]) {
for (let i = 0; i < 400; i++) {
let moved = false;
for (const t of tokens) {
const v = (await call(base, `/api/game/lobbies/${lobby}`, undefined, t)).json;
if (v.phase !== 'playing') return v;
// Play the first card if possible, else end the turn.
const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'commit');
if (a) { const r = await call(base, `/api/game/lobbies/${lobby}/actions`, { action: a }, t); assert.equal(r.status, 200, JSON.stringify(r.json)); moved = true; }
}
if (!moved) break;
}
return (await call(base, `/api/game/lobbies/${lobby}`, undefined, tokens[0])).json;
}
test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => {
const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101',
WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' },
{ get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) });
try {
const list = (await call(node.base, '/api/game/modes')).json;
ModeListSchema.parse(list);
assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']);
assert.equal(list.host.operator, 'Node A');
for (const id of ['classic', 'trending']) {
const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice);
assert.equal(a.status, 201);
const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob);
assert.equal(b.status, 200, JSON.stringify(b.json));
const peek = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`)).json;
assert.equal(peek.state, undefined);
const wrongSeat = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`, undefined, a.json.token)).json.legalActions[0];
const cheat = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/actions`, { action: { ...wrongSeat, player: 1 } }, a.json.token);
assert.equal(cheat.status, 400, 'cannot act for the other seat');
const end = await playToEnd(node.base, a.json.lobbyId, [a.json.token, b.json.token]);
assert.equal(end.phase, 'finished', JSON.stringify(end).slice(0, 300));
const rec = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(rec.modeId, id);
assert.equal(rec.decks[0].length, 12);
}
// Draft: 20 snake picks, 10-card decks.
const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
const tokens = [a.token, b.token];
let picks = 0;
for (;;) {
const v = (await call(node.base, `/api/game/lobbies/${a.lobbyId}`, undefined, a.token)).json;
if (v.phase !== 'drafting') { assert.equal(v.phase, 'playing'); break; }
const free = v.draft.pool.find((c: any) => c.takenBy === null);
const r = await call(node.base, `/api/game/lobbies/${a.lobbyId}/pick`, { index: free.index }, tokens[v.draft.toPick]);
assert.equal(r.status, 200, JSON.stringify(r.json));
picks++;
}
assert.equal(picks, 20);
const end = await playToEnd(node.base, a.lobbyId, tokens);
assert.equal(end.phase, 'finished');
const record = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(record.decks[1].length, 10);
// Anyone can audit a match: replaying the published record reproduces the result.
const replayed = replay(record.rules, record.decks, record.seed, record.actions.map((a: any) => a.action));
assert.equal(replayed.phase, 'over');
assert.equal(replayed.result?.winner ?? null, record.winner);
const after = (await call(node.base, '/api/game/modes')).json;
assert.equal(after.matchesHosted, 3);
const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json;
assert.equal(board.entries.length, 2);
assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404);
assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404);
} finally { await node.close(); }
});
test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => {
const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' });
const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A',
WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' });
try {
// One match on B so it leads the host leaderboard.
const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match
const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json;
const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json;
assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0);
const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json;
const rec = (await call(peerB.base, `/api/game/matches/${resigned.matchId}`)).json;
assert.equal(replay(rec.rules, rec.decks, rec.seed, rec.actions.map((x: any) => x.action)).result?.winner, 0, 'resign replays as concede');
const net = (await call(nodeA.base, '/api/game/network/modes')).json;
assert.equal(net.self.host.operator, 'Node A');
assert.equal(net.peers.length, 2);
assert.equal(net.peers[0].ok, true);
assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer');
assert.equal(net.peers[0].list.modes[0].mode.id, 'draft');
assert.equal(net.peers[1].ok, false);
const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts;
assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]);
} finally { await nodeA.close(); await peerB.close(); }
});
test('modes api: draft preview pool is deterministic and deck-legal', () => {
const p1 = previewPool(DEFAULT_RULESET, 'seed', 30), p2 = previewPool(DEFAULT_RULESET, 'seed', 30);
assert.deepEqual(p1, p2);
assert.equal(p1.length, 30);
assert.equal(new Set(p1.map(c => c.cardId)).size, 30);
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage);
});
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
for (const rules of [
{ turns: 4, energyByTurn: [3, 4, 5, 6] },
{ onTopicBonus: 4, trendUp: 10, trendDown: -10 },
{ deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 },
{ turns: 6, turnSeconds: 40 },
]) {
const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules));
}
});
test('modes api: mode rules that make starter decks illegal fail at startup; live trend arrows follow the ruleset', async () => {
const { ModeHost } = await import('../server/game/host.ts');
const { MatchStore } = await import('../server/game/store.ts');
const { engineBinding } = await import('../server/game/engine-binding.ts');
const big = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'big', version: 1, name: 'Big', description: 'x',
decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } });
assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding,
store: new MatchStore(null) }), /starter decks are illegal/);
const card = engineBinding.starterDeck(DEFAULT_RULESET, 's')[0]!;
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 30 }).trend, 1);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: -30 }).trend, -1);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 5 }).trend, 0);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: null }).trend, 0);
assert.equal(engineBinding.withPower(card, 99).power, 30, 'power stays within engine bounds');
});
test('modes api: turn timer applies the engine timeout action; AFK forfeits are replayable', async () => {
const { ModeHost } = await import('../server/game/host.ts');
const { MatchStore } = await import('../server/game/store.ts');
const { engineBinding } = await import('../server/game/engine-binding.ts');
let now = 0;
const classic = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } });
const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding,
store: new MatchStore(null), now: () => now });
const a = host.createLobby('classic', alice);
const b = await host.join(a.lobbyId, bob);
// Bob plays normally; Alice never acts.
for (let turn = 0; turn < 6; turn++) {
const v = host.view(a.lobbyId, b.token) as any;
if (v.phase !== 'playing') break;
await host.act(a.lobbyId, b.token, { type: 'commit', player: 1 });
now += (DEFAULT_RULESET.turnSeconds + 6) * 1000; host.sweep();
}
const end = host.view(a.lobbyId, a.token) as any;
assert.equal(end.phase, 'finished');
assert.deepEqual(end.outcome, { winner: 1, reason: 'afk' });
const rec = host.matchRecord(end.matchId);
assert.ok(rec.actions.some(x => (x.action as any).type === 'timeout'));
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner, 1);
});