418 lines
16 KiB
JavaScript
418 lines
16 KiB
JavaScript
// 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");
|
|
});
|