The 669 // comments sitting right above a function, method or hook become /** */ blocks, unchanged in wording; eslint directives stay right above the line they target. website/AGENTS.md now asks for JSDoc on function comments and // inside function bodies. ExpeditionPlanner.jsx grew past 300 lines and gets its full header, as the header test requires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
588 lines
40 KiB
JavaScript
588 lines
40 KiB
JavaScript
/**
|
||
* @file Catalogue de Sokko TCG : chargement et validation de catalog.json, génération des finitions, publication
|
||
* avec le contenu réglé en base, et petites aides de lecture (index, éditions tirables, variations mythiques).
|
||
*
|
||
* Contexte : deux catalogues coexistent. Le catalogue versionné (catalog.json, préparé par `loadCardsCatalog`)
|
||
* et le catalogue publié (`buildPublishedCatalog`), qui y ajoute variations mythiques, collections ouvertes et
|
||
* taux de tirage enregistrés par l'administration. Le navigateur reçoit `publicCatalog(publié)` par `/config`.
|
||
* Points d'entrée : `loadCardsCatalog`, `validateCardsCatalog`, `buildPublishedCatalog`, `publicCatalog`,
|
||
* `createCatalogIndex`, `collectionDrawableEditions`.
|
||
* Utilisé par : api.js et service.js ; game-rules.js, rewards.js, team-rules.js ; les scripts d'équilibrage et
|
||
* les tests.
|
||
* Dépend de : expedition-rules.js (stats et profils d'expédition, pour la validation).
|
||
* Attention :
|
||
* - `assertVersionedCatalogScope` refuse dans catalog.json ce qui appartient à la base (finitions, taux de
|
||
* tirage, état des collections, éditions mythiques non promotionnelles).
|
||
* - Les finitions ne sont pas déclarées : une par combinaison format × effet holographique × palette.
|
||
* - Une erreur de validation désactive tout le TCG (server.mjs le démarre sans lui) : son message doit dire
|
||
* quelle carte ou collection corriger.
|
||
* @see .claude/skills/new-card/SKILL.md
|
||
* @see docs/collections/archipel-lore.md
|
||
*/
|
||
|
||
import { readFileSync } from "node:fs";
|
||
import { POWER_IDS, STAT_IDS } from "./expedition-rules.js";
|
||
|
||
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
|
||
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
|
||
// `expedition` : collection qui ne s'obtient qu'en expédition (jamais en paquet, en boutique ni par un code).
|
||
const PACK_CATEGORIES = new Set(["permanent", "event", "shop", "expedition"]);
|
||
const PACK_BACK_SYMBOLS = new Set(["star", "rift", "orbit"]);
|
||
const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
|
||
// Formats d'une variation mythique : le premier est le format de référence ; `full-art` utilise `card.fullImage` sur toute la carte.
|
||
const STANDARD_FORMAT = "standard";
|
||
export const FULL_ART_FORMAT = "full-art";
|
||
// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation.
|
||
export const MATCH_HOLO_PALETTE_ID = "match-holo";
|
||
// Paliers d'une variation mythique, de 1 à 5 : l'intensité de la palette, commune à tous les effets, et le palier propre à
|
||
// l'effet (vitesse, amplitude…) quand il en déclare un. Le palier central, 3, est la valeur par défaut et le rendu de référence.
|
||
export const EFFECT_TUNING_STEPS = 5;
|
||
export const DEFAULT_EFFECT_TUNING = 3;
|
||
export const isEffectTuning = (value) => Number.isInteger(value) && value >= 1 && value <= EFFECT_TUNING_STEPS;
|
||
const validTuningScale = (scale) => typeof scale?.label === "string" && scale.label.length > 0 && Array.isArray(scale.levels)
|
||
&& scale.levels.length === EFFECT_TUNING_STEPS && scale.levels.every((label) => typeof label === "string" && label.length > 0);
|
||
|
||
// Particules persistantes d'une variation mythique : une animation du catalogue (`flareEffects`), un motif si elle en
|
||
// déclare, une palette holographique (celle de la finition par défaut), une zone (`flareScopes`) et les paliers qu'elle
|
||
// déclare. Les réglages par défaut (palier central, premier motif, palette héritée, zone « art ») ne sont pas publiés.
|
||
export const DEFAULT_FLARE_SCOPE = "art";
|
||
export const FLARE_TUNING_KEYS = ["intensity", "level", "count"];
|
||
const FLARE_TUNING_FIELDS = { intensity: "flareIntensity", level: "flareLevel", count: "flareCount" };
|
||
|
||
function validateFlares(catalog) {
|
||
const scopeIds = requireUnique(catalog.flareScopes || [], "flareScopes");
|
||
if (catalog.flareScopes?.[0]?.id !== DEFAULT_FLARE_SCOPE || catalog.flareScopes.some((scope) => !scope.label)) throw new TypeError(`Cards catalog flareScopes must start with ${DEFAULT_FLARE_SCOPE} and label every scope.`);
|
||
requireUnique(catalog.flareEffects || [], "flareEffects");
|
||
for (const effect of catalog.flareEffects || []) {
|
||
if (!effect.label) throw new TypeError(`Flare effect ${effect.id} needs a label.`);
|
||
if (effect.motifs != null) {
|
||
if (!Array.isArray(effect.motifs) || !effect.motifs.length || effect.motifs.some((motif) => !motif.label)) throw new TypeError(`Flare effect ${effect.id} needs labelled motifs.`);
|
||
requireUnique(effect.motifs, `flare effect ${effect.id} motifs`);
|
||
}
|
||
if (!Array.isArray(effect.tunings) || effect.tunings.some((tuning) => !FLARE_TUNING_KEYS.includes(tuning.key) || !validTuningScale(tuning))
|
||
|| new Set(effect.tunings.map((tuning) => tuning.key)).size !== effect.tunings.length) {
|
||
throw new TypeError(`Flare effect ${effect.id} tunings need a known key, a label and ${EFFECT_TUNING_STEPS} level labels.`);
|
||
}
|
||
}
|
||
return scopeIds;
|
||
}
|
||
|
||
/**
|
||
* Réglages normalisés d'un flare, ou un code d'erreur : `{ flare }` (null pour « aucune particule ») ou `{ error }`. Un palier
|
||
* que l'animation ne déclare pas revient au centre ; sans motif, celle qui en déclare prend le premier ; un motif inconnu est
|
||
* refusé ; une animation sans motifs ignore celui qu'on lui donne.
|
||
*/
|
||
export function normalizeFlare(catalog, input) {
|
||
if (!input?.id) return { flare: null };
|
||
const effect = catalog.flareEffects?.find((item) => item.id === input.id);
|
||
if (!effect) return { error: "FLARE_UNKNOWN" };
|
||
const motifId = effect.motifs ? input.motifId || effect.motifs[0].id : null;
|
||
if (effect.motifs && !effect.motifs.some((motif) => motif.id === motifId)) return { error: "FLARE_MOTIF_INVALID" };
|
||
const paletteId = input.paletteId && input.paletteId !== MATCH_HOLO_PALETTE_ID ? input.paletteId : null;
|
||
if (paletteId && !catalog.effectPalettes.some((palette) => palette.id === paletteId)) return { error: "FLARE_PALETTE_INVALID" };
|
||
const scope = input.scope || DEFAULT_FLARE_SCOPE;
|
||
if (!catalog.flareScopes?.some((item) => item.id === scope)) return { error: "FLARE_SCOPE_INVALID" };
|
||
const declared = new Set(effect.tunings.map((tuning) => tuning.key));
|
||
const tunings = {};
|
||
for (const key of FLARE_TUNING_KEYS) {
|
||
const value = input[key] ?? DEFAULT_EFFECT_TUNING;
|
||
if (!isEffectTuning(value)) return { error: "FLARE_TUNING_INVALID" };
|
||
tunings[key] = declared.has(key) ? value : DEFAULT_EFFECT_TUNING;
|
||
}
|
||
return { flare: { id: effect.id, motifId, paletteId, scope, ...tunings } };
|
||
}
|
||
|
||
/** Champs publiés sur l'édition pour un flare normalisé (ou des réglages enregistrés qui ne valent plus rien : aucun champ). */
|
||
export function publishedFlare(catalog, stored) {
|
||
const { flare } = normalizeFlare(catalog, stored);
|
||
if (!flare) return {};
|
||
const effect = catalog.flareEffects.find((item) => item.id === flare.id);
|
||
return {
|
||
flareId: flare.id,
|
||
...(flare.motifId && flare.motifId !== effect.motifs[0].id ? { flareMotifId: flare.motifId } : {}),
|
||
...(flare.paletteId ? { flarePaletteId: flare.paletteId } : {}),
|
||
...(flare.scope !== DEFAULT_FLARE_SCOPE ? { flareScope: flare.scope } : {}),
|
||
...Object.fromEntries(FLARE_TUNING_KEYS.filter((key) => flare[key] !== DEFAULT_EFFECT_TUNING).map((key) => [FLARE_TUNING_FIELDS[key], flare[key]]))
|
||
};
|
||
}
|
||
|
||
// Fichiers d'illustration qu'une finition demande à une carte : l'illustration pleine pour le format pleine illustration, et
|
||
// pour un effet à calques (`layers`, la Parallaxe prismatique) le héros détouré et le décor dans ce format. Renvoie les
|
||
// suffixes manquants (`__full`, `__cutout`, `__full__backdrop`…), vide si la carte peut porter la finition.
|
||
const FORMAT_FILES = {
|
||
[STANDARD_FORMAT]: { suffix: "", image: "image", cutout: "cutoutImage", backdrop: "backdropImage" },
|
||
[FULL_ART_FORMAT]: { suffix: "__full", image: "fullImage", cutout: "fullCutoutImage", backdrop: "fullBackdropImage" }
|
||
};
|
||
|
||
export function missingFinishFiles(catalog, card, finishId) {
|
||
const finish = catalog.finishes.find((item) => item.id === finishId);
|
||
const files = FORMAT_FILES[finish?.formatId || STANDARD_FORMAT];
|
||
if (!files) return [];
|
||
if (!card?.[files.image]) return [files.suffix || "image"];
|
||
if (!catalog.effectPresets.find((preset) => preset.id === finish?.effectPresetId)?.layers) return [];
|
||
return [[files.cutout, "__cutout"], [files.backdrop, "__backdrop"]].filter(([field]) => !card[field]).map(([, name]) => `${files.suffix}${name}`);
|
||
}
|
||
|
||
const EDITION_FLARE_FIELDS = ["flareId", "flareMotifId", "flarePaletteId", "flareScope", ...Object.values(FLARE_TUNING_FIELDS)];
|
||
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
|
||
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
|
||
// Étiquettes d'expédition : vocabulaire fermé, par famille (personnage, lieu, thème, objet).
|
||
export const EXPEDITION_TAG_PATTERN = /^(personnage|lieu|theme|objet):[a-z0-9-]+$/;
|
||
const MAX_CARD_TAGS = 8;
|
||
// Équipement d'une commune : un budget fixe de 6 points, réparti selon l'une de ces formes (valeurs triées).
|
||
export const EQUIPMENT_BUDGET = 6;
|
||
const EQUIPMENT_FORMS = new Set(["6", "3,3", "2,2,2", "8,-2"]);
|
||
// Chaque carte rare ou mieux doit partager une étiquette avec au moins ce nombre de communes (ses équipements en synergie).
|
||
export const MIN_COMPATIBLE_COMMONS = 3;
|
||
// Carte de destination : elle débloque une destination des Expéditions. Toujours rare, elle ne part jamais en équipe
|
||
// (ni étiquettes, ni profil, ni équipement) et s'affiche en pleine illustration.
|
||
export const DESTINATION_CARD_KIND = "destination";
|
||
const DESTINATION_ID_PATTERN = /^[a-z0-9-]+$/;
|
||
export const isDestinationCard = (card) => card?.kind === DESTINATION_CARD_KIND;
|
||
|
||
function requireUnique(items, label) {
|
||
const ids = new Set();
|
||
for (const item of items) {
|
||
if (!item?.id || typeof item.id !== "string") throw new TypeError(`${label}: every item needs a string id.`);
|
||
if (ids.has(item.id)) throw new TypeError(`${label}: duplicate id ${item.id}.`);
|
||
ids.add(item.id);
|
||
}
|
||
return ids;
|
||
}
|
||
|
||
// Profil d'expédition : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100, 50 au plus par stat
|
||
// (une carte reste jouable sur plusieurs stats ; les vocations du joueur la spécialisent davantage).
|
||
export const MAX_PROFILE_SHARE = 50;
|
||
export function validExpeditionProfile(profile) {
|
||
if (!profile || typeof profile !== "object" || Array.isArray(profile) || Object.keys(profile).length !== STAT_IDS.length) return false;
|
||
if (STAT_IDS.some((stat) => !Number.isInteger(profile[stat]) || profile[stat] < 0 || profile[stat] > MAX_PROFILE_SHARE)) return false;
|
||
return STAT_IDS.reduce((sum, stat) => sum + profile[stat], 0) === 100;
|
||
}
|
||
|
||
function validateExpeditionTags(tags) {
|
||
if (!Array.isArray(tags) || !tags.length) throw new TypeError("Cards catalog expeditionTags must be a non-empty array.");
|
||
const ids = requireUnique(tags, "expeditionTags");
|
||
for (const tag of tags) {
|
||
if (!EXPEDITION_TAG_PATTERN.test(tag.id) || typeof tag.label !== "string" || !tag.label || tag.label.length > 40) {
|
||
throw new TypeError(`Invalid expedition tag ${tag.id}: family:name id and a 1 to 40 character label.`);
|
||
}
|
||
}
|
||
return ids;
|
||
}
|
||
|
||
function validateCardExpedition(card, tagIds) {
|
||
const expedition = card.expedition;
|
||
if (!expedition || !Array.isArray(expedition.tags) || !expedition.tags.length || expedition.tags.length > MAX_CARD_TAGS) {
|
||
throw new TypeError(`Card ${card.id} needs 1 to ${MAX_CARD_TAGS} expedition tags.`);
|
||
}
|
||
if (new Set(expedition.tags).size !== expedition.tags.length) throw new TypeError(`Card ${card.id} repeats an expedition tag.`);
|
||
const unknown = expedition.tags.find((tag) => !tagIds.has(tag));
|
||
if (unknown) throw new TypeError(`Card ${card.id} uses unknown expedition tag ${unknown}.`);
|
||
if (expedition.profile != null && !validExpeditionProfile(expedition.profile)) throw new TypeError(`Card ${card.id} expedition profile must give integer shares of the four stats summing to 100, at most ${MAX_PROFILE_SHARE} each.`);
|
||
const synergyStat = expedition.equipment?.synergyStat;
|
||
if (synergyStat != null && !STAT_IDS.includes(synergyStat)) throw new TypeError(`Card ${card.id} synergyStat must be one of the four stats.`);
|
||
if (expedition.equipment?.power != null) {
|
||
if (!POWER_IDS.includes(expedition.equipment.power) || expedition.equipment.stats != null) throw new TypeError(`Card ${card.id} power equipment must name a known power and carry no stats.`);
|
||
if (synergyStat == null) throw new TypeError(`Card ${card.id} power equipment needs a synergyStat: it has no stats to choose from.`);
|
||
} else if (expedition.equipment != null) {
|
||
const stats = expedition.equipment.stats;
|
||
const values = stats && typeof stats === "object" && !Array.isArray(stats) ? Object.entries(stats) : null;
|
||
if (!values?.length || values.some(([stat, value]) => !STAT_IDS.includes(stat) || !Number.isInteger(value) || value === 0)
|
||
|| !EQUIPMENT_FORMS.has(values.map(([, value]) => value).sort((a, b) => b - a).join(","))) {
|
||
throw new TypeError(`Card ${card.id} equipment must spread ${EQUIPMENT_BUDGET} points as +6, +3/+3, +2/+2/+2 or +8/−2.`);
|
||
}
|
||
// La synergie renforce une stat que l'objet apporte ; à égalité, elle est choisie, jamais laissée à l'ordre des stats.
|
||
const top = Math.max(...values.map(([, value]) => value));
|
||
if (synergyStat != null && !(stats[synergyStat] > 0)) throw new TypeError(`Card ${card.id} synergyStat must be a stat its equipment raises.`);
|
||
if (synergyStat == null && values.filter(([, value]) => value === top).length > 1) throw new TypeError(`Card ${card.id} equipment ties on its best stat and needs a synergyStat.`);
|
||
}
|
||
}
|
||
|
||
/** Les communes sont les équipements, les autres cartes ne le sont pas ; chaque carte rare ou mieux a des équipements en synergie. */
|
||
function validateEquipmentCoverage(catalog) {
|
||
const rarityOf = new Map(catalog.editions.filter((edition) => !edition.promotional && edition.rarity !== "mythic").map((edition) => [edition.cardId, edition.rarity]));
|
||
const commons = [];
|
||
for (const card of catalog.cards.filter((item) => !isDestinationCard(item))) {
|
||
const common = rarityOf.get(card.id) === "common";
|
||
if (common && !card.expedition.equipment) throw new TypeError(`Common card ${card.id} needs equipment stats.`);
|
||
if (!common && card.expedition.equipment) throw new TypeError(`Card ${card.id} is not a common and cannot be equipment.`);
|
||
if (common) commons.push(card);
|
||
}
|
||
for (const card of catalog.cards) {
|
||
if (isDestinationCard(card) || !rarityOf.get(card.id) || rarityOf.get(card.id) === "common") continue;
|
||
const compatible = commons.filter((common) => common.expedition.tags.some((tag) => card.expedition.tags.includes(tag))).length;
|
||
if (compatible < MIN_COMPATIBLE_COMMONS) throw new TypeError(`Card ${card.id} shares a tag with only ${compatible} commons (at least ${MIN_COMPATIBLE_COMMONS} needed for equipment synergies).`);
|
||
}
|
||
}
|
||
|
||
export function validateCardsCatalog(catalog) {
|
||
if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1.");
|
||
for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) {
|
||
if (!Array.isArray(catalog[key]) || !catalog[key].length) throw new TypeError(`Cards catalog ${key} must be a non-empty array.`);
|
||
}
|
||
const rarityIds = requireUnique(catalog.rarities, "rarities");
|
||
const effectPresetIds = requireUnique(catalog.effectPresets, "effectPresets");
|
||
const effectPaletteIds = requireUnique(catalog.effectPalettes, "effectPalettes");
|
||
const particleShapeIds = requireUnique(catalog.particleShapes, "particleShapes");
|
||
const particlePaletteIds = requireUnique(catalog.particlePalettes, "particlePalettes");
|
||
const particlePresetIds = requireUnique(catalog.particlePresets, "particlePresets");
|
||
requireUnique(catalog.openingEffects, "openingEffects");
|
||
const finishIds = requireUnique(catalog.finishes, "finishes");
|
||
const collectionIds = requireUnique(catalog.collections, "collections");
|
||
const cardIds = requireUnique(catalog.cards, "cards");
|
||
requireUnique(catalog.editions, "editions");
|
||
const expeditionTagIds = validateExpeditionTags(catalog.expeditionTags);
|
||
if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities.");
|
||
// Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet.
|
||
validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights");
|
||
|
||
for (const preset of catalog.effectPresets) {
|
||
if (!preset.label || preset.kind !== "holographic") throw new TypeError(`Invalid holographic effect preset ${preset.id}.`);
|
||
if (preset.level != null && !validTuningScale(preset.level)) throw new TypeError(`Holographic effect preset ${preset.id} level needs a label and ${EFFECT_TUNING_STEPS} level labels.`);
|
||
if (preset.layers != null && typeof preset.layers !== "boolean") throw new TypeError(`Holographic effect preset ${preset.id} layers flag must be a boolean.`);
|
||
}
|
||
if (!validTuningScale(catalog.effectIntensity)) throw new TypeError(`Cards catalog effectIntensity needs a label and ${EFFECT_TUNING_STEPS} level labels.`);
|
||
validateFlares(catalog);
|
||
if (catalog.cardFormats?.[0]?.id !== STANDARD_FORMAT || catalog.cardFormats.some((format) => !format.label) || !catalog.cardFormats.some((format) => format.id === FULL_ART_FORMAT)) {
|
||
throw new TypeError("Cards catalog must declare the standard and full-art formats.");
|
||
}
|
||
for (const palette of catalog.effectPalettes) {
|
||
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length !== 7
|
||
|| new Set(palette.colors).size !== 7
|
||
|| palette.colors.some((color) => !COLOR_PATTERN.test(color)) || !COLOR_PATTERN.test(palette.highlight)) {
|
||
throw new TypeError(`Invalid effect palette ${palette.id}.`);
|
||
}
|
||
}
|
||
for (const shape of catalog.particleShapes) {
|
||
if (!shape.label || !PARTICLE_SHAPE_KINDS.has(shape.kind)) throw new TypeError(`Invalid particle shape ${shape.id}.`);
|
||
}
|
||
for (const palette of catalog.particlePalettes) {
|
||
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length < 1 || palette.colors.length > 7
|
||
|| palette.colors.some((color) => !COLOR_PATTERN.test(color))) {
|
||
throw new TypeError(`Invalid particle palette ${palette.id}.`);
|
||
}
|
||
}
|
||
for (const preset of catalog.particlePresets) {
|
||
if (!preset.label || !particleShapeIds.has(preset.shapeId) || !particlePaletteIds.has(preset.paletteId)
|
||
|| !Number.isInteger(preset.count) || preset.count < 1 || preset.count > 64) {
|
||
throw new TypeError(`Invalid particle preset ${preset.id}.`);
|
||
}
|
||
}
|
||
// Un seul effet d'ouverture par rareté ; les variantes mythiques passent par les réglages d'ouverture.
|
||
const openingEffectRarities = new Set();
|
||
for (const effect of catalog.openingEffects) {
|
||
if (!effect.label || !RARITY_IDS.has(effect.rarity) || effect.rarity === "common"
|
||
|| !Array.isArray(effect.auraColors) || effect.auraColors.length < 1 || effect.auraColors.length > 7
|
||
|| effect.auraColors.some((color) => !COLOR_PATTERN.test(color))
|
||
|| Object.hasOwn(effect, "collectionId")
|
||
|| !Number.isInteger(effect.auraDurationMs) || effect.auraDurationMs < 0 || effect.auraDurationMs > 2_000
|
||
|| !Number.isInteger(effect.particleDurationMs) || effect.particleDurationMs < 0 || effect.particleDurationMs > 2_000) {
|
||
throw new TypeError(`Invalid opening effect ${effect.id}.`);
|
||
}
|
||
if (effect.particlePresetId != null && !particlePresetIds.has(effect.particlePresetId)) throw new TypeError(`Opening effect ${effect.id} needs a known particle preset.`);
|
||
if (effect.particlePresetId == null && effect.particleDurationMs !== 0) throw new TypeError(`Opening effect ${effect.id} cannot animate missing particles.`);
|
||
if (openingEffectRarities.has(effect.rarity)) throw new TypeError(`Duplicate opening effect for rarity ${effect.rarity}.`);
|
||
openingEffectRarities.add(effect.rarity);
|
||
}
|
||
for (const rarity of ["rare", "epic", "legendary", "mythic"]) {
|
||
if (!openingEffectRarities.has(rarity)) throw new TypeError(`Cards catalog needs an opening effect for rarity ${rarity}.`);
|
||
}
|
||
const defaultMythicOpening = catalog.openingEffects.find((effect) => effect.rarity === "mythic");
|
||
if (!particlePresetIds.has(defaultMythicOpening.particlePresetId)) throw new TypeError("The default mythic opening effect needs particles.");
|
||
for (const finish of catalog.finishes) {
|
||
if (!finish.label
|
||
|| !Object.hasOwn(finish, "effectPresetId")
|
||
|| !Object.hasOwn(finish, "paletteId")) {
|
||
throw new TypeError(`Invalid finish ${finish.id}.`);
|
||
}
|
||
const hasEffect = finish.effectPresetId != null;
|
||
if (hasEffect && !effectPresetIds.has(finish.effectPresetId)) throw new TypeError(`Finish ${finish.id} needs a known holographic effect.`);
|
||
if (hasEffect && !effectPaletteIds.has(finish.paletteId)) throw new TypeError(`Holographic finish ${finish.id} needs a known palette.`);
|
||
if (!hasEffect && finish.paletteId != null) throw new TypeError(`Finish ${finish.id} cannot use a palette without a holographic effect.`);
|
||
}
|
||
|
||
for (const collection of catalog.collections) {
|
||
if (!collection.name || !collection.systemName || !collection.description || (collection.active != null && typeof collection.active !== "boolean") || typeof collection.promotional !== "boolean") {
|
||
throw new TypeError(`Invalid collection ${collection.id}.`);
|
||
}
|
||
if (!PACK_CATEGORIES.has(collection.packCategory)
|
||
|| !PACK_BACK_SYMBOLS.has(collection.back?.symbol)
|
||
|| !PACK_BACK_IMAGE_PATTERN.test(collection.back?.image)
|
||
|| !COLOR_PATTERN.test(collection.back?.primary)
|
||
|| !COLOR_PATTERN.test(collection.back?.secondary)) {
|
||
throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`);
|
||
}
|
||
if (!validExpeditionProfile(collection.expedition?.profile)) throw new TypeError(`Collection ${collection.id} needs an expedition profile giving integer shares of the four stats summing to 100.`);
|
||
}
|
||
|
||
for (const card of catalog.cards) {
|
||
if (!collectionIds.has(card.collectionId)) throw new TypeError(`Unknown collection for card ${card.id}.`);
|
||
if (!card.name || card.name.length > 40) throw new TypeError(`Card ${card.id} name must contain 1 to 40 characters.`);
|
||
if (!card.description || card.description.length > 200) throw new TypeError(`Card ${card.id} description must contain 1 to 200 characters.`);
|
||
if (card.image != null && !CARD_IMAGE_PATTERN.test(card.image)) throw new TypeError(`Card ${card.id} image must use a canonical WebP path.`);
|
||
if (card.fullImage != null && !CARD_IMAGE_PATTERN.test(card.fullImage)) throw new TypeError(`Card ${card.id} full image must use a canonical WebP path.`);
|
||
// Calques de la parallaxe prismatique : héros détouré (`__cutout`) et décor sans le héros (`__backdrop`), nommés d'après
|
||
// l'illustration de leur format. Un décor n'a de sens qu'avec le héros détouré qui se pose dessus.
|
||
for (const [layerKey, imageKey, label, suffix] of [
|
||
["cutoutImage", "image", "cutout image must be its image", "__cutout"],
|
||
["fullCutoutImage", "fullImage", "full cutout image must be its full image", "__cutout"],
|
||
["backdropImage", "image", "backdrop image must be its image", "__backdrop"],
|
||
["fullBackdropImage", "fullImage", "full backdrop image must be its full image", "__backdrop"]
|
||
]) {
|
||
if (card[layerKey] != null && (!card[imageKey] || card[layerKey] !== card[imageKey].replace(/\.webp$/, `${suffix}.webp`))) {
|
||
throw new TypeError(`Card ${card.id} ${label} suffixed with ${suffix}.`);
|
||
}
|
||
}
|
||
if (card.backdropImage != null && card.cutoutImage == null) throw new TypeError(`Card ${card.id} backdrop image needs a cutout image.`);
|
||
if (card.fullBackdropImage != null && card.fullCutoutImage == null) throw new TypeError(`Card ${card.id} full backdrop image needs a full cutout image.`);
|
||
if (card.kind != null && card.kind !== DESTINATION_CARD_KIND) throw new TypeError(`Card ${card.id} has an unknown kind.`);
|
||
if (isDestinationCard(card)) {
|
||
if (!DESTINATION_ID_PATTERN.test(card.destinationId ?? "")) throw new TypeError(`Destination card ${card.id} needs a destinationId.`);
|
||
if (card.expedition != null) throw new TypeError(`Destination card ${card.id} never joins a team and takes no expedition data.`);
|
||
} else {
|
||
if (card.destinationId != null) throw new TypeError(`Card ${card.id} is not a destination card and cannot name a destination.`);
|
||
validateCardExpedition(card, expeditionTagIds);
|
||
}
|
||
}
|
||
const destinationCards = catalog.cards.filter(isDestinationCard);
|
||
requireUnique(destinationCards.map((card) => ({ id: card.destinationId })), "destination cards");
|
||
|
||
for (const edition of catalog.editions) {
|
||
if (!cardIds.has(edition.cardId)) throw new TypeError(`Unknown card for edition ${edition.id}.`);
|
||
if (!RARITY_IDS.has(edition.rarity)) throw new TypeError(`Unknown rarity for edition ${edition.id}.`);
|
||
if (!Array.isArray(edition.finishIds) || edition.finishIds.some((id) => !finishIds.has(id))) throw new TypeError(`Unknown finish for edition ${edition.id}.`);
|
||
if (edition.retired != null && typeof edition.retired !== "boolean") throw new TypeError(`Edition ${edition.id} retired flag must be a boolean.`);
|
||
if (edition.holoIntensity != null || edition.holoLevel != null) {
|
||
const preset = catalog.effectPresets.find((item) => item.id === catalog.finishes.find((finish) => finish.id === edition.finishIds[0])?.effectPresetId);
|
||
if (!preset) throw new TypeError(`Edition ${edition.id} can only be tuned with a holographic finish.`);
|
||
if (edition.holoIntensity != null && !isEffectTuning(edition.holoIntensity)) throw new TypeError(`Edition ${edition.id} has an unknown holographic intensity.`);
|
||
if (edition.holoLevel != null && (!preset.level || !isEffectTuning(edition.holoLevel))) throw new TypeError(`Edition ${edition.id} has a level its effect does not declare.`);
|
||
}
|
||
// Une édition du catalogue versionné peut déclarer des particules ; elles doivent être valides et sur une finition holo.
|
||
if (EDITION_FLARE_FIELDS.some((field) => edition[field] != null)) {
|
||
const holo = catalog.finishes.find((finish) => finish.id === edition.finishIds[0])?.effectPresetId;
|
||
const { flare, error } = normalizeFlare(catalog, { id: edition.flareId, motifId: edition.flareMotifId ?? catalog.flareEffects?.find((item) => item.id === edition.flareId)?.motifs?.[0].id, paletteId: edition.flarePaletteId, scope: edition.flareScope, intensity: edition.flareIntensity, level: edition.flareLevel, count: edition.flareCount });
|
||
if (!holo || error || !flare) throw new TypeError(`Edition ${edition.id} has invalid particles.`);
|
||
}
|
||
if (destinationCards.some((card) => card.id === edition.cardId) && edition.rarity !== "rare") throw new TypeError(`Destination card edition ${edition.id} must be rare.`);
|
||
if (edition.promotional && edition.legendaryEditionId) throw new TypeError(`Promotional edition ${edition.id} cannot require a legendary parent.`);
|
||
if (edition.rarity === "mythic" && !edition.promotional) {
|
||
const parent = catalog.editions.find((candidate) => candidate.id === edition.legendaryEditionId);
|
||
if (!parent || parent.cardId !== edition.cardId || parent.rarity !== "legendary") throw new TypeError(`Mythic edition ${edition.id} needs a legendary edition of the same card.`);
|
||
}
|
||
}
|
||
validateEquipmentCoverage(catalog);
|
||
if (catalog.mythicOpeningSettings != null) {
|
||
if (!Array.isArray(catalog.mythicOpeningSettings)) throw new TypeError("Cards catalog mythicOpeningSettings must be an array.");
|
||
const settingKeys = new Set();
|
||
for (const setting of catalog.mythicOpeningSettings) {
|
||
const targets = setting?.scope === "collection" ? collectionIds : setting?.scope === "card" ? cardIds : null;
|
||
if (!targets?.has(setting.targetId)
|
||
|| (setting.particleShapeId != null && !particleShapeIds.has(setting.particleShapeId))
|
||
|| (setting.particlePaletteId != null && setting.particlePaletteId !== MATCH_HOLO_PALETTE_ID && !particlePaletteIds.has(setting.particlePaletteId))) {
|
||
throw new TypeError(`Invalid mythic opening setting ${setting?.scope}:${setting?.targetId}.`);
|
||
}
|
||
const key = `${setting.scope}:${setting.targetId}`;
|
||
if (settingKeys.has(key)) throw new TypeError(`Duplicate mythic opening setting ${key}.`);
|
||
settingKeys.add(key);
|
||
}
|
||
}
|
||
|
||
// Les taux de tirage n'existent que dans le catalogue publié (ils viennent de la base).
|
||
for (const collection of catalog.collections) {
|
||
if (collection.dropWeights != null) validateRarityWeights(collection.dropWeights, rarityIds, collection.id);
|
||
}
|
||
return catalog;
|
||
}
|
||
|
||
export const MAX_RARITY_WEIGHT = 1_000_000;
|
||
|
||
/** Poids entiers, positifs ou nuls, une entrée par rareté connue, total strictement positif. */
|
||
export function validateRarityWeights(weights, rarityIds, label = "drop weights") {
|
||
if (!weights || typeof weights !== "object" || Array.isArray(weights)) throw new TypeError(`Invalid drop weights in ${label}.`);
|
||
const entries = Object.entries(weights);
|
||
if (entries.length !== rarityIds.size || entries.some(([rarity, weight]) => !rarityIds.has(rarity) || !Number.isInteger(weight) || weight < 0 || weight > MAX_RARITY_WEIGHT)) {
|
||
throw new TypeError(`Invalid drop weight in ${label}.`);
|
||
}
|
||
if (entries.reduce((sum, [, weight]) => sum + weight, 0) <= 0) throw new TypeError(`Drop weights in ${label} must have a positive total.`);
|
||
return weights;
|
||
}
|
||
|
||
export const STANDARD_FINISH_ID = "standard";
|
||
|
||
/** Les finitions ne sont pas déclarées : « standard » plus une finition par combinaison effet holographique × palette. */
|
||
export function withGeneratedFinishes(catalog) {
|
||
const finishes = [{ id: STANDARD_FINISH_ID, label: "Standard", effectPresetId: null, paletteId: null, formatId: STANDARD_FORMAT }];
|
||
for (const format of catalog.cardFormats || []) {
|
||
for (const effect of catalog.effectPresets || []) {
|
||
for (const palette of catalog.effectPalettes || []) {
|
||
// Le format de référence garde des identifiants courts ; les autres sont préfixés par leur format.
|
||
const standard = format.id === STANDARD_FORMAT;
|
||
finishes.push({
|
||
id: `${standard ? "" : `${format.id}-`}${effect.id}-${palette.id}`,
|
||
label: `${standard ? "" : `${format.label} · `}${effect.label} — ${palette.label}`,
|
||
effectPresetId: effect.id,
|
||
paletteId: palette.id,
|
||
formatId: format.id
|
||
});
|
||
}
|
||
}
|
||
}
|
||
return { ...catalog, finishes };
|
||
}
|
||
|
||
/**
|
||
* catalog.json ne déclare ni finitions (générées) ni contenu géré en base depuis l'administration :
|
||
* variations mythiques, activation des paquets et taux de tirage.
|
||
*/
|
||
export function assertVersionedCatalogScope(catalog) {
|
||
if (catalog.finishes) throw new TypeError("Finishes are generated from effect presets and palettes: remove finishes from catalog.json.");
|
||
if (catalog.dropTables) throw new TypeError("Drop rates are managed from the admin database: remove dropTables from catalog.json.");
|
||
const withRates = catalog.collections?.find((collection) => Object.hasOwn(collection, "dropWeights"));
|
||
if (withRates) throw new TypeError(`Collection ${withRates.id} drop rates are managed from the admin database: remove dropWeights from catalog.json.`);
|
||
const withState = catalog.collections?.find((collection) => Object.hasOwn(collection, "active"));
|
||
if (withState) throw new TypeError(`Collection ${withState.id} availability is managed from the admin database: remove active from catalog.json.`);
|
||
const mythic = catalog.editions?.find((edition) => edition.rarity === "mythic" && !edition.promotional);
|
||
if (mythic) throw new TypeError(`Mythic edition ${mythic.id} must be managed from the admin database, not catalog.json.`);
|
||
return catalog;
|
||
}
|
||
|
||
/** Prépare le catalogue versionné tel qu'il est lu depuis catalog.json. */
|
||
export function prepareVersionedCatalog(raw) {
|
||
return validateCardsCatalog(withGeneratedFinishes(assertVersionedCatalogScope(raw)));
|
||
}
|
||
|
||
export function loadCardsCatalog(path) {
|
||
return prepareVersionedCatalog(JSON.parse(readFileSync(path, "utf8")));
|
||
}
|
||
|
||
export function createCatalogIndex(catalog) {
|
||
return {
|
||
collections: new Map(catalog.collections.map((item) => [item.id, item])),
|
||
cards: new Map(catalog.cards.map((item) => [item.id, item])),
|
||
editions: new Map(catalog.editions.map((item) => [item.id, item])),
|
||
finishes: new Map(catalog.finishes.map((item) => [item.id, item])),
|
||
effectPresets: new Map(catalog.effectPresets.map((item) => [item.id, item])),
|
||
effectPalettes: new Map(catalog.effectPalettes.map((item) => [item.id, item])),
|
||
particleShapes: new Map(catalog.particleShapes.map((item) => [item.id, item])),
|
||
particlePalettes: new Map(catalog.particlePalettes.map((item) => [item.id, item])),
|
||
particlePresets: new Map(catalog.particlePresets.map((item) => [item.id, item])),
|
||
openingEffects: new Map(catalog.openingEffects.map((item) => [item.id, item]))
|
||
};
|
||
}
|
||
|
||
export function isDrawableEdition(edition) {
|
||
return !edition.promotional && !edition.retired;
|
||
}
|
||
|
||
/** Éditions tirables d'une collection. */
|
||
export function collectionDrawableEditions(catalog, collectionId) {
|
||
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
|
||
return catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
|
||
}
|
||
|
||
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
|
||
const SHOP_FEATURED_RARITIES = new Set(["legendary", "mythic"]);
|
||
export function shopPackPools(catalog, collectionId) {
|
||
const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
|
||
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
|
||
const drawable = catalog.editions.filter(isDrawableEdition);
|
||
return {
|
||
others: drawable.filter((edition) => activeIds.has(sourceOf.get(edition.cardId))),
|
||
featured: drawable.filter((edition) => sourceOf.get(edition.cardId) === collectionId && SHOP_FEATURED_RARITIES.has(edition.rarity))
|
||
};
|
||
}
|
||
|
||
/** Nombre d'éditions qu'un paquet peut réellement donner par rareté, quels que soient ses taux. */
|
||
export function drawableCounts(catalog, collection) {
|
||
const pools = collection.packCategory === "shop" ? shopPackPools(catalog, collection.id) : null;
|
||
const editions = pools ? [...pools.others, ...pools.featured] : collectionDrawableEditions(catalog, collection.id);
|
||
return Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, editions.filter((edition) => edition.rarity === rarity.id).length]));
|
||
}
|
||
|
||
export function drawableRarities(catalog, collection) {
|
||
return Object.entries(drawableCounts(catalog, collection)).filter(([, count]) => count > 0).map(([rarity]) => rarity);
|
||
}
|
||
|
||
export function holographicFinishIds(catalog) {
|
||
return new Set(catalog.finishes.filter((finish) => finish.effectPresetId != null).map((finish) => finish.id));
|
||
}
|
||
|
||
export function legendaryParentEdition(catalog, cardId) {
|
||
return catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity === "legendary" && !edition.promotional) || null;
|
||
}
|
||
|
||
/**
|
||
* Identifiant donné à une variation à sa création. Il ne change plus ensuite, même si sa finition change :
|
||
* il ne faut donc pas en déduire la finition (lire `finishIds`).
|
||
*/
|
||
export function mythicEditionId(cardId, finishId) {
|
||
return `${cardId}-${finishId}`;
|
||
}
|
||
|
||
export function isMythicEditionIdOf(editionId, cardId) {
|
||
return typeof editionId === "string" && editionId.startsWith(`${cardId}-`);
|
||
}
|
||
|
||
/**
|
||
* Construit le catalogue publié : catalogue versionné + variations mythiques et réglages d'ouverture enregistrés en base.
|
||
* `variations` : [{ editionId, cardId, finishId, status: "active" | "retired", intensity?, level? }] ; un palier central ou absent
|
||
* n'est pas publié, et le palier d'effet seulement si l'effet de la finition en déclare un.
|
||
* `openingSettings` : [{ scope: "collection" | "card", targetId, particleShapeId | null, particlePaletteId | null }]
|
||
* `collectionStates` : [{ collectionId, active }] ; une collection sans état est inactive.
|
||
* `dropRates` : [{ collectionId, rarityWeights }] ; publiés sur chaque collection dans `dropWeights`.
|
||
*/
|
||
export function buildPublishedCatalog(versionedCatalog, { variations = [], openingSettings = [], collectionStates = [], dropRates = [] } = {}) {
|
||
const catalog = structuredClone(versionedCatalog);
|
||
const states = new Map(collectionStates.map((state) => [state.collectionId, Boolean(state.active)]));
|
||
const rates = new Map(dropRates.map((rate) => [rate.collectionId, rate.rarityWeights]));
|
||
catalog.collections = catalog.collections.map((collection) => {
|
||
const dropWeights = rates.get(collection.id);
|
||
return { ...collection, active: states.get(collection.id) ?? false, ...(dropWeights ? { dropWeights: { ...dropWeights } } : {}) };
|
||
});
|
||
for (const collection of catalog.collections.filter((item) => item.active)) {
|
||
if (!collection.dropWeights) throw new TypeError(`Active collection ${collection.id} needs drop rates.`);
|
||
}
|
||
const holographic = holographicFinishIds(catalog);
|
||
const effectOf = (finishId) => catalog.effectPresets.find((preset) => preset.id === catalog.finishes.find((finish) => finish.id === finishId)?.effectPresetId);
|
||
const knownIds = new Set(catalog.editions.map((edition) => edition.id));
|
||
const cardFinishes = new Set();
|
||
const mythics = variations.map((variation) => {
|
||
const parent = legendaryParentEdition(catalog, variation.cardId);
|
||
const cardFinish = `${variation.cardId}\n${variation.finishId}`;
|
||
if (!parent || !holographic.has(variation.finishId) || !isMythicEditionIdOf(variation.editionId, variation.cardId) || knownIds.has(variation.editionId)) {
|
||
throw new TypeError(`Mythic variation ${variation.editionId} needs a legendary card and a holographic finish.`);
|
||
}
|
||
if (cardFinishes.has(cardFinish)) throw new TypeError(`Mythic variation ${variation.editionId} repeats the finish ${variation.finishId}.`);
|
||
knownIds.add(variation.editionId);
|
||
cardFinishes.add(cardFinish);
|
||
return {
|
||
id: variation.editionId,
|
||
cardId: variation.cardId,
|
||
rarity: "mythic",
|
||
finishIds: [variation.finishId],
|
||
promotional: false,
|
||
legendaryEditionId: parent.id,
|
||
...(variation.status === "retired" ? { retired: true } : {}),
|
||
...(isEffectTuning(variation.intensity) && variation.intensity !== DEFAULT_EFFECT_TUNING ? { holoIntensity: variation.intensity } : {}),
|
||
...(isEffectTuning(variation.level) && variation.level !== DEFAULT_EFFECT_TUNING && effectOf(variation.finishId)?.level ? { holoLevel: variation.level } : {}),
|
||
...publishedFlare(catalog, variation.flare)
|
||
};
|
||
});
|
||
// Chaque variation suit sa carte légendaire, dans l'ordre des finitions.
|
||
const finishOrder = new Map(catalog.finishes.map((finish, index) => [finish.id, index]));
|
||
mythics.sort((left, right) => finishOrder.get(left.finishIds[0]) - finishOrder.get(right.finishIds[0]));
|
||
catalog.editions = catalog.editions.flatMap((edition) => edition.rarity === "legendary" && !edition.promotional
|
||
? [edition, ...mythics.filter((mythic) => mythic.legendaryEditionId === edition.id)]
|
||
: [edition]);
|
||
catalog.mythicOpeningSettings = openingSettings
|
||
.map(({ scope, targetId, particleShapeId = null, particlePaletteId = null }) => ({ scope, targetId, particleShapeId, particlePaletteId }))
|
||
.filter((setting) => setting.particleShapeId || setting.particlePaletteId);
|
||
return validateCardsCatalog(catalog);
|
||
}
|
||
|
||
export function publicCatalog(catalog) {
|
||
const published = JSON.parse(JSON.stringify(catalog));
|
||
published.collections = published.collections.map((collection) => ({ ...collection, drawableCounts: drawableCounts(published, collection), drawableRarities: drawableRarities(published, collection) }));
|
||
return published;
|
||
}
|