This commit is contained in:
599
tests/map-foundry-sync.test.js
Normal file
599
tests/map-foundry-sync.test.js
Normal file
@@ -0,0 +1,599 @@
|
||||
// Tests for the world's scenes arriving as the campaign's maps (Syndria98/dragonroll#99).
|
||||
// Only a scene's background picture and the grid laid over it travel: the campaign keeps its
|
||||
// own scale, its folders, its pinned notes and the tokens standing on the map, and none of it
|
||||
// goes back to the world.
|
||||
//
|
||||
// Same set-up as tests/item-folder-sync.test.js, which the repository root runs without
|
||||
// installing anything: the sync route is loaded into `node:vm` with express, mongoose and its
|
||||
// models stubbed (plain rows and a small filter matcher), so creating, adopting and pruning
|
||||
// maps is observable without a database. The Foundry module is loaded into a `node:vm` context
|
||||
// holding stubbed Foundry globals (`game.scenes` included) with fake timers, like
|
||||
// tests/foundry-sync-toggle.test.js.
|
||||
//
|
||||
// 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));
|
||||
|
||||
// --- The sync route against stubbed models -------------------------------------
|
||||
|
||||
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and
|
||||
// lets `select()`, `sort()` and `limit()` sit in between.
|
||||
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 scene sync uses: equality, $in, $nin, $exists.
|
||||
// Anything else is a filter this test did not expect and says so.
|
||||
function matches(document, filter = {}) {
|
||||
return Object.entries(filter).every(([key, expected]) => {
|
||||
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;
|
||||
if (operator === "$in") return wanted.some((entry) => String(value) === String(entry));
|
||||
if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry));
|
||||
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;
|
||||
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) {
|
||||
// A seeded row belongs to the campaign the requests are made against unless the seed
|
||||
// says otherwise: the sync scopes every lookup by campaign.
|
||||
const row = new Document({ campaign: campaignId, name: undefined, ...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)));
|
||||
model.deleteOne = async (filter) => {
|
||||
const hit = rows.filter((row) => matches(row, filter));
|
||||
for (const row of hit) rows.splice(rows.indexOf(row), 1);
|
||||
return { deletedCount: hit.length };
|
||||
};
|
||||
model.deleteMany = async (filter) => {
|
||||
const hit = rows.filter((row) => matches(row, filter));
|
||||
for (const row of hit) rows.splice(rows.indexOf(row), 1);
|
||||
return { deletedCount: hit.length };
|
||||
};
|
||||
return model;
|
||||
}
|
||||
|
||||
// The Foundry sync route with every model it requires stubbed. `seed` pre-fills the tables
|
||||
// with documents the campaign already holds.
|
||||
function loadSyncRoute({ seed = {}, worldId = "world-1", settings } = {}) {
|
||||
const routes = new Map();
|
||||
const router = {
|
||||
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
|
||||
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
|
||||
};
|
||||
const campaign = {
|
||||
_id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId,
|
||||
...(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)),
|
||||
"../models/Note": fakeModel("note", seeded(seed.notes)),
|
||||
"../models/Map": fakeModel("map", seeded(seed.maps)),
|
||||
};
|
||||
|
||||
const requireStub = (id) => {
|
||||
if (id === "express") return { Router: () => router };
|
||||
if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed
|
||||
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 { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
|
||||
if (id === "../services/item-foundry") return { foundryItemToItemData: () => null };
|
||||
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
|
||||
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.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
|
||||
);
|
||||
|
||||
async function call(route, body = {}) {
|
||||
const handlers = routes.get(route);
|
||||
assert.ok(handlers, `${route} is not mounted`);
|
||||
const res = { payload: null, json(payload) { this.payload = payload; }, set: () => {} };
|
||||
const req = { body, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token" : "") };
|
||||
await handlers[handlers.length - 1](req, res);
|
||||
return res.payload;
|
||||
}
|
||||
|
||||
return { call, models, campaign };
|
||||
}
|
||||
|
||||
// A scene of the world, as the module sends it: plain document data with its picture read
|
||||
// from the world. This one is 70 px cells and the picture of the ruined keep.
|
||||
function worldScene(over = {}) {
|
||||
return {
|
||||
_id: "scene-1",
|
||||
name: "The Ruined Keep",
|
||||
img: "http://vtt.test/images/keep.webp",
|
||||
grid: 70,
|
||||
flags: {},
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const maps = (sync) => sync.models["../models/Map"].rows;
|
||||
|
||||
// --- A scene arrives as a map -------------------------------------------------------
|
||||
|
||||
test("a world scene arrives as a map of the campaign", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
const response = await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
const [map] = maps(sync);
|
||||
assert.equal(map.name, "The Ruined Keep");
|
||||
assert.equal(map.image, "http://vtt.test/images/keep.webp", "the scene's background picture is the map's");
|
||||
assert.equal(map.gridSize, 70, "the scene's own cell size is the grid the campaign draws");
|
||||
assert.equal(map.offsetX, 0);
|
||||
assert.equal(map.offsetY, 0, "a scene that shifts nothing has its grid at the corner of the picture");
|
||||
assert.equal(map.foundrySceneId, "scene-1");
|
||||
assert.equal(map.campaign, sync.campaign._id, "the map belongs to the campaign the world is linked to");
|
||||
assert.deepEqual(response.maps, [{ foundrySceneId: "scene-1", mapId: map._id, created: true }]);
|
||||
});
|
||||
|
||||
test("a scene keeps the grid its world shifted onto the picture", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
await sync.call("POST /sync/scenes", {
|
||||
worldId: "world-1",
|
||||
scenes: [worldScene({ grid: 64, flags: { core: { shiftX: 12, shiftY: -8 } } })],
|
||||
});
|
||||
|
||||
const [map] = maps(sync);
|
||||
assert.equal(map.gridSize, 64);
|
||||
assert.equal(map.offsetX, 12);
|
||||
assert.equal(map.offsetY, -8, "a grid that starts off the corner of the picture arrives where the world puts it");
|
||||
});
|
||||
|
||||
test("a scene of a newer Foundry still arrives", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
// Since Foundry V13 the picture sits under `background.src` and the cell size under
|
||||
// `grid.size`.
|
||||
await sync.call("POST /sync/scenes", {
|
||||
worldId: "world-1",
|
||||
scenes: [worldScene({ img: undefined, background: { src: "http://vtt.test/images/keep.webp" }, grid: { size: 128 } })],
|
||||
});
|
||||
|
||||
const [map] = maps(sync);
|
||||
assert.equal(map.image, "http://vtt.test/images/keep.webp");
|
||||
assert.equal(map.gridSize, 128);
|
||||
});
|
||||
|
||||
test("a scene's picture is read against the world the campaign knows", async () => {
|
||||
// An older module sends Foundry's own relative path; it is read against the world's
|
||||
// address, the way an actor's portrait is (Syndria98/dragonroll#89).
|
||||
const sync = loadSyncRoute({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene({ img: "images/keep.webp" })] });
|
||||
|
||||
assert.equal(maps(sync)[0].image, "http://vtt.test:30000/images/keep.webp");
|
||||
});
|
||||
|
||||
test("a scene with no picture is not a map", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1", image: "http://vtt.test/images/keep.webp" }] },
|
||||
});
|
||||
|
||||
// The GM took the picture off the scene: its id still travels with the snapshot, so its
|
||||
// map is neither made blank nor dropped, and no new row is made for it either.
|
||||
const response = await sync.call("POST /sync/scenes", {
|
||||
worldId: "world-1",
|
||||
scenes: [worldScene({ img: "" })],
|
||||
fullSync: true,
|
||||
});
|
||||
|
||||
assert.deepEqual(response.maps, []);
|
||||
assert.equal(maps(sync).length, 1);
|
||||
assert.equal(maps(sync)[0].image, "http://vtt.test/images/keep.webp");
|
||||
});
|
||||
|
||||
test("what one of the map's cells stands for stays the campaign's", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1", gridSize: 50, scale: 1.5 }] },
|
||||
});
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene({ gridDistance: 1500, gridUnits: "m" })] });
|
||||
|
||||
assert.equal(maps(sync)[0].gridSize, 70, "the world's cell size arrives");
|
||||
assert.equal(maps(sync)[0].scale, 1.5, "and the distance the campaign says a cell covers is left alone");
|
||||
});
|
||||
|
||||
// --- One map per scene ---------------------------------------------------------------
|
||||
|
||||
test("the same scene is never made into two maps", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
|
||||
const response = await sync.call("POST /sync/scenes", {
|
||||
worldId: "world-1",
|
||||
scenes: [worldScene({ name: "The Ruined Keep, II", grid: 80 })],
|
||||
});
|
||||
|
||||
assert.equal(maps(sync).length, 1, "the scene was written over, not doubled");
|
||||
assert.equal(maps(sync)[0].name, "The Ruined Keep, II");
|
||||
assert.equal(maps(sync)[0].gridSize, 80);
|
||||
assert.equal(response.maps[0].created, false, "the push says it wrote a map it already had");
|
||||
});
|
||||
|
||||
test("a live scene edit lands on the map, however the campaign had it", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "Old name", foundrySceneId: "scene-1", image: "old.png", gridSize: 40 }] },
|
||||
});
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
|
||||
|
||||
const [map] = maps(sync);
|
||||
assert.equal(map.image, "http://vtt.test/images/keep.webp");
|
||||
assert.equal(map.gridSize, 70);
|
||||
assert.equal(map.name, "The Ruined Keep");
|
||||
});
|
||||
|
||||
test("a full snapshot leaves the picture and grid the campaign lined up alone", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "My keep", foundrySceneId: "scene-1", image: "my-keep.png", gridSize: 40 }] },
|
||||
});
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()], fullSync: true });
|
||||
|
||||
const [map] = maps(sync);
|
||||
assert.equal(map.image, "my-keep.png", "a GM reconnecting does not write over a map the campaign already had");
|
||||
assert.equal(map.gridSize, 40);
|
||||
assert.equal(map.name, "My keep");
|
||||
});
|
||||
|
||||
test("a scene takes over the map the campaign drew by hand", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", image: "hand-made.png", gridSize: 50 }] },
|
||||
});
|
||||
|
||||
const response = await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
|
||||
|
||||
assert.equal(maps(sync).length, 1, "the room the campaign drew first is not doubled by its scene");
|
||||
assert.equal(maps(sync)[0]._id, "map-1");
|
||||
assert.equal(maps(sync)[0].foundrySceneId, "scene-1", "and it is the scene's map from then on");
|
||||
assert.equal(response.maps[0].mapId, "map-1");
|
||||
});
|
||||
|
||||
test("a scene carrying the campaign's map id adopts that row", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-0123456789abcdef0123456789", name: "Keep under way", image: "hand-made.png" }] },
|
||||
});
|
||||
|
||||
const response = await sync.call("POST /sync/scenes", {
|
||||
worldId: "world-1",
|
||||
scenes: [worldScene({ name: "Somewhere else", flags: { "dragonroll-foundry": { mapId: "map-0123456789abcdef0123456789" } } })],
|
||||
});
|
||||
|
||||
assert.equal(maps(sync).length, 1);
|
||||
assert.equal(response.maps[0].mapId, "map-0123456789abcdef0123456789", "the flag says which map the scene is");
|
||||
});
|
||||
|
||||
// --- Pruning --------------------------------------------------------------------------
|
||||
|
||||
test("a full snapshot prunes the maps whose scene this world let go of", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
maps: [
|
||||
{ _id: "map-1", name: "Cellar", foundrySceneId: "scene-gone" },
|
||||
{ _id: "map-2", name: "Homebrew ford" },
|
||||
{ _id: "map-3", name: "The Ruined Keep", foundrySceneId: "scene-1" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()], fullSync: true });
|
||||
|
||||
assert.deepEqual(maps(sync).map((map) => map._id).sort(), ["map-2", "map-3"],
|
||||
"the scene that is gone takes its map with it, and the campaign's own maps stay");
|
||||
});
|
||||
|
||||
test("a live scene push never prunes", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: { maps: [{ _id: "map-1", name: "Cellar", foundrySceneId: "scene-gone" }] },
|
||||
});
|
||||
|
||||
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
|
||||
|
||||
assert.equal(maps(sync).length, 2, "a push of one scene says nothing about the world's other scenes");
|
||||
});
|
||||
|
||||
test("a scene the world deleted takes its map with it", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
maps: [
|
||||
{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1" },
|
||||
{ _id: "map-2", name: "Homebrew ford" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await sync.call("POST /sync/scene-delete", { worldId: "world-1", foundrySceneId: "scene-1" });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.deepEqual(maps(sync).map((map) => map._id), ["map-2"], "only the map of that scene goes");
|
||||
});
|
||||
|
||||
// --- What the route refuses -----------------------------------------------------------
|
||||
|
||||
test("a push that is not the campaign's world, or names no scenes, is refused", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
assert.equal((await sync.call("POST /sync/scenes", { worldId: "another-world", scenes: [worldScene()] })).msg, "errors.missing-data");
|
||||
assert.equal((await sync.call("POST /sync/scenes", { worldId: "world-1" })).msg, "errors.missing-data");
|
||||
assert.deepEqual(maps(sync), [], "nothing was written");
|
||||
});
|
||||
|
||||
test("a delete from another world, or naming no scene, is refused", async () => {
|
||||
const sync = loadSyncRoute({ seed: { maps: [{ _id: "map-1", name: "Keep", foundrySceneId: "scene-1" }] } });
|
||||
|
||||
assert.equal((await sync.call("POST /sync/scene-delete", { worldId: "another-world", foundrySceneId: "scene-1" })).msg, "errors.missing-data");
|
||||
assert.equal((await sync.call("POST /sync/scene-delete", { worldId: "world-1" })).msg, "errors.missing-data");
|
||||
assert.equal(maps(sync).length, 1, "and the map is still there");
|
||||
});
|
||||
|
||||
test("a map remembers which scene of the world it mirrors", () => {
|
||||
const model = read("backend", "src", "models", "Map.js");
|
||||
assert.match(model, /foundrySceneId:\s*{\s*type:\s*String\s*}/, "the scene a map mirrors is kept on the map");
|
||||
assert.match(model, /\{\s*campaign:\s*1,\s*foundrySceneId:\s*1\s*\}/, "and is unique within the campaign");
|
||||
});
|
||||
|
||||
// --- The Foundry module sends its scenes ---------------------------------------------
|
||||
|
||||
const MODULE_ID = "dragonroll-foundry";
|
||||
|
||||
function makeWorld({ autoSync = true } = {}) {
|
||||
const state = {
|
||||
hooks: new Map(),
|
||||
registered: new Map(),
|
||||
requests: [],
|
||||
timers: new Map(),
|
||||
intervals: new Map(),
|
||||
nextTimerId: 1,
|
||||
};
|
||||
|
||||
// A Scene document: the plain data `toObject()` answers with, which since V13 carries
|
||||
// the picture under `background` rather than `img`.
|
||||
const makeScene = (id, name, over = {}) => ({
|
||||
id, name, documentName: "Scene", img: "", grid: 50, flags: {},
|
||||
toObject() {
|
||||
return {
|
||||
_id: this.id, name: this.name, img: this.img, grid: this.grid, flags: this.flags,
|
||||
...(this.background ? { background: this.background } : {}),
|
||||
};
|
||||
},
|
||||
...over,
|
||||
});
|
||||
const scenes = [
|
||||
makeScene("scene-keep", "The Ruined Keep", { img: "images/keep.webp", grid: 70 }),
|
||||
// A newer Foundry keeps its picture under `background`, and this one is already an
|
||||
// absolute URL, which travels as it is.
|
||||
makeScene("scene-tavern", "Tavern", { img: undefined, background: { src: "http://other.test/tavern.jpg" }, grid: 50 }),
|
||||
];
|
||||
|
||||
const settingsStore = { autoSync, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
|
||||
const sandbox = {
|
||||
console: { log() {}, info() {}, warn() {}, error() {} },
|
||||
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 id = state.nextTimerId++;
|
||||
state.timers.set(id, { fn, delay });
|
||||
return id;
|
||||
},
|
||||
clearTimeout: (id) => state.timers.delete(id),
|
||||
setInterval: (fn, delay = 0) => {
|
||||
const id = state.nextTimerId++;
|
||||
state.intervals.set(id, { fn, delay });
|
||||
return id;
|
||||
},
|
||||
clearInterval: (id) => state.intervals.delete(id),
|
||||
fetch: async (url, options = {}) => {
|
||||
state.requests.push({
|
||||
href: String(url),
|
||||
method: options.method,
|
||||
body: options.body ? JSON.parse(options.body) : null,
|
||||
});
|
||||
return { ok: true, status: 200, json: async () => ({ status: "ok" }) };
|
||||
},
|
||||
Actor: { async create() { return null; } },
|
||||
Item: { async create() { return null; } },
|
||||
};
|
||||
|
||||
sandbox.game = {
|
||||
user: { isGM: true },
|
||||
world: { id: "world-1", title: "Test World" },
|
||||
system: { id: "dnd5e" },
|
||||
modules: { get: () => ({}) },
|
||||
actors: { contents: [], get: () => null },
|
||||
items: { contents: [], get: () => null },
|
||||
scenes: { contents: scenes, get: (id) => scenes.find((scene) => scene.id === id) },
|
||||
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.scene = (id) => scenes.find((scene) => scene.id === id);
|
||||
// The two routes the maps travel on: the campaign's reads live under the same prefix and
|
||||
// tell nothing about what the world sent.
|
||||
state.sceneRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/scenes")
|
||||
|| request.href.includes("foundry/sync/scene-delete"));
|
||||
state.pushes = (route) => state.requests.filter((request) => request.href.includes(route));
|
||||
|
||||
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
|
||||
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();
|
||||
}
|
||||
};
|
||||
// A world that is already linked: init, ready, and the pushes the world makes as it loads.
|
||||
state.setup = async () => {
|
||||
await state.fire("init");
|
||||
await state.fire("ready");
|
||||
await state.runTimers();
|
||||
return state;
|
||||
};
|
||||
// The same, with the world's own pushes out of the way, so a test only sees what it causes.
|
||||
state.linkedSetup = async () => {
|
||||
await state.setup();
|
||||
state.requests.length = 0;
|
||||
return state;
|
||||
};
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
test("the world sends its whole scene list as the campaign's maps when it loads", async () => {
|
||||
const world = await makeWorld().setup();
|
||||
|
||||
const [push] = world.pushes("foundry/sync/scenes");
|
||||
assert.ok(push, "a linked world pushes its scenes as it loads");
|
||||
assert.equal(push.body.fullSync, true, "the whole list travels, which is the push that lets the campaign prune");
|
||||
assert.deepEqual(push.body.worldId, "world-1");
|
||||
assert.deepEqual(push.body.scenes.map((scene) => [scene._id, scene.name]), [
|
||||
["scene-keep", "The Ruined Keep"],
|
||||
["scene-tavern", "Tavern"],
|
||||
]);
|
||||
assert.equal(push.body.scenes[0].img, "http://vtt.test/images/keep.webp",
|
||||
"the picture is read from this world, so it travels as an absolute URL");
|
||||
assert.equal(push.body.scenes[0].grid, 70, "the scene's own cell size travels with it");
|
||||
assert.equal(push.body.scenes[1].background.src, "http://other.test/tavern.jpg",
|
||||
"a picture that is already absolute is left as it is");
|
||||
});
|
||||
|
||||
test("a scene the GM changes reaches the campaign as that map", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
|
||||
const keep = world.scene("scene-keep");
|
||||
keep.name = "The Sunken Keep";
|
||||
keep.grid = 100;
|
||||
await world.fire("updateScene", keep);
|
||||
await world.runTimers();
|
||||
|
||||
const [push] = world.pushes("foundry/sync/scenes");
|
||||
assert.equal(push.body.fullSync, false, "a live scene edit never prunes the campaign's other maps");
|
||||
assert.deepEqual(push.body.scenes.map((scene) => [scene._id, scene.name, scene.grid]), [
|
||||
["scene-keep", "The Sunken Keep", 100],
|
||||
]);
|
||||
});
|
||||
|
||||
test("a scene the GM deletes takes its map off the campaign", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
|
||||
await world.fire("deleteScene", world.scene("scene-tavern"));
|
||||
await world.runTimers();
|
||||
|
||||
const [push] = world.pushes("foundry/sync/scene-delete");
|
||||
assert.equal(push.body.foundrySceneId, "scene-tavern");
|
||||
assert.deepEqual(world.pushes("foundry/sync/scenes"), [], "a deleted scene is not sent as a map to keep");
|
||||
});
|
||||
|
||||
test("autosync off: the world's scenes stop syncing, at world start and afterwards", async () => {
|
||||
const world = makeWorld({ autoSync: false });
|
||||
await world.fire("init");
|
||||
await world.fire("ready");
|
||||
await world.runTimers();
|
||||
assert.deepEqual(world.sceneRequests(), [], "a world with autosync off sends no scene list");
|
||||
|
||||
await world.fire("updateScene", world.scene("scene-keep"));
|
||||
await world.fire("deleteScene", world.scene("scene-tavern"));
|
||||
await world.runTimers();
|
||||
|
||||
assert.deepEqual(world.sceneRequests(), []);
|
||||
});
|
||||
|
||||
test("the scene edits queued while autosync was off are sent when it is turned back on", async () => {
|
||||
const world = await makeWorld({ autoSync: false });
|
||||
await world.fire("init");
|
||||
await world.fire("ready");
|
||||
await world.runTimers();
|
||||
|
||||
await world.fire("updateScene", world.scene("scene-keep"));
|
||||
await world.runTimers();
|
||||
assert.deepEqual(world.sceneRequests(), []);
|
||||
|
||||
await world.game.settings.set(MODULE_ID, "autoSync", true);
|
||||
await world.runTimers();
|
||||
|
||||
assert.ok(world.pushes("foundry/sync/scenes").some((push) => push.body.fullSync === true
|
||||
&& push.body.scenes.length === 2),
|
||||
"turning autosync back on sends this world's whole scene list again");
|
||||
assert.ok(world.pushes("foundry/sync/scenes").some((push) => push.body.fullSync === false
|
||||
&& push.body.scenes.map((scene) => scene._id).includes("scene-keep")),
|
||||
"and the scene edit queued while it was off is sent");
|
||||
});
|
||||
Reference in New Issue
Block a user