seitime-bridge/scripts/api.js
Vassili Minaev bc3aa10ab2 Initial scaffolding: settings + manifest push
Foundry v12 ESM module that pushes the world's PC actor manifest to a
companion Frappe app via webhook.

Structure:
- scripts/main.js: registers settings on init, exposes API on ready,
  wires createActor/deleteActor/periodic hooks. All push operations
  gated to game.users.activeGM to avoid duplicate pushes from co-GMs.
- scripts/settings.js: Frappe URL, shared secret, world ID, periodic
  interval. Secret uses `secret: true` for masked input but is still
  readable by all connected clients (documented in setting hint).
- scripts/api.js: bridgeFetch helper with X-Bridge-Secret/-World
  headers, pushManifest, testConnection.
- scripts/constants.js: MODULE_ID.

Public API exposed at globalThis.seitimeBridge:
  seitimeBridge.testConnection()  // round-trip empty manifest
  seitimeBridge.pushManifest()    // push current world manifest

dnd5e is declared as a related system in module.json.
Snapshot push and End Session macro come in subsequent commits.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 02:26:53 -06:00

97 lines
3.2 KiB
JavaScript

/**
* Outbound HTTP to the Frappe `st.api.foundry.*` endpoints.
*
* All calls are POST with `X-Bridge-Secret` and `X-Bridge-World` headers.
* Bodies are JSON. Errors include the Frappe server message when present.
*/
import { MODULE_ID } from "./constants.js";
function getConfig() {
const baseUrl = (game.settings.get(MODULE_ID, "frappeBaseUrl") || "").replace(/\/+$/, "");
const secret = game.settings.get(MODULE_ID, "sharedSecret") || "";
const worldId = game.settings.get(MODULE_ID, "worldId") || game.world?.id || "";
return { baseUrl, secret, worldId };
}
async function bridgeFetch(method, body) {
const { baseUrl, secret, worldId } = getConfig();
if (!baseUrl) throw new Error("Bridge not configured: set Frappe Base URL in module settings.");
if (!secret) throw new Error("Bridge not configured: set Shared Secret in module settings.");
if (!worldId) throw new Error("Bridge not configured: World ID could not be determined.");
const url = `${baseUrl}/api/method/st.api.foundry.${method}`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Bridge-Secret": secret,
"X-Bridge-World": worldId,
},
body: JSON.stringify(body),
});
if (!res.ok) {
let detail = "";
try {
const json = await res.json();
detail = json._server_messages || json.exception || JSON.stringify(json);
} catch {
detail = await res.text();
}
throw new Error(`Bridge ${method} failed: ${res.status} ${res.statusText}${detail}`);
}
return await res.json();
}
/**
* Produce a player display name for an actor by inspecting Foundry's
* ownership map. Returns the first non-GM user with OWNER permission, or
* null if none exists. The Frappe side reads this from `_player_name`
* during snapshot extraction (see `_actor_player_name` in foundry.py).
*/
function resolvePlayerName(actor) {
const ownership = actor.ownership || {};
for (const [userId, level] of Object.entries(ownership)) {
if (userId === "default") continue;
if (level < CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER) continue;
const user = game.users.get(userId);
if (user && !user.isGM) return user.name;
}
return null;
}
function buildManifest() {
return game.actors
.filter((a) => a.type === "character")
.map((a) => ({
id: a.id,
name: a.name,
player: resolvePlayerName(a),
}));
}
export async function pushManifest() {
const actors = buildManifest();
console.log(`[${MODULE_ID}] pushing manifest with ${actors.length} actor(s)`);
const result = await bridgeFetch("receive_actor_index", { actors });
console.log(`[${MODULE_ID}] manifest result:`, result);
return result;
}
/**
* Round-trip an empty manifest push to verify URL, secret, world ID, and
* Frappe-side enablement. Surfaces the result in the Foundry UI.
*/
export async function testConnection() {
console.log(`[${MODULE_ID}] testing connection...`);
try {
const result = await bridgeFetch("receive_actor_index", { actors: [] });
const received = result?.message?.received ?? 0;
ui.notifications.info(`Seitime Bridge OK — server accepted ${received} actor(s).`);
return result;
} catch (err) {
ui.notifications.error(`Seitime Bridge: ${err.message}`);
throw err;
}
}