Fix #54: Adding a background to an actor bug #60

Merged
Syndria98 merged 2 commits from ai/issue-54 into master 2026-10-15 13:18:07 +00:00
3 changed files with 489 additions and 9 deletions
Showing only changes of commit 7e1ed4475e - Show all commits

View File

@@ -1,5 +1,28 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an
// embedded item: `system.details.background` and friends hold that item's id, and the
// field's `fallback` option hands back the bare id when the item is gone. Dragonroll
// holds names, so a reference is read through the actor's items and an id that resolves
// to nothing is dropped. An id travelling back as a name is how Foundry ends up with a
// background item — and a details reference — that does not exist (Syndria98/dragonroll#54).
const FOUNDRY_DOCUMENT_ID = /^[A-Za-z0-9_-]{16}$/;
function looksLikeFoundryId(value) {
// Sixteen plain letters is a name; the ids Foundry generates carry a digit.
return FOUNDRY_DOCUMENT_ID.test(value) && /[0-9]/.test(value) && /[A-Za-z]/.test(value);
}
// The name a `system.details` entry stands for: an embedded item's id resolves to that
// item's name, and plain text (older system releases store the name here) is the name.
function detailsName(value, items) {
const text = asText(value).trim();
if (!text) return '';
const referenced = items.find((item) => asText(item?._id ?? item?.id).trim() === text);
if (referenced) return asText(referenced.name).trim();
return looksLikeFoundryId(text) ? '' : text;
}
function foundryActorToCharacter(foundryActor) {
const system = foundryActor.system || {};
const details = system.details || {};
@@ -25,11 +48,11 @@ function foundryActorToCharacter(foundryActor) {
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
? savedDragonrollType
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
species: asText(details.race || details.species),
className: asText(details.class || classItem?.name),
subclass: asText(details.subclass || subclassItem?.name),
species: detailsName(details.race || details.species, items),
className: detailsName(details.class, items) || asText(classItem?.name),
subclass: detailsName(details.subclass, items) || asText(subclassItem?.name),
level: numberOr(details.level ?? classItem?.system?.levels, 1),
background: asText(details.background || backgroundItem?.name),
background: detailsName(details.background, items) || asText(backgroundItem?.name),
challengeRating: String(details.cr ?? ''),
description: plainText(details.biography?.value || details.biography),
image: asText(foundryActor.img || foundryActor.image),

View File

@@ -1000,10 +1000,10 @@ function makeFoundryCharacterData(entry) {
type: entry.type === "character" ? "character" : "npc",
img: getDragonrollImageUrl(entry.image) || undefined,
system: {
// `details.race` and `details.background` are left out on purpose: they reference
// embedded items and are linked once the actor stands with its items made.
details: {
race: entry.species || "",
level: Number(entry.level) || 1,
background: entry.background || "",
biography: { value: entry.description || "" },
cr: entry.challengeRating || "",
},
@@ -1036,9 +1036,7 @@ function characterUpdateData(entry) {
const updates = {
name: entry.name,
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
"system.details.race": entry.species || "",
"system.details.level": Number(entry.level) || 1,
"system.details.background": entry.background || "",
"system.details.biography.value": entry.description || "",
"system.details.cr": entry.challengeRating || "",
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
@@ -1052,6 +1050,40 @@ function characterUpdateData(entry) {
return updates;
}
// `system.details.background` and `system.details.race` are LocalDocumentFields in
// D&D 5e: they hold the id of an item embedded in the actor, never its name. A name
// written into one is a reference that resolves to nothing, and adding that item in
// Foundry then fails, so each of these follows the actor's own item for it instead.
const EMBEDDED_DETAILS = [
// Dragonroll owns the background item it lists, so its reference follows it always and
// a background taken off in the campaign leaves no reference behind.
{ field: "background", path: "system.details.background", types: ["background"], clearWhenMissing: true },
// The species item belongs to the world: point at it when it carries the name, and
// leave the reference to the GM when it does not.
{ field: "species", path: "system.details.race", types: ["race", "species"] },
];
function localDocumentId(value) {
// The field resolves to the referenced document when it can and to the stored id
// when the document is gone (its `fallback` option).
if (typeof value === "string") return value;
return value?._id || "";
}
function embeddedDetailReferenceData(actor, entry) {
const updates = {};
for (const detail of EMBEDDED_DETAILS) {
const wanted = String(entry[detail.field] || "").trim();
const item = wanted
? actor.items?.contents?.find((candidate) => detail.types.includes(candidate.type) && candidate.name === wanted)
: null;
const reference = item?.id || "";
if (!reference && !detail.clearWhenMissing) continue;
if (localDocumentId(documentValue(actor, detail.path)) !== reference) updates[detail.path] = reference;
}
return updates;
}
async function reconcileEmbeddedItems(actor, entry) {
const desired = [];
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
@@ -1110,6 +1142,9 @@ async function applyDragonrollCharacter(actor, entry) {
await withActorSyncSuppressed(actor, async () => {
if (changed) await actor.update(updates);
await reconcileEmbeddedItems(actor, entry);
// The item references are written after the reconcile that makes the items they point at.
const references = embeddedDetailReferenceData(actor, entry);
if (Object.keys(references).length) await actor.update(references);
if (dragonrollActorId(actor) !== String(entry._id)
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
await actor.update({
@@ -1137,7 +1172,12 @@ async function createFoundryCharacter(entry) {
if (!actor) return;
await withActorSyncSuppressed(actor, async () => {
await actor.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
await actor.update({
// The actor was made with its items, so its background and species references
// can point at them right away.
...embeddedDetailReferenceData(actor, entry),
[`flags.${MODULE_ID}.syncMutation`]: false,
});
});
await mapDragonrollActor(entry._id, actor.id);
}

View File

@@ -0,0 +1,417 @@
// Tests for the D&D 5e details the system keeps as a reference to an embedded item
// (Syndria98/dragonroll#54). `system.details.background` and `system.details.race` are
// LocalDocumentFields: they hold the id of the actor's background / race item and never
// its name, and their `fallback` option hands the bare id back when that item is gone.
// Dragonroll holds names, so reading the id as a name and writing it back gave Foundry a
// background item that does not exist and a details reference resolving to nothing —
// adding a background in Foundry then failed.
//
// The backend mapper is plain CommonJS and is required directly. The Foundry module is
// loaded into a `node:vm` context holding stubbed Foundry globals with fake timers, like
// tests/foundry-sync-toggle.test.js: the characters Dragonroll answers with are applied
// to a stubbed actor, so the references it writes are observable.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const MODULE_ID = "dragonroll-foundry";
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
// Foundry generates document ids as sixteen characters of its alphabet, digits included.
const ID_GONE = "aB3cD9eF1gH2iJ4k";
const ID_SOLDIER = "Kx7pQ2mR9vT4wZ8n";
const ID_HUMAN = "7QcL2fYh5Bd0Mn3s";
function foundryActor(details = {}, items = []) {
return { _id: "actor-1", name: "Thalia", type: "character", system: { details }, items };
}
test("a background carried as an item arrives by its name, not its id", () => {
const character = foundryActor(
{ background: ID_SOLDIER },
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
);
assert.equal(foundryActorToCharacter(character).background, "Soldier");
});
test("a background reference whose item is gone does not become a background", () => {
// The item was deleted, and `fallback: true` gives the id back instead.
const character = foundryActor({ background: ID_GONE }, []);
assert.equal(foundryActorToCharacter(character).background, "");
});
test("a background item takes the place of a reference that resolves to nothing", () => {
const character = foundryActor(
{ background: ID_GONE },
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
);
assert.equal(foundryActorToCharacter(character).background, "Soldier");
});
test("a plain-text background from an older system release is still a name", () => {
const character = foundryActor({ background: "Sailor" }, []);
assert.equal(foundryActorToCharacter(character).background, "Sailor");
});
test("the class, subclass and species references resolve the same way", () => {
const items = [
{ _id: ID_HUMAN, name: "Human", type: "race" },
{ _id: "cls1Id00000000", name: "Fighter", type: "class" },
{ _id: "sub1Id00000000", name: "Oracle", type: "subclass" },
];
const character = foundryActor(
{ race: ID_HUMAN, class: "cls1Id00000000", subclass: "sub1Id00000000" },
items,
);
const fields = foundryActorToCharacter(character);
assert.equal(fields.species, "Human");
assert.equal(fields.className, "Fighter");
assert.equal(fields.subclass, "Oracle");
});
test("a class reference that resolves to nothing falls back to the class item", () => {
const character = foundryActor(
{ class: ID_GONE, race: ID_GONE },
[{ _id: "cls1Id00000000", name: "Fighter", type: "class" }],
);
const fields = foundryActorToCharacter(character);
assert.equal(fields.className, "Fighter", "the class the actor carries, not the id");
assert.equal(fields.species, "", "and nothing to name the species from");
});
// --- The Foundry module applies Dragonroll's character --------------------------
// A reference is either the id this sync wrote or the document the field resolves to.
function referenceId(actor, field) {
const value = actor.system.details?.[field];
return typeof value === "string" ? value : value?._id || "";
}
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
return {
_id: id,
id,
name,
type,
system,
flags,
parent: { documentName: "Actor" },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
toObject() {
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
},
};
}
function writeDotted(target, data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
}
let stubCounter = 0;
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
stubCounter += 1;
const id = `actor-${stubCounter}`;
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
const actor = {
id,
name,
type,
documentName: "Actor",
img: "icons/svg/mystery-man.svg",
system,
flags,
items: { contents },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
writeDotted(this, data);
return this;
},
async updateEmbeddedDocuments(documentName, updates) {
for (const update of updates) {
const item = contents.find((candidate) => candidate.id === update._id);
if (item) writeDotted(item, update);
}
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
},
async createEmbeddedDocuments(documentName, datas) {
const created = datas.map((data) => {
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
item.name = data.name;
item.type = data.type;
contents.push(item);
return item;
});
return created;
},
async deleteEmbeddedDocuments(documentName, ids) {
for (const id of ids) {
const index = contents.findIndex((item) => item.id === id);
if (index >= 0) contents.splice(index, 1);
}
return ids;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: this.img,
flags: this.flags,
system: this.system,
};
},
};
return actor;
}
// A linked world with the actors it holds, answering `foundry/sync/characters` with the
// campaign's characters. Each one is applied to its Foundry actor on the next reconcile.
function makeWorld({ actors = [], remoteActors = [] } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
logs: [],
};
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: {
log() {},
info() {},
warn: (...args) => state.logs.push(args.map(String).join(" ")),
error: (...args) => state.logs.push(args.map(String).join(" ")),
},
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: { notifications: { info() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const timerId = state.nextTimerId++;
state.timers.set(timerId, { fn, delay });
return timerId;
},
clearTimeout: (timerId) => state.timers.delete(timerId),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Item: { async create() { return null; } },
Actor: {
async create(data) {
const actor = makeStubActor(data.name, {
type: data.type,
system: structuredClone(data.system || {}),
flags: structuredClone(data.flags || {}),
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
});
actors.push(actor);
return actor;
},
},
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
items: { contents: [], get: () => null },
folders: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
state.game = sandbox.game;
state.actor = (actorId) => actors.find((actor) => actor.id === actorId);
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
// World start: the actors are pushed, then the campaign's characters are applied.
state.start = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
return state;
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
state.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
return state;
}
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
function campaignCharacter(actor, over = {}) {
return {
_id: "dr-actor-1",
name: "Thalia",
type: "character",
species: "",
className: "",
subclass: "",
level: 1,
background: "",
challengeRating: "",
description: "",
image: "",
abilityScores: {},
armorClass: 10,
speed: 30,
traits: "",
proficiencies: "",
spells: "",
inventory: [],
foundryActorId: actor?.id ?? null,
...over,
};
}
test("Dragonroll's background becomes the actor's background item, referenced by id", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: "" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "the character's background stands in Foundry as an item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "its details reference points at the item");
assert.equal(actor.system.details.background, background.id);
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the background an earlier sync invented is taken back out", async () => {
// What the bug left behind: an item named after the id the details field held, next to
// the real background, and a reference the old sync overwrote with that id.
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_GONE } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "item-bogus", name: ID_GONE, type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
assert.deepEqual(world.itemNames(actor), [["background", "Soldier"]], "only the real background is left");
assert.equal(referenceId(actor, "background"), ID_SOLDIER, "and the reference resolves to it");
});
test("a background taken off in Dragonroll clears the reference", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_SOLDIER } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({ actors: [actor], remoteActors: [campaignCharacter(actor)] }).start();
assert.deepEqual(world.itemNames(actor), [], "the background item went with it");
assert.equal(referenceId(actor, "background"), "", "and no reference is left pointing at nothing");
});
test("a species never lands in the details reference as a name", async () => {
const actor = makeStubActor("Thalia", {
// A species picked in the sheet: dnd5e made the race item and referenced it by id.
system: { details: { race: ID_HUMAN } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: ID_HUMAN, name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } }],
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human", background: "Soldier" })],
}).start();
assert.equal(referenceId(actor, "race"), ID_HUMAN, "the species reference still points at the race item");
assert.notEqual(actor.system.details.race, "Human", "a name in it would resolve to nothing");
});
test("a species the world keeps as plain text is left to the world", async () => {
// An actor migrated from an older system release: no race item, the name is what the
// field holds, and Dragonroll has nothing to reference.
const actor = makeStubActor("Thalia", {
system: { details: { race: "Human" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human" })],
}).start();
assert.equal(actor.system.details.race, "Human", "the text the sheet reads is kept as it was");
});
test("a character made in Dragonroll references the background it is created with", async () => {
const world = await makeWorld({ actors: [], remoteActors: [campaignCharacter(null, { background: "Soldier" })] }).start();
const [actor] = world.game.actors.contents;
assert.ok(actor, "the campaign's character was made in this world");
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "created together with its background item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "referenced by that item's id, never its name");
});