288 lines
13 KiB
JavaScript
288 lines
13 KiB
JavaScript
// Rôle : vérifie le contrat v2 des imports avant remappage et écriture.
|
|
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { TOOLBOX_MODULE_DEFINITIONS } from "../website/src/features/toolboxes/toolboxModuleRegistry.js";
|
|
import { useToolboxActions } from "../website/src/features/toolboxes/useToolboxActions.js";
|
|
import { createGlobalExportPayload, createToolboxExportPayload } from "../website/src/features/toolboxes/storage/toolboxStorage.js";
|
|
import { validateToolboxImportPayload } from "../website/src/features/toolboxes/storage/toolboxImportValidation.js";
|
|
|
|
const MODULE_TYPES = Object.keys(TOOLBOX_MODULE_DEFINITIONS);
|
|
|
|
function sourceToolbox() {
|
|
const modules = MODULE_TYPES.map((type) => ({ id: type === "taskPlanner" ? "planner" : type, type }));
|
|
const chunks = Array.from({ length: 5 }, () => []);
|
|
modules.forEach((module, index) => chunks[index % chunks.length].push(module.id));
|
|
const spaces = chunks.map((ids, index) => ({
|
|
id: `space-${index + 1}`,
|
|
name: index ? `Espace ${index + 1}` : "Défaut",
|
|
moduleOrder: { one: ids, two: [ids.filter((_, itemIndex) => itemIndex % 2 === 0), ids.filter((_, itemIndex) => itemIndex % 2 === 1)] }
|
|
}));
|
|
return {
|
|
id: "source", name: "Tous les outils", modules, spaces,
|
|
defaultSpaceId: spaces[0].id, activeSpaceId: spaces[4].id,
|
|
updatedAt: "2026-10-14T12:00:00.000Z"
|
|
};
|
|
}
|
|
|
|
function sourceModuleData() {
|
|
return {
|
|
"source:notepad": { pages: [{ id: "page", title: "Page 1", html: "<p>Notes</p>", text: "Notes" }] },
|
|
"source:memos": { plannerLink: "planner", items: [{ id: "memo", text: "Préparer", color: "#f6c453" }] },
|
|
"source:checklist": { items: [{ id: "item", label: "Objet", qtyTarget: 2 }] },
|
|
"source:images": { images: [{ id: "image", label: "Carte", dataUrl: "data:image/png;base64,AA==" }] },
|
|
"source:imageAnnotation": {
|
|
image: "data:image/png;base64,AA==",
|
|
markers: [{ id: "marker", x: 25, y: 75, label: "Cible" }]
|
|
},
|
|
"source:links": { links: [{ id: "link", title: "Guide", url: "https://example.com/" }] },
|
|
"source:counters": { counters: [{ id: "counter", label: "Score", value: 12 }] },
|
|
"source:randomizer": { wheel: { entries: [{ id: "choice", label: "Choix", weight: 1 }] } },
|
|
"source:rngSimulator": { rates: [{ id: "rate", label: "Rare", rate: "5" }] },
|
|
"source:combos": { combos: [{ id: "combo", name: "Attaque", inputs: [[{ kind: "button", value: "cross" }]] }] },
|
|
"source:planner": {
|
|
tasks: [{ id: "parent", title: "Parent", type: "unique", qtyTarget: 5, qtyCurrent: 5, progressAt: 1000 }, { id: "child", title: "Enfant", type: "daily", qtyTarget: 3, qtyCurrent: 1, progressAt: 2000 }],
|
|
relations: [{ id: "relation", fromTaskId: "child", toTaskId: "parent" }]
|
|
},
|
|
"source:calculator": {
|
|
entries: [{ id: "root", label: "Total", value: 2 }, { id: "child", parentId: "root", label: "Part", value: 1 }]
|
|
},
|
|
"source:equipmentPlanner": {
|
|
types: [{ id: "type", title: "Armure" }],
|
|
equipments: [{
|
|
id: "equipment", typeId: "type", name: "Casque",
|
|
socketItems: [{ id: "socket-a", name: "A" }, { id: "socket-b", name: "B" }],
|
|
socketLinks: [{ id: "socket-link", fromSocketItemId: "socket-a", toSocketItemId: "socket-b" }]
|
|
}]
|
|
},
|
|
"source:calendar": { events: [{ id: "event", title: "Raid", dayIndex: 2, startMinutes: 120 }] },
|
|
"source:table": { rows: 2, columns: 2, cells: { A1: "2", B1: "=A1*2" } },
|
|
"source:timer": { countdowns: [{ id: "countdown", label: "Départ", type: "duration", durationMs: 60000, targetAt: 100000 }] },
|
|
"source:goalTree": {
|
|
nodes: [
|
|
{ id: "goal", title: "Objectif" },
|
|
{ id: "step", parentId: "goal", title: "Étape", kind: "text", items: [{ id: "goal-item", label: "Détail" }] }
|
|
]
|
|
}
|
|
};
|
|
}
|
|
|
|
function validIndividualPayload() {
|
|
return JSON.parse(JSON.stringify(createToolboxExportPayload(sourceToolbox(), sourceModuleData())));
|
|
}
|
|
|
|
function clone(value) {
|
|
return structuredClone(value);
|
|
}
|
|
|
|
test("a v2 individual export round-trips all registered tool types and five spaces", async () => {
|
|
const payload = validIndividualPayload();
|
|
assert.equal(payload.toolbox.modules.length, 17);
|
|
assert.equal(payload.toolbox.spaces.length, 5);
|
|
assert.equal(validateToolboxImportPayload(payload, "single"), payload);
|
|
|
|
let state = { toolboxes: [], links: {}, moduleData: {} };
|
|
const actions = useToolboxActions({
|
|
store: {
|
|
ready: true,
|
|
persistToolboxSnapshot: async (updater) => {
|
|
state = { ...state, ...updater(state) };
|
|
return true;
|
|
}
|
|
},
|
|
notify() {},
|
|
setConfirmModal: (value) => assert.fail(value.message)
|
|
});
|
|
const imported = await actions.importToolbox({ text: async () => JSON.stringify(payload) });
|
|
assert.ok(imported);
|
|
assert.deepEqual(imported.modules.map((module) => module.type).sort(), MODULE_TYPES.toSorted());
|
|
assert.equal(imported.spaces.length, 5);
|
|
|
|
const roundTrip = JSON.parse(JSON.stringify(createToolboxExportPayload(imported, state.moduleData)));
|
|
validateToolboxImportPayload(roundTrip, "single");
|
|
assert.deepEqual(roundTrip.toolbox.modules.map((module) => module.type).sort(), MODULE_TYPES.toSorted());
|
|
assert.equal(Object.keys(roundTrip.modules).length, MODULE_TYPES.length);
|
|
const memos = roundTrip.toolbox.modules.find((module) => module.type === "memos");
|
|
const planner = roundTrip.toolbox.modules.find((module) => module.type === "taskPlanner");
|
|
assert.equal(roundTrip.modules[memos.id].plannerLink, planner.id);
|
|
assert.deepEqual(roundTrip.modules[planner.id], payload.modules[planner.id]);
|
|
});
|
|
|
|
test("v2 rejects noncanonical planner quantities before importing any toolbox", async () => {
|
|
for (const patch of [{ qtyTarget: 1 }, { qtyTarget: 2.5 }, { qtyCurrent: 99 }, { qtyCurrent: "2" }, { checked: true }, { progressAt: -1 }]) {
|
|
const payload = validIndividualPayload();
|
|
const planner = payload.toolbox.modules.find((module) => module.type === "taskPlanner");
|
|
Object.assign(payload.modules[planner.id].tasks[0], patch);
|
|
let writes = 0;
|
|
const actions = useToolboxActions({
|
|
store: { ready: true, persistToolboxSnapshot: async () => { writes += 1; return true; } },
|
|
notify() {},
|
|
setConfirmModal() {}
|
|
});
|
|
assert.throws(() => validateToolboxImportPayload(payload, "single"));
|
|
await actions.importToolbox({ text: async () => JSON.stringify(payload) });
|
|
assert.equal(writes, 0);
|
|
}
|
|
});
|
|
|
|
test("compact empty individual and global v2 exports remain valid", () => {
|
|
const toolbox = {
|
|
id: "empty", name: "Vide", modules: [],
|
|
spaces: [{ id: "default", name: "Défaut", moduleOrder: { one: [], two: [[], []] } }],
|
|
defaultSpaceId: "default", activeSpaceId: "default", updatedAt: "2026-10-14T12:00:00.000Z"
|
|
};
|
|
const individual = createToolboxExportPayload(toolbox, {});
|
|
validateToolboxImportPayload(individual, "single");
|
|
const global = createGlobalExportPayload([], {}, {});
|
|
validateToolboxImportPayload(global, "global");
|
|
});
|
|
|
|
test("unknown versions, tool types and duplicate ids are rejected with their location", () => {
|
|
const version = clone(validIndividualPayload());
|
|
version.version = 999;
|
|
assert.throws(() => validateToolboxImportPayload(version), /version 999 non prise en charge/);
|
|
|
|
const type = clone(validIndividualPayload());
|
|
type.toolbox.modules[0].type = "unknown";
|
|
assert.throws(() => validateToolboxImportPayload(type), /modules\[0\]\.type « unknown » est inconnu/);
|
|
|
|
const duplicate = clone(validIndividualPayload());
|
|
duplicate.toolbox.modules[1].id = duplicate.toolbox.modules[0].id;
|
|
assert.throws(() => validateToolboxImportPayload(duplicate), /identifiant dupliqué/);
|
|
});
|
|
|
|
test("orphan storage, space and business references are rejected", () => {
|
|
const moduleData = clone(validIndividualPayload());
|
|
moduleData.modules.orphan = { pages: [{ id: "page", title: "Page 1", text: "Orpheline", html: "<p>Orpheline</p>" }] };
|
|
assert.throws(() => validateToolboxImportPayload(moduleData), /ne correspond à aucun outil déclaré/);
|
|
|
|
const order = clone(validIndividualPayload());
|
|
order.toolbox.spaces[0].moduleOrder.one[0] = "missing";
|
|
assert.throws(() => validateToolboxImportPayload(order), /référence l'identifiant absent « missing »/);
|
|
|
|
const planner = clone(validIndividualPayload());
|
|
const memosId = planner.toolbox.modules.find((module) => module.type === "memos").id;
|
|
planner.modules[memosId].plannerLink = "missing";
|
|
assert.throws(() => validateToolboxImportPayload(planner), /plannerLink référence un planificateur absent/);
|
|
|
|
const memos = clone(validIndividualPayload());
|
|
const duplicateMemosId = memos.toolbox.modules.find((module) => module.type === "memos").id;
|
|
memos.modules[duplicateMemosId].items.push(clone(memos.modules[duplicateMemosId].items[0]));
|
|
assert.throws(() => validateToolboxImportPayload(memos), /identifiant dupliqué/);
|
|
});
|
|
|
|
test("global imports reject duplicate toolboxes, orphan module keys and orphan game links", () => {
|
|
const toolbox = sourceToolbox();
|
|
const payload = createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData());
|
|
validateToolboxImportPayload(payload, "global");
|
|
|
|
const duplicate = clone(payload);
|
|
duplicate.toolboxes.push(clone(duplicate.toolboxes[0]));
|
|
assert.throws(() => validateToolboxImportPayload(duplicate, "global"), /identifiant dupliqué « source » dans toolboxes/);
|
|
|
|
const moduleData = clone(payload);
|
|
moduleData.modules["source:missing"] = { pages: [{ id: "page", title: "Page 1", text: "X", html: "<p>X</p>" }] };
|
|
assert.throws(() => validateToolboxImportPayload(moduleData, "global"), /ne correspond à aucun outil déclaré/);
|
|
|
|
const link = clone(payload);
|
|
link.links.game = "missing";
|
|
assert.throws(() => validateToolboxImportPayload(link, "global"), /links\.game référence l'identifiant absent/);
|
|
});
|
|
|
|
test("a global import remaps toolbox, game and planner references together", async () => {
|
|
const toolbox = sourceToolbox();
|
|
const payload = JSON.parse(JSON.stringify(createGlobalExportPayload(
|
|
[toolbox],
|
|
{ game: toolbox.id },
|
|
sourceModuleData()
|
|
)));
|
|
let state = { toolboxes: [], links: {}, moduleData: {} };
|
|
const actions = useToolboxActions({
|
|
store: {
|
|
ready: true,
|
|
persistToolboxSnapshot: async (updater) => {
|
|
state = { ...state, ...updater(state) };
|
|
return true;
|
|
}
|
|
},
|
|
notify() {},
|
|
setConfirmModal: (value) => assert.fail(value.message)
|
|
});
|
|
|
|
assert.equal(await actions.importAllToolboxes({ text: async () => JSON.stringify(payload) }), true);
|
|
const imported = state.toolboxes[0];
|
|
const memos = imported.modules.find((module) => module.type === "memos");
|
|
const planner = imported.modules.find((module) => module.type === "taskPlanner");
|
|
assert.notEqual(imported.id, toolbox.id);
|
|
assert.equal(state.links.game, imported.id);
|
|
assert.equal(state.moduleData[`${imported.id}:${memos.id}`].plannerLink, planner.id);
|
|
});
|
|
|
|
test("a global import asks before reassigning an existing game and writes only after confirmation", async () => {
|
|
const source = sourceToolbox();
|
|
const payload = JSON.parse(JSON.stringify(createGlobalExportPayload(
|
|
[source],
|
|
{ game: source.id },
|
|
sourceModuleData()
|
|
)));
|
|
let state = {
|
|
toolboxes: [{ id: "existing", name: "Existante", modules: [] }],
|
|
links: { game: "existing" },
|
|
moduleData: {}
|
|
};
|
|
let writes = 0;
|
|
let confirmation;
|
|
const actions = useToolboxActions({
|
|
store: {
|
|
ready: true,
|
|
...state,
|
|
persistToolboxSnapshot: async (updater) => {
|
|
writes += 1;
|
|
state = { ...state, ...updater(state) };
|
|
return true;
|
|
}
|
|
},
|
|
notify() {},
|
|
setConfirmModal: (value) => { confirmation = value; }
|
|
});
|
|
|
|
const cancelledImport = actions.importAllToolboxes({ text: async () => JSON.stringify(payload) });
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
assert.equal(writes, 0);
|
|
assert.match(confirmation.message, /associations de jeu existantes \(1\)/);
|
|
confirmation.onResolve(false);
|
|
assert.equal(await cancelledImport, false);
|
|
assert.equal(state.links.game, "existing");
|
|
|
|
const confirmedImport = actions.importAllToolboxes({ text: async () => JSON.stringify(payload) });
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
confirmation.onResolve(true);
|
|
assert.equal(await confirmedImport, true);
|
|
assert.equal(writes, 1);
|
|
assert.notEqual(state.links.game, "existing");
|
|
assert.equal(state.toolboxes.some((toolbox) => toolbox.id === "existing"), true);
|
|
});
|
|
|
|
test("non-canonical values are rejected instead of being silently normalized", () => {
|
|
const payload = validIndividualPayload();
|
|
const counterId = payload.toolbox.modules.find((module) => module.type === "counters").id;
|
|
payload.modules[counterId] = { counters: [{ id: "counter", label: "Score", value: "12" }] };
|
|
assert.throws(
|
|
() => validateToolboxImportPayload(payload),
|
|
/ne respecte pas le format canonique du type « counters »/
|
|
);
|
|
});
|
|
|
|
test("invalid imports never reach the storage transaction", async () => {
|
|
let writes = 0;
|
|
let message = "";
|
|
const actions = useToolboxActions({
|
|
store: { ready: true, persistToolboxSnapshot: () => { writes += 1; return Promise.resolve(true); } },
|
|
notify() {},
|
|
setConfirmModal: (value) => { message = value.message; }
|
|
});
|
|
const payload = validIndividualPayload();
|
|
payload.version = 999;
|
|
assert.equal(await actions.importToolbox({ text: async () => JSON.stringify(payload) }), null);
|
|
assert.equal(writes, 0);
|
|
assert.match(message, /version 999/);
|
|
});
|