Fix #89: Traits and items are mixed up #92

Merged
Syndria98 merged 1 commits from ai/issue-89 into master 2026-10-15 22:01:34 +00:00
7 changed files with 586 additions and 5 deletions

View File

@@ -9,6 +9,7 @@ const Item = require('../models/Item');
const Folder = require('../models/Folder'); const Folder = require('../models/Folder');
const { foundryActorToCharacter } = require('../services/actor-foundry'); const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry'); const { foundryItemToItemData } = require('../services/item-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
// Upper bound for the Foundry names remembered per synced item (see Item model). // Upper bound for the Foundry names remembered per synced item (see Item model).
const MAX_FOUNDRY_NAMES = 20; const MAX_FOUNDRY_NAMES = 20;
@@ -41,10 +42,33 @@ function requestMatchesWorld(campaign, worldId) {
return typeof worldId === 'string' && worldId === campaign.foundryWorldId; return typeof worldId === 'string' && worldId === campaign.foundryWorldId;
} }
// Foundry serves its data directory from the world's own address, which is the one the
// campaign keeps under `settings.integrations.foundryUrl` — the icon window already loads
// the world's icons through it. The module sends the images it publishes as absolute URLs;
// the bridge's snapshot and older modules carry Foundry's relative paths, and a sheet
// reading one of those against Dragonroll's upload folder finds nothing, which is how the
// icons stopped loading (Syndria98/dragonroll#89). An absolute URL travels as it is, and so
// does a path when the campaign has no world address to read it against.
function worldAssetUrl(image, worldUrl) {
const value = String(image ?? '').trim();
if (!value || /^(https?:|data:|\/\/)/i.test(value)) return value;
return joinFoundryAssetUrl(worldUrl, value) || value;
}
// The images a world document arrives with, read against its world before they land.
function resolveWorldAssets(fields, campaign) {
const worldUrl = campaign?.settings?.integrations?.foundryUrl;
if (typeof fields.image === 'string') fields.image = worldAssetUrl(fields.image, worldUrl);
if (Array.isArray(fields.inventory)) {
for (const entry of fields.inventory) entry.icon = worldAssetUrl(entry.icon, worldUrl);
}
}
async function saveFoundryActor(campaign, source, fullSync = false) { async function saveFoundryActor(campaign, source, fullSync = false) {
const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120); const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryActorToCharacter(source || {}); const fields = foundryActorToCharacter(source || {});
if (!foundryActorId || !fields.name) return null; if (!foundryActorId || !fields.name) return null;
resolveWorldAssets(fields, campaign);
let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId }); let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId });
const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId; const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId;
@@ -85,6 +109,7 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120); const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {}); const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null; if (!foundryItemId || !fields) return null;
resolveWorldAssets(fields, campaign);
let item = await Item.findOne({ campaign: campaign._id, foundryItemId }); let item = await Item.findOne({ campaign: campaign._id, foundryItemId });
const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId; const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId;

View File

