sokko-g/tests/nebula-cards-expedition-service.test.mjs

958 lines
72 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, départ solo, retour, réglages, suppression de compte).
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 { createCardsApiHandler } from "../services/cards/api.js";
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js";
import { CardsDatabase } from "../services/cards/database.js";
import { CardsService } from "../services/cards/service.js";
import { DEFAULT_EXPEDITION_SETTINGS } from "../services/cards/expedition-settings.js";
import { createDiscordAlertSender, dispatchAlerts } from "../services/cards/discord-alerts.js";
const DEFAULT_GROUP = DEFAULT_EXPEDITION_SETTINGS.group;
const rawCatalogText = await readFile("website/public/data/cards/catalog.json", "utf8");
const baseCatalog = prepareVersionedCatalog(JSON.parse(rawCatalogText));
const published = buildPublishedCatalog(baseCatalog, { collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES });
const HOUR = 3_600_000;
const rarityOf = (cardId) => published.editions.find((edition) => edition.cardId === cardId && !edition.promotional).rarity;
const editionsOf = (rarity, collectionId = "primordial-nebula") => published.editions
.filter((edition) => edition.rarity === rarity && published.cards.find((card) => card.id === edition.cardId).collectionId === collectionId)
.map((edition) => edition.id);
// Par défaut, le joueur a toutes les cartes de destination : ses 4 destinations du jour sont tirées parmi toutes.
const destinationEditions = published.editions.filter((edition) => published.cards.find((card) => card.id === edition.cardId).kind === "destination").map((edition) => edition.id);
function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0, catalog = baseCatalog, allDestinations = true } = {}) {
const clock = { now: start };
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog, now: () => clock.now, random });
const admin = service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "expedition-player", displayName: "Player" });
const open = (changes = {}) => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, enabled: true, ...changes });
const rares = editionsOf("rare");
database.transaction(() => rares.slice(0, 4).forEach((editionId) => service.addCard(player.id, editionId)));
if (allDestinations) database.transaction(() => destinationEditions.forEach((editionId) => service.addCard(player.id, editionId)));
return { clock, database, service, admin, player, open, rares };
}
const soloBody = (view, slots, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, durationHours: 2, slots, ...changes });
test("expeditions stay closed until an administrator opens them", () => {
const { service, player, open, rares } = expeditionService();
const closed = service.expeditions.getExpeditions(player.id);
assert.equal(closed.enabled, false);
assert.deepEqual(closed.destinations, []);
assert.equal(service.getState(player.id).expeditions.enabled, false);
assert.throws(() => service.expeditions.startSolo(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares.slice(0, 2)), "k1"), (error) => error.code === "EXPEDITIONS_CLOSED");
assert.throws(() => service.expeditions.updateSettings(player.id, { ...service.expeditions.settings, enabled: true }), (error) => error.code === "ADMIN_REQUIRED");
open();
const view = service.expeditions.getExpeditions(player.id);
assert.equal(view.enabled, true);
assert.equal(view.day, "2026-11-15");
assert.equal(view.destinations.length, 4);
// La difficulté est tirée avec les destinations : un niveau de chaque, le groupe une étoile au-dessus du solo.
assert.deepEqual(view.destinations.map((item) => item.level).sort(), [0, 1, 2, 3]);
assert.ok(view.destinations.every((item) => item.groupStar === item.soloStar + 1 && Object.keys(item.stars).join() === String(item.soloStar) && Object.keys(item.groupStars).join() === String(item.groupStar)));
assert.equal(view.destinations.find((item) => item.soloStar === 4).stars[4].dangers.length, 1);
assert.equal(view.destinations.find((item) => item.soloStar === 2).stars[2].condition, null);
assert.equal(view.cards.length, 4);
// Le tirage du jour du joueur est gardé en base.
assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id));
});
// Cartes de destination : on ne tire que les destinations débloquées (une destination sans carte au catalogue reste ouverte),
// avec un niveau de chaque jusqu'au nombre de destinations tirées ; une carte obtenue dans la journée complète le tirage.
test("each player draws the day among the destinations their cards unlock", () => {
const { service, player, open, database } = expeditionService({ allDestinations: false });
const other = service.upsertPlayer({ discordId: "expedition-other", displayName: "Other" });
// Avant sa première visite : aucune carte, seules les destinations encore sans carte au catalogue sont ouvertes.
const unlocked = service.expeditions.unlockedDestinationIds(player.id);
assert.equal(unlocked.has("light-currents"), false);
assert.equal(unlocked.has("cosmic-cloud-heart"), false);
assert.equal(unlocked.has("crimson-passage"), false);
// Seules trois destinations restent proposées : les Courants, le Grand Vide et le Cœur du Nuage.
const kept = new Set(["light-currents", "great-void", "cosmic-cloud-heart"]);
open({ destinations: Object.fromEntries(Object.entries(service.expeditions.settings.destinations).map(([id, value]) => [id, { ...value, active: kept.has(id) }])) });
// Première visite : la carte de départ (random() = 0, les Courants) ouvre une seule destination, au niveau le plus facile.
const before = service.expeditions.getExpeditions(player.id);
assert.deepEqual(before.destinations.map((item) => [item.id, item.level, item.soloStar]), [["light-currents", 0, 1]]);
assert.deepEqual(before.unlocked.count >= 1 && before.unlocked.total, 13);
// Sa carte du Cœur du Nuage complète le tirage du jour, avec les niveaux 1 et 2 ; l'autre joueur, sans la carte, ne la voit pas.
database.transaction(() => service.addCard(player.id, "cosmic-cloud-heart-standard"));
const after = service.expeditions.getExpeditions(player.id).destinations;
assert.deepEqual(after.map((item) => item.id).sort(), ["cosmic-cloud-heart", "light-currents"]);
assert.deepEqual(after.map((item) => item.level).sort(), [0, 1]);
const view = service.expeditions.getExpeditions(other.id);
assert.deepEqual(view.destinations.map((item) => item.id), ["light-currents"]);
// Une destination qui n'est pas dans son tirage ne se lance pas.
assert.throws(() => service.expeditions.preview(other.id, { day: view.day, destinationId: "cosmic-cloud-heart", durationHours: 2, slots: [] }), (error) => error.code === "EXPEDITION_INVALID");
});
const destinationCardsOf = (service, playerId) => service.getState(playerId).collection.map((entry) => entry.editionId).filter((id) => destinationEditions.includes(id));
// Obtention : une carte de destination de départ offerte une fois, une carte non possédée rapportée d'expédition, et la carte de la
// destination d'un groupe rejoint sans l'avoir.
test("players receive a starter destination card, then find more on expeditions and in groups", () => {
const { clock, service, player, open, rares, database, second, arcade } = groupService({ allDestinations: false });
open({ destinationCards: { dropPct: 100, groupJoinPct: 100 } });
// random() = 0 : la carte de départ est la première des Carnets, les Courants de Lumière.
service.expeditions.getExpeditions(player.id);
assert.deepEqual(destinationCardsOf(service, player.id), ["light-currents-standard"]);
service.expeditions.getExpeditions(player.id);
assert.equal(destinationCardsOf(service, player.id).length, 1);
assert.equal(service.getState(player.id).history.filter((entry) => entry.type === "destination_starter").length, 1);
assert.ok(service.expeditions.unlockedDestinationIds(player.id).has("light-currents"));
assert.equal(service.expeditions.unlockedDestinationIds(player.id).has("dawn-shore"), false);
// Un groupe vers les Courants : le second joueur, sans leur carte, la gagne ; le créateur gagne une carte qu'il n'a pas.
const view = service.expeditions.getExpeditions(player.id);
const destination = view.destinations.find((item) => item.id === "light-currents");
const [mainRole, secondRole] = destination.groupRoles;
const created = service.expeditions.createGroup(player.id, { mode: "group", day: view.day, destinationId: destination.id, durationHours: 2, editionId: rares[0], role: mainRole }, "dest-group");
const groupId = created.expeditions.groups[0].id;
// Le second joueur a déjà reçu sa carte de départ, une autre : il n'a pas celle des Courants.
database.db.prepare("INSERT INTO audit_log(player_id, event_type, entity_id, details_json, created_at) VALUES (?, 'destination_starter', 'other', '{}', 0)").run(second.id);
service.expeditions.joinGroup(second.id, groupId, { editionId: arcade[0], role: secondRole });
service.expeditions.departGroup(player.id, groupId);
const rewardOf = (playerId) => JSON.parse(database.db.prepare("SELECT reward_json FROM expedition_members WHERE expedition_id = ? AND player_id = ?").get(groupId, playerId).reward_json).cards;
// Le second gagne la carte des Courants (groupe rejoint), puis une carte qu'il n'a pas, la première restante : le Rivage de l'Aube.
assert.deepEqual(rewardOf(second.id).filter((id) => destinationEditions.includes(id)), ["light-currents-standard", "dawn-shore-standard"]);
assert.deepEqual(rewardOf(player.id).filter((id) => destinationEditions.includes(id)), ["dawn-shore-standard"]);
clock.now += 3 * HOUR;
service.expeditions.claim(second.id, groupId);
assert.ok(destinationCardsOf(service, second.id).includes("light-currents-standard"));
// Trophée : la carte d'une destination cachée revient à coup sûr à qui y va sans l'avoir, mais n'est jamais tirée au hasard.
const settings = { ...service.expeditions.settings, destinationCards: { dropPct: 0, groupJoinPct: 0 } };
assert.deepEqual(service.expeditions.rollDestinationCards(second.id, { id: "lost-observatory" }, settings, { group: false, random: () => 99 }), ["lost-observatory-standard"]);
assert.ok(!service.expeditions.destinationCardEditions({ expeditionOnly: true }).some((edition) => edition.id === "lost-observatory-standard"));
// Toutes les cartes des Carnets possédées : plus rien à trouver.
database.transaction(() => destinationEditions.forEach((editionId) => service.addCard(player.id, editionId)));
assert.deepEqual(service.expeditions.rollDestinationCards(player.id, { id: "light-currents" }, service.expeditions.settings, { group: true, random: () => 0 }), []);
assert.deepEqual(service.expeditions.rollDestinationCards(player.id, { id: "lost-observatory" }, settings, { group: false, random: () => 0 }), []);
});
test("a solo expedition freezes its team, hides its result until it returns and pays once", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
// Une difficulté envoyée par un ancien client est ignorée : les étoiles sont celles de la destination.
const body = soloBody(view, rares.slice(0, 2), { difficulty: 4, durationHours: 6 });
const preview = service.expeditions.preview(player.id, body).preview;
assert.ok(["struggle", "success", "triumph"].includes(preview.tier));
assert.equal(preview.requirements.length, 2);
assert.ok(preview.expected.eclats > 0);
const started = service.expeditions.startSolo(player.id, body, "start-1");
assert.equal(started.expedition.status, "running");
assert.equal(started.expedition.stars, view.destinations[0].soloStar);
assert.equal(started.expedition.result, null);
assert.equal(started.expedition.reward, null);
assert.equal(started.expedition.returnsAt, clock.now + 6 * HOUR);
assert.equal(started.state.expeditions.running, 1);
assert.equal(started.state.expeditions.launchedToday, true);
assert.deepEqual(started.state.expeditions.busyEditions.map((item) => item.editionId).sort(), rares.slice(0, 2).sort());
// Même clé : même expédition ; nouvelle clé : la limite solo s'applique, et les cartes sont occupées.
assert.equal(service.expeditions.startSolo(player.id, body, "start-1").expedition.id, started.expedition.id);
assert.throws(() => service.expeditions.startSolo(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY");
assert.throws(() => service.expeditions.startSolo(player.id, { ...body, slots: rares.slice(2, 4) }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT");
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_RETURNED");
// Une amélioration des réglages pendant le trajet ne change rien : tout est figé au départ.
clock.now += 6 * HOUR;
const before = service.getState(player.id);
assert.equal(before.expeditions.returned, 1);
const returned = service.expeditions.getExpeditions(player.id).expeditions[0];
assert.equal(returned.status, "returned");
assert.equal(returned.result.tier, preview.tier);
const claimed = service.expeditions.claim(player.id, started.expedition.id);
assert.equal(claimed.expedition.status, "completed");
assert.equal(claimed.state.wallet.eclats, returned.reward.eclats);
assert.equal(claimed.state.wallet.stardust, before.wallet.stardust + returned.reward.stardust);
assert.ok(returned.reward.eclats >= Math.floor(preview.expected.eclats));
// random() = 0 : tous les tirages réussissent, donc une carte rapportée à l'unité (des Carnets de cette destination sans
// collection), ajoutée à la collection ; plus de paquet offert.
const rewardCards = returned.reward.cards.filter((editionId) => !destinationEditions.includes(editionId));
assert.equal(rewardCards.length, 1);
assert.deepEqual(returned.reward.packs, []);
assert.equal(claimed.state.giftPacks.length, 0);
assert.ok(service.quantityOf(player.id, rewardCards[0]) >= 1);
const history = claimed.state.history.find((entry) => entry.type === "expedition_completed");
assert.equal(history.details.eclats, returned.reward.eclats);
// Deuxième retour : même rapport, aucun crédit en plus ; les cartes sont libres.
const again = service.expeditions.claim(player.id, started.expedition.id);
assert.equal(again.state.wallet.eclats, claimed.state.wallet.eclats);
assert.deepEqual(again.state.expeditions.busyEditions, []);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE source = 'expedition'").get().count, 0);
});
// Une carte rapportée vient des Carnets de la destination ; une destination rattachée à une collection ouverte la tire le plus
// souvent dans sa collection (rewardCards.linkedCollectionPct), sinon dans ses Carnets.
test("reward cards come from the Carnets, or mostly from the destination's collection when it is open", () => {
const { service, admin, player, open } = expeditionService();
open();
const collectionOf = (editionId) => service.catalog.cards.find((card) => card.id === service.index.editions.get(editionId).cardId).collectionId;
const settings = service.expeditions.settings;
const draw = (destination, random) => collectionOf(service.expeditions.drawRewardCard(player.id, destination, settings, random));
const ruins = { rewardCollectionId: "dream-arcade", logbookCards: ["cartographer-gecko"] };
// Sans collection, ou collection fermée (l'Arcade, au départ) : une carte des Carnets de la destination.
assert.equal(draw({ logbookCards: ["cartographer-gecko"] }, () => 0), "watchers-logbooks");
assert.equal(draw(ruins, () => 0), "watchers-logbooks");
assert.equal(service.expeditions.drawRewardCard(player.id, { logbookCards: [] }, settings, () => 0), null);
service.setDropRates(admin.id, "dream-arcade", { common: 70, rare: 20, epic: 7, legendary: 2, mythic: 1 });
service.setCollectionActive(admin.id, "dream-arcade", true);
// Ouverte : sa collection sous linkedCollectionPct (75 par défaut), les Carnets au-dessus.
assert.equal(draw(ruins, (max) => (max === 100 ? settings.rewardCards.linkedCollectionPct - 1 : 0)), "dream-arcade");
assert.equal(draw(ruins, (max) => (max === 100 ? settings.rewardCards.linkedCollectionPct : 0)), "watchers-logbooks");
// Sans carte des Carnets, toujours sa collection.
assert.equal(draw({ rewardCollectionId: "dream-arcade", logbookCards: [] }, (max) => max - 1), "dream-arcade");
});
// Une carte de destination est unique : jamais en double, remplacée dans un paquet, jamais échangée ni donnée.
test("destination cards are unique: never twice in a collection, replaced in packs, never traded", () => {
const { service, player, database } = expeditionService({ allDestinations: false });
const other = service.upsertPlayer({ discordId: "unique-other", displayName: "Other" });
const cloud = "cosmic-cloud-heart-standard";
database.transaction(() => {
assert.equal(service.addCard(player.id, cloud), true);
assert.equal(service.addCard(player.id, cloud), false);
});
assert.equal(service.quantityOf(player.id, cloud), 1);
// Dans un paquet : déjà possédée, elle devient une autre rare de la Nébuleuse ; tirée deux fois, la seconde est remplacée.
const rarity = (editionId) => service.index.editions.get(editionId).rarity;
const collectionOf = (editionId) => service.index.cards.get(service.index.editions.get(editionId).cardId).collectionId;
const first = database.transaction(() => service.insertOpening(player.id, "primordial-nebula", [cloud, rares(service)[0], cloud]));
service.completeOpening(player.id, first.openingId);
const replaced = first.editionIds;
assert.ok(replaced.every((editionId) => !service.isDestinationEdition(editionId) || editionId !== cloud));
assert.ok(replaced.every((editionId) => rarity(editionId) === "rare" && collectionOf(editionId) === "primordial-nebula"));
const second = database.transaction(() => service.insertOpening(other.id, "primordial-nebula", [cloud, cloud, rares(service)[0]]));
service.completeOpening(other.id, second.openingId);
const fresh = second.editionIds;
assert.deepEqual(fresh.filter((editionId) => editionId === cloud), [cloud]);
assert.equal(service.quantityOf(other.id, cloud), 1);
// Ni échange ni don, même avec un ancien doublon.
database.db.prepare("UPDATE collection_cards SET quantity = 2 WHERE player_id = ? AND edition_id = ?").run(player.id, cloud);
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: other.id, editionId: cloud }), (error) => error.code === "DESTINATION_CARD_LOCKED");
});
const rares = (service) => editionsOf("rare").filter((editionId) => !service.isDestinationEdition(editionId));
test("unlucky rolls keep the average and never hand out a collection card", () => {
const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 });
open();
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "unlucky");
clock.now += 2 * HOUR;
const returned = service.expeditions.claim(player.id, started.expedition.id).expedition;
assert.deepEqual(returned.reward.packs, []);
assert.equal(returned.reward.eclats, Math.floor(returned.reward.eclats));
});
test("solo departures refuse stale days, unknown destinations, commons, duplicates and cards the player lacks", () => {
const { clock, service, player, open, rares } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
const start = (changes, key) => () => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), changes), key);
assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID");
assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID");
assert.throws(start({ slots: [rares[0]] }, "d"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], rares[0]] }, "e"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], editionsOf("common")[0]] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], rares[10]] }, "g"), (error) => error.code === "CARD_NOT_OWNED");
assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), ""), (error) => error.code === "IDEMPOTENCY_REQUIRED");
clock.now += 24 * HOUR;
assert.throws(start({}, "h"), (error) => error.code === "EXPEDITION_DAY_EXPIRED");
assert.equal(rarityOf("starvoid-dragon"), "legendary");
});
test("administrators tune settings with bounds and history, and can cancel an expedition", () => {
const { service, admin, player, open, rares, database } = expeditionService();
assert.throws(() => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, score: { ...service.expeditions.settings.score, successPct: 500 } }), (error) => error.code === "EXPEDITION_SETTINGS_INVALID");
open();
assert.throws(() => open(), (error) => error.code === "EXPEDITION_SETTINGS_UNCHANGED");
const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'expedition_settings_updated'").get();
assert.deepEqual(JSON.parse(audit.details_json).changes, [{ path: "enabled", previous: false, next: true }]);
assert.ok(service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "expedition_settings_updated"));
const dashboard = service.getAdminDashboard(admin.id);
assert.equal(dashboard.expeditionSettings.settings.enabled, true);
assert.equal(dashboard.expeditionSettings.destinations.length, 15);
assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents"));
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "cancel-me");
assert.equal(service.getAdminDashboard(admin.id).expeditionsToday.running, 1);
assert.throws(() => service.expeditions.cancel(player.id, started.expedition.id), (error) => error.code === "ADMIN_REQUIRED");
service.expeditions.cancel(admin.id, started.expedition.id);
const state = service.getState(player.id);
assert.deepEqual(state.expeditions.busyEditions, []);
assert.ok(state.history.some((entry) => entry.type === "expedition_cancelled_by_guild"));
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_FOUND");
assert.throws(() => service.expeditions.cancel(admin.id, started.expedition.id), (error) => error.code === "EXPEDITION_FINISHED");
});
test("deleting an account cancels its expeditions and resets its Éclats", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "first");
clock.now += 2 * HOUR;
service.expeditions.claim(player.id, first.expedition.id);
const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(2, 4)), "second");
service.deleteAccount(player.id);
assert.equal(database.db.prepare("SELECT eclats FROM players WHERE id = ?").get(player.id).eclats, 0);
assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(second.expedition.id).status, "cancelled");
});
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 expeditions API requires a session, CSRF protection, an administrator for settings and an idempotency key to start", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
t.after(() => handler.close());
assert.equal((await call(handler, { path: "/api/cards/expeditions" })).status, 401);
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
const cookie = login.headers["set-cookie"].split(";")[0];
const headers = { cookie, "x-csrf-token": login.json.csrfToken };
const closed = await call(handler, { path: "/api/cards/expeditions", headers: { cookie } });
assert.equal(closed.status, 200);
assert.equal(closed.json.enabled, false);
assert.equal((await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers: { cookie }, body: {} })).status, 403);
const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie } });
const settings = { ...dashboard.json.expeditionSettings.settings, enabled: true };
const invalid = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings: { ...settings, solo: { ...settings.solo, maxStars: 9 } } } });
assert.equal(invalid.status, 400);
assert.equal(invalid.json.error.code, "EXPEDITION_SETTINGS_INVALID");
const opened = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings } });
assert.equal(opened.status, 200);
assert.equal(opened.json.expeditionSettings.settings.enabled, true);
const devId = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id;
handler.service.database.transaction(() => editionsOf("rare").slice(0, 2).forEach((editionId) => handler.service.addCard(devId, editionId)));
const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json;
const slots = view.cards.slice(0, 2).map((card) => card.editionId);
assert.equal(slots.length, 2, "the development account owns rare or better cards");
const body = soloBody(view, slots);
const preview = await call(handler, { method: "POST", path: "/api/cards/expeditions/preview", headers, body });
assert.equal(preview.status, 200);
const noKey = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers, body });
assert.equal(noKey.json.error.code, "IDEMPOTENCY_REQUIRED");
const started = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body });
assert.equal(started.status, 201);
assert.equal(started.json.expedition.status, "running");
const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${started.json.expedition.id}/claim`, headers });
assert.equal(early.status, 409);
assert.equal(early.json.error.code, "EXPEDITION_NOT_RETURNED");
const cancelled = await call(handler, { method: "POST", path: `/api/cards/admin/expeditions/${started.json.expedition.id}/cancel`, headers });
assert.equal(cancelled.status, 200);
});
// Groupe : deux joueurs de plus, avec chacun des cartes rares de collections différentes (Nébuleuse, Arcade des Rêves).
function groupService(options) {
const context = expeditionService(options);
const { service, database } = context;
const second = service.upsertPlayer({ discordId: "expedition-second", displayName: "Second" });
const third = service.upsertPlayer({ discordId: "expedition-third", displayName: "Third" });
const arcade = editionsOf("rare", "dream-arcade");
database.transaction(() => {
arcade.slice(0, 2).forEach((editionId) => service.addCard(second.id, editionId));
context.rares.slice(5, 7).forEach((editionId) => service.addCard(third.id, editionId));
// Mêmes cartes de destination que le premier joueur : les trois tirent les mêmes destinations du jour.
if (options?.allDestinations !== false) destinationEditions.forEach((editionId) => [second, third].forEach((member) => service.addCard(member.id, editionId)));
});
return { ...context, second, third, arcade };
}
const groupBody = (view, editionId, role, changes = {}) => ({ mode: "group", day: view.day, destinationId: view.destinations[0].id, durationHours: 2, editionId, role, ...changes });
test("a group opens on the Guild board, fills its roles and leaves when its creator launches it", () => {
const { clock, service, player, second, third, open, rares, arcade, database } = groupService();
open();
const view = service.expeditions.getExpeditions(player.id);
assert.deepEqual(view.group.stars, { min: 2, max: 5 });
assert.equal(view.destinations[0].groupRoles.length, 4);
assert.deepEqual(Object.keys(view.destinations[0].groupStars), [String(view.destinations[0].groupStar)]);
const [mainRole, secondRole] = view.destinations[0].groupRoles;
// Aperçu du groupe que le joueur ouvrirait : les trois autres places tenues par le Veilleur.
const preview = service.expeditions.preview(player.id, groupBody(view, rares[0], mainRole)).preview;
assert.equal(preview.requirements.length, view.destinations[0].groupStars[view.destinations[0].groupStar].requirements.length);
assert.throws(() => service.expeditions.createGroup(player.id, groupBody(view, rares[0], "nothing"), "g0"), (error) => error.code === "EXPEDITION_INVALID");
const created = service.expeditions.createGroup(player.id, groupBody(view, rares[0], mainRole), "g1");
assert.equal(service.expeditions.createGroup(player.id, groupBody(view, rares[0], mainRole), "g1").expeditions.groups.length, 1);
const group = created.expeditions.groups[0];
assert.equal(group.isCreator, true);
assert.equal(group.canDepart, false);
assert.deepEqual(group.freeRoles, view.destinations[0].groupRoles.slice(1));
assert.equal(created.state.expeditions.busyEditions[0].editionId, rares[0]);
// La carte du créateur est occupée : elle ne peut pas partir en solo en même temps.
assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "solo-busy"), (error) => error.code === "EXPEDITION_CARD_BUSY");
// Le tableau est visible des autres joueurs, et la Guilde le signale à ceux qui peuvent rejoindre.
assert.equal(service.getState(second.id).expeditions.joinableGroups, 1);
const board = service.expeditions.getExpeditions(second.id).groups[0];
assert.equal(board.canJoin, true);
assert.equal(board.creatorName, "Player");
assert.throws(() => service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: mainRole }), (error) => error.code === "EXPEDITION_ROLE_TAKEN");
assert.throws(() => service.expeditions.joinGroup(second.id, group.id, { editionId: rares[0], role: secondRole }), (error) => error.code === "CARD_NOT_OWNED");
assert.throws(() => service.expeditions.joinGroup(player.id, group.id, { editionId: rares[1], role: secondRole }), (error) => error.code === "EXPEDITION_ALREADY_JOINED");
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: secondRole });
assert.throws(() => service.expeditions.departGroup(second.id, group.id), (error) => error.code === "EXPEDITION_NOT_CREATOR");
const before = service.expeditions.getExpeditions(player.id).groups[0];
assert.equal(before.members.length, 2);
assert.equal(before.canDepart, true);
// Collections différentes : bonus de cohésion.
assert.equal(before.projected.cohesionPct, 10);
service.expeditions.departGroup(player.id, group.id);
assert.deepEqual(service.expeditions.getExpeditions(third.id).groups, []);
const slots = database.db.prepare("SELECT player_id, role FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(group.id);
assert.equal(slots.length, 4);
// Le Veilleur tient les deux places vides, sans rôle.
assert.deepEqual(slots.filter((slot) => slot.player_id == null).map((slot) => slot.role), [null, null]);
assert.throws(() => service.expeditions.joinGroup(third.id, group.id, { editionId: rares[5], role: view.destinations[0].groupRoles[2] }), (error) => error.code === "EXPEDITION_GROUP_DEPARTED");
clock.now += 2 * HOUR;
const first = service.expeditions.claim(player.id, group.id);
assert.equal(first.expedition.result.players, 2);
assert.equal(first.expedition.result.lootPct, 150);
assert.equal(first.expedition.status, "returned");
assert.ok(first.state.wallet.eclats > 0);
const last = service.expeditions.claim(second.id, group.id);
assert.equal(last.expedition.status, "completed");
assert.equal(last.state.history.find((entry) => entry.type === "expedition_completed").details.mode, "group");
});
test("an unlaunched group departs alone with enough players at the end of recruitment, or dissolves", () => {
const { clock, service, player, second, third, open, rares, arcade } = groupService();
open({ group: { ...DEFAULT_GROUP, recruitHours: 1 } });
const view = service.expeditions.getExpeditions(player.id);
const roles = view.destinations[0].groupRoles;
const lonely = service.expeditions.createGroup(third.id, groupBody(view, rares[5], roles[0]), "lonely").expeditions.groups[0];
const full = service.expeditions.createGroup(player.id, groupBody(view, rares[0], view.destinations[1].groupRoles[0], { destinationId: view.destinations[1].id }), "full").expeditions.groups.find((group) => group.isCreator);
service.expeditions.joinGroup(second.id, full.id, { editionId: arcade[0], role: view.destinations[1].groupRoles[1] });
clock.now += HOUR + 1;
const state = service.getState(third.id);
assert.ok(state.history.some((entry) => entry.type === "expedition_dissolved"));
assert.deepEqual(state.expeditions.busyEditions, []);
const departed = service.expeditions.getExpeditions(player.id).expeditions.find((expedition) => expedition.id === full.id);
assert.equal(departed.status, "running");
// Le départ automatique a lieu à la fin de l'inscription, pas à la lecture.
assert.equal(departed.departsAt, departed.returnsAt - 2 * HOUR);
assert.equal(lonely.id === full.id, false);
});
test("leaving a forming group frees the card, and the creator leaving dissolves it", () => {
const { service, player, second, open, rares, arcade } = groupService();
open();
const view = service.expeditions.getExpeditions(player.id);
const roles = view.destinations[0].groupRoles;
const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0], roles[0]), "leave").expeditions.groups[0];
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
service.expeditions.leaveGroup(second.id, group.id);
assert.deepEqual(service.getState(second.id).expeditions.busyEditions, []);
assert.equal(service.expeditions.getExpeditions(player.id).groups[0].members.length, 1);
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
service.expeditions.leaveGroup(player.id, group.id);
assert.deepEqual(service.expeditions.getExpeditions(second.id).groups, []);
assert.ok(service.getState(second.id).history.some((entry) => entry.type === "expedition_dissolved" && entry.details.reason === "creator_left"));
assert.ok(!service.getState(player.id).history.some((entry) => entry.type === "expedition_dissolved"));
});
test("a player deleted during a group expedition forfeits their share and the others still claim", () => {
const { clock, service, player, second, open, rares, arcade, database } = groupService();
open();
const view = service.expeditions.getExpeditions(player.id);
const roles = view.destinations[0].groupRoles;
const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0], roles[0]), "forfeit").expeditions.groups[0];
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
service.expeditions.departGroup(player.id, group.id);
service.deleteAccount(second.id);
clock.now += 2 * HOUR;
assert.equal(service.expeditions.claim(player.id, group.id).expedition.status, "completed");
assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(group.id).status, "completed");
});
test("the group API opens, joins, leaves and launches through dedicated routes", 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 cookie = login.headers["set-cookie"].split(";")[0];
const headers = { cookie, "x-csrf-token": login.json.csrfToken };
const { service } = handler;
const devId = service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id;
const other = service.upsertPlayer({ discordId: "api-other", displayName: "Other" });
service.database.transaction(() => {
service.addCard(devId, editionsOf("rare")[0]);
service.addCard(other.id, editionsOf("rare")[1]);
});
service.expeditions.updateSettings(devId, { ...service.expeditions.settings, enabled: true });
const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json;
const roles = view.destinations[0].groupRoles;
const created = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-group" }, body: groupBody(view, view.cards[0].editionId, roles[0]) });
assert.equal(created.status, 201);
const groupId = created.json.expeditions.groups[0].id;
const tooSmall = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/depart`, headers });
assert.equal(tooSmall.json.error.code, "EXPEDITION_GROUP_TOO_SMALL");
service.expeditions.joinGroup(other.id, groupId, { editionId: editionsOf("rare")[1], role: roles[1] });
const unknownRole = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/join`, headers, body: { editionId: view.cards[0].editionId, role: roles[2] } });
assert.equal(unknownRole.json.error.code, "EXPEDITION_ALREADY_JOINED");
const departed = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/depart`, headers });
assert.equal(departed.status, 200);
assert.equal(departed.json.expeditions.expeditions[0].status, "running");
const leave = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/leave`, headers });
assert.equal(leave.json.error.code, "EXPEDITION_GROUP_DEPARTED");
});
test("cards level up with Éclats or a duplicate, gain field experience and stronger expedition stats", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const [card] = rares;
database.transaction(() => service.addCard(player.id, card));
database.db.prepare("UPDATE players SET eclats = 25 WHERE id = ?").run(player.id);
const before = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
assert.deepEqual([before.level, before.power, before.nextCost, before.maxLevel, before.spare], [0, 40, 10, 12, 1]);
const upgraded = service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" });
assert.deepEqual([upgraded.progress.level, upgraded.progress.power, upgraded.progress.nextCost], [1, 45, 20]);
assert.equal(upgraded.state.wallet.eclats, 15);
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }), (error) => error.code === "NOT_ENOUGH_ECLATS");
// Un doublon de la même édition donne un niveau entier, et part de la collection.
const byDuplicate = service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" });
assert.equal(byDuplicate.progress.level, 2);
assert.equal(service.quantityOf(player.id, card), 1);
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" }), (error) => error.code === "NOT_A_DUPLICATE");
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: editionsOf("common")[0], method: "eclats" }), (error) => error.code === "CARD_NOT_OWNED");
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "magic" }), (error) => error.code === "UPGRADE_METHOD_INVALID");
const history = service.getState(player.id).history.filter((entry) => entry.type === "card_upgraded");
assert.deepEqual(history.map((entry) => entry.details.method).sort(), ["duplicate", "eclats"]);
// Les expéditions utilisent la Puissance améliorée, et chaque retour donne 10 % de niveau aux cartes envoyées.
const view = service.expeditions.getExpeditions(player.id);
assert.equal(view.cards.find((item) => item.editionId === card).power, 50);
const started = service.expeditions.startSolo(player.id, soloBody(view, [card, rares[1]]), "levelled");
clock.now += 2 * HOUR;
service.expeditions.claim(player.id, started.expedition.id);
const after = service.getState(player.id).cardProgress;
assert.equal(after.find((item) => item.editionId === card).fieldXp, 10);
assert.equal(after.find((item) => item.editionId === rares[1]).fieldXp, 10);
// Au plafond, plus de niveau ; la suppression du compte efface la progression.
database.db.prepare("UPDATE card_progress SET level = 12 WHERE player_id = ? AND edition_id = ?").run(player.id, card);
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }), (error) => error.code === "CARD_MAX_LEVEL");
assert.equal(service.getState(player.id).cardProgress.find((item) => item.editionId === card).nextCost, null);
service.deleteAccount(player.id);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM card_progress WHERE player_id = ?").get(player.id).count, 0);
});
test("progression plans spread level points by vocation or by hand, and a Parchemin d'oubli pays for each change", () => {
const { service, player, open, rares, database } = expeditionService();
open();
const [card] = rares;
// Niveau 4 d'une rare : Puissance 60, dont 20 points de niveau, 12 au plus dans une stat (60 %).
database.db.prepare("INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, 4, 0, 0)").run(player.id, card);
const progressOf = () => service.getState(player.id).cardProgress.find((item) => item.editionId === card);
const sum = (stats) => Object.values(stats).reduce((total, value) => total + value, 0);
const before = progressOf();
assert.deepEqual([before.power, before.plan.id, before.plan.points, before.plan.maxStatPoints, before.plan.paid], [60, "collection", 20, 12, false]);
assert.deepEqual(before.stats, before.plan.previews.collection);
assert.equal(sum(before.plan.levelBase), 40);
// Tant que la carte suit sa collection, choisir une vocation est gratuit et s'applique aux points déjà gagnés.
const guardian = service.expeditions.setCardPlan(player.id, { editionId: card, plan: "guardian" }).progress;
const base = before.plan.levelBase;
assert.deepEqual(guardian.stats, { bravoure: base.bravoure + 4, endurance: base.endurance + 12, fortune: base.fortune, orientation: base.orientation + 4 });
assert.deepEqual(guardian.stats, before.plan.previews.guardian);
assert.equal(guardian.plan.paid, true);
assert.deepEqual(service.expeditions.getExpeditions(player.id).cards.find((item) => item.editionId === card).stats, guardian.stats);
// Ensuite, changer de plan consomme un Parchemin d'oubli, acheté en boutique avec de la poussière.
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" }), (error) => error.code === "NOT_ENOUGH_ITEMS");
database.db.prepare("UPDATE players SET stardust = 400 WHERE id = ?").run(player.id);
assert.throws(() => service.expeditions.buyOblivion(player.id, { count: 3 }), (error) => error.code === "NOT_ENOUGH_STARDUST");
assert.throws(() => service.expeditions.buyOblivion(player.id, { count: 0 }), (error) => error.code === "PURCHASE_INVALID");
assert.equal(service.expeditions.buyOblivion(player.id, { count: 2 }).wallet.stardust, 100);
assert.equal(service.expeditions.itemsOf(player.id).oblivion, 2);
assert.equal(service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" }).progress.stats.orientation, base.orientation + 12);
assert.equal(service.expeditions.itemsOf(player.id).oblivion, 1);
// Reprendre le même plan ne coûte rien.
service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" });
assert.equal(service.expeditions.itemsOf(player.id).oblivion, 1);
// En libre : au plus 12 points dans une stat et 20 en tout ; ajouter des points est gratuit, en retirer coûte un Parchemin.
const allocation = (bravoure, fortune) => ({ bravoure, endurance: 0, fortune, orientation: 0 });
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(13, 0) }), (error) => error.code === "ALLOCATION_INVALID");
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: { bravoure: 12, fortune: 12 } }), (error) => error.code === "ALLOCATION_INVALID");
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: { bravoure: 1.5 } }), (error) => error.code === "ALLOCATION_INVALID");
const free = service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 3) }).progress;
assert.equal(service.expeditions.itemsOf(player.id).oblivion, 0);
assert.deepEqual(free.plan.allocation, allocation(12, 3));
assert.equal(sum(free.stats), 55, "5 points restent à placer");
service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 8) });
assert.equal(sum(progressOf().stats), 60);
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(10, 8) }), (error) => error.code === "NOT_ENOUGH_ITEMS");
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "wizard" }), (error) => error.code === "PLAN_INVALID");
// Un niveau de plus en libre : 5 nouveaux points à placer, les anciens restent.
database.db.prepare("UPDATE card_progress SET level = 5 WHERE player_id = ? AND edition_id = ?").run(player.id, card);
assert.deepEqual([progressOf().plan.points, sum(progressOf().stats)], [25, 60]);
// Le plan d'une carte en expédition ne change pas avant son retour.
const view = service.expeditions.getExpeditions(player.id);
service.expeditions.startSolo(player.id, soloBody(view, [card, rares[1]]), "planned");
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 13) }), (error) => error.code === "EXPEDITION_CARD_BUSY");
assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: editionsOf("common")[0], plan: "guardian" }), (error) => error.code === "CARD_NOT_OWNED");
const history = service.getState(player.id).history;
assert.deepEqual(history.filter((entry) => entry.type === "card_plan_changed").map((entry) => [entry.details.plan, entry.details.oblivion]),
[["guardian", false], ["navigator", true], ["free", true], ["free", false]]);
assert.ok(history.some((entry) => entry.type === "oblivion_bought" && entry.details.count === 2 && entry.details.stardust === 300));
assert.equal(service.getState(player.id).shop.oblivionPrice, 150);
});
test("the one-way bridge turns stardust into Éclats at the configured rate", async (t) => {
const { service, player, admin, database } = expeditionService();
database.db.prepare("UPDATE players SET stardust = 40 WHERE id = ?").run(player.id);
const state = service.expeditions.convertStardust(player.id, { eclats: 10 });
assert.deepEqual([state.wallet.stardust, state.wallet.eclats], [10, 10]);
assert.throws(() => service.expeditions.convertStardust(player.id, { eclats: 4 }), (error) => error.code === "NOT_ENOUGH_STARDUST");
assert.throws(() => service.expeditions.convertStardust(player.id, { eclats: 0 }), (error) => error.code === "CONVERT_INVALID");
service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, progression: { ...service.expeditions.settings.progression, stardustPerEclat: 5 } });
assert.equal(service.expeditions.convertStardust(player.id, { eclats: 2 }).wallet.stardust, 0);
assert.ok(service.getState(player.id).history.some((entry) => entry.type === "eclats_converted" && entry.details.stardust === 30));
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 };
handler.service.db.prepare("UPDATE players SET stardust = 30 WHERE discord_id = 'dev-admin'").run();
const converted = await call(handler, { method: "POST", path: "/api/cards/eclats/convert", headers, body: { eclats: 3 } });
assert.equal(converted.status, 200);
assert.equal(converted.json.wallet.eclats, 3);
const upgrade = await call(handler, { method: "POST", path: "/api/cards/progress/upgrade", headers, body: { editionId: "nowhere", method: "eclats" } });
assert.equal(upgrade.json.error.code, "CARD_NOT_OWNED");
});
test("commons equip open slots, add stats with synergies, move between cards and enter the Grimoire", async (t) => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const [card, other] = rares;
const tagsOf = (editionId) => service.catalog.cards.find((item) => item.id === service.index.editions.get(editionId).cardId).expedition.tags;
const commons = editionsOf("common");
// Une commune qui partage une étiquette avec la carte, et une autre qui n'en partage aucune.
const partner = commons.find((editionId) => tagsOf(editionId).some((tag) => tagsOf(card).includes(tag)));
const stranger = commons.find((editionId) => !tagsOf(editionId).some((tag) => tagsOf(card).includes(tag)) && !tagsOf(editionId).some((tag) => tagsOf(other).includes(tag)));
database.transaction(() => [partner, stranger].forEach((editionId) => service.addCard(player.id, editionId)));
const before = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
assert.deepEqual([before.slots, before.maxSlots, before.equipment], [1, 3, []]);
assert.equal(service.getState(player.id).equipment.length, 2);
const equipped = service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: partner });
assert.equal(equipped.progress.equipment[0].editionId, partner);
assert.ok(equipped.progress.equipment[0].synergyTag);
const added = (stats) => Object.values(stats).reduce((sum, value) => sum + value, 0);
assert.equal(added(equipped.progress.stats) - added(equipped.progress.baseStats), 6 + 2);
assert.ok(service.expeditions.grimoireOf(player.id).some((entry) => entry.id.startsWith("pair:")));
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 1, equipmentEditionId: stranger }), (error) => error.code === "EQUIPMENT_SLOT_LOCKED");
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: other }), (error) => error.code === "EQUIPMENT_INVALID");
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: commons.at(-1) }), (error) => error.code === "CARD_NOT_OWNED");
// Une commune ne pose qu'à un endroit : l'équiper ailleurs la déplace.
const moved = service.expeditions.equip(player.id, { editionId: other, slot: 0, equipmentEditionId: partner });
assert.equal(moved.state.cardProgress.find((item) => item.editionId === card).equipment.length, 0);
assert.equal(moved.state.equipment.find((item) => item.editionId === partner).equippedOn, other);
service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: stranger });
const strangerStats = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
assert.equal(added(strangerStats.stats) - added(strangerStats.baseStats), 6);
// Les stats équipées partent en expédition, et l'équipement d'une carte en route ne change pas.
const view = service.expeditions.getExpeditions(player.id);
assert.deepEqual(view.cards.find((item) => item.editionId === card).stats, strangerStats.stats);
const started = service.expeditions.startSolo(player.id, soloBody(view, [card, other]), "equipped");
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: null }), (error) => error.code === "EXPEDITION_CARD_BUSY");
clock.now += 2 * HOUR;
service.expeditions.claim(player.id, started.expedition.id);
service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: null });
assert.deepEqual(service.getState(player.id).cardProgress.find((item) => item.editionId === card).equipment, []);
service.deleteAccount(player.id);
for (const table of ["card_equipment", "grimoire_entries"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(player.id).count, 0);
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 refused = await call(handler, { method: "PUT", path: "/api/cards/equipment", headers, body: { editionId: "nowhere", slot: 0, equipmentEditionId: null } });
assert.equal(refused.json.error.code, "CARD_NOT_OWNED");
});
test("resonances and destination affinity raise the score and are written to every player's Grimoire", () => {
const { service, player, open, database } = expeditionService();
open();
// Écho : le hamster de la Nébuleuse et sa version de l'Arcade des Rêves.
database.transaction(() => ["solar-seed-hamster-standard", "steel-ball-hamster-standard"].forEach((editionId) => service.addCard(player.id, editionId)));
const view = service.expeditions.getExpeditions(player.id);
const body = soloBody(view, ["solar-seed-hamster-standard", "steel-ball-hamster-standard"]);
const preview = service.expeditions.preview(player.id, body).preview;
assert.ok(preview.resonances.some((resonance) => resonance.type === "echo" && resonance.key === "personnage:hamster"));
assert.ok(preview.synergyPct >= 10);
service.expeditions.startSolo(player.id, body, "echo");
assert.ok(service.expeditions.getExpeditions(player.id).grimoire.some((entry) => entry.id === "resonance:echo:personnage:hamster"));
});
test("Discord alerts stay off until a player opts in, then queue group openings and returns once", async () => {
const context = expeditionService();
const { clock, service, player, open, rares, database } = context;
// Bot configuré : alertes disponibles ; lien des messages vers l'adresse publique.
service.expeditions.alertsAvailable = true;
service.expeditions.publicOrigin = "https://sokko.example";
open();
const friend = service.upsertPlayer({ discordId: "123456789012345678", displayName: "Friend" });
const silent = service.upsertPlayer({ discordId: "223456789012345678", displayName: "Silent" });
database.db.prepare("UPDATE players SET discord_id = '323456789012345678' WHERE id = ?").run(player.id);
database.transaction(() => editionsOf("rare").slice(8, 10).forEach((editionId) => service.addCard(friend.id, editionId)));
assert.deepEqual(service.getState(friend.id).alerts, { available: true, groupOpened: false, expeditionReturned: false });
assert.equal(service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: true }).alerts.groupOpened, true);
service.expeditions.setAlertPreferences(player.id, { groupOpened: true, expeditionReturned: true });
assert.throws(() => service.expeditions.setAlertPreferences(friend.id, { groupOpened: "yes" }), (error) => error.code === "ALERTS_INVALID");
// Groupe ouvert par le joueur : seul l'ami qui a activé l'alerte est prévenu, jamais le créateur ni le joueur silencieux.
const view = service.expeditions.getExpeditions(player.id);
const roles = view.destinations[0].groupRoles;
const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0], roles[0]), "alert-group").expeditions.groups[0];
let pending = service.expeditions.pendingAlerts();
assert.equal(pending.length, 1);
assert.equal(pending[0].discordId, "123456789012345678");
assert.match(pending[0].content, /Player ouvre un groupe d’expédition vers .+ Rejoignez-le sur le tableau de la Guilde : https:\/\/sokko\.example\/#\/cards\/expeditions$/);
assert.equal(silent.id === friend.id, false);
// Retours : une alerte par membre qui l'a activée, une seule fois.
service.expeditions.joinGroup(friend.id, group.id, { editionId: editionsOf("rare")[8], role: roles[1] });
service.expeditions.departGroup(player.id, group.id);
assert.equal(service.expeditions.queueReturnAlerts(), 0);
clock.now += 2 * HOUR;
assert.equal(service.expeditions.queueReturnAlerts(), 2);
assert.equal(service.expeditions.queueReturnAlerts(), 0);
// Envoi : un succès, un échec définitif, un échec qu'on réessaie.
const outcomes = [null, Object.assign(new Error("palico-bot answered 422"), { permanent: true }), new Error("timeout")];
const sent = [];
const send = async (discordId, content) => {
const outcome = outcomes.shift();
if (outcome) throw outcome;
sent.push({ discordId, content });
};
assert.equal(await dispatchAlerts(service.expeditions, send), 1);
pending = service.expeditions.pendingAlerts();
assert.equal(pending.length, 1);
assert.equal(pending[0].attempts, 1);
const rows = database.db.prepare("SELECT kind, sent_at, failed_at, attempts FROM alert_outbox ORDER BY created_at, kind").all();
assert.equal(rows.filter((row) => row.sent_at).length, 1);
assert.equal(rows.filter((row) => row.failed_at).length, 1);
// Coupées par l'administration : plus rien n'est mis en file.
service.expeditions.updateSettings(context.admin.id, { ...service.expeditions.settings, alerts: { enabled: false } });
assert.equal(service.getState(friend.id).alerts.available, false);
service.deleteAccount(friend.id);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM alert_outbox WHERE player_id = ?").get(friend.id).count, 0);
});
test("the alert sender posts to palico-bot with its key and flags permanent refusals", async () => {
const calls = [];
const answers = [204, 422, 503];
const send = createDiscordAlertSender({
url: "http://127.0.0.1:3000/api/notifications/dm",
key: "secret",
fetchImpl: async (url, options) => {
calls.push({ url, options });
return { ok: answers[0] < 300, status: answers.shift() };
}
});
await send("123456789012345678", "Bonjour");
assert.equal(calls[0].options.headers.Authorization, "Bearer secret");
assert.deepEqual(JSON.parse(calls[0].options.body), { userId: "123456789012345678", content: "Bonjour" });
await assert.rejects(send("123456789012345678", "x"), (error) => error.permanent === true);
await assert.rejects(send("123456789012345678", "x"), (error) => error.permanent === false);
});
test("the alerts API saves a player's choices, and the server dispatches queued alerts through its sender", async (t) => {
const delivered = [];
const handler = createCardsApiHandler({
projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test", CARDS_PUBLIC_ORIGIN: "http://localhost:5173" }, random: () => 0,
sendAlert: async (discordId, content) => { delivered.push({ discordId, content }); }
});
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 saved = await call(handler, { method: "PUT", path: "/api/cards/alerts", headers, body: { groupOpened: true, expeditionReturned: false } });
assert.equal(saved.status, 200);
assert.deepEqual(saved.json.alerts, { available: true, groupOpened: true, expeditionReturned: false });
const refused = await call(handler, { method: "PUT", path: "/api/cards/alerts", headers, body: {} });
assert.equal(refused.json.error.code, "ALERTS_INVALID");
const { service } = handler;
const friend = service.upsertPlayer({ discordId: "123456789012345678", displayName: "Friend" });
service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: true });
service.database.transaction(() => service.expeditions.enqueueInTx(friend.id, "group_opened", "Un groupe vous attend."));
await handler.runAlerts();
assert.deepEqual(delivered, [{ discordId: "123456789012345678", content: "Un groupe vous attend." }]);
});
test("objects add bonus destinations, recall an expedition with an anchor and engrave equipment", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const give = (items) => database.transaction(() => service.expeditions.addItemsInTx(player.id, items));
// Étoile guide : une 5e destination, pour ce joueur seulement ; une seule par jour.
give(["guideStar", "guideStar", "anchor", "engraving", "fragment", "fragment", "fragment", "fragment"]);
const before = service.expeditions.getExpeditions(player.id);
assert.equal(before.items.guideStar, 2);
const added = service.expeditions.addBonusDestination(player.id, { item: "guideStar" }).expeditions;
assert.equal(added.destinations.length, 5);
const bonus = added.destinations.find((destination) => destination.bonusSlot === "5");
assert.ok(!before.destinations.some((destination) => destination.id === bonus.id));
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "guideStar" }), (error) => error.code === "BONUS_ALREADY_USED");
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "skyChart" }), (error) => error.code === "NOT_ENOUGH_ITEMS");
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "anchor" }), (error) => error.code === "ITEM_INVALID");
// Carte au trésor : 4 fragments ouvrent une destination cachée, au butin multiplié.
const hidden = service.expeditions.addBonusDestination(player.id, { item: "fragment" }).expeditions.destinations.find((destination) => destination.bonusSlot === "hidden");
assert.ok(["crimson-passage", "lost-observatory"].includes(hidden.id));
assert.equal(service.expeditions.getExpeditions(player.id).items.fragment, 0);
// Les destinations bonus restent à ce joueur.
assert.ok(service.expeditions.getExpeditions(service.upsertPlayer({ discordId: "other", displayName: "Other" }).id).destinations.every((destination) => !destination.bonusSlot));
// Ancre : rappel à mi-chemin, la moitié des Éclats et de la poussière, sans paquet ni objet.
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), { destinationId: hidden.id, durationHours: 12 }), "hidden-trip");
assert.equal(started.expedition.destination.id, hidden.id);
clock.now += 6 * HOUR;
const recalled = service.expeditions.recallExpedition(player.id, started.expedition.id);
assert.equal(recalled.expedition.status, "returned");
assert.equal(recalled.expedition.reward.recalledPct, 50);
assert.deepEqual([recalled.expedition.reward.packs, recalled.expedition.reward.items], [[], []]);
assert.throws(() => service.expeditions.recallExpedition(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_RETURNED");
service.expeditions.claim(player.id, started.expedition.id);
// Burin : une étiquette gravée crée la synergie avec la carte équipée.
const tagsOf = (editionId) => service.catalog.cards.find((item) => item.id === service.index.editions.get(editionId).cardId).expedition.tags;
const stranger = editionsOf("common").find((editionId) => !tagsOf(editionId).some((tag) => tagsOf(rares[0]).includes(tag)));
database.transaction(() => service.addCard(player.id, stranger));
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: stranger });
assert.equal(service.getState(player.id).cardProgress.find((item) => item.editionId === rares[0]).equipment[0].synergyTag, null);
assert.throws(() => service.expeditions.engrave(player.id, { editionId: stranger, tag: tagsOf(stranger)[0] }), (error) => error.code === "ENGRAVING_INVALID");
const engraved = service.expeditions.engrave(player.id, { editionId: stranger, tag: tagsOf(rares[0])[0] });
assert.equal(engraved.cardProgress.find((item) => item.editionId === rares[0]).equipment[0].synergyTag, tagsOf(rares[0])[0]);
assert.throws(() => service.expeditions.engrave(player.id, { editionId: stranger, tag: "theme:voyage" }), (error) => error.code === "ENGRAVING_EXISTS");
assert.ok(service.getState(player.id).history.filter((entry) => entry.type === "item_used").length >= 4);
service.deleteAccount(player.id);
for (const table of ["player_items", "equipment_engravings", "player_bonus_destinations"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(player.id).count, 0);
});
test("returned expeditions credit the objects they bring back", () => {
const { clock, service, player, open, rares } = expeditionService();
open({ items: { ...DEFAULT_EXPEDITION_SETTINGS.items, chancePerHourPermille: 1000, maxPerExpedition: 2, orientationPerSlot: 0 } });
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "objects");
clock.now += 2 * HOUR;
const claimed = service.expeditions.claim(player.id, started.expedition.id);
assert.equal(claimed.expedition.reward.items.length, 2);
// Le plan d'atelier n'est pas rapporté tant que l'atelier n'a pas de commune de pouvoir illustrée.
assert.ok(!claimed.expedition.reward.items.includes("plan"));
const items = service.expeditions.getExpeditions(player.id).items;
assert.equal(Object.values(items).reduce((sum, count) => sum + count, 0), 2);
});
// Toutes les cartes des Carnets n'ont pas encore leur illustration : les tests leur en donnent une, ou la leur retirent,
// en mémoire, pour ce service seulement.
function illustrateLogbooks(service) {
for (const card of service.catalog.cards.filter((item) => item.collectionId === "watchers-logbooks")) card.image = `/static/img/cards/watchers-logbooks/${card.id}.webp`;
}
function unillustrateLogbooks(service) {
for (const card of service.catalog.cards.filter((item) => item.collectionId === "watchers-logbooks")) {
delete card.image;
delete card.fullImage;
}
}
test("the Carnets des Veilleurs never come from packs, and their cards only drop once illustrated", () => {
const { clock, service, admin, player, open, rares } = expeditionService();
assert.throws(() => service.setCollectionActive(admin.id, "watchers-logbooks", true), (error) => error.code === "EXPEDITION_COLLECTION");
assert.throws(() => service.openPack(player.id, "watchers-logbooks", "logbook-pack"), (error) => error.code === "EXPEDITION_COLLECTION");
assert.throws(() => service.createCampaign(admin.id, { name: "Carnets", code: "CARNETS", reward: { items: [{ type: "pack", collectionId: "watchers-logbooks" }] } }), /expédition/);
open({ loot: { ...service.expeditions.settings.loot, cardPerHourPermille: 1000, maxCards: 1 } });
const view = service.expeditions.getExpeditions(player.id);
// Sans illustration, aucune carte des Carnets n'est rapportée, même avec une chance pleine.
unillustrateLogbooks(service);
const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "no-art");
clock.now += 2 * HOUR;
const logbooksOf = (cards) => cards.filter((editionId) => service.catalog.cards.find((card) => card.id === service.index.editions.get(editionId).cardId).collectionId === "watchers-logbooks");
assert.deepEqual(logbooksOf(service.expeditions.claim(player.id, first.expedition.id).expedition.reward.cards), []);
illustrateLogbooks(service);
const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "with-art");
clock.now += 2 * HOUR;
const reward = service.expeditions.claim(player.id, second.expedition.id).expedition.reward;
assert.equal(logbooksOf(reward.cards).length, 1);
assert.ok(service.quantityOf(player.id, logbooksOf(reward.cards)[0]) >= 1);
});
test("power commons equip one per card, change travel time and hide requirements, and the workshop crafts them", () => {
const { service, player, open, rares, database } = expeditionService();
open();
illustrateLogbooks(service);
const [longsight, compass] = ["watchers-longsight-standard", "mad-compass-standard"];
database.transaction(() => {
[longsight, compass].forEach((editionId) => service.addCard(player.id, editionId));
service.expeditions.writeProgress(player.id, rares[0], { level: 6, fieldXp: 0 });
});
// Puissance 70 : deux emplacements ; un seul pouvoir par carte.
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: longsight });
assert.throws(() => service.expeditions.equip(player.id, { editionId: rares[0], slot: 1, equipmentEditionId: compass }), (error) => error.code === "POWER_LIMIT");
const view = service.expeditions.getExpeditions(player.id);
assert.deepEqual(view.cards.find((card) => card.editionId === rares[0]).powers, ["longsight"]);
const body = soloBody(view, rares.slice(0, 2), { durationHours: 6 });
assert.equal(service.expeditions.preview(player.id, body).preview.travelHours, 8);
const started = service.expeditions.startSolo(player.id, body, "longsight");
assert.equal(started.expedition.returnsAt - started.expedition.departsAt, 8 * HOUR);
service.expeditions.cancel(service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true }).id, started.expedition.id);
// Boussole folle : l'aperçu ne montre ni exigences ni résultat.
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: compass });
const hidden = service.expeditions.preview(player.id, body).preview;
assert.equal(hidden.hiddenRequirements, true);
assert.equal(hidden.requirements, undefined);
// Atelier : un plan et 3 doublons de communes donnent une commune de pouvoir illustrée.
const commons = editionsOf("common").slice(0, 2);
database.transaction(() => {
commons.forEach((editionId) => { service.addCard(player.id, editionId); service.addCard(player.id, editionId); });
service.addCard(player.id, commons[1]);
service.expeditions.addItemsInTx(player.id, ["plan"]);
});
assert.throws(() => service.expeditions.craft(player.id, { editionIds: [commons[0], commons[0], commons[1]] }), (error) => error.code === "NOT_A_DUPLICATE");
assert.throws(() => service.expeditions.craft(player.id, { editionIds: [rares[0], commons[1], commons[1]] }), (error) => error.code === "ATELIER_INVALID");
const crafted = service.expeditions.craft(player.id, { editionIds: [commons[0], commons[1], commons[1]] });
assert.ok(service.index.cards.get(service.index.editions.get(crafted.crafted).cardId).expedition.equipment.power);
assert.equal(crafted.state.items.plan, 0);
assert.equal(service.quantityOf(player.id, commons[1]), 1);
});