Stop orphan game links from blocking global imports
A game link could outlive its toolbox when one tab linked a game while another tab, unaware of that link, deleted the toolbox. Auto-backups and manual exports then copied the orphan link, and the global import rejected the whole file. - Drop links to missing toolboxes inside the IndexedDB transaction. - Remove orphan links already stored when the page loads. - Ignore a link request to a toolbox that no longer exists. - Leave orphan links out of exports and skip them on global import, so older backups import again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
98c442a9cd
commit
d030c3f59f
9 changed files with 137 additions and 9 deletions
|
|
@ -319,3 +319,5 @@
|
|||
{"id":"int-2642091412a820a6521b354808de0b39","kind":"field_change","created_at":"2026-11-09T10:25:39.662355866Z","actor":"Shinuwa","issue_id":"sokko-g-t7nx","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Collection long-night ajoutée au catalogue (inactive) : 30 cartes, images webp, lore documenté"}}
|
||||
{"id":"int-a88b8e1a2c7f8a4d970921494533f421","kind":"field_change","created_at":"2026-11-09T10:51:47.512008767Z","actor":"Shinuwa","issue_id":"sokko-g-n3mf","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Descriptions de collection raccourcies (62/63 car.), tests e2e admin mis à jour (4 collections) ; test:e2e:cards 11/11, tests unitaires 251/251, lint OK"}}
|
||||
{"id":"int-c17c3702be7114f750b1f97592c4142c","kind":"field_change","created_at":"2026-11-09T12:23:33.595084433Z","actor":"Shinuwa","issue_id":"sokko-g-3ijw","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}}
|
||||
{"id":"int-e910f5b4c041480fb8e708c515e62f6d","kind":"field_change","created_at":"2026-11-11T14:02:45.210027976Z","actor":"Shinuwa","issue_id":"sokko-g-0ku7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Associations orphelines écartées au chargement, à l'export et à l'import global ; le fichier .local/sokkog-global-2026-11-11.json s'importe (3 toolboxes, 24 outils)."}}
|
||||
{"id":"int-f91a8b7bc318291bfa072ad6cff3b328","kind":"field_change","created_at":"2026-11-11T14:11:39.343142458Z","actor":"Shinuwa","issue_id":"sokko-g-ocss","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"mutateToolboxStorage retire dans la même transaction toute association vers une toolbox absente ; removeOrphanLinks nettoie la base au chargement ; linkToolboxToGame ignore une toolbox absente. Test e2e deux onglets : échoue sans la correction, passe avec."}}
|
||||
|
|
|
|||
|
|
@ -185,3 +185,31 @@ test("a stale toolbox replacement shows a conflict and reloads the confirmed ver
|
|||
expect(confirmed.toolboxes.find((toolbox) => toolbox.name === "Version distante")).toBeTruthy();
|
||||
expect(confirmed.toolboxes.find((toolbox) => toolbox.name === "Version locale")).toBeFalsy();
|
||||
});
|
||||
|
||||
test("deleting a toolbox also removes game links written by another tab", async ({ page, context }) => {
|
||||
await resetSokkoStorage(page);
|
||||
const otherPage = await context.newPage();
|
||||
await otherPage.goto("/");
|
||||
const toolbox = (id) => ({ id, name: id, modules: [] });
|
||||
const empty = { toolboxes: [], links: {}, moduleData: {} };
|
||||
const both = { toolboxes: [toolbox("a"), toolbox("b")], links: {}, moduleData: {} };
|
||||
expect(await runMutation(page, empty, both)).toEqual({ ok: true });
|
||||
|
||||
// L'autre onglet associe un jeu à « a » ; cet onglet supprime « a » sans avoir vu l'association.
|
||||
expect(await runMutation(otherPage, both, { ...both, links: { game: "a", other: "b" } })).toEqual({ ok: true });
|
||||
expect(await runMutation(page, both, { ...both, toolboxes: [toolbox("b")] })).toEqual({ ok: true });
|
||||
|
||||
const links = await page.evaluate(async () => (await import("/src/utils/indexedDbStorage.js")).getLinks());
|
||||
expect(links).toEqual({ other: "b" });
|
||||
});
|
||||
|
||||
test("orphan game links already stored are removed from IndexedDB", async ({ page }) => {
|
||||
await resetSokkoStorage(page);
|
||||
const result = await page.evaluate(async () => {
|
||||
const db = await import("/src/utils/indexedDbStorage.js");
|
||||
await db.setToolboxSnapshot([{ id: "kept", modules: [] }], { mhwilds: "deleted", diablo4: "kept" }, {});
|
||||
const removed = await db.removeOrphanLinks();
|
||||
return { removed, links: await db.getLinks(), again: await db.removeOrphanLinks() };
|
||||
});
|
||||
expect(result).toEqual({ removed: 1, links: { diablo4: "kept" }, again: 0 });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -244,6 +244,24 @@ test("failed toolbox deletion preserves registry links and modules together", as
|
|||
assert.deepEqual(queue.getCurrent(), initial);
|
||||
});
|
||||
|
||||
test("a game cannot be linked to a toolbox that no longer exists", async () => {
|
||||
let state = { toolboxes: [{ id: "kept", modules: [] }], links: { game: "kept" }, moduleData: {} };
|
||||
const actions = useToolboxActions({
|
||||
store: {
|
||||
ready: true,
|
||||
...state,
|
||||
persistToolboxSnapshot: async (apply) => {
|
||||
state = { ...state, ...apply(state) };
|
||||
return true;
|
||||
}
|
||||
}
|
||||
});
|
||||
await actions.linkToolboxToGame("other", "deleted");
|
||||
assert.deepEqual(state.links, { game: "kept" });
|
||||
await actions.linkToolboxToGame("other", "kept");
|
||||
assert.deepEqual(state.links, { game: "kept", other: "kept" });
|
||||
});
|
||||
|
||||
test("storage mutations target independent records and preserve deferred media deletions", () => {
|
||||
const expected = {
|
||||
toolboxes: [{ id: "a", modules: [{ id: "media", type: "images" }] }],
|
||||
|
|
|
|||
|
|
@ -171,7 +171,7 @@ test("orphan storage, space and business references are rejected", () => {
|
|||
assert.throws(() => validateToolboxImportPayload(memos), /identifiant dupliqué/);
|
||||
});
|
||||
|
||||
test("global imports reject duplicate toolboxes, orphan module keys and orphan game links", () => {
|
||||
test("global imports reject duplicate toolboxes and orphan module keys", () => {
|
||||
const toolbox = sourceToolbox();
|
||||
const payload = createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData());
|
||||
validateToolboxImportPayload(payload, "global");
|
||||
|
|
@ -185,8 +185,37 @@ test("global imports reject duplicate toolboxes, orphan module keys and orphan g
|
|||
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/);
|
||||
link.links.game = 3;
|
||||
assert.throws(() => validateToolboxImportPayload(link, "global"), /links\.game doit être une chaîne non vide/);
|
||||
});
|
||||
|
||||
test("a global export drops game links whose toolbox no longer exists", () => {
|
||||
const toolbox = sourceToolbox();
|
||||
const payload = createGlobalExportPayload([toolbox], { game: toolbox.id, removed: "deleted-toolbox" }, sourceModuleData());
|
||||
assert.deepEqual(payload.links, { game: toolbox.id });
|
||||
});
|
||||
|
||||
test("a global import skips orphan game links from older backups instead of failing", async () => {
|
||||
const toolbox = sourceToolbox();
|
||||
const payload = JSON.parse(JSON.stringify(createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData())));
|
||||
payload.links.removed = "deleted-toolbox";
|
||||
let state = { toolboxes: [], links: {}, moduleData: {} };
|
||||
const actions = useToolboxActions({
|
||||
store: {
|
||||
ready: true,
|
||||
links: { removed: "existing" },
|
||||
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);
|
||||
assert.deepEqual(Object.keys(state.links), ["game"]);
|
||||
assert.equal(state.links.game, state.toolboxes[0].id);
|
||||
});
|
||||
|
||||
test("a global import remaps toolbox, game and planner references together", async () => {
|
||||
|
|
|
|||
|
|
@ -292,9 +292,10 @@ export function validateToolboxImportPayload(payload, mode = "single") {
|
|||
});
|
||||
validateModuleData(validated, payload.modules, true);
|
||||
assertRecord(payload.links, "links");
|
||||
// Une association vers une toolbox absente vient d'une ancienne sauvegarde : elle est ignorée à l'import.
|
||||
for (const [gameId, toolboxId] of Object.entries(payload.links)) {
|
||||
assertString(gameId, "identifiant de jeu");
|
||||
assertReference(toolboxId, toolboxIds, `links.${gameId}`, { allowEmpty: false });
|
||||
assertString(toolboxId, `links.${gameId}`, { allowColon: false });
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -510,6 +510,14 @@ export function createToolboxExportPayload(toolbox, moduleData) {
|
|||
return { version: 2, toolbox: exportedToolbox, modules };
|
||||
}
|
||||
|
||||
// Ne garde que les associations de jeu dont la toolbox existe encore.
|
||||
export function pruneGameLinks(links, toolboxes) {
|
||||
if (!links || typeof links !== "object") return {};
|
||||
const toolboxIds = new Set((toolboxes || []).map((toolbox) => toolbox?.id));
|
||||
return Object.fromEntries(Object.entries(links)
|
||||
.filter(([, toolboxId]) => typeof toolboxId === "string" && toolboxIds.has(toolboxId)));
|
||||
}
|
||||
|
||||
export function createGlobalExportPayload(toolboxes, links, moduleData) {
|
||||
const modules = {};
|
||||
toolboxes.forEach((toolbox) => {
|
||||
|
|
@ -523,6 +531,6 @@ export function createGlobalExportPayload(toolboxes, links, moduleData) {
|
|||
exportedAt: new Date().toISOString(),
|
||||
toolboxes: compactToolboxesForStorage(toolboxes),
|
||||
modules,
|
||||
links
|
||||
links: pruneGameLinks(links, toolboxes)
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,13 +8,15 @@ import {
|
|||
getToolboxSnapshot as dbGetToolboxSnapshot,
|
||||
getToolboxes as dbGetToolboxes,
|
||||
mutateToolboxStorage as dbMutateToolboxStorage,
|
||||
removeOrphanLinks as dbRemoveOrphanLinks,
|
||||
setSetting as dbSetSetting,
|
||||
} from "../../../utils/indexedDbStorage.js";
|
||||
import {
|
||||
compactToolboxesForStorage,
|
||||
moduleStorageKey,
|
||||
normalizeToolbox,
|
||||
prepareModuleDataForStorage
|
||||
prepareModuleDataForStorage,
|
||||
pruneGameLinks
|
||||
} from "./toolboxStorage.js";
|
||||
import { applyModuleDataValue, removeModuleDataKeys } from "./optimisticModuleData.js";
|
||||
import { createPersistenceQueue } from "./persistenceQueue.js";
|
||||
|
|
@ -62,7 +64,7 @@ async function readStoredState({ preservedModuleData = {}, refreshedModuleKeys =
|
|||
}
|
||||
return {
|
||||
toolboxes: normalizedToolboxes,
|
||||
links: links && typeof links === "object" ? links : {},
|
||||
links: pruneGameLinks(links, normalizedToolboxes),
|
||||
moduleData,
|
||||
toastPosition: toastPosition === "left" ? "left" : "right"
|
||||
};
|
||||
|
|
@ -107,6 +109,8 @@ export function useIndexedToolboxes(onError) {
|
|||
let cancelled = false;
|
||||
async function loadStore() {
|
||||
try {
|
||||
// Le nettoyage est accessoire : un échec ne doit pas empêcher le chargement.
|
||||
await dbRemoveOrphanLinks().catch(() => 0);
|
||||
const storedState = await readStoredState();
|
||||
if (cancelled) return;
|
||||
queue.initialize(storedState);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
globalModuleKey,
|
||||
labelFromFileName,
|
||||
normalizeToolbox,
|
||||
pruneGameLinks,
|
||||
remapMemosPlannerLink,
|
||||
remapModuleOrderIds,
|
||||
uid
|
||||
|
|
@ -198,6 +199,7 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
|
|||
function linkToolboxToGame(gameId, toolboxId) {
|
||||
const updatedAt = new Date().toISOString();
|
||||
return store.persistToolboxSnapshot((current) => {
|
||||
if (toolboxId && !current.toolboxes.some((toolbox) => toolbox.id === toolboxId)) return current;
|
||||
const links = { ...current.links };
|
||||
const touched = new Set([links[gameId], toolboxId].filter(Boolean));
|
||||
if (toolboxId) links[gameId] = toolboxId;
|
||||
|
|
@ -431,7 +433,8 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
|
|||
importAllToolboxes: async (file) => {
|
||||
if (!store.ready) return false;
|
||||
try {
|
||||
const payload = validateToolboxImportPayload(JSON.parse(await file.text()), "global");
|
||||
const validated = validateToolboxImportPayload(JSON.parse(await file.text()), "global");
|
||||
const payload = { ...validated, links: pruneGameLinks(validated.links, validated.toolboxes) };
|
||||
const reassignedLinks = Object.keys(payload.links || {}).filter((gameId) => store.links?.[gameId]);
|
||||
const runImport = () => importAllToolboxesPayload(payload).then(() => true);
|
||||
const imported = reassignedLinks.length
|
||||
|
|
|
|||
|
|
@ -232,6 +232,39 @@ function applyToolboxChanges(current, mutation, conflicts) {
|
|||
return [...remote, ...ordered];
|
||||
}
|
||||
|
||||
function keepLinksToToolboxes(links, toolboxIds) {
|
||||
return Object.fromEntries(Object.entries(links || {})
|
||||
.filter(([, toolboxId]) => typeof toolboxId === "string" && toolboxIds.has(toolboxId)));
|
||||
}
|
||||
|
||||
// Retire du stockage les associations de jeu dont la toolbox n'existe plus.
|
||||
export async function removeOrphanLinks() {
|
||||
const db = await openDatabase();
|
||||
let removed = 0;
|
||||
await new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(KV_STORE, "readwrite");
|
||||
const kv = transaction.objectStore(KV_STORE);
|
||||
const toolboxRequest = kv.get("toolboxes");
|
||||
const linksRequest = kv.get("links");
|
||||
let remaining = 2;
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(transaction.error);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
function cleanWhenReady() {
|
||||
remaining -= 1;
|
||||
if (remaining) return;
|
||||
const links = linksRequest.result && typeof linksRequest.result === "object" ? linksRequest.result : {};
|
||||
const toolboxIds = new Set((Array.isArray(toolboxRequest.result) ? toolboxRequest.result : []).map((toolbox) => toolbox?.id));
|
||||
const kept = keepLinksToToolboxes(links, toolboxIds);
|
||||
removed = Object.keys(links).length - Object.keys(kept).length;
|
||||
if (removed) kv.put(kept, "links");
|
||||
}
|
||||
toolboxRequest.onsuccess = cleanWhenReady;
|
||||
linksRequest.onsuccess = cleanWhenReady;
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (value) => value } = {}) {
|
||||
if (!mutation?.changed) return;
|
||||
const db = await openDatabase();
|
||||
|
|
@ -291,7 +324,9 @@ export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (val
|
|||
}
|
||||
|
||||
if (mutation.toolboxes.changes.length || mutation.toolboxes.order) kv.put(nextToolboxes, "toolboxes");
|
||||
if (mutation.links.length) kv.put(nextLinks, "links");
|
||||
// Une toolbox supprimée emporte aussi les associations écrites par un autre onglet.
|
||||
const keptLinks = keepLinksToToolboxes(nextLinks, validToolboxIds);
|
||||
if (mutation.links.length || !storageValuesEqual(keptLinks, currentLinks)) kv.put(keptLinks, "links");
|
||||
for (const change of mutation.modules) {
|
||||
if (change.nextExists) modules.put({ key: change.key, data: change.nextValue });
|
||||
else modules.delete(change.key);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue