Add the Sokko TCG collectible card mini-game

Add the server-backed card game: Discord login, recharging pack openings,
album, trades, gifts, stardust shop, campaign codes and its administration,
stored in SQLite and disabled in production until configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-05 17:47:35 +01:00
parent 243465720f
commit 5ce35cd7ba
193 changed files with 12159 additions and 28 deletions

View file

@ -87,6 +87,7 @@ export function validateSiteContent(site) {
"navigation.home",
"navigation.toolboxes",
"navigation.games",
"navigation.cards",
"navigation.library",
"navigation.about",
"sidebar.badge",
@ -95,6 +96,7 @@ export function validateSiteContent(site) {
"topbar.toolbox",
"topbar.library",
"topbar.games",
"topbar.cards",
"topbar.gameViewLabel",
"topbar.guideView",
"topbar.toolboxView",
@ -106,6 +108,129 @@ export function validateSiteContent(site) {
"gamesPage.emptyTitle",
"gamesPage.emptyText",
"gamesPage.retryLabel",
"cards.eyebrow",
"cards.title",
"cards.description",
"cards.loadingTitle",
"cards.loadingText",
"cards.disabledTitle",
"cards.disabled",
"cards.errorTitle",
"cards.loginDescription",
"cards.discordLogin",
"cards.discordUnavailable",
"cards.discordErrors.denied",
"cards.discordErrors.expired",
"cards.discordErrors.failed",
"cards.devLogin",
"cards.admin.backToGame",
"cards.admin.restrictedTitle",
"cards.admin.restrictedText",
"cards.home.eyebrow",
"cards.home.title",
"cards.home.available",
"cards.home.next",
"cards.home.full",
"cards.home.rarestEyebrow",
"cards.home.rarestTitle",
"cards.home.noPull",
"cards.home.browsePacks",
"cards.home.resume",
"cards.home.resumeAction",
"cards.home.cardsDiscovered",
"cards.home.editionsDiscovered",
"cards.home.ownedCopies",
"cards.home.packsOpened",
"cards.navigation.home",
"cards.navigation.packs",
"cards.navigation.collection",
"cards.navigation.shop",
"cards.navigation.transfers",
"cards.navigation.history",
"cards.transfers.eyebrow",
"cards.transfers.title",
"cards.transfers.newGift",
"cards.transfers.newTrade",
"cards.transfers.inboxTitle",
"cards.transfers.sentTitle",
"cards.transfers.finishedTitle",
"cards.transfers.empty",
"cards.transfers.giftFrom",
"cards.transfers.giftTo",
"cards.transfers.tradeWith",
"cards.transfers.expires",
"cards.transfers.youGive",
"cards.transfers.youReceive",
"cards.transfers.accept",
"cards.transfers.decline",
"cards.transfers.cancel",
"cards.transfers.close",
"cards.transfers.statusCompleted",
"cards.transfers.statusCancelled",
"cards.transfers.statusDeclined",
"cards.transfers.statusExpired",
"cards.transfers.acceptedNotice",
"cards.transfers.declinedNotice",
"cards.transfers.cancelledNotice",
"cards.transfers.typeLabel",
"cards.transfers.typeTrade",
"cards.transfers.typeGift",
"cards.transfers.playerLabel",
"cards.transfers.playerPlaceholder",
"cards.transfers.playerLoading",
"cards.transfers.noPlayers",
"cards.transfers.duplicatesShort",
"cards.transfers.noDuplicates",
"cards.transfers.playerNoDuplicates",
"cards.transfers.choosePlayerFirst",
"cards.transfers.missingBadge",
"cards.transfers.giftHelp",
"cards.transfers.tradeHelp",
"cards.transfers.sameCard",
"cards.transfers.giveAction",
"cards.transfers.toPlayer",
"cards.transfers.sendTrade",
"cards.transfers.giftSentNotice",
"cards.transfers.tradeSentNotice",
"cards.collection.eyebrow",
"cards.collection.title",
"cards.collection.resetFilters",
"cards.history.pendingCards",
"cards.recycling.barLabel",
"cards.recycling.viewDuplicates",
"cards.recycling.viewAll",
"cards.recycling.allButton",
"cards.recycling.ratesLabel",
"cards.recycling.pending",
"cards.recycling.pendingAction",
"cards.home.stardust",
"cards.home.recyclable",
"cards.packs.eyebrow",
"cards.packs.title",
"cards.packs.permanent",
"cards.packs.permanentDescription",
"cards.packs.event",
"cards.packs.eventDescription",
"cards.packs.open",
"cards.packs.probabilities",
"cards.packs.back",
"cards.packs.shopShare",
"cards.shop.packDescription",
"cards.shop.packAction",
"cards.shop.packPending",
"cards.packs.purchasedLabel",
"cards.packs.purchasedHelp",
"cards.packs.empty",
"cards.packs.redeemTitle",
"cards.packs.redeemHelp",
"cards.packs.redeemPlaceholder",
"cards.packs.redeemButton",
"cards.packs.redeemReceived",
"cards.packs.redeemWhere",
"cards.packs.giftTitle",
"cards.packs.giftDescription",
"cards.packs.giftOpen",
"cards.packs.noOpening",
"guideChecklist.label",
"guideChecklist.selectLabel",
"guideChecklist.selectPlaceholder",

View file

@ -0,0 +1,229 @@
// Rôle : vérifie le contrat HTTP, la session, le CSRF et l'idempotence de l'API Sokko TCG.
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { test } from "node:test";
import { resolve } from "node:path";
import { createCardsApiHandler } from "../services/cards/api.js";
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: {}, body: "" };
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.body += value; }
};
await handler(mockRequest(options), res);
response.json = response.body ? JSON.parse(response.body) : null;
return response;
}
test("Discord OAuth preserves the dedicated admin route", async (t) => {
const handler = createCardsApiHandler({
projectRoot: resolve("."),
enabled: true,
devAuth: false,
databasePath: ":memory:",
env: {
NODE_ENV: "test",
DISCORD_CLIENT_ID: "discord-client",
DISCORD_CLIENT_SECRET: "discord-secret",
CARDS_ADMIN_DISCORD_IDS: "discord-admin"
},
fetchImpl: async (url) => {
if (String(url).includes("/oauth2/token")) return { ok: true, json: async () => ({ access_token: "discord-token" }) };
return { ok: true, json: async () => ({ id: "discord-admin", username: "Admin", global_name: "TCG Admin", avatar: null }) };
}
});
t.after(() => handler.close());
const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fadmin" });
assert.equal(authorization.status, 302);
const authorizationUrl = new URL(authorization.headers.location);
const state = authorizationUrl.searchParams.get("state");
const oauthCookies = authorization.headers["set-cookie"];
assert.ok(oauthCookies.some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=%2Fcards%2Fadmin;")));
// Le retour après connexion accepte les sections joueur, jamais une adresse hors de Sokko TCG.
for (const [returnTo, expected] of [["/cards/shop", "%2Fcards%2Fshop"], ["/cards/admin/collections/nebula", "%2Fcards%2Fadmin%2Fcollections%2Fnebula"], ["/cards/shop/extra", "%2Fcards"], ["//evil.example/cards", "%2Fcards"], ["/cards/../toolboxes", "%2Fcards"]]) {
const response = await call(handler, { path: `/api/cards/auth/discord?returnTo=${encodeURIComponent(returnTo)}` });
assert.ok(response.headers["set-cookie"].some((cookie) => cookie.startsWith(`sokkog_cards_oauth_return=${expected};`)), returnTo);
}
const callback = await call(handler, {
path: `/api/cards/auth/callback?state=${encodeURIComponent(state)}&code=discord-code`,
headers: { cookie: oauthCookies.map((cookie) => cookie.split(";")[0]).join("; ") }
});
assert.equal(callback.status, 302);
assert.equal(callback.headers.location, "http://localhost:5173/#/cards/admin");
assert.ok(callback.headers["set-cookie"].some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=;")));
});
test("Discord OAuth failures return to the login screen without opening a session", async (t) => {
const env = { NODE_ENV: "test", DISCORD_CLIENT_ID: "discord-client", DISCORD_CLIENT_SECRET: "discord-secret" };
let discordResponse = { ok: false, status: 400 };
const logged = [];
t.mock.method(console, "error", (error) => logged.push(error));
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: false, databasePath: ":memory:", env, fetchImpl: async () => discordResponse });
t.after(() => handler.close());
const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fshop" });
const state = new URL(authorization.headers.location).searchParams.get("state");
const cookie = authorization.headers["set-cookie"].map((value) => value.split(";")[0]).join("; ");
const callback = (query, headers = { cookie }) => call(handler, { path: `/api/cards/auth/callback?${query}`, headers });
for (const [query, headers, reason] of [
[`state=${state}&error=access_denied`, { cookie }, "denied"],
[`state=${state}&code=abc`, {}, "expired"],
[`state=other&code=abc`, { cookie }, "expired"],
[`state=${state}&code=abc`, { cookie }, "failed"],
[`state=${state}`, { cookie }, "failed"]
]) {
const response = await callback(query, headers);
assert.equal(response.status, 302, query);
assert.equal(response.headers.location, `http://localhost:5173/?cardsAuth=${reason}#${reason === "expired" && !headers.cookie ? "/cards" : "/cards/shop"}`, query);
assert.equal(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_session=")), false, query);
assert.ok(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_oauth_state=;")), query);
}
assert.equal(logged.length, 2);
assert.equal(logged.some((error) => String(error.message).includes("discord-secret")), false);
discordResponse = { ok: true, status: 200, json: async () => { throw new Error("invalid body"); } };
assert.equal((await callback(`state=${state}&code=abc`)).headers.location, "http://localhost:5173/?cardsAuth=failed#/cards/shop");
});
test("production refuses to start Sokko TCG without a public origin", () => {
assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, databasePath: ":memory:", env: { NODE_ENV: "production", CARDS_DB_PATH: ":memory:" } }), /CARDS_PUBLIC_ORIGIN/);
});
test("cards API authenticates dev sessions and protects mutations", async (t) => {
const handler = createCardsApiHandler({
projectRoot: resolve("."),
enabled: true,
devAuth: true,
databasePath: ":memory:",
env: { NODE_ENV: "test" },
random: () => 0
});
t.after(() => handler.close());
const config = await call(handler, { path: "/api/cards/config" });
assert.equal(config.status, 200);
assert.equal(config.json.enabled, true);
assert.equal(config.json.catalog.collections.length, 3);
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
assert.equal(login.status, 200);
assert.equal(login.json.player.isAdmin, true);
const sessionCookie = login.headers["set-cookie"].split(";")[0];
const csrfToken = login.json.csrfToken;
const rejected = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } });
assert.equal(rejected.status, 403);
assert.equal(rejected.json.error.code, "CSRF");
const opened = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } });
assert.equal(opened.status, 201);
assert.equal(opened.json.opening.cards.length, 3);
const repeated = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } });
assert.equal(repeated.json.opening.id, opened.json.opening.id);
const state = await call(handler, { path: "/api/cards/state", headers: { cookie: sessionCookie } });
assert.equal(state.status, 200);
assert.equal(state.json.collection.reduce((total, entry) => total + entry.quantity, 0), 3);
const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } });
assert.equal(dashboard.status, 200);
assert.equal(dashboard.json.stats.totalPlayers, 1);
assert.equal(dashboard.json.players[0].totalCards, 3);
assert.equal(dashboard.json.shopSetting.openingPrice, 30);
const recycled = await call(handler, { method: "POST", path: "/api/cards/recycle", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: {} });
assert.ok([200, 409].includes(recycled.status));
const shopUpdate = await call(handler, { method: "PUT", path: "/api/cards/admin/shop", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { stardustValues: dashboard.json.shopSetting.stardustValues, openingPrice: 1 } });
assert.equal(shopUpdate.status, 200);
assert.equal(shopUpdate.json.shopSetting.openingPrice, 1);
const noCsrf = await call(handler, { method: "POST", path: "/api/cards/shop/openings", headers: { cookie: sessionCookie }, body: {} });
assert.equal(noCsrf.status, 403);
assert.equal("discordId" in dashboard.json.players[0], false);
const regularPlayer = handler.service.upsertPlayer({ discordId: "regular-player", displayName: "Regular" });
const regularSession = handler.service.createSession(regularPlayer.id);
const forbidden = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } });
assert.equal(forbidden.status, 403);
assert.equal(forbidden.json.error.code, "ADMIN_REQUIRED");
const forbiddenHistory = await call(handler, { path: "/api/cards/admin/history", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } });
assert.equal(forbiddenHistory.status, 403);
assert.equal((await call(handler, { path: "/api/cards/admin/history?before=abc", headers: { cookie: sessionCookie } })).status, 400);
assert.equal((await call(handler, { path: "/api/cards/admin/history", headers: { cookie: sessionCookie } })).status, 200);
const mythicPath = "/api/cards/admin/catalog/cards/mythic-card-pull/mythic";
const mythicBody = { finishIds: ["spectral-prism-solar", "spectral-prism-cosmic"], opening: { particleShapeId: "snowflakes", particlePaletteId: null } };
const missingCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie }, body: mythicBody });
assert.equal(missingCsrf.status, 403);
assert.equal(missingCsrf.json.error.code, "CSRF");
const regularCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: mythicBody });
assert.equal(regularCsrf.status, 403);
assert.equal(regularCsrf.json.error.code, "ADMIN_REQUIRED");
const updated = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: mythicBody });
assert.equal(updated.status, 200);
assert.ok(updated.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic"));
const collectionOpening = await call(handler, { method: "PUT", path: "/api/cards/admin/catalog/collections/astral-genesis/mythic-opening", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { particleShapeId: null, particlePaletteId: "match-holo" } });
assert.equal(collectionOpening.status, 200);
const refreshedConfig = await call(handler, { path: "/api/cards/config" });
assert.ok(refreshedConfig.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic"));
assert.deepEqual(refreshedConfig.json.catalog.mythicOpeningSettings.map((item) => item.scope).sort(), ["card", "collection"]);
const dropPath = "/api/cards/admin/collections/astral-genesis/drop-rates";
const weights = { common: 60, rare: 25, epic: 10, legendary: 4, mythic: 1 };
const dropForbidden = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { rarityWeights: weights } });
assert.equal(dropForbidden.status, 403);
const dropUpdated = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } });
assert.equal(dropUpdated.status, 200);
assert.deepEqual(dropUpdated.json.catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights, weights);
const dropUnchanged = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } });
assert.equal(dropUnchanged.status, 409);
const closed = await call(handler, { method: "PUT", path: "/api/cards/admin/collections/astral-genesis/state", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { active: false } });
assert.equal(closed.status, 200);
const afterClose = await call(handler, { path: "/api/cards/config" });
assert.equal(afterClose.json.catalog.collections.find((collection) => collection.id === "astral-genesis").active, false);
assert.equal("dropTables" in afterClose.json.catalog, false);
const rechargeForbidden = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { intervalMs: 7_200_000 } });
assert.equal(rechargeForbidden.status, 403);
const rechargeUpdated = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: 7_200_000 } });
assert.equal(rechargeUpdated.status, 200);
assert.equal(rechargeUpdated.json.rechargeSetting.intervalMs, 7_200_000);
const rechargeInvalid = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: "1h" } });
assert.equal(rechargeInvalid.status, 400);
const dashboardAfterRecharge = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } });
assert.equal(dashboardAfterRecharge.json.rechargeSetting.intervalMs, 7_200_000);
});
test("gift pack codes are claimed and opened through the API", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
t.after(() => handler.close());
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
const headers = { cookie: login.headers["set-cookie"].split(";")[0], "x-csrf-token": login.json.csrfToken };
const created = await call(handler, { method: "POST", path: "/api/cards/admin/campaigns", headers, body: { name: "Live", reward: { items: [{ type: "pack", collectionId: "astral-genesis", guarantee: { type: "rarity", rarity: "epic", count: 1 } }] }, code: "API-LIVE", maxClaims: null, expiresAt: Date.now() + 60_000 } });
assert.equal(created.status, 201);
const detail = await call(handler, { path: `/api/cards/admin/campaigns/${created.json.campaign.id}`, headers });
assert.equal(detail.json.campaign.code, "API-LIVE");
const claimed = await call(handler, { method: "POST", path: "/api/cards/rewards/claim", headers, body: { code: "api-live" } });
assert.equal(claimed.status, 200);
assert.equal(claimed.json.state.giftPacks.length, 1);
const opened = await call(handler, { method: "POST", path: `/api/cards/gift-packs/${claimed.json.state.giftPacks[0].id}/open`, headers: { ...headers, "idempotency-key": "gift" } });
assert.equal(opened.status, 201);
assert.equal(opened.json.opening.cards.length, 3);
const extended = await call(handler, { method: "PUT", path: `/api/cards/admin/campaigns/${created.json.campaign.id}/expiry`, headers, body: { expiresAt: Date.now() + 120_000 } });
assert.equal(extended.status, 200);
});

