diff --git a/AGENTS.md b/AGENTS.md
index a309b38d..eeb2c8ee 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -83,7 +83,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `User` — `name*`, `username*`, `email*` (both unique), `password` (bcrypt, 10 rounds), `admin`, `image`, `setupCode`, `settings`
- `Campaign` — `name*`, `createdBy*`→User, `description`, `color`, `settings`, `foundryWorldId`/`foundryWorldTitle`/`foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId`
-- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`
+- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`, `foundryPageId`
- `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color`
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), `discordUserId` (the Discord player holding the character, unique per campaign — set only by `routes/discord.js`), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs)
- `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description`
@@ -114,11 +114,13 @@ rest, expire after 10 min, and Obsidian gets a long-lived (365 d) token back.
Foundry then syncs with that token on `/api/foundry/sync/*` (`routes/foundry-link.js`, mounted before
the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync` also prunes),
-`item-snapshot`, `item-delete`, `characters`, `items`, `status`, `map` / `map-item`, `delete`. Rules:
+`item-snapshot`, `item-delete`, `characters`, `items`, `notes` / `map-note`, `status`,
+`map` / `map-item`, `delete`. Rules:
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
- **Only the world's item directory reaches the item list** (Syndria98/dragonroll#67) — `snapshotItemSources` reads `body.items` (`game.items`) alone; gear embedded in a character is that actor's `inventory` (see the `Actor` model), not an `Item`. A world item still folds into a hand-made or renamed row it matches by name (`foundryNames`), so a rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped.
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree and the world owns its names and nesting. `color` is the one field the campaign sets too, so it travels back with the folders `GET /foundry/sync/items` answers with (`{items, folders}`) and the module writes it onto the world's folder.
+- **Notes reach the world as journal pages, one way** (Syndria98/dragonroll#98): the module reads `GET /sync/notes` and stands every campaign note as a page of one world `JournalEntry` named Dragonroll — the page carries the note's id in a `dragonroll-foundry.noteId` flag, the note keeps the page's id in `foundryPageId` (`POST /sync/map-note`). The reconcile rewrites pages from the notes and drops the page of a deleted note; journal edits never travel back.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge. Its one write, `POST /import`, pulls the bridge's actors or world items into the campaign through the same writers as a sync push.
diff --git a/backend/src/models/Note.js b/backend/src/models/Note.js
index ae357062..74eb754d 100644
--- a/backend/src/models/Note.js
+++ b/backend/src/models/Note.js
@@ -14,7 +14,16 @@ const NoteSchema = new Schema({
ref: 'Folder'
},
color: { type: String },
+ // The journal page this note is written as in the linked Foundry world: the
+ // page of the one "Dragonroll" journal whose rows carry this note's id in
+ // their `dragonroll-foundry.noteId` flag (see the module's notes sync).
+ foundryPageId: { type: String },
date: { type: Date, default: Date.now }
});
+NoteSchema.index(
+ { campaign: 1, foundryPageId: 1 },
+ { unique: true, partialFilterExpression: { foundryPageId: { $type: 'string' } } }
+);
+
module.exports = mongoose.model('Note', NoteSchema);
\ No newline at end of file
diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js
index 09e62430..e1bcd749 100644
--- a/backend/src/routes/foundry-link.js
+++ b/backend/src/routes/foundry-link.js
@@ -7,6 +7,7 @@ const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
+const Note = require('../models/Note');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
@@ -481,6 +482,57 @@ router.post('/sync/map-item', async (req, res) => {
}
});
+// --- Note pages ------------------------------------------------------------
+// The campaign's notes are read where their authors' table sits: every note
+// stands as a page of the one journal the world calls "Dragonroll". Notes are
+// written in Dragonroll, so this copy runs one way — the module reads the notes
+// and rewrites their pages; nothing of the journal travels back. Its pages keep
+// the note's id in a `dragonroll-foundry.noteId` flag, and the note keeps the
+// page's id here, so either side recognises the pairing again after a restart.
+
+// Every note of the campaign, content included: enough for the module to write
+// each one as a page. Folders of the notes do not travel — the journal is flat.
+router.get('/sync/notes', async (req, res) => {
+ try {
+ const campaign = await syncCampaign(req, res);
+ if (!campaign) return;
+ const notes = await Note.find({ campaign: campaign._id })
+ .select('_id title content foundryPageId date')
+ .sort({ date: -1 })
+ .lean();
+ res.json({ status: 'ok', notes });
+ } catch (err) {
+ console.error(err);
+ res.json({ status: 'error', msg: 'errors.internal' });
+ }
+});
+
+// The page the module made for a note, kept on the note so the next reconcile —
+// or a world whose page flags were lost — writes that page instead of a second
+// one under the same title.
+router.post('/sync/map-note', async (req, res) => {
+ try {
+ const campaign = await syncCampaign(req, res);
+ if (!campaign) return;
+ const { noteId, foundryPageId, worldId } = req.body;
+ if (!requestMatchesWorld(campaign, worldId) || !noteId || !foundryPageId) {
+ return res.json({ status: 'error', msg: 'errors.missing-data' });
+ }
+
+ const note = await Note.findOne({ _id: noteId, campaign: campaign._id });
+ if (!note) return res.json({ status: 'error', msg: 'errors.notfound' });
+ const existing = await Note.findOne({ campaign: campaign._id, foundryPageId, _id: { $ne: note._id } });
+ if (existing) return res.json({ status: 'error', msg: 'foundry.errors.note-already-synced' });
+
+ note.foundryPageId = String(foundryPageId).trim().slice(0, 120);
+ await note.save();
+ res.json({ status: 'ok', note });
+ } catch (err) {
+ console.error(err);
+ res.json({ status: 'error', msg: 'errors.internal' });
+ }
+});
+
module.exports = router;
// The writers every Foundry document goes through: the sync pushes above, and the
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of
diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md
index bcb6e6f7..fa0e65d4 100644
--- a/dragonroll-foundry/README.md
+++ b/dragonroll-foundry/README.md
@@ -107,6 +107,17 @@ else (Syndria98/dragonroll#67):
the whole world directory and can tell which synced rows it has let go of. Deleting a synced item in
Dragonroll removes its Foundry world copy on the next reconcile.
+### Notes
+
+The campaign's notes read like the campaign's journal in the world (Syndria98/dragonroll#98): every
+note stands as a page of one JournalEntry named **Dragonroll**. The module creates that journal — or
+adopts one the GM already made under that name, marking it as the notes' journal — and renders each
+note's markdown into page HTML with Foundry's own renderer. Notes are written in Dragonroll, so this
+copy runs one way: a note made or edited in the campaign rewrites its page on the next reconcile, and
+a note deleted there takes its page with it. Pages the campaign does not own — the GM's own pages in
+that journal — are left alone, and nothing written in the journal travels back. Autosync off stops it
+too, like the rest of the sync.
+
The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login):
| Route | Use |
@@ -116,12 +127,16 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items, and the item folders with their Dragonroll colours, to apply back in Foundry |
+| `GET /api/foundry/sync/notes` | The campaign's notes, markdown and all, and the journal page each stands as |
+| `POST /api/foundry/sync/map-note` | Store a note's journal page id after creating that page |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted |
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
-flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
+flag, and a journal page the module made for a note keeps its note's id in the `dragonroll-foundry.noteId`
+flag, so the notes reconcile recognises its own pages. World items are marked with
+`dragonroll-foundry.syncMutation` while Dragonroll writes them so
the write is not echoed back. A folder colour is written with that folder held in the client's set of
folders being synced, for the same reason.
diff --git a/dragonroll-foundry/module.json b/dragonroll-foundry/module.json
index 55b396e7..8430a92d 100644
--- a/dragonroll-foundry/module.json
+++ b/dragonroll-foundry/module.json
@@ -2,7 +2,7 @@
"id": "dragonroll-foundry",
"title": "Dragonroll Foundry API",
"description": "Links a Foundry world to a Dragonroll campaign and exposes a client-side API for world data.",
- "version": "0.4.0",
+ "version": "0.5.0",
"library": true,
"compatibility": {
"minimum": "12",
diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js
index 72e96a79..ca12d589 100644
--- a/dragonroll-foundry/scripts/api.js
+++ b/dragonroll-foundry/scripts/api.js
@@ -450,6 +450,7 @@ function handleAutoSyncChange(value) {
initializeCharacterSync();
reconcileDragonrollItems();
queueFoundryItemFolders(400);
+ reconcileDragonrollNotes();
if (queuedActorChanges.size) {
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
@@ -1360,6 +1361,157 @@ function queueFoundryActorChange(kind, actor) {
queueActorChange(kind, actor);
}
+// --- Note pages ------------------------------------------------------------
+// The campaign's notes read like the campaign's journal in the world: every note
+// stands as a page of one JournalEntry named "Dragonroll". Notes are written in
+// Dragonroll, so this copy runs one way — the reconcile writes each note into its
+// page and drops the page of a note the campaign deleted. Nothing of the journal
+// is read back, and the GM's own pages in that journal are left alone: only the
+// ones this module made carry the `dragonroll-foundry.noteId` flag.
+
+const NOTES_JOURNAL_NAME = "Dragonroll";
+let noteSyncRunning = false;
+let noteSyncErrorLogged = false;
+
+function dragonrollNoteId(page) {
+ return page.getFlag?.(MODULE_ID, "noteId") || page.flags?.[MODULE_ID]?.noteId || "";
+}
+
+// A note is markdown, a journal page is HTML. Foundry's own renderer keeps the
+// page readable in the journal and in its styles; where this Foundry does not
+// offer one, escaped paragraphs keep the text legible until it does.
+function notePageHtml(content) {
+ const markdown = String(content ?? "");
+ if (!markdown.trim()) return "";
+ if (typeof TextEditor !== "undefined" && typeof TextEditor._getMarkdown === "function") {
+ const html = TextEditor._getMarkdown(markdown);
+ if (html) return html;
+ }
+ return markdown
+ .split(/\n\s*\n/)
+ .map((block) => `
${escapeNoteHtml(block.trim()).replace(/\n/g, "
")}
`)
+ .join("\n");
+}
+
+function escapeNoteHtml(value) {
+ return String(value).replace(/&/g, "&").replace(//g, ">");
+}
+
+function notePageTitle(entry) {
+ return String(entry.title || "").trim() || "Untitled note";
+}
+
+// The journal this module writes the campaign's notes into: the one it flagged as
+// its own, or one the GM already made under that name. An unflagged one is
+// flagged on use, so renaming it afterwards still leaves the notes' home findable.
+function notesJournal() {
+ const journals = game.journals?.contents || [];
+ return journals.find((journal) => journal.getFlag?.(MODULE_ID, "notesJournal"))
+ || journals.find((journal) => journal.name === NOTES_JOURNAL_NAME)
+ || null;
+}
+
+async function ensureNotesJournal() {
+ const existing = notesJournal();
+ if (existing) {
+ if (!existing.getFlag?.(MODULE_ID, "notesJournal")) {
+ await existing.update({ [`flags.${MODULE_ID}.notesJournal`]: true });
+ }
+ return existing;
+ }
+ const created = await JournalEntry.create(
+ { name: NOTES_JOURNAL_NAME, flags: { [MODULE_ID]: { notesJournal: true } } },
+ { renderSheet: false },
+ );
+ return Array.isArray(created) ? created[0] : created;
+}
+
+// The page a note stands as: rewrite what the campaign changed, and claim a page
+// the campaign mapped by id but whose flag was lost.
+async function applyDragonrollNotePage(page, entry) {
+ const title = notePageTitle(entry);
+ const html = notePageHtml(entry.content);
+ const updates = {};
+ if (String(page.title?.text ?? page.title ?? "") !== title) updates["title.text"] = title;
+ if (String(page.text?.content ?? "") !== html) updates["text.content"] = html;
+ if (!dragonrollNoteId(page)) updates[`flags.${MODULE_ID}.noteId`] = String(entry._id);
+ if (Object.keys(updates).length) await page.update(updates);
+}
+
+async function createDragonrollNotePage(journal, entry) {
+ const pages = await journal.createEmbeddedDocuments("JournalEntryPage", [{
+ title: { text: notePageTitle(entry) },
+ text: { content: notePageHtml(entry.content) },
+ flags: { [MODULE_ID]: { noteId: String(entry._id) } },
+ }], { renderSheet: false });
+ return Array.isArray(pages) ? pages[0] : pages;
+}
+
+async function mapDragonrollNote(noteId, foundryPageId) {
+ const token = getSyncToken();
+ return postDragonroll("foundry/sync/map-note", {
+ worldId: game.world.id,
+ noteId: String(noteId),
+ foundryPageId: String(foundryPageId),
+ }, token);
+}
+
+function reportNoteSyncError(error) {
+ if (noteSyncErrorLogged) return;
+ noteSyncErrorLogged = true;
+ console.warn(`${MODULE_ID} | Note journal sync failed and will retry.`, error);
+}
+
+async function reconcileDragonrollNotes() {
+ const token = getSyncToken();
+ if (!token || !game.user?.isGM || !game.world || noteSyncRunning || !isAutoSyncEnabled()) return;
+ noteSyncRunning = true;
+ try {
+ const result = await getDragonroll("foundry/sync/notes", token);
+ const remoteNotes = result.notes || [];
+ // A campaign without notes gets no journal of its own — but one it once had
+ // stays, so the pages of notes it deleted can go with them.
+ if (!remoteNotes.length && !notesJournal()) return;
+ const journal = await ensureNotesJournal();
+ if (!journal) return;
+
+ const remoteById = new Map(remoteNotes.map((entry) => [String(entry._id), entry]));
+ const localByRemoteId = new Map((journal.pages?.contents || [])
+ .map((page) => [String(dragonrollNoteId(page)), page])
+ .filter(([noteId]) => noteId));
+ const retainedPageIds = new Set();
+
+ for (const entry of remoteNotes) {
+ let page = entry.foundryPageId ? journal.pages?.get(entry.foundryPageId) : null;
+ if (!page) page = localByRemoteId.get(String(entry._id));
+ if (page) {
+ retainedPageIds.add(page.id);
+ await applyDragonrollNotePage(page, entry);
+ if (!entry.foundryPageId) await mapDragonrollNote(entry._id, page.id);
+ } else {
+ const created = await createDragonrollNotePage(journal, entry);
+ if (created) {
+ retainedPageIds.add(created.id);
+ await mapDragonrollNote(entry._id, created.id);
+ }
+ }
+ }
+
+ // Pages whose note the campaign deleted go with it. Only pages this module
+ // made are its business: an unflagged page is the GM's own.
+ for (const page of journal.pages?.contents || []) {
+ const noteId = dragonrollNoteId(page);
+ if (!noteId || retainedPageIds.has(page.id) || remoteById.has(String(noteId))) continue;
+ await page.delete();
+ }
+ noteSyncErrorLogged = false;
+ } catch (error) {
+ reportNoteSyncError(error);
+ } finally {
+ noteSyncRunning = false;
+ }
+}
+
async function publishSnapshot() {
if (!game.user?.isGM || !game.world) return;
if (syncInProgress) {
@@ -1452,6 +1604,10 @@ Hooks.once("ready", () => {
// already seen the world directory when it starts sending its own items back.
setTimeout(reconcileDragonrollItems, 2000);
setInterval(reconcileDragonrollItems, 5000);
+ // The campaign's notes arrive as pages of the world's Dragonroll journal on
+ // the same rhythm: a note written in the app is on the journal within seconds.
+ setTimeout(reconcileDragonrollNotes, 3000);
+ setInterval(reconcileDragonrollNotes, 5000);
for (const event of [
"createActor", "updateActor", "deleteActor",
diff --git a/frontend/app/content/docs/03-integrations/03-foundry.md b/frontend/app/content/docs/03-integrations/03-foundry.md
index c10d2c7d..0c6d088f 100644
--- a/frontend/app/content/docs/03-integrations/03-foundry.md
+++ b/frontend/app/content/docs/03-integrations/03-foundry.md
@@ -51,6 +51,7 @@ Worth knowing:
| The world's **item directory** (the items tab) | The campaign's item list, with category, rarity, quantity, weight, properties and description |
| The folders grouping that item directory | Item folders with the same names and nesting |
| A folder's colour | The campaign's folder colour — and the other way round, what you colour in Dragonroll lands on the world's folder |
+| A journal called **Dragonroll** — one page per note | Your campaign's notes. They arrive **from** Dragonroll: what you write in the journal does not go back |
The item list is the world's item directory and nothing else. The gear a character carries is that
character's inventory: it travels with the character and stays on its sheet, so a sword a fighter owns
@@ -67,6 +68,12 @@ few seconds. A **full** snapshot — the one taken when the world links, or forc
directory — is the only thing that prunes: it is the only moment either side can see the whole list and
notice what is gone. Live edits never delete anything.
+Notes are the exception that runs one way, because notes are written in Dragonroll: every note stands
+as a page of a single journal called **Dragonroll**. A note you make or edit in the app appears on that
+journal within a few seconds, and deleting one takes its page with it. Pages the campaign does not own
+— one the GM made in that journal themselves — are left alone, and nothing written in the journal
+travels back to the campaign.
+
## Auto-sync, and sending one actor on purpose
**Dragonroll Auto-sync** is what keeps the two in step: actors and world items you create, change or
diff --git a/tests/character-sheet-traits-items.test.js b/tests/character-sheet-traits-items.test.js
index c8a39f06..ea816a1a 100644
--- a/tests/character-sheet-traits-items.test.js
+++ b/tests/character-sheet-traits-items.test.js
@@ -133,6 +133,7 @@ function loadFoundryWriters({ seed = {}, settings } = {}) {
"../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)),
};
const requireStub = (id) => {
diff --git a/tests/foundry-force-import.test.js b/tests/foundry-force-import.test.js
index 62c79667..18e70a59 100644
--- a/tests/foundry-force-import.test.js
+++ b/tests/foundry-force-import.test.js
@@ -271,6 +271,7 @@ function loadFoundryWriters({ seed = {} } = {}) {
"../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)),
};
const requireStub = (id) => {
diff --git a/tests/foundry-note-journal.test.js b/tests/foundry-note-journal.test.js
new file mode 100644
index 00000000..b18ca08c
--- /dev/null
+++ b/tests/foundry-note-journal.test.js
@@ -0,0 +1,532 @@
+// Tests for the campaign's notes reaching the Foundry world as journal pages
+// (Syndria98/dragonroll#98): every Dragonroll note stands as a page of the one
+// journal the world calls "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 remembers each note's page; the module reads
+// them, renders the markdown, 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.journals` 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)),
+ };
+
+ 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 (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 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("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({ markdown = true } = {}) {
+ 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: [],
+ nextId: 1,
+ };
+
+ const journals = [];
+
+ const makePage = (journal, data = {}) => {
+ const page = {
+ id: `page-${state.nextId++}`,
+ documentName: "JournalEntryPage",
+ title: data.title,
+ text: { content: data.text?.content ?? "" },
+ flags: data.flags ?? {},
+ writes: 0,
+ 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 ?? {},
+ 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 createEmbeddedDocuments(documentName, docs) {
+ assert.equal(documentName, "JournalEntryPage", "the notes' pages are journal pages");
+ 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" } },
+ 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 }) };
+ }
+ 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];
+ },
+ },
+ };
+ if (markdown) sandbox.TextEditor = { _getMarkdown: (md) => `${md}` };
+
+ 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 },
+ journals: { 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"));
+
+ 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();
+ };
+ 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.title.text, page.text.content]), [
+ ["Session 1", "**The start**"],
+ ["Tavern Brawl", "A rope, a chandelier."],
+ ], "each note is a page, its markdown rendered by Foundry's own renderer");
+ 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("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.title.text), ["Session 1"]);
+ assert.equal(gmsOwn.getFlag(MODULE_ID, "notesJournal"), true, "and it is marked, so renaming it keeps the notes' home findable");
+});
+
+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].title.text, "Session 1 — revisited");
+ assert.equal(journal.pages.contents[0].text.content, "**A different start**");
+ 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, { title: { text: "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.title.text), ["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("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, { title: { text: "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.title.text, "Session 1");
+ assert.equal(orphan.getFlag(MODULE_ID, "noteId"), "note-1", "and the page is marked again");
+});
+
+test("without Foundry's markdown renderer the fallback keeps the text legible", async () => {
+ const world = await makeWorld({ markdown: false }).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,
+ "a & b < c
line two
\nsecond para
",
+ "escaped paragraphs instead of nothing, until this Foundry offers a renderer",
+ );
+});
+
+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");
+});
diff --git a/tests/item-folder-sync.test.js b/tests/item-folder-sync.test.js
index cc9c302a..d4af8362 100644
--- a/tests/item-folder-sync.test.js
+++ b/tests/item-folder-sync.test.js
@@ -132,6 +132,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
"../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)),
};
const requireStub = (id) => {