938 lines
42 KiB
JavaScript
938 lines
42 KiB
JavaScript
// Tests for the campaign's notes reaching the Foundry world as journal pages
|
|
// (Syndria98/dragonroll#98): each Dragonroll folder stands as a journal named after
|
|
// its path (root notes share "Dragonroll"), written by the module and kept in step
|
|
// with the campaign. The copy runs one way — notes are written in Dragonroll — so
|
|
// the backend answers with the notes and their folder paths and remembers each
|
|
// note's page; the module reads them, renders the markdown, moves a page when its
|
|
// note changes folder, and prunes the page of a note the campaign deleted.
|
|
//
|
|
// Both sides are loaded the way the other Foundry tests do it: the sync route runs
|
|
// against a stubbed `require` (models answer with plain objects and a small filter
|
|
// matcher), and the Foundry module is loaded into a `node:vm` context holding
|
|
// stubbed Foundry globals (`game.journal` and `JournalEntry` included) with fake
|
|
// timers, like tests/item-folder-sync.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 MODULE_ID = "dragonroll-foundry";
|
|
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 note routes use: equality, $or, $in, $nin,
|
|
// $exists, $ne. Anything else is a filter this test did not expect and says so.
|
|
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;
|
|
if (operator === "$in") return wanted.some((entry) => String(value) === String(entry));
|
|
if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry));
|
|
if (operator === "$ne") return String(value ?? "") !== String(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) {
|
|
// A seeded row belongs to the campaign the requests are made against unless the
|
|
// seed says otherwise: the routes scope every lookup by campaign.
|
|
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)));
|
|
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 };
|
|
};
|
|
model.updateMany = async (filter, update) => {
|
|
const hit = rows.filter((row) => matches(row, filter));
|
|
for (const row of hit) Object.assign(row, update.$set ?? {});
|
|
return { modifiedCount: 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" } = {}) {
|
|
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 };
|
|
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 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 (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 };
|
|
}
|
|
|
|
// --- The sync route: the notes it answers and the page ids it keeps ---------------
|
|
|
|
test("the notes revision folds the campaign's notes into one hash", async () => {
|
|
const sync = loadSyncRoute({
|
|
seed: {
|
|
notes: [
|
|
{ _id: "note-1", title: "Session 1", content: "hi" },
|
|
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
|
|
],
|
|
},
|
|
});
|
|
|
|
const first = await sync.call("GET /sync/notes/revision");
|
|
assert.equal(first.status, "ok");
|
|
assert.match(first.revision, /^[0-9a-f]{64}$/, "a sha-256 of the notes, not their content");
|
|
|
|
sync.models["../models/Note"].rows[0].content = "hi there";
|
|
const edited = await sync.call("GET /sync/notes/revision");
|
|
assert.notEqual(edited.revision, first.revision, "editing a note moves the revision");
|
|
|
|
sync.models["../models/Note"].rows[0].content = "hi";
|
|
sync.models["../models/Note"].rows[0].foundryPageId = "page-9";
|
|
const mapped = await sync.call("GET /sync/notes/revision");
|
|
assert.equal(mapped.revision, first.revision, "mapping a note to its page is not an edit");
|
|
});
|
|
|
|
test("the world reads the campaign's notes with their content and page mapping", async () => {
|
|
const sync = loadSyncRoute({
|
|
seed: {
|
|
notes: [
|
|
{ _id: "note-1", title: "Session 1", content: "**The start**", foundryPageId: "page-9" },
|
|
{ _id: "note-2", title: "Tavern Brawl", content: "- rope" },
|
|
],
|
|
},
|
|
});
|
|
|
|
const response = await sync.call("GET /sync/notes");
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(response.notes.map((note) => note.title), ["Session 1", "Tavern Brawl"]);
|
|
assert.equal(response.notes[0].content, "**The start**", "the markdown source travels: the module renders it");
|
|
assert.equal(response.notes[0].foundryPageId, "page-9", "and the note says which page it already stands as");
|
|
});
|
|
|
|
test("the world reads each note with the path of the folder it lives in", async () => {
|
|
const sync = loadSyncRoute({
|
|
seed: {
|
|
folders: [
|
|
{ _id: "folder-1", name: "Sessions", parentFolder: null },
|
|
{ _id: "folder-2", name: "Arc 1", parentFolder: "folder-1" },
|
|
],
|
|
notes: [
|
|
{ _id: "note-1", title: "Root", content: "root" },
|
|
{ _id: "note-2", title: "In folder", content: "folder", folder: "folder-1" },
|
|
{ _id: "note-3", title: "Deep", content: "deep", folder: "folder-2" },
|
|
],
|
|
},
|
|
});
|
|
|
|
const response = await sync.call("GET /sync/notes");
|
|
const pathByTitle = Object.fromEntries(response.notes.map((note) => [note.title, note.folderPath]));
|
|
|
|
assert.deepEqual(pathByTitle, {
|
|
Root: "",
|
|
"In folder": "Sessions",
|
|
Deep: "Sessions / Arc 1",
|
|
}, "the module names the journal of a note after its whole folder path");
|
|
});
|
|
|
|
test("renaming a folder moves the notes revision", async () => {
|
|
const sync = loadSyncRoute({
|
|
seed: {
|
|
folders: [{ _id: "folder-1", name: "Sessions", parentFolder: null }],
|
|
notes: [{ _id: "note-1", title: "Session 1", content: "hi", folder: "folder-1" }],
|
|
},
|
|
});
|
|
|
|
const before = await sync.call("GET /sync/notes/revision");
|
|
sync.models["../models/Folder"].rows[0].name = "Chapters";
|
|
const after = await sync.call("GET /sync/notes/revision");
|
|
|
|
assert.notEqual(after.revision, before.revision,
|
|
"a folder rename has to reach the world as another journal name");
|
|
});
|
|
|
|
test("mapping a note to the page the module made keeps them paired", async () => {
|
|
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
|
|
|
|
const response = await sync.call("POST /sync/map-note", {
|
|
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
|
|
});
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.equal(sync.models["../models/Note"].rows[0].foundryPageId, "page-9");
|
|
|
|
// Mapping the same pair again is the module checking, not a conflict.
|
|
const again = await sync.call("POST /sync/map-note", {
|
|
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
|
|
});
|
|
assert.equal(again.status, "ok");
|
|
});
|
|
|
|
test("a page already mapped to another note is refused", async () => {
|
|
const sync = loadSyncRoute({
|
|
seed: {
|
|
notes: [
|
|
{ _id: "note-1", title: "Session 1", content: "hi", foundryPageId: "page-9" },
|
|
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
|
|
],
|
|
},
|
|
});
|
|
|
|
const response = await sync.call("POST /sync/map-note", {
|
|
worldId: "world-1", noteId: "note-2", foundryPageId: "page-9",
|
|
});
|
|
|
|
assert.equal(response.status, "error");
|
|
assert.equal(response.msg, "foundry.errors.note-already-synced");
|
|
assert.equal(sync.models["../models/Note"].rows.find((row) => row._id === "note-2").foundryPageId, undefined,
|
|
"the first note keeps its page");
|
|
});
|
|
|
|
test("map-note wants this world's note and a page for it", async () => {
|
|
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
|
|
|
|
assert.equal((await sync.call("POST /sync/map-note", { worldId: "world-1" })).msg, "errors.missing-data");
|
|
assert.equal((await sync.call("POST /sync/map-note", { noteId: "note-1", foundryPageId: "page-9" })).msg, "errors.missing-data",
|
|
"another world cannot map this campaign's note");
|
|
const gone = await sync.call("POST /sync/map-note", {
|
|
worldId: "world-1", noteId: "note-gone", foundryPageId: "page-9",
|
|
});
|
|
assert.equal(gone.msg, "errors.notfound");
|
|
});
|
|
|
|
// --- The Foundry module writes the journal ---------------------------------------
|
|
|
|
// Foundry's `update` takes dotted paths ("flags.dragonroll-foundry.noteId"); an
|
|
// embedded document's own id is not a path to set.
|
|
function writeFoundryPaths(target, data) {
|
|
for (const [key, value] of Object.entries(data)) {
|
|
if (key === "_id") continue;
|
|
const parts = key.split(".");
|
|
const last = parts.pop();
|
|
let node = target;
|
|
for (const part of parts) node = node[part] ??= {};
|
|
node[last] = value;
|
|
}
|
|
return target;
|
|
}
|
|
|
|
function makeWorld() {
|
|
const state = {
|
|
hooks: new Map(),
|
|
registered: new Map(),
|
|
requests: [],
|
|
timers: new Map(),
|
|
intervals: new Map(),
|
|
// What Dragonroll answers the notes reconcile with. Mapping a page answers
|
|
// like the real backend: the note keeps the page id, so later reads carry it.
|
|
remoteNotes: [],
|
|
rollMessages: [],
|
|
clickListeners: [],
|
|
nextId: 1,
|
|
};
|
|
|
|
const journals = [];
|
|
|
|
const makePage = (journal, data = {}) => {
|
|
const page = {
|
|
id: `page-${state.nextId++}`,
|
|
documentName: "JournalEntryPage",
|
|
name: data.name,
|
|
text: { content: data.text?.content ?? "" },
|
|
flags: data.flags ?? {},
|
|
writes: 0,
|
|
get uuid() { return `JournalEntry.${journal.id}.JournalEntryPage.${this.id}`; },
|
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
|
async update(update) {
|
|
page.writes += 1;
|
|
writeFoundryPaths(page, update);
|
|
return page;
|
|
},
|
|
async delete() {
|
|
const index = journal.pages.contents.indexOf(page);
|
|
if (index >= 0) journal.pages.contents.splice(index, 1);
|
|
},
|
|
};
|
|
return page;
|
|
};
|
|
|
|
const makeJournal = (data = {}) => {
|
|
const pages = [];
|
|
return {
|
|
id: `journal-${state.nextId++}`,
|
|
name: data.name,
|
|
documentName: "JournalEntry",
|
|
flags: data.flags ?? {},
|
|
get uuid() { return `JournalEntry.${this.id}`; },
|
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
|
pages: { contents: pages, get: (id) => pages.find((page) => page.id === id) },
|
|
async update(update) { return writeFoundryPaths(this, update); },
|
|
async delete() {
|
|
const index = journals.indexOf(this);
|
|
if (index >= 0) journals.splice(index, 1);
|
|
},
|
|
async createEmbeddedDocuments(documentName, docs) {
|
|
assert.equal(documentName, "JournalEntryPage", "the notes' pages are journal pages");
|
|
// Foundry's own page validation refuses a page without a name.
|
|
for (const doc of docs) assert.ok(doc.name, "a journal page needs a non-empty name");
|
|
const created = docs.map((doc) => makePage(this, doc));
|
|
pages.push(...created);
|
|
return created;
|
|
},
|
|
};
|
|
};
|
|
|
|
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
|
|
const sandbox = {
|
|
console: { log() {}, info() {}, warn() {}, error() {} },
|
|
URL,
|
|
CONFIG: {},
|
|
window: { location: { origin: "http://vtt.test" } },
|
|
document: {
|
|
addEventListener(name, fn) {
|
|
if (name === "click") state.clickListeners.push(fn);
|
|
},
|
|
},
|
|
Roll: class FakeRoll {
|
|
constructor(formula) {
|
|
this.formula = formula;
|
|
this.evaluated = false;
|
|
}
|
|
async evaluate() {
|
|
this.evaluated = true;
|
|
return this;
|
|
}
|
|
async toMessage(data) {
|
|
assert.equal(this.evaluated, true, "the roll is evaluated before it reaches chat");
|
|
state.rollMessages.push({ formula: this.formula, ...data });
|
|
}
|
|
},
|
|
ChatMessage: { getSpeaker: () => ({ alias: "GM" }) },
|
|
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.nextId++;
|
|
state.timers.set(id, { fn, delay });
|
|
return id;
|
|
},
|
|
clearTimeout: (id) => state.timers.delete(id),
|
|
setInterval: (fn, delay = 0) => {
|
|
// Recorded, never run by itself: tests ask for a periodic reconcile with
|
|
// `runIntervals`, so the ones watching single pushes stay on their own.
|
|
const id = state.nextId++;
|
|
state.intervals.set(id, { fn, delay });
|
|
return id;
|
|
},
|
|
clearInterval: (id) => state.intervals.delete(id),
|
|
fetch: async (url, options = {}) => {
|
|
const href = String(url);
|
|
const body = options.body ? JSON.parse(options.body) : null;
|
|
state.requests.push({ href, method: options.method, body });
|
|
if (href.includes("foundry/sync/map-note")) {
|
|
const note = state.remoteNotes.find((entry) => String(entry._id) === String(body.noteId));
|
|
if (note) note.foundryPageId = body.foundryPageId;
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", note }) };
|
|
}
|
|
// The cheap change check: a hash of the notes' content, so changing
|
|
// `remoteNotes` (and nothing else) is what makes the module pull them over,
|
|
// like the backend hashing the campaign's notes does.
|
|
if (href.includes("foundry/sync/notes/revision")) {
|
|
const revision = state.remoteNotes
|
|
.map((note) => [
|
|
note._id, note.title ?? "", note.content ?? "",
|
|
note.folder ?? "", note.folderPath ?? "",
|
|
].join("\u0000"))
|
|
.sort()
|
|
.join("\u0001");
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", revision }) };
|
|
}
|
|
if (href.includes("foundry/sync/notes")) {
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", notes: state.remoteNotes }) };
|
|
}
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
|
},
|
|
Actor: { async create() { return null; } },
|
|
Item: { async create() { return null; } },
|
|
JournalEntry: {
|
|
async create(data) {
|
|
const journal = makeJournal(data);
|
|
journals.push(journal);
|
|
return [journal];
|
|
},
|
|
},
|
|
};
|
|
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 },
|
|
folders: { contents: [], get: () => null },
|
|
journal: { contents: journals, get: (id) => journals.find((journal) => journal.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.journals = () => journals;
|
|
state.addJournal = (name, flags = {}) => {
|
|
const journal = makeJournal({ name, flags });
|
|
journals.push(journal);
|
|
return journal;
|
|
};
|
|
state.addPage = (journal, data) => {
|
|
const page = makePage(journal, data);
|
|
journal.pages.contents.push(page);
|
|
return page;
|
|
};
|
|
state.mapNoteRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/map-note"));
|
|
state.notesReads = () => state.requests.filter((request) => request.href.includes("foundry/sync/notes"));
|
|
// The full note pulls, not the cheap revision pings the change check makes.
|
|
state.notesPulls = () => state.requests.filter((request) =>
|
|
request.href.includes("foundry/sync/notes") && !request.href.includes("/revision"));
|
|
|
|
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();
|
|
}
|
|
};
|
|
// The reconciles `setInterval` registered: what runs every few seconds on a
|
|
// linked world, and so what carries each note into its journal page.
|
|
state.runIntervals = async () => {
|
|
for (const interval of [...state.intervals.values()]) await interval.fn();
|
|
await drain();
|
|
};
|
|
// Press a dice button the journal drew: the module listens on the document and
|
|
// finds the button through `closest`, like a click inside a journal page.
|
|
state.clickRoll = async (formula) => {
|
|
const button = { dataset: { dragonrollRoll: formula } };
|
|
const event = {
|
|
target: { closest: (selector) => (selector === "[data-dragonroll-roll]" ? button : null) },
|
|
defaultPrevented: false,
|
|
preventDefault() { this.defaultPrevented = true; },
|
|
};
|
|
for (const listener of state.clickListeners) await listener(event);
|
|
await drain();
|
|
return event;
|
|
};
|
|
state.linkedSetup = async () => {
|
|
await state.fire("init");
|
|
await state.fire("ready");
|
|
await state.runTimers();
|
|
state.requests.length = 0;
|
|
return state;
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
// The fetch stub updates a note with the page it maps, like the real backend
|
|
// does, so every test works on notes of its own.
|
|
const sessionNote = (over = {}) => ({ _id: "note-1", title: "Session 1", content: "**The start**", ...over });
|
|
const tavernNote = (over = {}) => ({ _id: "note-2", title: "Tavern Brawl", content: "A rope, a chandelier.", ...over });
|
|
|
|
test("the campaign's notes become pages of one Dragonroll journal", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote(), tavernNote()];
|
|
|
|
await world.runIntervals();
|
|
|
|
assert.equal(world.journals().length, 1, "one journal carries the campaign's notes");
|
|
const journal = world.journals()[0];
|
|
assert.equal(journal.name, "Dragonroll");
|
|
assert.deepEqual(journal.pages.contents.map((page) => [page.name, page.text.content]), [
|
|
["Session 1", "<p><strong>The start</strong></p>"],
|
|
["Tavern Brawl", "<p>A rope, a chandelier.</p>"],
|
|
], "each note is a page, its markdown drawn into the page's HTML");
|
|
assert.deepEqual(journal.pages.contents.map((page) => page.getFlag(MODULE_ID, "noteId")), ["note-1", "note-2"],
|
|
"each page keeps the note it stands for");
|
|
assert.deepEqual(world.mapNoteRequests().map((request) => [request.body.noteId, request.body.foundryPageId]), [
|
|
["note-1", journal.pages.contents[0].id],
|
|
["note-2", journal.pages.contents[1].id],
|
|
], "and the campaign remembers each note's page");
|
|
});
|
|
|
|
test("notes in a folder share the journal named after its path", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [
|
|
sessionNote(),
|
|
{ _id: "note-2", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
|
{ _id: "note-3", title: "The cave", content: "dark", folder: "folder-2", folderPath: "Sessions / Arc 1" },
|
|
];
|
|
|
|
await world.runIntervals();
|
|
|
|
const byName = new Map(world.journals().map((journal) => [journal.name, journal]));
|
|
assert.deepEqual([...byName.keys()].sort(), ["Dragonroll", "Sessions", "Sessions / Arc 1"],
|
|
"the root notes and each folder path get a journal of their own");
|
|
assert.deepEqual(byName.get("Dragonroll").pages.contents.map((page) => page.name), ["Session 1"]);
|
|
assert.deepEqual(byName.get("Sessions").pages.contents.map((page) => page.name), ["The road"]);
|
|
assert.deepEqual(byName.get("Sessions / Arc 1").pages.contents.map((page) => page.name), ["The cave"],
|
|
"a subfolder's notes stand in a journal named after the whole path");
|
|
assert.equal(byName.get("Sessions").getFlag(MODULE_ID, "notesFolder"), "folder-1",
|
|
"each folder journal keeps the folder it belongs to");
|
|
assert.equal(byName.get("Sessions / Arc 1").getFlag(MODULE_ID, "notesFolder"), "folder-2");
|
|
});
|
|
|
|
test("renaming a folder renames its journal", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [
|
|
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
|
];
|
|
await world.runIntervals();
|
|
|
|
world.remoteNotes = [{ ...world.remoteNotes[0], folderPath: "Chapters" }];
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals().map((journal) => journal.name), ["Chapters"],
|
|
"the journal follows the folder's path without being made again");
|
|
assert.equal(world.journals()[0].pages.contents.length, 1, "and its page stays where it was");
|
|
});
|
|
|
|
test("a note moved to another folder takes its page to that folder's journal", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [
|
|
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
|
];
|
|
await world.runIntervals();
|
|
|
|
const firstPage = world.journals()[0].pages.contents[0];
|
|
world.remoteNotes = [{
|
|
...world.remoteNotes[0],
|
|
folder: "folder-2",
|
|
folderPath: "Sessions / Arc 1",
|
|
}];
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals().map((journal) => journal.name), ["Sessions / Arc 1"],
|
|
"the journal the note left goes when it has nothing else in it");
|
|
const moved = world.journals()[0].pages.contents[0];
|
|
assert.equal(moved.name, "The road");
|
|
assert.notEqual(moved.id, firstPage.id, "the page is made in the journal the note moved to");
|
|
assert.equal(world.remoteNotes[0].foundryPageId, moved.id, "and the campaign maps the note to its new page");
|
|
});
|
|
|
|
test("reconciling again does not double the journal or its pages", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote(), tavernNote()];
|
|
|
|
await world.runIntervals();
|
|
await world.runIntervals();
|
|
await world.runIntervals();
|
|
|
|
assert.equal(world.journals().length, 1, "the journal is made once, not per reconcile");
|
|
assert.equal(world.journals()[0].pages.contents.length, 2, "and each note stands as the one page it was given");
|
|
assert.equal(world.mapNoteRequests().length, 2, "an already-mapped note is not mapped again");
|
|
});
|
|
|
|
test("an existing journal named Dragonroll is used, not doubled", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
const gmsOwn = world.addJournal("Dragonroll");
|
|
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
assert.equal(world.journals().length, 1, "the journal the world already had is the notes' one");
|
|
assert.deepEqual(gmsOwn.pages.contents.map((page) => page.name), ["Session 1"]);
|
|
assert.equal(gmsOwn.getFlag(MODULE_ID, "notesJournal"), true, "and it is marked, so renaming it keeps the notes' home findable");
|
|
});
|
|
|
|
test("extra journals named Dragonroll are removed before the notes are written", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
const kept = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
|
|
const gmDuplicate = world.addJournal("Dragonroll");
|
|
const flaggedDuplicate = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
|
|
const unrelated = world.addJournal("Session Log");
|
|
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals(), [kept, unrelated],
|
|
"only the journal the reconcile writes into survives, beside the GM's other journals");
|
|
assert.deepEqual(kept.pages.contents.map((page) => page.name), ["Session 1"]);
|
|
assert.equal(gmDuplicate.pages.contents.length, 0);
|
|
assert.equal(flaggedDuplicate.pages.contents.length, 0);
|
|
assert.ok(unrelated, "a journal of another name is left alone");
|
|
});
|
|
|
|
test("several journals named Dragonroll collapse into the first one", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
const first = world.addJournal("Dragonroll");
|
|
world.addJournal("Dragonroll");
|
|
world.addJournal("Dragonroll");
|
|
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals(), [first], "the duplicates go, the first one stays the notes' home");
|
|
assert.deepEqual(first.pages.contents.map((page) => page.name), ["Session 1"]);
|
|
assert.equal(first.getFlag(MODULE_ID, "notesJournal"), true);
|
|
});
|
|
|
|
test("a note edited in Dragonroll rewrites its page", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
const first = world.remoteNotes[0];
|
|
world.remoteNotes = [{ ...first, title: "Session 1 — revisited", content: "**A different start**" }];
|
|
await world.runIntervals();
|
|
|
|
const journal = world.journals()[0];
|
|
assert.equal(journal.pages.contents.length, 1, "the note still stands as the same single page");
|
|
assert.deepEqual(journal.pages.contents[0].name, "Session 1 — revisited");
|
|
assert.equal(journal.pages.contents[0].text.content, "<p><strong>A different start</strong></p>");
|
|
assert.equal(world.mapNoteRequests().length, 1, "the pairing the world reads back needs no remapping");
|
|
});
|
|
|
|
test("a note deleted in Dragonroll takes its page with it", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote(), tavernNote()];
|
|
await world.runIntervals();
|
|
|
|
const journal = world.journals()[0];
|
|
const gmsPage = world.addPage(journal, { name: "My own notes", text: { content: "not from Dragonroll" } });
|
|
world.remoteNotes = world.remoteNotes.filter((note) => note._id !== "note-2");
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(journal.pages.contents.map((page) => page.name), ["Session 1", "My own notes"],
|
|
"the deleted note's page goes; the GM's own page stays");
|
|
assert.ok(journal.pages.contents.includes(gmsPage));
|
|
});
|
|
|
|
test("pages already in step with the campaign are not rewritten", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
const [page] = world.journals()[0].pages.contents;
|
|
assert.equal(page.writes, 0, "the page was created whole, not patched");
|
|
await world.runIntervals();
|
|
assert.equal(page.writes, 0, "a reconcile that changes nothing leaves the page alone");
|
|
});
|
|
|
|
test("an unchanged campaign is not pulled over again", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
assert.equal(world.notesPulls().length, 1, "the first reconcile pulls the notes");
|
|
|
|
await world.runIntervals();
|
|
assert.equal(world.notesPulls().length, 1,
|
|
"with the revision and the journal unchanged, only the cheap revision is asked for");
|
|
});
|
|
|
|
test("a page a GM edited is written back from the campaign's note", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
const page = world.journals()[0].pages.contents[0];
|
|
page.name = "GM renamed it";
|
|
page.text.content = "GM wrote this";
|
|
await world.runIntervals();
|
|
|
|
assert.equal(page.name, "Session 1", "the campaign's title is written back over the GM's");
|
|
assert.equal(page.text.content, "<p><strong>The start</strong></p>", "and so is its content");
|
|
});
|
|
|
|
test("a journal page a GM removed is built again from the campaign's note", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
world.journals()[0].pages.contents.length = 0;
|
|
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals()[0].pages.contents.map((entry) => entry.name), ["Session 1"],
|
|
"the journal holds the note's page again");
|
|
});
|
|
|
|
test("the campaign's page mapping claims a page whose flag was lost", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
const journal = world.addJournal("Dragonroll");
|
|
const orphan = world.addPage(journal, { name: "Old name", text: { content: "old" } });
|
|
|
|
world.remoteNotes = [{ _id: "note-1", title: "Session 1", content: "**The start**", foundryPageId: orphan.id }];
|
|
await world.runIntervals();
|
|
|
|
assert.equal(journal.pages.contents.length, 1, "no second page under the same title");
|
|
assert.equal(orphan.name, "Session 1");
|
|
assert.equal(orphan.getFlag(MODULE_ID, "noteId"), "note-1", "and the page is marked again");
|
|
});
|
|
|
|
test("text that is not markdown is escaped, not injected", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{ _id: "note-1", title: "Session 1", content: "a & b < c\nline two\n\nsecond para" }];
|
|
|
|
await world.runIntervals();
|
|
|
|
assert.equal(
|
|
world.journals()[0].pages.contents[0].text.content,
|
|
"<p>a & b < c<br />line two</p>\n<p>second para</p>",
|
|
"the raw text is escaped and stays legible",
|
|
);
|
|
});
|
|
|
|
test("a note's markdown is drawn into the page: headings, lists and marks", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{
|
|
_id: "note-1",
|
|
title: "Session 1",
|
|
content: "# Session One\n\n## The Tavern\n\n- rope\n- **torch**\n\n> danger\n\n---\n\n`code` and [a link](https://dragonroll.test)",
|
|
}];
|
|
|
|
await world.runIntervals();
|
|
|
|
assert.equal(
|
|
world.journals()[0].pages.contents[0].text.content,
|
|
"<h1>Session One</h1>\n"
|
|
+ "<h2>The Tavern</h2>\n"
|
|
+ "<ul>\n<li>rope</li>\n<li><strong>torch</strong></li>\n</ul>\n"
|
|
+ "<blockquote><p>danger</p></blockquote>\n"
|
|
+ "<hr />\n"
|
|
+ "<p><code>code</code> and <a href=\"https://dragonroll.test\">a link</a></p>",
|
|
"the note is drawn as the elements Foundry's journal styles know",
|
|
);
|
|
});
|
|
|
|
test("a note's dice widgets become buttons that roll in Foundry", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{
|
|
_id: "note-1",
|
|
title: "Goblin",
|
|
content: "The goblin attacks with @roll[1d20+4].\n\n@roll\n8d6\n@end",
|
|
}];
|
|
|
|
await world.runIntervals();
|
|
|
|
const html = world.journals()[0].pages.contents[0].text.content;
|
|
assert.match(html,
|
|
/<p>The goblin attacks with <button type="button" class="dragonroll-note-roll" data-dragonroll-roll="1d20\+4" title="Roll 1d20\+4"><i class="fa-solid fa-dice-d20" aria-hidden="true"><\/i><span>1d20\+4<\/span><\/button>\.<\/p>/,
|
|
"the inline widget is a button showing the expression the note wrote");
|
|
assert.match(html,
|
|
/<button type="button" class="dragonroll-note-roll dragonroll-note-roll-block" data-dragonroll-roll="8d6" title="Roll 8d6">/,
|
|
"the block widget is a button of its own, drawn full width");
|
|
|
|
const event = await world.clickRoll("1d20+4");
|
|
assert.equal(event.defaultPrevented, true, "the click does not navigate the journal");
|
|
assert.deepEqual(world.rollMessages.map((message) => message.formula), ["1d20+4"],
|
|
"pressing the button evaluates that expression in Foundry");
|
|
assert.equal(world.rollMessages[0].speaker.alias, "GM");
|
|
assert.match(world.rollMessages[0].flavor, /1d20\+4/,
|
|
"the chat card says the roll came from Dragonroll");
|
|
});
|
|
|
|
test("advantage and disadvantage become Foundry's keep-highest and keep-lowest", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{
|
|
_id: "note-1",
|
|
title: "Rolls",
|
|
content: "@roll[d20adv] @roll[2d20dis] @roll[4d6kh1]",
|
|
}];
|
|
|
|
await world.runIntervals();
|
|
|
|
const html = world.journals()[0].pages.contents[0].text.content;
|
|
assert.match(html, /data-dragonroll-roll="2d20kh1"/, "advantage rolls twice and keeps the higher die");
|
|
assert.match(html, /data-dragonroll-roll="2d20kl1"/, "disadvantage rolls twice and keeps the lower die");
|
|
assert.match(html, /data-dragonroll-roll="4d6kh1"/, "a keep-highest expression already reads as Foundry does");
|
|
});
|
|
|
|
test("a dice widget inside a code span stays text", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{ _id: "note-1", title: "Syntax", content: "`@roll[1d6]`" }];
|
|
|
|
await world.runIntervals();
|
|
|
|
assert.equal(world.journals()[0].pages.contents[0].text.content,
|
|
"<p><code>@roll[1d6]</code></p>",
|
|
"code that shows the widget syntax is not turned into a button");
|
|
});
|
|
|
|
// --- Wiki links and embeds in the journal page -----------------------------------
|
|
|
|
test("a note's [[links]] and ![[embeds]] become Foundry's own enrichers", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.game.actors.contents.push({ id: "actor-1", name: "Mira", documentName: "Actor" });
|
|
world.game.items.contents.push({ id: "item-1", name: "Rope of Climbing", documentName: "Item" });
|
|
world.remoteNotes = [{
|
|
_id: "note-1",
|
|
title: "Links",
|
|
content: "[[Mira]] and ![[Mira]]\n\n[[Rope of Climbing]] and ![[Rope of Climbing]]",
|
|
}];
|
|
|
|
await world.runIntervals();
|
|
|
|
const html = world.journals()[0].pages.contents[0].text.content;
|
|
assert.match(html, /@UUID\[Actor\.actor-1\]\{Mira\}/,
|
|
"a link to a character opens it in Foundry");
|
|
assert.match(html, /@Embed\[Actor\.actor-1\]\{Mira\}/,
|
|
"an embedded character is drawn as a sheet preview");
|
|
assert.match(html, /@UUID\[Item\.item-1\]\{Rope of Climbing\}/,
|
|
"a link to an item opens it in Foundry");
|
|
assert.match(html, /@Embed\[Item\.item-1\]\{Rope of Climbing\}/,
|
|
"an embedded item is drawn as its sheet");
|
|
});
|
|
|
|
test("a name the world does not have is left dimmed, and only sheets can be embedded", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [{
|
|
_id: "note-1",
|
|
title: "Missing",
|
|
content: "[[Nobody]]\n\n![[Nobody]]\n\n![[Tavern Brawl]]",
|
|
}];
|
|
|
|
await world.runIntervals();
|
|
|
|
const html = world.journals()[0].pages.contents[0].text.content;
|
|
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Nobody<\/span>/,
|
|
"an unresolved link still reads, but cannot be opened");
|
|
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Tavern Brawl<\/span>/,
|
|
"a note written with the bang is not embedded as a sheet");
|
|
assert.doesNotMatch(html, /@Embed\[/, "nothing is embedded when there is no character or item");
|
|
});
|
|
|
|
test("a note can link to another note created in the same pull", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
world.remoteNotes = [
|
|
sessionNote({ content: "See [[Tavern Brawl]]." }),
|
|
tavernNote(),
|
|
];
|
|
|
|
await world.runIntervals();
|
|
|
|
const journal = world.journals()[0];
|
|
const sessionPage = journal.pages.contents.find((page) => page.name === "Session 1");
|
|
const tavernPage = journal.pages.contents.find((page) => page.name === "Tavern Brawl");
|
|
assert.match(
|
|
sessionPage.text.content,
|
|
new RegExp(`@UUID\\[JournalEntry\\.${journal.id}\\.JournalEntryPage\\.${tavernPage.id}\\]\\{Tavern Brawl\\}`),
|
|
"the page of the note it points at opens from the link"
|
|
);
|
|
});
|
|
|
|
test("autosync off: the campaign's notes are not written into the world", async () => {
|
|
const world = await makeWorld().linkedSetup();
|
|
await world.game.settings.set(MODULE_ID, "autoSync", false);
|
|
|
|
world.remoteNotes = [sessionNote()];
|
|
await world.runIntervals();
|
|
|
|
assert.deepEqual(world.journals(), [], "no journal is made");
|
|
assert.deepEqual(world.notesReads(), [], "and the campaign is not even asked");
|
|
});
|