934
tests/nebula-cards.test.mjs Normal file
View file

@ -0,0 +1,934 @@
// Rôle : vérifie les règles, la persistance et les mutations protégées de Sokko TCG.
import assert from "node:assert/strict";
import { access, readdir, readFile } from "node:fs/promises";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { assertVersionedCatalogScope, buildPublishedCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js";
import { planRecycling } from "../services/cards/stardust.js";
import { resolveMythicOpeningStyle, resolveOpeningEffect } from "../website/src/features/cards/openingEffects.js";
import { summarizeReward } from "../website/src/features/cards/rewardText.js";
import { CardsDatabase } from "../services/cards/database.js";
import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/game-rules.js";
import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js";
import { visibleCollections } from "../website/src/features/cards/collectionState.js";
import { backupCardsDatabase, restoreCardsDatabase, verifyCardsDatabase } from "../services/cards/backup.js";
// Catalogue versionné (finitions générées, sans variation mythique) et catalogue publié avec une variation de test.
const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"));
const baseCatalog = prepareVersionedCatalog(rawCatalog);
const TEST_MYTHIC_VARIATIONS = [{ editionId: "mythic-card-pull-spectral-prism-solar", cardId: "mythic-card-pull", finishId: "spectral-prism-solar", status: "active" }];
const catalog = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS, collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES });
test("Sokko TCG uses design system dropdowns instead of native selects", async () => {
const entries = await readdir("website/src/features/cards", { recursive: true });
const sources = entries.filter((entry) => entry.endsWith(".jsx"));
assert.ok(sources.length > 10);
for (const source of sources) {
assert.doesNotMatch(await readFile(join("website/src/features/cards", source), "utf8"), /<select\b/, `${source} must use SelectDropdown or CardsFilterMenu`);
assert.doesNotMatch(await readFile(join("website/src/features/cards", source), "utf8"), /type="datetime-local"/, `${source} must use ExpiryField`);
}
});
test("closed event collections stay hidden until the player owns one of their cards", () => {
const visibleCatalog = {
collections: [{ id: "open-event", packCategory: "event", active: true }, { id: "closed-event", packCategory: "event", active: false }, { id: "closed-permanent", packCategory: "permanent", active: false }],
cards: [{ id: "event-card", collectionId: "closed-event" }]
};
const ids = (owned) => visibleCollections(visibleCatalog, new Set(owned)).map((collection) => collection.id);
assert.deepEqual(ids([]), ["open-event", "closed-permanent"]);
assert.deepEqual(ids(["event-card"]), ["open-event", "closed-event", "closed-permanent"]);
});
test("the shop pack mixes active collections with its featured cards at the configured share", () => {
const shopCatalog = buildPublishedCatalog(baseCatalog, {
variations: TEST_MYTHIC_VARIATIONS,
collectionStates: [...INITIAL_COLLECTION_STATES, { collectionId: "stardust", active: true }],
dropRates: [...INITIAL_DROP_RATES, { collectionId: "stardust", rarityWeights: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 } }]
});
const sourceOf = (editionId) => shopCatalog.cards.find((card) => card.id === shopCatalog.editions.find((edition) => edition.id === editionId).cardId).collectionId;
const rarityOf = (editionId) => shopCatalog.editions.find((edition) => edition.id === editionId).rarity;
// Générateur déterministe : le test reste stable d'une exécution à l'autre.
let seed = 42;
const random = (max) => {
seed = (seed * 1664525 + 1013904223) % 4294967296;
return Math.floor(seed / 4294967296 * max);
};
const draws = Array.from({ length: 40000 }, () => drawShopPack(shopCatalog, "stardust", random, 50)).flat();
const legendaries = draws.filter((id) => rarityOf(id) === "legendary");
const dragons = legendaries.filter((id) => id === "stardust-dragon-standard").length;
assert.ok(Math.abs(dragons / legendaries.length - 0.5) < 0.03, `part observée : ${dragons / legendaries.length}`);
assert.ok(Math.abs(legendaries.length / draws.length - 0.03) < 0.003);
assert.deepEqual(new Set(draws.map(sourceOf)), new Set(["primordial-nebula", "astral-genesis", "stardust"]));
// Seules les légendaires et mythiques de la collection sont mises en avant ; une part nulle ne tire jamais le Dragon.
assert.ok(draws.filter((id) => sourceOf(id) === "stardust").every((id) => ["legendary", "mythic"].includes(rarityOf(id))));
assert.ok(!Array.from({ length: 3000 }, () => drawShopPack(shopCatalog, "stardust", random, 0)).flat().includes("stardust-dragon-standard"));
// Le Dragon ne sort d'aucun autre paquet, et une collection fermée quitte le paquet de la boutique.
assert.ok(!Array.from({ length: 3000 }, () => [...drawPack(shopCatalog, "primordial-nebula", random), ...drawPack(shopCatalog, "astral-genesis", random)]).flat().includes("stardust-dragon-standard"));
const closed = structuredClone(shopCatalog);
closed.collections.find((item) => item.id === "astral-genesis").active = false;
assert.ok(!Array.from({ length: 3000 }, () => drawShopPack(closed, "stardust", random, 50)).flat().some((id) => sourceOf(id) === "astral-genesis"));
});
test("the shop pack is bought with stardust, opens at once and cannot be obtained elsewhere", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-shop-pack-"));
const database = new CardsDatabase(join(directory, "cards.sqlite"));
t.after(async () => {
database.close();
await rm(directory, { recursive: true, force: true });
});
const service = new CardsService({ database, catalog: baseCatalog, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "buyer", displayName: "Acheteur" });
const giveStardust = (amount) => database.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(amount, player.id);
assert.throws(() => service.buyShopPack(player.id, "broke"), /Pas assez/);
assert.throws(() => service.openPack(player.id, "stardust", "direct"), /boutique/);
assert.throws(() => service.createCampaign(admin.id, { name: "Code", code: "SHOP-PACK", reward: { items: [{ type: "pack", collectionId: "stardust" }] } }), /boutique/);
giveStardust(130);
const balanceBefore = service.getState(player.id).recharge.openingsBalance;
const bought = service.buyShopPack(player.id, "buy-1");
assert.equal(bought.opening.collectionId, "stardust");
assert.equal(bought.opening.cards.length, 3);
assert.equal(bought.state.wallet.stardust, 70);
assert.equal(bought.state.recharge.openingsBalance, balanceBefore);
// Rejouer la même requête ne fait pas payer deux fois ; une ouverture en attente bloque un nouvel achat, sans rien débiter.
assert.equal(service.buyShopPack(player.id, "buy-1").opening.id, bought.opening.id);
assert.throws(() => service.buyShopPack(player.id, "buy-2"), /ouverture en cours/);
assert.equal(service.getState(player.id).wallet.stardust, 70);
service.completeOpening(player.id, bought.opening.id);
// Prix et part se règlent dans l'administration ; une collection fermée n'est plus en vente.
const { stardustValues, openingPrice } = service.shopSetting;
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues, openingPrice, shopPackShare: 101 }), /Part/);
assert.equal(service.updateShopSetting(admin.id, { stardustValues, openingPrice, shopPackPrice: 70, shopPackShare: 25 }).shopSetting.shopPackShare, 25);
assert.equal(service.getState(player.id).shop.shopPackPrice, 70);
service.setCollectionActive(admin.id, "stardust", false);
assert.throws(() => service.buyShopPack(player.id, "buy-3"), /pas disponible/);
assert.equal(service.getState(player.id).wallet.stardust, 70);
});
test("full-art mythics need a full image and declare one per legendary card", async (t) => {
const legendaryIds = baseCatalog.editions.filter((edition) => edition.rarity === "legendary").map((edition) => edition.cardId);
for (const cardId of legendaryIds) {
const card = baseCatalog.cards.find((item) => item.id === cardId);
assert.ok(card.fullImage, `${cardId} needs a full image`);
await access(`website/public${card.image}`);
await access(`website/public${card.fullImage}`);
}
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-full-art-"));
const database = new CardsDatabase(join(directory, "cards.sqlite"));
t.after(async () => {
database.close();
await rm(directory, { recursive: true, force: true });
});
const withoutImage = structuredClone(baseCatalog);
delete withoutImage.cards.find((card) => card.id === "aurora-wolf").fullImage;
const service = new CardsService({ database, catalog: withoutImage, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
assert.throws(() => service.setCardMythicConfig(admin.id, "aurora-wolf", { finishIds: ["full-art-spectral-prism-aurora"] }), /illustration pleine/);
service.setCardMythicConfig(admin.id, "starvoid-dragon", { finishIds: ["full-art-spectral-prism-solar"] });
assert.ok(service.catalog.editions.some((edition) => edition.id === "starvoid-dragon-full-art-spectral-prism-solar" && edition.rarity === "mythic"));
const finish = service.catalog.finishes.find((item) => item.id === "full-art-spectral-prism-solar");
assert.deepEqual([finish.formatId, finish.effectPresetId, finish.paletteId], ["full-art", "spectral-prism", "solar"]);
});
test("dev perks pin the dev account resources without touching other players", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-dev-perks-"));
const database = new CardsDatabase(join(directory, "cards.sqlite"));
t.after(async () => {
database.close();
await rm(directory, { recursive: true, force: true });
});
let now = Date.UTC(2026, 0, 1);
const hour = 60 * 60 * 1000;
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0, devPerks: true });
const dev = service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "Dev", isAdmin: true });
const other = service.upsertPlayer({ discordId: "player", displayName: "Joueur" });
const initial = service.getState(dev.id);
assert.equal(initial.wallet.stardust, 1000);
assert.equal(initial.recharge.openingsBalance, 4);
assert.equal(service.getState(other.id).wallet.stardust, 0);
// Un nouveau compte reçoit 3 ouvertures, et le journal garde la quantité offerte.
const otherState = service.getState(other.id);
assert.equal(otherState.recharge.openingsBalance, 3);
assert.deepEqual(otherState.history.find((entry) => entry.type === "welcome_opening").details, { amount: 3 });
// Dépenser ne réduit ni la poussière ni la réserve affichées.
const afterPurchase = service.buyOpening(dev.id);
assert.equal(afterPurchase.wallet.stardust, 1000);
assert.equal(afterPurchase.wallet.purchasedOpenings, 1);
const opened = service.openPack(dev.id, "primordial-nebula", "dev-open");
assert.equal(opened.state.recharge.openingsBalance, 4);
service.completeOpening(dev.id, opened.opening.id);
// Le minuteur continue de tourner et repart à chaque échéance, sans atteindre 5/5.
const nextOpeningAt = service.getState(dev.id).recharge.nextOpeningAt;
assert.ok(nextOpeningAt > now);
now = nextOpeningAt + 6 * hour;
const later = service.getState(dev.id).recharge;
assert.equal(later.openingsBalance, 4);
assert.ok(later.nextOpeningAt > now);
// Sans l'option, le même compte suit les règles normales.
const regular = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
regular.buyOpening(dev.id);
assert.equal(regular.getState(dev.id).wallet.stardust, 1000 - regular.shopSetting.openingPrice);
now += 6 * hour;
assert.equal(regular.getState(dev.id).recharge.openingsBalance, 5);
});
test("card catalog keeps mythic editions attached to legendary cards", async () => {
const nebulaCards = catalog.cards.filter((card) => card.collectionId === "primordial-nebula");
const primordialCollection = catalog.collections.find((collection) => collection.id === "primordial-nebula");
assert.equal(primordialCollection.name, "La Nébuleuse Originelle");
assert.equal(primordialCollection.systemName, "Primordial Nebula");
assert.equal(nebulaCards.length, 82);
assert.deepEqual(
Object.fromEntries(["common", "rare", "epic", "legendary"].map((rarity) => [rarity, catalog.editions.filter((edition) => !edition.promotional && edition.rarity === rarity && nebulaCards.some((card) => card.id === edition.cardId)).length])),
{ common: 36, rare: 20, epic: 20, legendary: 6 }
);
await Promise.all(nebulaCards.map((card) => access(`website/public${card.image}`)));
const mythics = catalog.editions.filter((edition) => edition.rarity === "mythic" && !edition.promotional);
assert.ok(mythics.length >= 1);
for (const mythic of mythics) {
const parent = catalog.editions.find((edition) => edition.id === mythic.legendaryEditionId);
assert.equal(parent.rarity, "legendary");
assert.equal(parent.cardId, mythic.cardId);
}
assert.equal(drawPack(catalog, "primordial-nebula", () => 0).length, 3);
const launchCollection = catalog.collections.find((collection) => collection.id === "astral-genesis");
assert.equal(launchCollection.packCategory, "event");
assert.equal(launchCollection.name, "Genèse Astrale");
assert.equal(launchCollection.systemName, "Astral Genesis");
const astralCards = catalog.cards.filter((card) => card.collectionId === launchCollection.id);
assert.equal(astralCards.length, 10);
assert.deepEqual(
Object.fromEntries(["common", "rare", "epic", "legendary"].map((rarity) => [rarity, catalog.editions.filter((edition) => edition.rarity === rarity && astralCards.some((card) => card.id === edition.cardId)).length])),
{ common: 4, rare: 3, epic: 2, legendary: 1 }
);
assert.deepEqual(drawPack(catalog, launchCollection.id, () => 0), Array(3).fill("astral-booster-standard"));
assert.deepEqual(drawPack(catalog, launchCollection.id, (maximum) => maximum - 1), Array(3).fill("mythic-card-pull-spectral-prism-solar"));
await Promise.all(astralCards.map((card) => access(`website/public${card.image}`)));
assert.deepEqual(new Set(catalog.collections.map((collection) => collection.packCategory)), new Set(["permanent", "event", "shop"]));
assert.ok(catalog.collections.every((collection) => collection.systemName && /^#[0-9a-f]{6}$/i.test(collection.back.primary) && collection.back.symbol && /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/.test(collection.back.image)));
});
test("finishes are generated: standard plus one per holographic effect and seven-color palette", () => {
assert.equal("finishes" in rawCatalog, false);
const preset = catalog.effectPresets.find((effect) => effect.id === "spectral-prism");
assert.equal(preset.kind, "holographic");
assert.deepEqual(catalog.finishes.map((finish) => finish.id), ["standard", ...["", "full-art-"].flatMap((format) => ["spectral-prism", "diffraction-sheen"].flatMap((effect) => ["rainbow", "solar", "dusk", "crimson", "nature", "aurora", "winter", "cosmic", "darkness"].map((palette) => `${format}${effect}-${palette}`)))]);
assert.deepEqual(catalog.finishes[0], { id: "standard", label: "Standard", effectPresetId: null, paletteId: null, formatId: "standard" });
assert.ok(catalog.finishes.every((finish) => !("particlePresetId" in finish)));
assert.ok(catalog.effectPalettes.every((palette) => palette.colors.length === 7 && new Set(palette.colors).size === 7));
assert.deepEqual(catalog.effectPalettes.find((palette) => palette.id === "solar").colors, ["#fff4c2", "#ffe14d", "#ffc400", "#ff9d00", "#ff6a00", "#ffab1a", "#ffd84d"]);
const solarEdition = catalog.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar");
assert.equal(solarEdition.rarity, "mythic");
assert.equal(solarEdition.legendaryEditionId, "mythic-card-pull-standard");
const withNewEffect = structuredClone(rawCatalog);
withNewEffect.effectPresets.push({ id: "effect-x", kind: "holographic", label: "Effet X" });
withNewEffect.effectPalettes.push({ id: "ember", label: "Braise", colors: ["#7f1d1d", "#b91c1c", "#ef4444", "#f97316", "#fb923c", "#fdba74", "#fff7ed"], highlight: "#ffffff" });
const generated = prepareVersionedCatalog(withNewEffect).finishes;
assert.equal(generated.length, 1 + 2 * 3 * 10);
assert.deepEqual(generated.find((finish) => finish.id === "effect-x-ember"), { id: "effect-x-ember", label: "Effet X — Braise", effectPresetId: "effect-x", paletteId: "ember", formatId: "standard" });
const invalidPalette = structuredClone(rawCatalog);
invalidPalette.effectPalettes[0].colors = invalidPalette.effectPalettes[0].colors.slice(0, 6);
assert.throws(() => prepareVersionedCatalog(invalidPalette), /Invalid effect palette/);
const declaredFinishes = { ...structuredClone(rawCatalog), finishes: [] };
assert.throws(() => assertVersionedCatalogScope(declaredFinishes), /generated/);
const invalidFinish = withGeneratedFinishes(structuredClone(rawCatalog));
invalidFinish.finishes.find((finish) => finish.id === "spectral-prism-aurora").paletteId = "unknown-palette";
assert.throws(() => validateCardsCatalog(invalidFinish), /known palette/);
});
test("opening effects compose rarity auras with a single default mythic opening", () => {
const defaultEffects = catalog.openingEffects;
const customEffects = defaultEffects.filter((effect) => effect.rarity === "mythic");
assert.deepEqual(defaultEffects.map((effect) => effect.rarity), ["rare", "epic", "legendary", "mythic"]);
const collectionScoped = structuredClone(rawCatalog);
collectionScoped.openingEffects[3].collectionId = "astral-genesis";
assert.throws(() => prepareVersionedCatalog(collectionScoped), /Invalid opening effect/);
assert.equal(catalog.openingEffects.some((effect) => effect.rarity === "common"), false);
assert.deepEqual(defaultEffects.find((effect) => effect.rarity === "rare").auraColors, ["#3b82f6"]);
assert.deepEqual(defaultEffects.find((effect) => effect.rarity === "epic").auraColors, ["#d946ef"]);
assert.deepEqual(customEffects[0].auraColors, ["#67e8f9", "#8b5cf6", "#d946ef", "#f6c453"]);
assert.equal(defaultEffects.find((effect) => effect.rarity === "rare").particlePresetId, null);
const epicParticles = catalog.particlePresets.find((preset) => preset.id === defaultEffects.find((effect) => effect.rarity === "epic").particlePresetId);
const legendaryParticles = catalog.particlePresets.find((preset) => preset.id === defaultEffects.find((effect) => effect.rarity === "legendary").particlePresetId);
const mythicParticles = catalog.particlePresets.find((preset) => preset.id === customEffects[0].particlePresetId);
assert.deepEqual(catalog.particlePresets.map((preset) => preset.id), ["epic-opening-sparks", "legendary-opening-burst", "mythic-rainbow-sparks"]);
assert.equal(epicParticles.count, 18);
assert.equal(legendaryParticles.count, 32);
assert.equal(mythicParticles.count, 48);
assert.equal(mythicParticles.shapeId, "sparks");
assert.equal(mythicParticles.paletteId, "rainbow");
for (const mythicEffect of customEffects) {
assert.equal(mythicEffect.auraDurationMs, defaultEffects.find((effect) => effect.rarity === "legendary").auraDurationMs);
assert.equal(mythicEffect.particleDurationMs, defaultEffects.find((effect) => effect.rarity === "legendary").particleDurationMs);
}
assert.deepEqual(catalog.particleShapes.map((shape) => [shape.id, shape.kind]), [["sparks", "sparks"], ["snowflakes", "snowflakes"]]);
assert.equal(catalog.particlePalettes.find((palette) => palette.id === "rainbow").colors.length, 7);
const duplicateRarity = structuredClone(catalog);
duplicateRarity.openingEffects.push({ ...duplicateRarity.openingEffects[0], id: "another-rare-opening" });
assert.throws(() => validateCardsCatalog(duplicateRarity), /Duplicate opening effect for rarity rare/);
const unknownRarity = structuredClone(catalog);
unknownRarity.openingEffects[0].rarity = "unknown";
assert.throws(() => validateCardsCatalog(unknownRarity), /Invalid opening effect/);
const invalidCommon = structuredClone(catalog);
invalidCommon.openingEffects[0].rarity = "common";
assert.throws(() => validateCardsCatalog(invalidCommon), /Invalid opening effect/);
const unknownParticles = structuredClone(catalog);
unknownParticles.openingEffects[1].particlePresetId = "unknown-particles";
assert.throws(() => validateCardsCatalog(unknownParticles), /known particle preset/);
const unknownShape = structuredClone(catalog);
unknownShape.particlePresets[0].shapeId = "unknown-shape";
assert.throws(() => validateCardsCatalog(unknownShape), /Invalid particle preset/);
const unknownShapeKind = structuredClone(catalog);
unknownShapeKind.particleShapes[1].kind = "bubbles";
assert.throws(() => validateCardsCatalog(unknownShapeKind), /Invalid particle shape snowflakes/);
const unknownPalette = structuredClone(catalog);
unknownPalette.particlePresets[0].paletteId = "unknown-palette";
assert.throws(() => validateCardsCatalog(unknownPalette), /Invalid particle preset/);
const missingDefaultMythic = structuredClone(catalog);
missingDefaultMythic.openingEffects = missingDefaultMythic.openingEffects.filter((effect) => effect.id !== "mythic-default-opening");
assert.throws(() => validateCardsCatalog(missingDefaultMythic), /opening effect for rarity mythic/);
const defaultMythic = defaultEffects.find((effect) => effect.rarity === "mythic");
assert.equal(defaultMythic.particlePresetId, "mythic-rainbow-sparks");
});
test("recharge honors the cap and keeps partial elapsed time", () => {
const setting = { intervalMs: 60_000, maxOpenings: 5 };
assert.deepEqual(calculateRecharge({ openingsBalance: 1, rechargeAnchor: 10_000 }, 139_999, setting), {
openingsBalance: 3,
rechargeAnchor: 130_000,
nextOpeningAt: 190_000
});
assert.deepEqual(calculateRecharge({ openingsBalance: 4, rechargeAnchor: 10_000 }, 130_000, setting), {
openingsBalance: 5,
rechargeAnchor: null,
nextOpeningAt: null
});
});
test("recharge delay is a single admin setting applied immediately", () => {
let now = 1_800_000_000_000;
const hour = 60 * 60 * 1000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
assert.deepEqual({ intervalMs: service.rechargeSetting.intervalMs, maxOpenings: service.rechargeSetting.maxOpenings }, INITIAL_RECHARGE_SETTING);
const admin = service.upsertPlayer({ discordId: "recharge-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "recharge-player", displayName: "Player" });
const opened = service.openPack(player.id, "primordial-nebula", "recharge-pack");
service.completeOpening(player.id, opened.opening.id);
assert.equal(service.getState(player.id).recharge.nextOpeningAt, now + hour);
assert.throws(() => service.updateRechargeSetting(player.id, { intervalMs: hour }), /administrateur/);
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 30_000 }), /Délai invalide/);
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 90_500 }), /Délai invalide/);
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 8 * 24 * hour }), /Délai invalide/);
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: hour }), /déjà en vigueur/);
// Trente minutes écoulées, puis passage à 20 min : le nouveau délai s'applique aussi au temps déjà écoulé.
const minute = 60_000;
now += 30 * minute;
const updated = service.updateRechargeSetting(admin.id, { intervalMs: 20 * minute });
assert.deepEqual(updated.rechargeSetting, { intervalMs: 20 * minute, maxOpenings: 5, updatedAt: now });
const recharge = service.getState(player.id).recharge;
assert.equal(recharge.openingsBalance, 3);
assert.equal(recharge.nextOpeningAt, now + 10 * minute);
assert.equal(service.getAdminDashboard(admin.id).rechargeSetting.intervalMs, 20 * minute);
assert.equal(new CardsService({ database, catalog: baseCatalog, now: () => now }).rechargeSetting.intervalMs, 20 * minute);
database.close();
});
test("player history hides administration events without losing them", () => {
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
service.updateRechargeSetting(admin.id, { intervalMs: 20 * 60_000 });
const adminEvents = ["recharge_updated", "shop_updated", "catalog_card_mythic_updated", "collection_opened", "collection_closed", "drop_rates_updated", "catalog_collection_opening_updated", "campaign_created", "campaign_revoked", "campaign_extended"];
// Plus de 100 actions d'administration ne doivent pas non plus évincer les entrées du joueur.
for (let index = 0; index < 101; index += 1) service.audit(admin.id, adminEvents[index % adminEvents.length], "entity", {});
assert.deepEqual(service.getState(admin.id).history.map((entry) => entry.type), ["welcome_opening"]);
assert.equal(database.db.prepare("SELECT COUNT(*) AS total FROM audit_log WHERE player_id = ? AND event_type = 'campaign_revoked'").get(admin.id).total, 10);
database.close();
});
test("admin history lists administration events by page, without player events", () => {
const database = new CardsDatabase(":memory:");
let now = 1_800_000_000_000;
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "admin-discord-id", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "player-discord-id", displayName: "Joueur" });
assert.deepEqual(service.getAdminHistory(admin.id), { entries: [], nextBefore: null });
assert.throws(() => service.getAdminHistory(player.id), /administrateur/);
service.updateRechargeSetting(admin.id, { intervalMs: 20 * 60_000 });
service.audit(player.id, "pack_opened", "opening", {});
for (let index = 0; index < 50; index += 1) {
now += 1;
service.audit(admin.id, "future_admin_action", `entity-${index}`, {});
}
const first = service.getAdminHistory(admin.id);
assert.equal(first.entries.length, 50);
assert.equal(first.entries[0].entityId, "entity-49");
assert.equal(first.entries[0].adminName, "Admin");
assert.equal(first.entries.some((entry) => JSON.stringify(entry).includes("admin-discord-id")), false);
assert.ok(first.nextBefore);
const second = service.getAdminHistory(admin.id, { before: first.nextBefore });
assert.deepEqual(second.entries.map((entry) => entry.type), ["recharge_updated"]);
assert.deepEqual(second.entries[0].details, { previousIntervalMs: INITIAL_RECHARGE_SETTING.intervalMs, intervalMs: 20 * 60_000 });
assert.equal(second.nextBefore, null);
database.close();
});
test("opening is idempotent and server inventory owns the result", () => {
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const player = service.upsertPlayer({ discordId: "one", displayName: "One" });
const first = service.openPack(player.id, "primordial-nebula", "request-one");
assert.equal(first.opening.cards.length, 3);
assert.equal(first.state.recharge.openingsBalance, 2);
const repeated = service.openPack(player.id, "primordial-nebula", "request-one");
assert.equal(repeated.opening.id, first.opening.id);
assert.deepEqual(repeated.state.collection.map((entry) => entry.quantity), [3]);
assert.equal(repeated.state.stats.openingsCount, 1);
assert.equal(repeated.state.rarestPull.id, first.opening.cards[2].id);
assert.equal(repeated.state.rarestPull.openedAt, now);
assert.equal(repeated.state.rarestPull.edition.rarity, "common");
service.completeOpening(player.id, first.opening.id);
now += INITIAL_RECHARGE_SETTING.intervalMs;
assert.equal(service.getState(player.id).recharge.openingsBalance, 3);
database.close();
});
test("admin dashboard aggregates current player activity without Discord identifiers", () => {
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "dashboard-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "dashboard-player", displayName: "Player" });
service.openPack(player.id, "primordial-nebula", "dashboard-pack");
now += INITIAL_RECHARGE_SETTING.intervalMs;
const dashboard = service.getAdminDashboard(admin.id);
const playerRow = dashboard.players.find((item) => item.id === player.id);
assert.deepEqual(dashboard.stats, { totalPlayers: 2, activePlayers7d: 1 });
assert.equal(playerRow.transfersCount, 0);
assert.equal(playerRow.stardust, 0);
assert.equal(playerRow.purchasedOpenings, 0);
assert.equal(Object.values(playerRow.rarityCounts).reduce((total, count) => total + count, 0), 3);
assert.equal(playerRow.giftPacks, 0);
assert.equal(playerRow.openingsBalance, 3);
assert.equal(playerRow.totalCards, 3);
assert.equal(playerRow.lastOpeningAt, 1_800_000_000_000);
assert.equal("discordId" in playerRow, false);
assert.throws(() => service.getAdminDashboard(player.id), /administrateur/);
database.close();
});
test("recycling plan only takes duplicates that are not reserved by a transfer", () => {
const options = { rarityOf: (id) => (id.startsWith("rare") ? "rare" : "common"), stardustValues: { common: 1, rare: 3 } };
const collection = [
{ editionId: "common-a", quantity: 3, reserved: 0 },
{ editionId: "rare-b", quantity: 3, reserved: 1 },
{ editionId: "common-single", quantity: 1, reserved: 0 }
];
const all = planRecycling(collection, options);
assert.deepEqual(all.items, [{ editionId: "common-a", count: 2, stardust: 2 }, { editionId: "rare-b", count: 1, stardust: 3 }]);
assert.deepEqual([all.count, all.stardust], [3, 5]);
assert.deepEqual(planRecycling(collection, { ...options, editionId: "common-a" }).items, [{ editionId: "common-a", count: 1, stardust: 1 }]);
assert.equal(planRecycling(collection, { ...options, editionId: "common-single" }).count, 0);
});
test("duplicates become stardust that buys openings kept apart from the recharge reserve", () => {
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "shop-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "shop-player", displayName: "Player" });
const opened = service.openPack(player.id, "primordial-nebula", "shop-pack");
assert.throws(() => service.recycleDuplicates(player.id), /ouverture en cours/);
service.completeOpening(player.id, opened.opening.id);
const [editionId] = new Set(opened.opening.cards.map((card) => card.editionId));
const rarity = service.index.editions.get(editionId).rarity;
const value = INITIAL_SHOP_SETTING.stardustValues[rarity];
const before = service.getState(player.id);
assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0 });
assert.deepEqual(before.shop, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: INITIAL_SHOP_SETTING.openingPrice, shopPackPrice: 60, shopPackShare: 50 });
assert.deepEqual(before.recycling, { count: 2, stardust: 2 * value });
// Une favorite garde son exemplaire : ses doublons se recyclent comme les autres.
service.setFavorite(player.id, editionId, true);
const one = service.recycleDuplicates(player.id, { editionId });
assert.deepEqual(one.recycled, { count: 1, stardust: value });
assert.equal(one.state.collection[0].quantity, 2);
const all = service.recycleDuplicates(player.id);
assert.deepEqual(all.recycled, { count: 1, stardust: value });
assert.equal(all.state.collection[0].quantity, 1);
assert.equal(all.state.wallet.stardust, 2 * value);
assert.throws(() => service.recycleDuplicates(player.id), /Aucun doublon/);
// L'ouverture garde sa référence à la carte tirée et reste lisible après le recyclage.
const history = service.openingById(opened.opening.id, player.id);
assert.deepEqual(history.cards.map((card) => card.card?.name), opened.opening.cards.map((card) => card.card.name));
assert.equal(service.getState(player.id).rarestPull.editionId, editionId);
service.updateShopSetting(admin.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 2 * value });
assert.throws(() => service.updateShopSetting(player.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 1 }), /administrateur/);
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues: { ...INITIAL_SHOP_SETTING.stardustValues, rare: -1 }, openingPrice: 1 }), /rare/);
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 0 }), /Prix/);
// Vide les ouvertures de bienvenue restantes sans changer la collection vérifiée plus bas.
database.db.prepare("UPDATE players SET openings_balance = 0 WHERE id = ?").run(player.id);
const bought = service.buyOpening(player.id);
assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1 });
assert.throws(() => service.buyOpening(player.id), /Pas assez/);
// La réserve est vide : seule l'ouverture achetée permet d'ouvrir, sans toucher à la réserve.
assert.equal(bought.recharge.openingsBalance, 0);
assert.throws(() => service.openPack(player.id, "primordial-nebula", "reserve-pack"), /ouverture/i);
const purchased = service.openPack(player.id, "primordial-nebula", "purchased-pack", { purchased: true });
assert.equal(purchased.state.wallet.purchasedOpenings, 0);
assert.equal(purchased.state.recharge.openingsBalance, 0);
service.completeOpening(player.id, purchased.opening.id);
assert.throws(() => service.openPack(player.id, "primordial-nebula", "purchased-again", { purchased: true }), /aucune ouverture achetée/);
const row = service.getAdminDashboard(admin.id).players.find((item) => item.id === player.id);
assert.equal(row.stardust, 0);
assert.equal(row.totalCards, 4);
database.close();
});
test("trades and gifts move duplicates only and campaign claims add cards", () => {
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const quantity = (playerId, editionId) => service.getState(playerId).collection.find((entry) => entry.editionId === editionId)?.quantity ?? 0;
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "player", displayName: "Player" });
const adminOpening = service.openPack(admin.id, "primordial-nebula", "admin-pack").opening;
service.completeOpening(admin.id, adminOpening.id);
// Le hasard fixe tire trois fois la même carte : un exemplaire et deux doublons.
const drawn = adminOpening.cards[0].editionId;
assert.deepEqual(adminOpening.cards.map((card) => [card.isNewEdition, card.quantityBefore]), [[true, 0], [false, 1], [false, 2]]);
assert.equal(quantity(admin.id, drawn), 3);
const campaign = service.createCampaign(admin.id, {
name: "Premiers explorateurs",
reward: { items: [{ type: "card", editionId: "aurora-wolf-standard" }] },
code: "explo",
maxClaims: 1,
expiresAt: now + 60_000
});
assert.equal(campaign.campaign.code, "EXPLO");
const claimed = service.claimCampaign(player.id, "explo");
assert.deepEqual(claimed.reward, { items: [{ type: "card", editionId: "aurora-wolf-standard", quantity: 1 }] });
assert.equal(quantity(player.id, "aurora-wolf-standard"), 1);
assert.throws(() => service.claimCampaign(player.id, "EXPLO"), /déjà reçu/);
assert.throws(() => service.claimCampaign(admin.id, "EXPLO"), /nombre maximal/);
// Un exemplaire unique ne part jamais, ni en don ni dans un échange.
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: admin.id, editionId: "aurora-wolf-standard" }), /doublons/);
assert.throws(() => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: drawn, requestedEditionId: "aurora-wolf-standard" }), /plus ce doublon/);
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: admin.id, editionId: drawn }), /vous envoyer/);
assert.throws(() => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: drawn, requestedEditionId: drawn }), /différentes/);
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: "inconnu", editionId: drawn }), /introuvable/);
// Seuls l'identité publique et les doublons disponibles des autres joueurs sont exposés.
const traders = service.listTraders(player.id).traders;
assert.deepEqual(traders.map((trader) => trader.id).includes(player.id), false);
const adminTrader = traders.find((trader) => trader.id === admin.id);
assert.deepEqual(Object.keys(adminTrader).sort(), ["avatarUrl", "displayName", "duplicates", "id"]);
assert.deepEqual(adminTrader.duplicates.find((entry) => entry.editionId === drawn), { editionId: drawn, spare: 2 });
// Don : le doublon arrive immédiatement, le donneur garde ses autres exemplaires et le journal cite la carte.
const gift = service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn });
assert.equal(gift.transfer.status, "completed");
assert.equal(gift.state.collection.find((entry) => entry.editionId === drawn).spare, 1);
assert.equal(quantity(player.id, drawn), 1);
assert.equal(service.getState(player.id).transfers.find((item) => item.id === gift.transfer.id).direction, "received");
assert.equal(service.getState(player.id).history.find((item) => item.type === "gift_completed").details.received, drawn);
assert.equal(service.getAdminDashboard(admin.id).players.find((item) => item.id === player.id).transfersCount, 1);
service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn });
assert.equal(quantity(player.id, drawn), 2);
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn }), /doublons/);
// Échange refusé, annulé puis accepté : le doublon proposé est réservé, puis libéré ou échangé.
const adminCard = adminOpening.cards.map((card) => card.edition.id).find((id) => id !== drawn) || drawn;
for (let copies = 0; copies < 3; copies += 1) service.addCard(admin.id, "aurora-wolf-standard");
const propose = () => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: "aurora-wolf-standard", requestedEditionId: drawn });
const spareOf = (playerId, id) => service.getState(playerId).collection.find((entry) => entry.editionId === id)?.spare ?? 0;
const reservedBefore = spareOf(admin.id, "aurora-wolf-standard");
const declined = propose();
assert.equal(declined.transfer.status, "open");
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore - 1);
assert.throws(() => service.acceptTransfer(admin.id, declined.transfer.id), /plus disponible/);
assert.throws(() => service.cancelTransfer(player.id, declined.transfer.id), /plus disponible/);
const afterDecline = service.declineTransfer(player.id, declined.transfer.id);
assert.equal(afterDecline.transfers.find((item) => item.id === declined.transfer.id).declined, true);
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore);
const cancelled = propose();
service.cancelTransfer(admin.id, cancelled.transfer.id);
assert.throws(() => service.acceptTransfer(player.id, cancelled.transfer.id), /plus disponible/);
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore);
const accepted = propose();
const playerWolves = quantity(player.id, "aurora-wolf-standard");
const adminDrawn = quantity(admin.id, drawn);
const afterAccept = service.acceptTransfer(player.id, accepted.transfer.id);
assert.equal(afterAccept.transfers.find((item) => item.id === accepted.transfer.id).status, "completed");
assert.equal(quantity(player.id, "aurora-wolf-standard"), playerWolves + 1);
assert.equal(quantity(player.id, drawn), 1);
assert.equal(quantity(admin.id, drawn), adminDrawn + 1);
assert.ok(adminCard);
// Le doublon demandé peut partir avant la réponse : l'acceptation est alors refusée, sans rien déplacer.
service.addCard(player.id, drawn);
const stale = propose();
service.recycleDuplicates(player.id, { editionId: drawn });
assert.throws(() => service.acceptTransfer(player.id, stale.transfer.id), /doublons/);
assert.equal(service.getState(admin.id).transfers.find((item) => item.id === stale.transfer.id).status, "open");
// Une proposition sans réponse expire au bout de 7 jours et libère le doublon réservé.
now += 7 * 24 * 60 * 60 * 1000;
assert.equal(service.getState(admin.id).transfers.find((item) => item.id === stale.transfer.id).status, "expired");
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore - 1);
now += 24 * 60 * 60 * 1000;
database.close();
});
test("legacy in-progress transfers are cancelled by the migration and free their duplicates", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-transfers-"));
const path = join(directory, "cards.sqlite");
t.after(() => rm(directory, { recursive: true, force: true }));
let database = new CardsDatabase(path);
const service = new CardsService({ database, catalog: baseCatalog, random: () => 0 });
const player = service.upsertPlayer({ discordId: "legacy", displayName: "Ancien" });
for (const [id, status] of [["t-open", "open"], ["t-joined", "joined"], ["t-done", "completed"]]) {
database.db.prepare("INSERT INTO transfers(id, code, type, initiator_id, offered_edition_id, status, created_at, expires_at) VALUES (?, ?, 'gift', ?, 'aurora-wolf-standard', ?, 1, 1)").run(id, id, player.id, status);
}
database.db.prepare("DELETE FROM schema_migrations WHERE version = 3").run();
database.db.exec("ALTER TABLE transfers DROP COLUMN declined");
database.close();
database = new CardsDatabase(path);
assert.deepEqual(database.db.prepare("SELECT status FROM transfers ORDER BY id").all().map((row) => row.status), ["completed", "cancelled", "cancelled"]);
database.close();
});
test("database backup passes integrity checks and restores ownership", async () => {
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-backup-"));
const source = join(directory, "source.sqlite");
const backup = join(directory, "backup.sqlite");
const restored = join(directory, "restored.sqlite");
try {
const database = new CardsDatabase(source);
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
const player = service.upsertPlayer({ discordId: "backup-player", displayName: "Backup" });
service.openPack(player.id, "primordial-nebula", "backup-pack");
database.close();
await backupCardsDatabase(source, backup);
assert.equal(verifyCardsDatabase(backup), true);
restoreCardsDatabase(backup, restored);
const restoredDatabase = new CardsDatabase(restored);
assert.equal(restoredDatabase.db.prepare("SELECT SUM(quantity) AS count FROM collection_cards").get().count, 3);
restoredDatabase.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("published catalog adds mythic variations and opening settings stored in the database", () => {
const legendary = baseCatalog.editions.find((edition) => edition.cardId === "starvoid-dragon" && edition.rarity === "legendary");
const published = buildPublishedCatalog(baseCatalog, {
variations: [
{ editionId: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", finishId: "spectral-prism-solar", status: "active" },
{ editionId: "starvoid-dragon-spectral-prism-aurora", cardId: "starvoid-dragon", finishId: "spectral-prism-aurora", status: "retired" }
],
openingSettings: [
{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "snowflakes", particlePaletteId: null },
{ scope: "collection", targetId: "astral-genesis", particleShapeId: null, particlePaletteId: null }
]
});
const dragonEditions = published.editions.filter((edition) => edition.cardId === "starvoid-dragon");
// Les variations suivent leur légendaire, dans l'ordre des finitions.
assert.deepEqual(dragonEditions.map((edition) => [edition.id, edition.retired ?? false]), [
[legendary.id, false],
["starvoid-dragon-spectral-prism-solar", false],
["starvoid-dragon-spectral-prism-aurora", true]
]);
assert.equal(dragonEditions[2].legendaryEditionId, legendary.id);
assert.equal(baseCatalog.editions.some((edition) => edition.rarity === "mythic"), false);
assert.deepEqual(published.mythicOpeningSettings, [{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "snowflakes", particlePaletteId: null }]);
const variation = (overrides) => ({ editionId: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", finishId: "spectral-prism-solar", status: "active", ...overrides });
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation({ editionId: "astral-booster-spectral-prism-solar", cardId: "astral-booster" })] }), /legendary card/);
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation({ editionId: "starvoid-dragon-standard", finishId: "standard" })] }), /legendary card/);
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation(), variation()] }), /legendary card/);
assert.throws(() => buildPublishedCatalog(baseCatalog, { openingSettings: [{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "bubbles" }] }), /Invalid mythic opening setting/);
assert.doesNotThrow(() => buildPublishedCatalog(baseCatalog, { openingSettings: [{ scope: "card", targetId: "starvoid-dragon", particlePaletteId: "match-holo" }] }));
const astral = structuredClone(catalog);
astral.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar").retired = true;
assert.ok(drawPack(astral, "astral-genesis", (maximum) => maximum - 1).every((id) => id !== "mythic-card-pull-spectral-prism-solar"));
});
test("mythic opening style inherits shape and palette independently from card, collection and default", () => {
const cardId = "mythic-card-pull";
const collectionId = "astral-genesis";
const plain = resolveMythicOpeningStyle(catalog, cardId, collectionId);
assert.equal(plain.effect.id, "mythic-default-opening");
assert.deepEqual([plain.shape, plain.palette], [{ id: "sparks", source: "default" }, { id: "rainbow", source: "default" }]);
const configured = { ...catalog, mythicOpeningSettings: [
{ scope: "collection", targetId: collectionId, particleShapeId: "snowflakes", particlePaletteId: "epic-violet" },
{ scope: "card", targetId: cardId, particleShapeId: null, particlePaletteId: "match-holo" }
] };
const style = resolveMythicOpeningStyle(configured, cardId, collectionId);
assert.deepEqual([style.shape, style.palette], [{ id: "snowflakes", source: "collection" }, { id: "match-holo", source: "card" }]);
const sibling = resolveMythicOpeningStyle(configured, "astral-booster", collectionId);
assert.deepEqual([sibling.shape.source, sibling.palette], ["collection", { id: "epic-violet", source: "collection" }]);
assert.equal(resolveOpeningEffect(catalog, "rare").id, "rare-opening");
});
test("admin catalog mutations persist mythic variations and keep owned ones out of drops only", () => {
const now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: (maximum) => maximum - 1 });
const admin = service.upsertPlayer({ discordId: "catalog-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "catalog-player", displayName: "Player" });
assert.throws(() => service.setCardMythicConfig(player.id, "mythic-card-pull", { finishIds: [] }), /administrateur/);
assert.throws(() => service.setCardMythicConfig(admin.id, "astral-booster", { finishIds: [] }), /légendaire/);
assert.throws(() => service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["standard"] }), /holographiques/);
assert.throws(() => service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: { particleShapeId: "bubbles" } }), /Forme/);
const result = service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar", "spectral-prism-aurora"], opening: { particleShapeId: "snowflakes", particlePaletteId: "match-holo" } });
assert.ok(result.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-aurora" && !edition.retired));
assert.deepEqual(result.catalog.mythicOpeningSettings, [{ scope: "card", targetId: "mythic-card-pull", particleShapeId: "snowflakes", particlePaletteId: "match-holo" }]);
const opened = service.openPack(player.id, "astral-genesis", "catalog-pack");
const ownedMythic = opened.opening.cards.find((card) => card.edition.rarity === "mythic").editionId;
assert.equal(service.getAdminDashboard(admin.id).editionOwners[ownedMythic], 1);
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: {} });
const reloaded = new CardsService({ database, catalog: baseCatalog, now: () => now });
const owned = reloaded.catalog.editions.find((edition) => edition.id === ownedMythic);
assert.equal(owned.retired, true);
assert.ok(reloaded.catalog.editions.filter((edition) => edition.cardId === "mythic-card-pull" && edition.rarity === "mythic").every((edition) => edition.retired || edition.id === ownedMythic));
assert.equal(reloaded.catalog.mythicOpeningSettings.length, 0);
// Une variation que personne ne possède mais qu'une campagne cite est retirée, pas supprimée : le code reste utilisable.
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-cosmic"], opening: {} });
const cosmic = "mythic-card-pull-spectral-prism-cosmic";
service.createCampaign(admin.id, { name: "Cosmique", reward: { items: [{ type: "card", editionId: cosmic }, { type: "pack", collectionId: "astral-genesis", guarantee: { type: "edition", editionId: cosmic } }] }, code: "COSMIC", maxClaims: null, expiresAt: null });
assert.equal(service.getAdminDashboard(admin.id).editionCampaigns[cosmic], 1);
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: {} });
assert.equal(service.catalog.editions.find((edition) => edition.id === cosmic)?.retired, true);
service.completeOpening(player.id, opened.opening.id);
const claimed = service.claimCampaign(player.id, "COSMIC");
assert.ok(claimed.state.collection.some((item) => item.editionId === cosmic));
const gift = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "cosmic-gift");
assert.ok(gift.opening.cards.some((card) => card.editionId === cosmic));
assert.equal(service.getState(player.id).collection.some((item) => item.editionId === ownedMythic && item.edition), true);
service.setCollectionMythicOpening(admin.id, "astral-genesis", { particleShapeId: "snowflakes" });
assert.deepEqual(service.catalog.mythicOpeningSettings, [{ scope: "collection", targetId: "astral-genesis", particleShapeId: "snowflakes", particlePaletteId: null }]);
assert.throws(() => service.setCollectionMythicOpening(admin.id, "astral-genesis", { particlePaletteId: "unknown" }), /inconnue/);
service.setCollectionMythicOpening(admin.id, "astral-genesis", {});
assert.deepEqual(service.catalog.mythicOpeningSettings, []);
database.close();
});
test("mythic variations live only in the database and a new database starts without any", () => {
const versionedMythic = structuredClone(rawCatalog);
versionedMythic.editions.push({ id: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", rarity: "mythic", finishIds: ["spectral-prism-solar"], promotional: false, transferable: true, legendaryEditionId: "starvoid-dragon-standard" });
assert.throws(() => assertVersionedCatalogScope(versionedMythic), /admin database/);
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000 });
assert.equal(service.catalog.editions.some((edition) => edition.rarity === "mythic"), false);
assert.deepEqual(service.catalog.mythicOpeningSettings, []);
// Le poids mythique reste en place : le tirage ignore la rareté tant qu'aucune variation n'existe.
for (const collectionId of ["primordial-nebula", "astral-genesis"]) {
assert.equal(service.catalog.collections.find((collection) => collection.id === collectionId).dropWeights.mythic, 1);
assert.ok(drawPack(service.catalog, collectionId, (maximum) => maximum - 1).every((id) => service.catalog.editions.find((edition) => edition.id === id).rarity !== "mythic"));
}
// Une variation que personne ne possède suit la règle commune : elle est supprimée, pas seulement retirée.
const admin = service.upsertPlayer({ discordId: "seed-admin", displayName: "Admin", isAdmin: true });
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar"] });
assert.ok(service.catalog.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar").legendaryEditionId === "mythic-card-pull-standard");
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-aurora"] });
assert.equal(service.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-solar"), false);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM mythic_variations WHERE edition_id = 'mythic-card-pull-spectral-prism-solar'").get().count, 0);
database.close();
});
test("pack availability and drop rates live in the database and apply immediately", () => {
assert.equal("dropTables" in rawCatalog, false);
assert.ok(rawCatalog.collections.every((collection) => !("active" in collection) && !("dropWeights" in collection)));
assert.deepEqual(rawCatalog.rarities.map((rarity) => rarity.recommendedWeight), [64, 24, 8, 3, 1]);
assert.throws(() => assertVersionedCatalogScope({ ...structuredClone(rawCatalog), dropTables: [] }), /dropTables/);
const withState = structuredClone(rawCatalog);
withState.collections[0].active = true;
assert.throws(() => assertVersionedCatalogScope(withState), /availability/);
const withRates = structuredClone(rawCatalog);
withRates.collections[0].dropWeights = { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 };
assert.throws(() => assertVersionedCatalogScope(withRates), /drop rates/);
const badRecommendation = structuredClone(rawCatalog);
badRecommendation.rarities[0].recommendedWeight = -1;
assert.throws(() => prepareVersionedCatalog(badRecommendation), /recommended weights/);
// Une collection sans état est fermée ; un paquet ouvert doit avoir des taux de tirage.
assert.ok(buildPublishedCatalog(baseCatalog).collections.every((collection) => collection.active === false && !collection.dropWeights));
assert.throws(() => buildPublishedCatalog(baseCatalog, { collectionStates: [{ collectionId: "astral-genesis", active: true }] }), /needs drop rates/);
assert.deepEqual(catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights, { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 });
let now = Date.parse("2026-11-04T12:00:00.000Z");
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "packs-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "packs-player", displayName: "Player" });
assert.throws(() => service.setDropRates(player.id, "astral-genesis", { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 }), /administrateur/);
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 1, rare: 0, epic: 0, legendary: 0 }), /Poids invalides/);
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 0 }), /Poids invalides/);
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 1.5, rare: 0, epic: 0, legendary: 0, mythic: 1 }), /Poids invalides/);
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 }), /déjà en vigueur/);
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar"] });
service.setDropRates(admin.id, "astral-genesis", { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 1 });
const opening = service.openPack(player.id, "astral-genesis", "packs-mythic");
assert.ok(opening.opening.cards.every((card) => card.edition.rarity === "mythic"));
// Le journal d'audit garde les anciens et les nouveaux poids.
const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'drop_rates_updated' AND entity_id = 'astral-genesis'").get();
assert.deepEqual(JSON.parse(audit.details_json), { previous: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 }, rarityWeights: { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 1 } });
service.completeOpening(player.id, opening.opening.id);
service.setCollectionActive(admin.id, "astral-genesis", false);
assert.equal(service.catalog.collections.find((collection) => collection.id === "astral-genesis").active, false);
now += INITIAL_RECHARGE_SETTING.intervalMs;
assert.throws(() => service.openPack(player.id, "astral-genesis", "packs-closed"), /pas disponible/);
service.setCollectionActive(admin.id, "astral-genesis", true);
assert.throws(() => service.setCollectionActive(admin.id, "astral-genesis", "yes"), /invalide/);
assert.throws(() => service.setCollectionActive(admin.id, "unknown", true), /introuvable/);
const reloaded = new CardsService({ database, catalog: baseCatalog, now: () => now });
assert.equal(reloaded.catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights.mythic, 1);
database.close();
});
test("gift packs apply custom rates and guarantees without spending recharge", () => {
const rank = (rarity) => catalog.rarities.findIndex((item) => item.id === rarity);
const rarityOf = (id) => catalog.editions.find((edition) => edition.id === id).rarity;
const commonOnly = { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 };
assert.ok(drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly }).every((id) => rarityOf(id) === "common"));
// « Au moins 2 cartes rares ou mieux » : les cartes les plus communes sont améliorées.
const upgraded = drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly, guarantee: { type: "rarity", rarity: "rare", count: 2 } });
assert.equal(upgraded.filter((id) => rank(rarityOf(id)) >= rank("rare")).length, 2);
const legendaryOrBetter = drawPack(catalog, "astral-genesis", () => 0, { guarantee: { type: "rarity", rarity: "legendary", count: 3 } });
assert.ok(legendaryOrBetter.every((id) => rank(rarityOf(id)) >= rank("legendary")));
const withCard = drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly, guarantee: { type: "edition", editionId: "mythic-card-pull-spectral-prism-solar" } });
assert.ok(withCard.includes("mythic-card-pull-spectral-prism-solar"));
const closed = { ...catalog, collections: catalog.collections.map((collection) => ({ ...collection, active: false })) };
assert.throws(() => drawPack(closed, "astral-genesis", () => 0), /pas disponible/);
assert.equal(drawPack(closed, "astral-genesis", () => 0, { requireActive: false }).length, 3);
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "gift-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "gift-player", displayName: "Player" });
const other = service.upsertPlayer({ discordId: "gift-other", displayName: "Other" });
const pack = { type: "pack", collectionId: "astral-genesis", rarityWeights: commonOnly, guarantee: { type: "rarity", rarity: "legendary", count: 1 } };
const reward = { items: [pack] };
assert.throws(() => service.createCampaign(player.id, { name: "X", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /administrateur/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "rarity", rarity: "legendary", count: 4 } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /Garantie invalide/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "edition", editionId: "starvoid-dragon-standard" } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /appartenir/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward, code: "x", maxClaims: 2, expiresAt: now + 60_000 }), /4 à 24/);
const shared = service.createCampaign(admin.id, { name: "Live", reward, code: "live-2026", maxClaims: 2, expiresAt: now + 60_000 });
assert.equal(shared.campaign.code, "LIVE-2026");
assert.throws(() => service.createCampaign(admin.id, { name: "Copie", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /déjà utilisé/);
// Le paquet est mis de côté, puis ouvert sans consommer la réserve, même collection fermée.
const before = service.getState(player.id).recharge.openingsBalance;
const claim = service.claimCampaign(player.id, "LIVE-2026");
assert.equal(claim.reward.items[0].type, "pack");
assert.equal(claim.state.giftPacks.length, 1);
service.claimCampaign(other.id, "LIVE-2026");
assert.throws(() => service.claimCampaign(admin.id, "LIVE-2026"), /nombre maximal/);
service.setCollectionActive(admin.id, "astral-genesis", false);
const opened = service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-1");
// L'ouverture porte les options du paquet offert : l'écran de révélation affiche les taux réellement appliqués.
assert.deepEqual(opened.opening.options, claim.state.giftPacks[0].options);
assert.equal(opened.state.recharge.openingsBalance, before);
assert.equal(opened.state.giftPacks.length, 0);
assert.ok(opened.opening.cards.some((card) => rank(card.edition.rarity) >= rank("legendary")));
assert.equal(service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-1").opening.id, opened.opening.id);
assert.throws(() => service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-2"), /ouverture en cours/);
service.completeOpening(player.id, opened.opening.id);
assert.throws(() => service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-2"), /plus disponible/);
const detail = service.campaignDetail(admin.id, shared.campaign.id);
assert.equal(detail.campaign.claimedCount, 2);
assert.deepEqual(detail.claims.map((item) => item.playerName), ["Player", "Other"]);
// Révocation et expiration.
const revoked = service.createCampaign(admin.id, { name: "Révoquée", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "REVOKED", maxClaims: null, expiresAt: null });
service.revokeCampaign(admin.id, revoked.campaign.id);
assert.throws(() => service.claimCampaign(other.id, "REVOKED"), /révoqué/);
const short = service.createCampaign(admin.id, { name: "Courte", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "SHORT", maxClaims: null, expiresAt: now + 60_000 }).campaign;
service.claimCampaign(other.id, "SHORT");
now += 120_000;
assert.throws(() => service.claimCampaign(admin.id, "SHORT"), /expiré/);
assert.throws(() => service.extendCampaign(admin.id, short.id, now - 1), /futur/);
service.extendCampaign(admin.id, short.id, now + 60_000);
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, now + 60_000);
// Sans date d'expiration : le code reste valable indéfiniment, et une campagne peut perdre son échéance.
service.extendCampaign(admin.id, short.id, null);
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, null);
const forever = service.createCampaign(admin.id, { name: "Permanent", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "FOREVER", maxClaims: null, expiresAt: null });
now += 10 * 365 * 24 * 3_600_000;
service.claimCampaign(other.id, "FOREVER");
assert.equal(service.campaignDetail(admin.id, forever.campaign.id).campaign.claimedCount, 1);
// Plusieurs éléments et quantités dans une même récompense, code partagé sans limite (une utilisation par joueur).
assert.throws(() => service.createCampaign(admin.id, { name: "Vide", reward: { items: [] }, code: "EMPTY", maxClaims: null, expiresAt: now + 60_000 }), /au moins une/);
assert.throws(() => service.createCampaign(admin.id, { name: "Trop", reward: { items: [{ type: "pack", collectionId: "primordial-nebula", quantity: 11 }] }, code: "TOO-MANY", maxClaims: null, expiresAt: now + 60_000 }), /Quantité invalide/);
assert.throws(() => service.createCampaign(admin.id, { name: "Double", reward: { items: [{ type: "card", editionId: "astral-booster-standard", quantity: 2 }] }, code: "DOUBLE", maxClaims: null, expiresAt: now + 60_000 }), /un seul exemplaire/);
assert.throws(() => service.createCampaign(admin.id, { name: "Doublon", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "astral-booster-standard" }] }, code: "DOUBLON", maxClaims: null, expiresAt: now + 60_000 }), /qu’une fois/);
const bundle = service.createCampaign(admin.id, {
name: "Pack de bienvenue",
reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "aurora-wolf-standard" }, { type: "pack", collectionId: "primordial-nebula", quantity: 3 }] },
code: "WELCOME", maxClaims: null, expiresAt: now + 60_000
});
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.maxClaims, null);
const players = Array.from({ length: 3 }, (_, index) => service.upsertPlayer({ discordId: `bundle-${index}`, displayName: `Bundle ${index}` }));
for (const member of players) {
const received = service.claimCampaign(member.id, "WELCOME");
assert.equal(received.state.collection.filter((item) => ["astral-booster-standard", "aurora-wolf-standard"].includes(item.editionId)).length, 2);
assert.equal(received.state.giftPacks.length, 3);
}
assert.throws(() => service.claimCampaign(players[0].id, "WELCOME"), /déjà reçu/);
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.claimedCount, 3);
assert.equal(service.getAdminDashboard(admin.id).campaigns.length, 5);
assert.equal("campaigns" in service.getState(admin.id), false);
const published = service.catalog;
assert.equal(summarizeReward(bundle.campaign.reward, published), "Carte Booster Astral (Commun) + Carte Loup des Aurores (Légendaire) + 3 × Paquet La Nébuleuse Originelle");
const many = { items: [...["astral-booster-standard", "aurora-wolf-standard", "starvoid-dragon-standard"].map((editionId) => ({ type: "card", editionId, quantity: 1 })), { type: "pack", collectionId: "primordial-nebula", quantity: 2 }] };
assert.equal(summarizeReward(many, published), "3 cartes + 2 paquets");
database.close();
});