@@ -1,4 +1,5 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields'); const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
const { isFoundryGearType } = require('./item-foundry');
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an // 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 // embedded item: `system.details.background` and friends hold that item's id, and the
@@ -169,8 +170,11 @@ function foundryActorToCharacter(foundryActor) {
armorClass: numberOr(attributes.ac?.value ?? attributes.ac, 10), armorClass: numberOr(attributes.ac?.value ?? attributes.ac, 10),
speed: numberOr(movement.walk ?? movement.value, 30), speed: numberOr(movement.walk ?? movement.value, 30),
proficiencies: foundryProficiencies || asText(savedDragonrollFields.proficiencies), proficiencies: foundryProficiencies || asText(savedDragonrollFields.proficiencies),
// What the character carries: gear, and gear only (Syndria98/dragonroll#89). A feat
// is a trait — its tab shows it — and a race is the species; standing them in the
// inventory next to the longswords is how traits and items got mixed up.
inventory: items inventory: items
.filter((item) => !['class', 'subclass', 'background', 'spell'].includes(item.type)) .filter((item) => isFoundryGearType(item.type))
.map((item) => ({ .map((item) => ({
name: asText(item.name).trim(), name: asText(item.name).trim(),
quantity: numberOr(item.system?.quantity, 1), quantity: numberOr(item.system?.quantity, 1),

View File

@@ -23,6 +23,14 @@ const NON_GEAR_FOUNDRY_TYPES = new Set([
'spell', 'class', 'subclass', 'background', 'feat', 'race', 'species', 'status', 'spellbook', 'language' 'spell', 'class', 'subclass', 'background', 'feat', 'race', 'species', 'status', 'spellbook', 'language'
]); ]);
// Whether a Foundry document of this type is gear: something a character carries. Traits,
// species, spells and the rest are documents of the world that mean something else on a
// Dragonroll sheet — a feat is a trait and a race is a species — so they stand in the
// character's own fields, never in its inventory (Syndria98/dragonroll#89).
function isFoundryGearType(type) {
return !NON_GEAR_FOUNDRY_TYPES.has(asText(type).toLowerCase().trim());
}
// Item categories the Dragonroll Item model accepts. // Item categories the Dragonroll Item model accepts.
const CATEGORIES = ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other']; const CATEGORIES = ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other'];
@@ -107,4 +115,4 @@ function foundryItemToItemData(foundryItem) {
}; };
} }
module.exports = { foundryItemToItemData }; module.exports = { foundryItemToItemData, isFoundryGearType };

View File

@@ -523,9 +523,16 @@ function isSupportedCharacterActor(actor) {
return ["character", "npc", "creature"].includes(savedType || actor.type); return ["character", "npc", "creature"].includes(savedType || actor.type);
} }
// Embedded documents the world owns outright (Syndria98/dragonroll#89): a feat is a trait
// and a race is a species — they reach the campaign through its traits and species fields,
// never through its inventory. Dragonroll must neither mark them as its own nor delete one
// when it writes the character, and an older campaign still holding such a row in its
// inventory must be let to write it out of the campaign without the document going with it.
const WORLD_OWNED_EMBEDDED_TYPES = new Set(["feat", "race", "species", "status", "spellbook", "language"]);
async function markActorItemsAsSynced(actor) { async function markActorItemsAsSynced(actor) {
const updates = actor.items.contents const updates = actor.items.contents
.filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem")) .filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
.map((item) => ({ .map((item) => ({
_id: item.id, _id: item.id,
[`flags.${MODULE_ID}.syncedItem`]: true, [`flags.${MODULE_ID}.syncedItem`]: true,
@@ -1194,7 +1201,19 @@ async function reconcileEmbeddedItems(actor, entry) {
const existing = actor.items.contents.find((item) => item.name === wanted.name const existing = actor.items.contents.find((item) => item.name === wanted.name
&& item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem")) && item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem"))
|| actor.items.contents.find((item) => item.name === wanted.name || actor.items.contents.find((item) => item.name === wanted.name
&& item.getFlag?.(MODULE_ID, "syncedItem")); && item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
// A carried row holding the name of one of the world's own trait or species documents
// — a trait a campaign that synced before #89 still has in its inventory — stands in
// the world as that document: no loot is made after its name, and the document itself
// is let be. Writing it out of the campaign is the campaign's to do, keeping it is the world's.
if (!existing && wanted.type === "loot") {
const worldOwned = actor.items.contents.find((item) => item.name === wanted.name
&& WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
if (worldOwned) {
retainedIds.add(worldOwned.id);
continue;
}
}
if (existing) { if (existing) {
retainedIds.add(existing.id); retainedIds.add(existing.id);
const update = { _id: existing.id }; const update = { _id: existing.id };
@@ -1220,7 +1239,8 @@ async function reconcileEmbeddedItems(actor, entry) {
} }
const staleItemIds = actor.items.contents const staleItemIds = actor.items.contents
.filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id)) .filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id)
&& !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
.map((item) => item.id); .map((item) => item.id);
if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds); if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds);
} }

View File

@@ -0,0 +1,522 @@
// Tests for Syndria98/dragonroll#89: on the character sheet traits and items were all
// displayed together and the icons did not load. The world's mapper put every embedded
// document that was not a class, subclass, background or spell into the character's
// inventory — so its traits (feat items) and its species (the race item) stood in the
// inventory list beside the gear, while the sheet already shows both in fields of their
// own. And a world image that arrives as a Foundry path — the bridge's snapshot and older
// modules send those, where the module sends absolute URLs — was read against Dragonroll's
// uploads folder, where nothing of that name is, so nothing loaded.
//
// The mapper is plain CommonJS and is required for real. The writers run in a stubbed
// `require` against fake models, like tests/foundry-force-import.test.js runs them. And
// since the campaign's inventory no longer claims trait and species documents, the module
// must stop deleting ones earlier syncs marked as its own: the Foundry module goes into a
// `node:vm` context holding stubbed Foundry globals with fake timers, like
// tests/foundry-actor-details.test.js, so what writing a character leaves behind is 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const repoRequire = (relative) => require(path.join(__dirname, "..", relative));
const MODULE_ID = "dragonroll-foundry";
// --- What the world's mapper keeps where -------------------------------------------------
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
test("traits and species stand in their own fields, not among the carried items", () => {
const character = foundryActorToCharacter({
name: "Thalia",
system: { details: {} },
items: [
{ name: "Longsword", type: "weapon", img: "http://vtt.test/icons/sword.svg", system: { quantity: 1, weight: { value: 3 } } },
{ name: "Rope", type: "equipment", system: { quantity: 2 } },
{ name: "Darkvision", type: "feat", system: { featType: "trs", description: { value: "<p>See in the dark.</p>" } } },
{ name: "Human", type: "race" },
{ name: "Spellbook", type: "spellbook" },
{ name: "Magic Missile", type: "spell" },
{ name: "Fighter", type: "class" },
{ name: "Oracle", type: "subclass" },
{ name: "Soldier", type: "background" },
],
});
assert.deepEqual(character.inventory.map((item) => item.name), ["Longsword", "Rope"],
"the inventory holds what the character carries, and nothing else");
assert.deepEqual(character.inventory[0],
{ name: "Longsword", quantity: 1, weight: 3, icon: "http://vtt.test/icons/sword.svg" });
assert.equal(character.traits, "Darkvision\nSee in the dark.", "the feat is read as a trait, where the sheet shows it");
assert.equal(character.spells, "Magic Missile", "and the spell where its tab shows it");
});
test("gear of a type the mapper has never seen is still carried", () => {
const character = foundryActorToCharacter({
name: "Thalia",
items: [{ name: "Strange Relic", type: "loot", system: { quantity: 1 } }],
});
assert.deepEqual(character.inventory.map((item) => item.name), ["Strange Relic"],
"only the listed non-gear types are let out of the inventory");
});
// --- The writers read a world's paths off the world's address ----------------------------
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(value.slice(0, count)),
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Enough of the query language the writers use: equality and $or.
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected)) {
return Object.entries(expected).every(([operator, wanted]) => {
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = [], campaignId) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
this.foundryNames = [];
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) {
const row = new Document({ campaign: campaignId, ...data });
row.isNew = false;
rows.push(row);
}
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
return model;
}
// The sync writers against fake models. `settings` is what the campaign keeps — the world
// address the icons are loaded from stands in it, as it does in the real one.
function loadFoundryWriters({ seed = {}, settings } = {}) {
const campaign = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1", ...(settings ? { settings } : {}) };
const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
const models = {
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => ({ get: () => {}, post: () => {} }) };
if (id.startsWith("node:")) return require(id);
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
return { campaign, models, writers: moduleStub.exports };
}
test("a world image that arrives as a path is stored as the address the sheet can load", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000/" } } });
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1",
name: "Thalia",
type: "character",
img: "icons/actors/thalia.svg",
items: [
{ name: "Torch", type: "loot", img: "icons/tools/torch torch.svg", system: { quantity: 2 } },
{ name: "Darkvision", type: "feat", img: "icons/svg/eye.svg" },
],
});
const actor = sync.models["../models/Actor"].rows[0];
assert.equal(actor.image, "http://vtt.test:30000/icons/actors/thalia.svg", "the portrait is read off the world's address");
assert.deepEqual(actor.inventory.map((item) => item.name), ["Torch"], "the feat is not carried into the inventory");
assert.equal(actor.inventory[0].icon, "http://vtt.test:30000/icons/tools/torch%20torch.svg", "and the gear's icon is");
});
test("the absolute addresses the module sends travel as they are", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1",
name: "Thalia",
img: "http://elsewhere.test/portraits/thalia.png",
items: [{ name: "Torch", type: "loot", img: "data:image/png;base64,TgA=" }],
});
const actor = sync.models["../models/Actor"].rows[0];
assert.equal(actor.image, "http://elsewhere.test/portraits/thalia.png");
assert.equal(actor.inventory[0].icon, "data:image/png;base64,TgA=");
});
test("a campaign with no world address keeps the path as it came", async () => {
const sync = loadFoundryWriters();
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1", name: "Thalia", img: "icons/actors/thalia.svg",
});
assert.equal(sync.models["../models/Actor"].rows[0].image, "icons/actors/thalia.svg",
"with no world to read it against, nothing is invented for it");
});
test("a world item's icon is read off the world's address the same way", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
await sync.writers.saveFoundryItem(sync.campaign, {
_id: "item-1", name: "Longsword", type: "weapon", img: "icons/equipment/sword.svg",
});
const item = sync.models["../models/Item"].rows[0];
assert.equal(item.image, "http://vtt.test:30000/icons/equipment/sword.svg");
assert.equal(item.foundryImage, "http://vtt.test:30000/icons/equipment/sword.svg",
"the icon the item window offers back is the loadable one too");
});
// --- The module leaves the world's own documents alone ------------------------------------
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);
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;
}
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;
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]);
state.actorPushes = () => state.requests
.filter((request) => request.href.includes("foundry/sync/snapshot"))
.map((request) => request.body.actors[0]);
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("a trait row an older campaign left in the inventory does not become a loot duplicate", async () => {
// A campaign that synced before #89 still carries its world's traits as inventory
// rows. Writing the character must neither make a piece of loot after a trait's name
// nor touch the world's feat it holds that name — the row is the campaign's to write
// off, and the document is the world's to keep.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: "feat-1", name: "Darkvision", type: "feat", system: { featType: "trs" } }],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Darkvision", quantity: 1, weight: 0 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [["feat", "Darkvision"]],
"no gear made after the trait's name, and the feat stands where it was");
assert.equal(actor.items.contents[0].system.quantity, undefined, "the world's feat is not written as gear");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("writing the character leaves the world's trait and species documents where they stand", async () => {
// An earlier sync marked everything in the actor as its own. The campaign no longer
// carries traits and species in the inventory, so those marks must not cost the world
// its documents — while loot the campaign truly dropped still goes.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: "feat-1", name: "Darkvision", type: "feat", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "race-1", name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "loot-old", name: "Torch", type: "loot", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
species: "Human",
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Rations", quantity: 1, weight: 0.5 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [
["feat", "Darkvision"],
["race", "Human"],
["loot", "Rations"],
], "the trait and the species survive, the carried gear follows the campaign");
assert.equal(actor.system.details.race, "race-1", "the species reference still resolves to the surviving item");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the snapshot marks the carried gear and no longer the world's own documents", async () => {
const actor = makeStubActor("Grimnir", {
system: { details: {} },
items: [
{ name: "Longsword", type: "weapon" },
{ name: "Darkvision", type: "feat" },
{ name: "Giant", type: "race" },
],
});
await makeWorld({ actors: [actor], remoteActors: [] }).start();
const [sword, feat, race] = actor.items.contents;
assert.equal(sword.getFlag(MODULE_ID, "syncedItem"), true, "the gear the campaign carries is marked as its own");
assert.equal(feat.getFlag(MODULE_ID, "syncedItem"), undefined, "a trait is not");
assert.equal(race.getFlag(MODULE_ID, "syncedItem"), undefined, "neither is a species");
});
test("an actor snapshot still sends the feats its traits are made of", async () => {
// Leaving feats out of the inventory must not leave them out of the snapshot: they are
// what the campaign's traits tab reads.
const actor = makeStubActor("Thalia", {
system: { details: {} },
items: [{ name: "Darkvision", type: "feat", system: { featType: "trs" } }],
});
const world = await makeWorld({ actors: [actor], remoteActors: [] }).start();
const sent = world.actorPushes().at(-1);
assert.deepEqual(sent.items.map((item) => [item.type, item.name]), [["feat", "Darkvision"]],
"the feat still travels with its actor, as the traits text is read off it");
});

View File

@@ -280,6 +280,7 @@ function loadFoundryWriters({ seed = {} } = {}) {
if (id === "../models/Campaign") return { findOne: async () => campaign }; if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js")); if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js")); if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id]; if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`); throw new Error(`require("${id}") is not stubbed`);
}; };

View File

@@ -141,6 +141,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
if (id === "../models/Campaign") return { findOne: async () => campaign }; if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) }; if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js")); if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id]; if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`); throw new Error(`require("${id}") is not stubbed`);
}; };