sokko-g/tests/nebula-cards-daily.test.mjs
Shinuwa d5c2900eed
Some checks failed
Validate and deploy Sokko G / validate (push) Failing after 20m47s
Validate and deploy Sokko G / deploy (push) Has been skipped
Replace the rarity hint of the daily card with the theme of its name
The rarity alone left 71 cards out of 246 and only helped to filter the album; the theme leaves 15 and helps every player. It opens after three wrong guesses and is no longer offered once a guess has found it. Games that had flipped the rarity get their hint back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:48:50 +01:00

417 lines
28 KiB
JavaScript

// Rôle : vérifie les règles, le service et l'API de la Carte du jour de Sokko TCG.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { Readable } from "node:stream";
import { test } from "node:test";
import sharp from "sharp";
import { createCardsApiHandler } from "../services/cards/api.js";
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
import { computeStreak, dailyCandidates, dailyCrop, dailyDayKey, dailyZoom, drawDailyPuzzle, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "../services/cards/daily.js";
import { canUseDailyHint, compareClues, DAILY_HINTS, dailyCluesIssues, dailyHintCredits, damagedPage, loadDailyClues, nameShape, prepareDailyClues } from "../services/cards/daily-clues.js";
import { CardsDatabase } from "../services/cards/database.js";
import { CardsService } from "../services/cards/service.js";
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
const ACTIVE_STATES = [{ collectionId: "primordial-nebula", active: true }, { collectionId: "dream-arcade", active: false }];
const catalog = buildPublishedCatalog(baseCatalog, { variations: [], collectionStates: ACTIVE_STATES, dropRates: [{ collectionId: "primordial-nebula", rarityWeights: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 } }] });
test("the daily day changes at midnight in Paris, in winter and in summer", () => {
assert.equal(dailyDayKey(Date.parse("2026-11-13T22:59:59Z")), "2026-11-13");
assert.equal(dailyDayKey(Date.parse("2026-11-13T23:00:00Z")), "2026-11-14");
assert.equal(dailyDayKey(Date.parse("2026-07-01T21:59:59Z")), "2026-07-01");
assert.equal(dailyDayKey(Date.parse("2026-07-01T22:00:00Z")), "2026-07-02");
assert.equal(nextDailyAt(Date.parse("2026-11-13T12:00:00Z")), Date.parse("2026-11-13T23:00:00Z"));
// Passage à l'heure d'été le 29 mars 2026 : le minuit suivant est à 22 h UTC.
assert.equal(nextDailyAt(Date.parse("2026-03-29T12:00:00Z")), Date.parse("2026-03-29T22:00:00Z"));
assert.equal(nextDailyAt(Date.parse("2026-10-25T12:00:00Z")), Date.parse("2026-10-25T23:00:00Z"));
assert.equal(shiftDayKey("2026-03-01", -1), "2026-02-28");
assert.equal(shiftDayKey("2026-12-31", 1), "2027-01-01");
});
test("the daily streak counts consecutive won days up to today or yesterday", () => {
assert.equal(computeStreak([], "2026-11-13"), 0);
assert.equal(computeStreak(["2026-11-11", "2026-11-12", "2026-11-13"], "2026-11-13"), 3);
assert.equal(computeStreak(["2026-11-11", "2026-11-12"], "2026-11-13"), 2);
assert.equal(computeStreak(["2026-11-10", "2026-11-12"], "2026-11-13"), 1);
assert.equal(computeStreak(["2026-11-11"], "2026-11-13"), 0);
});
test("the daily card comes from an open collection and avoids recent cards", () => {
const candidates = dailyCandidates(catalog);
assert.ok(candidates.length > 0);
assert.ok(candidates.every((item) => item.collectionId === "primordial-nebula"));
const first = drawDailyPuzzle(catalog, [], () => 0);
assert.equal(first.cardId, candidates[0].id);
assert.deepEqual([first.focusX, first.focusY], [20, 20]);
const last = drawDailyPuzzle(catalog, [], (max) => max - 1);
assert.deepEqual([last.focusX, last.focusY], [80, 80]);
assert.equal(drawDailyPuzzle(catalog, [candidates[0].id], () => 0).cardId, candidates[1].id);
// Quand toutes les cartes sont récentes, le tirage reprend sur toute la liste.
assert.equal(drawDailyPuzzle(catalog, candidates.map((item) => item.id), () => 0).cardId, candidates[0].id);
assert.equal(drawDailyPuzzle({ ...catalog, collections: catalog.collections.map((item) => ({ ...item, active: false })) }, [], () => 0), null);
// Une carte encore sans illustration n'est jamais tirée.
const withoutImage = { ...catalog, cards: catalog.cards.map((item) => item.id === candidates[0].id ? { ...item, image: null } : item) };
assert.ok(!dailyCandidates(withoutImage).some((item) => item.id === candidates[0].id));
});
test("the daily zoom loosens with each wrong guess", () => {
assert.equal(dailyZoom(0, false), 6);
assert.equal(dailyZoom(5, false), 1.15);
assert.equal(dailyZoom(9, false), 1.15);
assert.equal(dailyZoom(2, true), 1);
});
const clues = loadDailyClues();
const cardNamed = (name) => baseCatalog.cards.find((item) => item.name === name);
const shown = (parts) => parts.map((part) => (part.hidden ? "▒" : part.text)).join("");
test("every card of the catalog has a daily subject and a theme, and no subject holds too many cards", () => {
assert.deepEqual(dailyCluesIssues(baseCatalog, clues), []);
const incomplete = dailyCluesIssues({ cards: [...baseCatalog.cards, { id: "new-card", name: "Chose Inconnue" }] }, clues);
assert.deepEqual(incomplete, ["new-card: no subject", "new-card: no theme for « Chose Inconnue »"]);
assert.deepEqual(dailyCluesIssues({ cards: baseCatalog.cards.slice(1) }, clues), [`${baseCatalog.cards[0].id}: unknown card`]);
});
test("a daily theme comes from the words of the name, the subject only by default", () => {
const theme = (name) => clues.themeLabels.get(clues.themeOf(name));
assert.equal(theme("Renardeau des Congères"), "Hiver");
assert.equal(theme("Renardeau des Neiges Astrales"), "Hiver");
// « Voie lactée » et « Îles réunies » se lisent en entier ; « Astral » cède devant un mot plus parlant.
assert.equal(theme("Panda de la Voie Lactée"), "Cosmos");
assert.equal(theme("Sapin des Îles Réunies"), "Fête");
assert.equal(theme("Encrier Astral"), "Cosmos");
assert.equal(theme("Constellation du Loup"), "Lumière");
assert.equal(theme("Premier Croissant"), "Lune");
const content = { subjects: [{ id: "animal", label: "Animal" }], themes: [{ id: "one", label: "Un", words: ["lune"] }, { id: "two", label: "Deux", words: ["Lune"] }], compoundSubjects: [], cards: {} };
assert.throws(() => prepareDailyClues(content), /already belongs to one/);
assert.throws(() => prepareDailyClues({ ...content, themes: [], subjects: [{ id: "animal/oiseau", label: "Oiseau" }] }), /has no parent animal/);
assert.throws(() => prepareDailyClues({ ...content, themes: [], cards: { card: { subject: "objet" } } }), /unknown subject objet/);
});
test("a daily guess shows the common part of the subject and the theme, never the rest of the answer", () => {
const answer = cardNamed("Renardeau des Congères");
const compare = (name) => compareClues(clues, answer, cardNamed(name));
assert.deepEqual(compare("Épée du Socle Ancien"), { subject: { common: [], different: "Objet" }, theme: { label: "Combat", same: false } });
assert.deepEqual(compare("Loutre Pilote du Bateau du Ciel").subject, { common: ["Animal", "Mammifère"], different: "Mustélidé" });
assert.deepEqual(compare("Loup des Aurores").subject, { common: ["Animal", "Mammifère", "Canidé"], different: null });
// Une espèce sans branche s'arrête à « Mammifère » : rien ne dit que la réponse va plus loin.
assert.deepEqual(compare("Phoque des Glaces Lunaires"), { subject: { common: ["Animal", "Mammifère"], different: null }, theme: { label: "Hiver", same: true } });
// Une carte sans indices reste jouable, sans comparaison.
assert.deepEqual(compareClues(clues, answer, { id: "new-card", name: "Chose Inconnue" }), { subject: { common: [], different: null }, theme: null });
});
test("the damaged page and the name shape hide words without sending them", () => {
const hedgehog = cardNamed("Hérisson à la Guirlande");
assert.equal(shown(damagedPage(hedgehog)), "En voulant aider à décorer le sapin, il s'est emmêlé dans la ▒.");
assert.equal(shown(nameShape("Renardeau des Neiges Astrales")), "▒ des ▒ ▒");
assert.equal(shown(nameShape("L'Échange de l'Aube")), "L'▒ de l'▒");
assert.ok(nameShape(hedgehog.name).filter((part) => part.hidden).every((part) => Object.keys(part).join() === "hidden"));
for (const card of baseCatalog.cards) assert.ok(damagedPage(card).some((part) => part.text) && nameShape(card.name).some((part) => part.hidden), card.id);
});
test("a wrong daily guess earns one hint of the player's choice", () => {
assert.equal(dailyHintCredits(0, 0), 0);
assert.equal(dailyHintCredits(3, 1), 2);
assert.equal(dailyHintCredits(6, 0), DAILY_HINTS.length);
assert.equal(canUseDailyHint("album", 0, []), false);
assert.equal(canUseDailyHint("album", 1, []), true);
assert.equal(canUseDailyHint("album", 2, ["album"]), false);
assert.equal(canUseDailyHint("collection", 1, ["album"]), false);
assert.equal(canUseDailyHint("theme", 2, []), false);
assert.equal(canUseDailyHint("theme", 3, []), true);
// Un thème déjà trouvé par un essai n'est plus un indice.
assert.equal(canUseDailyHint("theme", 3, [], ["theme"]), false);
assert.equal(canUseDailyHint("rarity", 6, []), false);
assert.equal(canUseDailyHint("page", 1, []), false);
assert.equal(canUseDailyHint("shape", 3, []), false);
assert.equal(canUseDailyHint("shape", 4, ["album"]), true);
assert.equal(canUseDailyHint("unknown", 6, []), false);
});
function dailyService(start = Date.parse("2026-11-13T09:00:00Z"), random = () => 0) {
const clock = { now: start };
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random });
const admin = service.upsertPlayer({ discordId: "daily-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "daily-player", displayName: "Player" });
const wrongCards = () => {
const answer = service.todayPuzzle(player.id).cardId;
return service.catalog.cards.filter((item) => item.collectionId === "primordial-nebula" && item.id !== answer).map((item) => item.id);
};
return { clock, database, service, admin, player, wrongCards };
}
test("the daily crop keeps the visible part of the illustration around the focus point", () => {
assert.deepEqual(dailyCrop(800, 800, { x: 20, y: 20 }, 6), { left: 133, top: 133, width: 133, height: 133 });
assert.deepEqual(dailyCrop(800, 800, { x: 100, y: 0 }, 4.2), { left: 610, top: 0, width: 190, height: 190 });
assert.deepEqual(dailyCrop(640, 640, { x: 50, y: 80 }, 1.15), { left: 42, top: 66, width: 557, height: 557 });
assert.deepEqual(dailyCrop(800, 800, { x: 20, y: 20 }, 1), { left: 0, top: 0, width: 800, height: 800 });
});
test("each player draws a daily card on the first visit and the answer stays hidden while playing", () => {
const { service, admin, player, database } = dailyService();
// Le tableau de bord résume la quête sans tirer de carte : seul le passage par la Carte du jour en tire une.
assert.equal(service.getState(player.id).daily.status, "playing");
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts").get().count, 0);
const daily = service.getDaily(player.id);
assert.equal(daily.day, "2026-11-13");
assert.equal(daily.number, 1);
assert.equal(daily.status, "playing");
assert.equal(daily.zoom, 6);
assert.equal(daily.maxGuesses, MAX_DAILY_GUESSES);
assert.equal(daily.reward, 10);
assert.equal(daily.answerCardId, null);
// Les mots de recherche couvrent toutes les cartes proposables : ils ne désignent pas la réponse.
const { searchWords, ...hiddenAnswer } = daily;
assert.deepEqual(searchWords["starlit-ice-penguin"], ["pingouin", "oiseau"]);
assert.equal(Object.keys(searchWords).some((cardId) => service.index.cards.get(cardId).collectionId === "dream-arcade"), false);
assert.ok(!JSON.stringify(hiddenAnswer).includes(service.todayPuzzle(player.id).cardId));
assert.deepEqual(daily.hints, []);
assert.equal(daily.hintCredits, 0);
assert.deepEqual(daily.hintChoices.map((choice) => choice.available), [false, false, false, false, false]);
// Le point de zoom reste au serveur, qui n'envoie que la zone visible de l'illustration.
assert.equal(daily.focus, undefined);
assert.deepEqual(service.dailyImage(player.id).focus, { x: 20, y: 20 });
assert.equal(daily.nextAt, Date.parse("2026-11-13T23:00:00Z"));
assert.ok(daily.collectionIds.includes("primordial-nebula"));
assert.ok(!daily.collectionIds.includes("dream-arcade"));
assert.equal(service.getDaily(admin.id).day, daily.day);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_days").get().count, 1);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts").get().count, 2);
// Ouvrir la page tire une carte sans jouer : l'administration ne compte que les joueurs qui ont proposé une carte.
assert.deepEqual(service.getAdminDashboard(admin.id).daily, { day: "2026-11-13", number: 1, players: 0, winners: 0 });
assert.equal(service.getState(player.id).daily.status, "playing");
});
test("players get different daily cards, so a shared answer does not help", () => {
let draw = 0;
const { service, admin, player } = dailyService(undefined, (max) => (draw++ * 7) % max);
const mine = service.todayPuzzle(player.id).cardId;
const theirs = service.todayPuzzle(admin.id).cardId;
assert.notEqual(mine, theirs);
assert.equal(service.todayPuzzle(player.id).cardId, mine);
assert.equal(service.guessDaily(player.id, { day: "2026-11-13", cardId: theirs }).daily.status, "playing");
});
test("wrong daily guesses unzoom the card until the player runs out of guesses", () => {
const { service, player, wrongCards } = dailyService();
const [first, ...others] = wrongCards();
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: first });
assert.deepEqual({ status: state.daily.status, guessCount: state.daily.guessCount }, { status: "playing", guessCount: 1 });
assert.equal(daily.guesses.length, 1);
assert.equal(daily.guesses[0].correct, false);
assert.ok(Array.isArray(daily.guesses[0].subject.common));
assert.equal(typeof daily.guesses[0].theme.same, "boolean");
assert.equal(daily.zoom, 4.2);
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: first }), (error) => error.code === "DAILY_GUESS_REPEATED");
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: "unknown-card" }), (error) => error.code === "DAILY_GUESS_INVALID");
const closedCard = service.catalog.cards.find((item) => item.collectionId === "dream-arcade");
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: closedCard.id }), (error) => error.code === "DAILY_GUESS_INVALID");
assert.throws(() => service.guessDaily(player.id, { day: "13/11/2026", cardId: others[0] }), (error) => error.code === "DAILY_GUESS_INVALID");
let last;
for (const cardId of others.slice(0, MAX_DAILY_GUESSES - 1)) last = service.guessDaily(player.id, { day: "2026-11-13", cardId }).daily;
assert.equal(last.status, "lost");
assert.equal(last.zoom, 1);
assert.equal(last.earned, 0);
assert.equal(last.answerCardId, service.todayPuzzle(player.id).cardId);
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: others.at(-1) }), (error) => error.code === "DAILY_FINISHED");
assert.equal(service.getState(player.id).wallet.stardust, 0);
});
test("a player flips the daily hints in the order of their choice, for free", () => {
const { clock, service, player, wrongCards } = dailyService();
const day = "2026-11-13";
const flip = (hint) => service.useDailyHint(player.id, { day, hint });
const others = wrongCards();
const puzzle = service.todayPuzzle(player.id);
const answer = service.index.cards.get(puzzle.cardId);
assert.throws(() => flip("album"), (error) => error.code === "DAILY_HINT_LOCKED");
assert.throws(() => flip("answer"), (error) => error.code === "DAILY_HINT_INVALID");
assert.throws(() => service.useDailyHint(player.id, { day: "demain", hint: "album" }), (error) => error.code === "DAILY_HINT_INVALID");
assert.deepEqual(service.guessDaily(player.id, { day, cardId: others[0] }).daily.hintChoices.filter((choice) => choice.available).map((choice) => choice.id), ["album", "collection"]);
assert.throws(() => flip("page"), (error) => error.code === "DAILY_HINT_LOCKED");
// La possession est celle du tirage : une carte reçue pendant la partie ne change pas l'indice.
const edition = service.catalog.editions.find((item) => item.cardId === answer.id);
service.db.prepare("INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, 0)").run(player.id, edition.id);
const album = flip("album");
assert.deepEqual(album.hints, [{ id: "album", value: false }]);
assert.equal(album.hintCredits, 0);
assert.equal(album.guesses.length, 1);
assert.deepEqual(flip("album").hints, album.hints);
assert.throws(() => flip("collection"), (error) => error.code === "DAILY_HINT_LOCKED");
for (const cardId of others.slice(1, 4)) service.guessDaily(player.id, { day, cardId });
assert.equal(service.getDaily(player.id).hintCredits, 3);
flip("shape");
flip("page");
const view = flip("collection");
assert.deepEqual(view.hints.map((hint) => hint.id), ["album", "shape", "page", "collection"]);
assert.equal(view.hints.at(-1).value, answer.collectionId);
assert.deepEqual(view.hints[1].value, nameShape(answer.name));
assert.ok(!JSON.stringify(view).includes(answer.id));
const won = service.guessDaily(player.id, { day, cardId: answer.id }).daily;
assert.equal(won.hints.length, 4);
assert.equal(won.earned, 10);
assert.equal(won.hintCredits, 0);
assert.throws(() => flip("theme"), (error) => error.code === "DAILY_FINISHED");
clock.now = Date.parse("2026-11-13T23:00:00Z");
assert.throws(() => flip("theme"), (error) => error.code === "DAILY_EXPIRED");
});
test("the theme hint names the theme of the answer, unless a guess already found it", () => {
const day = "2026-11-13";
const play = (sameTheme) => {
const { service, player, wrongCards } = dailyService();
const themeOf = (cardId) => clues.themeOf(service.index.cards.get(cardId).name);
const theme = themeOf(service.todayPuzzle(player.id).cardId);
const others = wrongCards().filter((cardId) => themeOf(cardId) !== theme);
const guesses = sameTheme ? [wrongCards().find((cardId) => themeOf(cardId) === theme), ...others] : others;
let daily;
for (const cardId of guesses.slice(0, 3)) daily = service.guessDaily(player.id, { day, cardId }).daily;
return { service, player, others, choice: daily.hintChoices.find((item) => item.id === "theme"), flip: () => service.useDailyHint(player.id, { day, hint: "theme" }), label: clues.themeLabels.get(theme) };
};
const unknown = play(false);
assert.deepEqual(unknown.choice, { id: "theme", after: 3, known: false, available: true });
assert.deepEqual(unknown.flip().hints, [{ id: "theme", value: unknown.label }]);
const found = play(true);
assert.deepEqual(found.choice, { id: "theme", after: 3, known: true, available: false });
assert.throws(found.flip, (error) => error.code === "DAILY_HINT_LOCKED");
// Le crédit que le thème aurait pris n'est pas annoncé quand il ne reste rien à retourner.
for (const cardId of found.others.slice(2, 4)) found.service.guessDaily(found.player.id, { day, cardId });
for (const hint of ["album", "collection", "page", "shape"]) found.service.useDailyHint(found.player.id, { day, hint });
assert.equal(found.service.getDaily(found.player.id).hintCredits, 0);
});
test("games that had flipped the former rarity hint get their hint back", () => {
const { service, player, database } = dailyService();
service.todayPuzzle(player.id);
database.db.prepare("UPDATE daily_attempts SET hints_json = '[\"album\",\"rarity\",\"page\"]'").run();
database.db.prepare("DELETE FROM schema_migrations WHERE version = 27").run();
database.migrate();
assert.equal(database.db.prepare("SELECT hints_json FROM daily_attempts").get().hints_json, '["album","page"]');
});
test("a daily game drawn before the hints reads the ownership in the collection", () => {
const { service, player, wrongCards } = dailyService();
const answer = service.todayPuzzle(player.id).cardId;
service.db.prepare("UPDATE daily_attempts SET owned = NULL").run();
const edition = service.catalog.editions.find((item) => item.cardId === answer);
service.db.prepare("INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, 0)").run(player.id, edition.id);
service.guessDaily(player.id, { day: "2026-11-13", cardId: wrongCards()[0] });
assert.deepEqual(service.useDailyHint(player.id, { day: "2026-11-13", hint: "album" }).hints, [{ id: "album", value: true }]);
});
test("finding the daily card credits the reward once and records it in the player history", () => {
const { service, admin, player, wrongCards } = dailyService();
service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: 25 });
const answer = service.todayPuzzle(player.id).cardId;
service.guessDaily(player.id, { day: "2026-11-13", cardId: wrongCards()[0] });
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: answer });
assert.equal(daily.status, "won");
assert.equal(daily.earned, 25);
assert.equal(daily.streak, 1);
assert.equal(daily.zoom, 1);
assert.equal(daily.answerCardId, answer);
assert.equal(state.wallet.stardust, 25);
assert.deepEqual(state.history.find((entry) => entry.type === "daily_won"), { type: "daily_won", entityId: "2026-11-13", details: { number: 1, cardId: answer, guesses: 2, stardust: 25 }, createdAt: Date.parse("2026-11-13T09:00:00Z") });
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: answer }), (error) => error.code === "DAILY_FINISHED");
assert.equal(service.getState(player.id).wallet.stardust, 25);
assert.deepEqual(service.getAdminDashboard(admin.id).daily, { day: "2026-11-13", number: 1, players: 1, winners: 1 });
// La récompense de la Carte du jour n'est pas une action d'administration.
assert.ok(!service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "daily_won"));
assert.throws(() => service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: -1 }), /Carte du jour/);
});
test("a new daily card arrives at midnight in Paris and the streak continues", () => {
const { clock, service, player } = dailyService();
const firstAnswer = service.todayPuzzle(player.id).cardId;
service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer });
clock.now = Date.parse("2026-11-13T23:00:00Z");
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer }), (error) => error.code === "DAILY_EXPIRED");
const daily = service.getDaily(player.id);
assert.equal(daily.day, "2026-11-14");
assert.equal(daily.number, 2);
assert.equal(daily.status, "playing");
assert.equal(daily.streak, 1);
const secondAnswer = service.todayPuzzle(player.id).cardId;
assert.notEqual(secondAnswer, firstAnswer);
assert.equal(service.guessDaily(player.id, { day: "2026-11-14", cardId: secondAnswer }).daily.streak, 2);
});
test("deleting an account erases its daily games", () => {
const { service, player, database } = dailyService();
service.guessDaily(player.id, { day: "2026-11-13", cardId: service.todayPuzzle(player.id).cardId });
service.deleteAccount(player.id);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts WHERE player_id = ?").get(player.id).count, 0);
});
function mockRequest({ method = "GET", path, body, headers = {} }) {
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
req.method = method;
req.url = path;
req.headers = { host: "localhost:5173", ...headers };
req.socket = { remoteAddress: "127.0.0.1" };
return req;
}
async function call(handler, options) {
const response = { status: 0, headers: {}, chunks: [] };
const res = {
setHeader(name, value) { response.headers[name.toLowerCase()] = value; },
writeHead(status, headers = {}) {
response.status = status;
for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value;
},
end(value = "") { response.chunks.push(Buffer.from(value)); }
};
await handler(mockRequest(options), res);
response.raw = Buffer.concat(response.chunks);
response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null;
return response;
}
test("the daily API requires a session, protects guesses and serves only the visible part of the image while playing", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
t.after(() => handler.close());
for (const path of ["/api/cards/daily", "/api/cards/daily/image"]) assert.equal((await call(handler, { path })).status, 401);
for (const path of ["/api/cards/daily/guesses", "/api/cards/daily/hints"]) assert.equal((await call(handler, { method: "POST", path, body: {} })).status, 401);
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
const cookie = login.headers["set-cookie"].split(";")[0];
const csrf = login.json.csrfToken;
const daily = await call(handler, { path: "/api/cards/daily", headers: { cookie } });
assert.equal(daily.status, 200);
assert.equal(daily.json.answerCardId, null);
const image = await call(handler, { path: "/api/cards/daily/image", headers: { cookie } });
assert.equal(image.status, 200);
assert.equal(image.headers["content-type"], "image/webp");
assert.equal(image.headers["cache-control"], "private, no-store");
assert.equal(image.headers["content-disposition"], undefined);
assert.equal(image.raw.subarray(8, 12).toString("ascii"), "WEBP");
const player = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get();
const answer = handler.service.todayPuzzle(player.id).cardId;
assert.ok(!JSON.stringify(image.headers).includes(answer));
// Pendant la partie, un morceau recadré de 720 px, jamais le fichier de l'illustration.
const original = await readFile(resolve("website/public", `.${handler.service.index.cards.get(answer).image}`));
assert.notDeepEqual(image.raw, original);
assert.equal((await sharp(image.raw).metadata()).width, 720);
const unprotected = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie }, body: { day: daily.json.day, cardId: answer } });
assert.equal(unprotected.status, 403);
const wrong = handler.service.catalog.cards.find((item) => item.id !== answer && daily.json.collectionIds.includes(item.collectionId)).id;
await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: wrong } });
assert.equal((await call(handler, { method: "POST", path: "/api/cards/daily/hints", headers: { cookie }, body: { day: daily.json.day, hint: "collection" } })).status, 403);
const hint = await call(handler, { method: "POST", path: "/api/cards/daily/hints", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, hint: "collection" } });
assert.equal(hint.status, 200);
assert.deepEqual(hint.json.daily.hints, [{ id: "collection", value: handler.service.index.cards.get(answer).collectionId }]);
const won = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
assert.equal(won.status, 200);
assert.equal(won.json.daily.status, "won");
assert.ok(won.json.state.history.some((entry) => entry.type === "daily_won"));
// La partie finie, l'illustration entière.
assert.deepEqual((await call(handler, { path: "/api/cards/daily/image", headers: { cookie } })).raw, original);
const again = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
assert.equal(again.status, 409);
assert.equal(again.json.error.code, "DAILY_FINISHED");
});