Use shared BGS viewer and chat protocol

This commit is contained in:
coyotte508 2026-09-13 20:14:09 +02:00
commit 74507bc2ed
15 changed files with 158 additions and 408 deletions

View file

@ -4,7 +4,7 @@
Engine entry point: `dist/wrapper.js` from `fuji-engine`. The wrapper exports init, move, ended, scores, rankings, currentPlayer, dropPlayer, logLength, logSlice, stripSecret, round, replay and setPlayerMetaData, plus the optional isLiveUpdate hook. `hashSeed = true`; the seed never appears in a stripped view. `moveAI(state, player)` returns a new state using the shared baseline bot; the harness and simulations use the same implementation.
Viewer: self-contained IIFE, global `fuji`, function `launch(selector)` returning an emitter. The bridge consumes state/player events, requests fresh state on state updates and game logs, forwards moves without double wrapping, and announces readiness after rendering the initial state. The host provides chat transport and storage, clocks, identity and iframe messaging. Set `viewer.chat: true`: Fuji renders chat during and after the expedition, including lobby history. The bridge handles `chat:messages`, `chat:appended`, `chat:updated`, `chat:deleted`, `chat:state`, `chat:disabled` and `chat:result`; sends carry a request ID and visible messages emit `chat:read`. Chat drafts and updates are independent of game animation playback. The `chat:state` roster supplies mention suggestions. Messages use BGS-provided text, link and mention segments, with plain text as a fallback; outgoing mentions use `@name` or `@"Full Name"`. Links follow platform trust rules, and reading the chat clears the platform mention badge. The local harness keeps its chat separately in local storage; switch seats to test multiple authors. Source assets are bundled as data URLs, so the initial viewer has no independent asset-hosting requirement.
Viewer: self-contained IIFE, global `fuji`, function `launch(selector)` returning an emitter. `@boardgamers/protocol` handles viewer registration, validated events, state refreshes, readiness and cleanup. Its `ChatController` handles chat history, unread messages and send acknowledgements; the Svelte UI subscribes to its snapshots. The host provides chat transport and storage, clocks, identity and iframe messaging. Set `viewer.chat: true`: Fuji renders chat during and after the expedition, including lobby history. The bridge handles `chat:messages`, `chat:appended`, `chat:updated`, `chat:deleted`, `chat:state`, `chat:disabled` and `chat:result`; sends carry a request ID and visible messages emit `chat:read`. Chat drafts and updates are independent of game animation playback. The `chat:state` roster supplies mention suggestions. Messages use BGS-provided text, link and mention segments, with plain text as a fallback; outgoing mentions use `@name` or `@"Full Name"`. Links follow platform trust rules, and reading the chat clears the platform mention badge. The local harness keeps its chat separately in local storage; switch seats to test multiple authors. Source assets are bundled as data URLs, so the initial viewer has no independent asset-hosting requirement.
```sh
pnpm check

View file

@ -10,7 +10,7 @@
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
"simulate": "pnpm --filter fuji-engine build && node scripts/simulate.mjs",
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs && node tests/mobile-readiness-smoke.mjs && node tests/chat-tabs-smoke.mjs && node tests/chat-mentions-smoke.mjs"
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs && node tests/mobile-readiness-smoke.mjs && node tests/chat-tabs-smoke.mjs && node tests/chat-mentions-smoke.mjs && node tests/protocol-lifecycle-smoke.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -10,6 +10,7 @@
"check": "svelte-check --tsconfig ./tsconfig.json"
},
"dependencies": {
"@boardgamers/protocol": "0.1.0",
"fuji-engine": "workspace:*"
},
"devDependencies": {

View file

@ -69,11 +69,11 @@
let journal = $state(true);
let socialTab = $state("chat");
$effect(() => {
store.chat.playerIndex = seat;
store.chat.setPlayer(seat);
});
function openChat() {
socialTab = "chat";
store.chat.open = true;
store.chat.setOpen(true);
requestAnimationFrame(() =>
document.querySelector(".expedition-chat")?.scrollIntoView({ behavior: "smooth", block: "center" })
);
@ -450,8 +450,8 @@
<StaminaGuide difficulty={s.difficulty} expanded />
</span>
</div>
{#if store.chat.enabled}<button class="text-button" onclick={openChat}
>Chat{store.chat.unread ? ` · ${store.chat.unread}` : ""}</button
{#if store.chatState.enabled}<button class="text-button" onclick={openChat}
>Chat{store.chatState.unreadIds.length ? ` · ${store.chatState.unreadIds.length}` : ""}</button
>{/if}
<button class="text-button" onclick={() => (help = true)} aria-label="Open playing guide">Help</button>
<button
@ -462,7 +462,9 @@
requestAnimationFrame(() =>
document
.querySelector(
window.innerWidth <= 850 && store.chat.enabled ? ".mobile-journal .inline-journal" : ".inline-journal"
window.innerWidth <= 850 && store.chatState.enabled
? ".mobile-journal .inline-journal"
: ".inline-journal"
)
?.scrollIntoView({ behavior: "smooth", block: "nearest" })
);
@ -557,8 +559,8 @@
(s.phase === "equipment" && me.ready && !canReopenChoice(s, seat!)) ||
(s.phase === "eruption" && seat !== 0)}>{mobileLabel} →</button
>
{#if store.chat.enabled}<button class="dock-chat" onclick={openChat}
>Chat{store.chat.unread ? ` · ${store.chat.unread}` : ""}</button
{#if store.chatState.enabled}<button class="dock-chat" onclick={openChat}
>Chat{store.chatState.unreadIds.length ? ` · ${store.chatState.unreadIds.length}` : ""}</button
>{/if}
</div>{/if}
<section class="team" aria-label="Your expedition">
@ -804,17 +806,17 @@
</div>{/if}
{/if}
</section>
<div class:desktop-journal={store.chat.enabled}>{@render journalPanel("desktop")}</div>
<div class:desktop-journal={store.chatState.enabled}>{@render journalPanel("desktop")}</div>
</div>
<aside class="journey">
<div class="social-panel" data-tab={socialTab}>
{#if store.chat.enabled}<nav class="social-tabs" aria-label="Chat and journal">
{#if store.chatState.enabled}<nav class="social-tabs" aria-label="Chat and journal">
<button
class:active={socialTab === "chat"}
onclick={() => {
socialTab = "chat";
store.chat.open = true;
}}>Chat{store.chat.unread ? ` · ${store.chat.unread}` : ""}</button
store.chat.setOpen(true);
}}>Chat{store.chatState.unreadIds.length ? ` · ${store.chatState.unreadIds.length}` : ""}</button
>
<button
class:active={socialTab === "journal"}
@ -825,7 +827,7 @@
>
</nav>{/if}
<ChatPanel {store} />
{#if store.chat.enabled}<div class="mobile-journal">{@render journalPanel("mobile")}</div>{/if}
{#if store.chatState.enabled}<div class="mobile-journal">{@render journalPanel("mobile")}</div>{/if}
</div>
<div class="journey-actions">
<h2 class="sr-only">{nextAction}</h2>

View file

@ -1,6 +1,5 @@
import { mount } from "svelte";
import { parseMentions } from "./lib/mentions";
import type { ChatSegment } from "./lib/chat.svelte";
import { chatSegments } from "@boardgamers/protocol/chat";
import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import { initGame, applyMove, moveAI, stripSecret, activePlayers, type State } from "fuji-engine";
@ -8,8 +7,7 @@ import "./lib/theme.css";
import enginePackage from "../../engine/package.json";
const store = new Store();
store.local = true;
store.chat.enabled = true;
store.chat.canSend = true;
store.chat.setState({ canSend: true });
try {
store.chat.replace(JSON.parse(localStorage.getItem("fuji-dev-chat") ?? "[]"));
} catch {
@ -19,24 +17,16 @@ store.chat.send = ({ text, requestId }) => {
const playerIndex = store.seat ?? 0;
store.chat.append([
{
_id: crypto.randomUUID(),
_id: Date.now().toString(16).padStart(12, "0") + crypto.randomUUID().replaceAll("-", "").slice(0, 12),
author: store.state?.players[playerIndex]?.name ?? `Player ${playerIndex + 1}`,
playerIndex,
text,
segments: parseMentions(text, new Map(store.chat.mentions.map((p) => [p.id, p.name]))).flatMap(
(segment): ChatSegment[] =>
segment.kind === "mention"
? [segment]
: segment.text
.split(/(https?:\/\/[^\s<>"'`]+)/g)
.filter(Boolean)
.map((text) => (/^https?:\/\//.test(text) ? { kind: "link", url: text, text } : { kind: "text", text }))
),
segments: chatSegments(text, new Map(store.chatState.mentions.map((p) => [p.id, p.name])), true),
type: "text",
createdAt: new Date().toISOString(),
},
]);
localStorage.setItem("fuji-dev-chat", JSON.stringify(store.chat.messages));
localStorage.setItem("fuji-dev-chat", JSON.stringify(store.chatState.messages));
store.chat.result({ requestId, ok: true });
};
store.setSound(localStorage.getItem("fuji-sound") !== "false");
@ -88,11 +78,14 @@ if (import.meta.hot)
function publish() {
localStorage.setItem("fuji-dev-v1", JSON.stringify(game));
store.receive(stripSecret(game, store.seat));
store.chat.mentions = game.players.map((p, playerIndex) => ({
id: `local-${playerIndex}`,
name: p.name,
playerIndex,
}));
store.chat.setState({
canSend: true,
mentions: game.players.map((p, playerIndex) => ({
id: `local-${playerIndex}`,
name: p.name,
playerIndex,
})),
});
scheduleTeammate();
}
store.send = (move) => {
@ -108,7 +101,7 @@ store.restart = (players, seed, difficulty, scenario = 1, skillAssignment = "ran
game = initGame(players, { difficulty, scenario, skillAssignment }, seed);
store.seat = 0;
store.chat.replace([]);
store.chat.draft = "";
store.chat.setDraft("");
localStorage.removeItem("fuji-dev-chat");
publish();
};

View file

@ -1,26 +1,23 @@
<script lang="ts">
import { tick } from "svelte";
import type { Store } from "./store.svelte";
import { mentionQueryAt, filterMentionCandidates, applyMention } from "./mentions";
import { mentionQueryAt, applyMention } from "@boardgamers/protocol/chat";
let { store }: { store: Store } = $props();
const chat = $derived(store.chat);
const chat = $derived(store.chatState);
let composer: HTMLInputElement | undefined = $state();
let caret = $state(0);
let choice = $state(0);
let dismissed = $state(false);
const query = $derived(dismissed ? null : mentionQueryAt(chat.draft, caret));
const candidates = $derived(
query
? filterMentionCandidates(
chat.mentions.filter((player) => store.seat === undefined || player.playerIndex !== store.seat),
query.query
)
: []
);
const candidates = $derived.by(() => {
void chat.mentions;
void chat.playerIndex;
return query ? store.chat.suggestions(query.query) : [];
});
async function chooseMention(name: string) {
if (!query) return;
const next = applyMention(chat.draft, query, name);
chat.draft = next.text;
store.chat.setDraft(next.text);
caret = next.caret + 1;
dismissed = true;
await tick();
@ -56,7 +53,7 @@
return r.bottom <= Math.min(bounds.bottom, window.innerHeight) && r.bottom > Math.max(bounds.top, 0);
});
const id = latest?.dataset.messageId;
if (id) chat.markRead(id);
if (id) store.chat.markRead(id);
}
function followLatest() {
if (scrollFrame !== undefined) cancelAnimationFrame(scrollFrame);
@ -105,7 +102,7 @@
aria-label={chat.open ? "Collapse chat" : "Expand chat"}
aria-expanded={chat.open}
onclick={() => {
chat.open = !chat.open;
store.chat.setOpen(!chat.open);
pinned = true;
}}>{chat.open ? "−" : "+"}</button
>
@ -189,9 +186,10 @@
type="text"
aria-label="Chat message"
placeholder="Message your teammates…"
bind:value={chat.draft}
value={chat.draft}
bind:this={composer}
oninput={() => {
oninput={(event) => {
store.chat.setDraft(event.currentTarget.value);
caret = composer?.selectionStart ?? 0;
choice = 0;
dismissed = false;
@ -220,7 +218,7 @@
}
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault();
chat.submit();
store.chat.submit();
}
}}
/>
@ -228,7 +226,7 @@
class="chat-send"
disabled={!!chat.pending || !chat.draft.trim()}
type="button"
onclick={() => chat.submit()}>{chat.pending ? "Sending…" : "Send"}</button
onclick={() => store.chat.submit()}>{chat.pending ? "Sending…" : "Send"}</button
>
</div>
{:else}<p class="notice">{notice}</p>{/if}

View file

@ -1,104 +0,0 @@
export type ChatSegment =
| { kind: "text"; text: string }
| { kind: "link"; text: string; url: string }
| { kind: "mention"; id: string; name: string };
export type ChatMention = { id: string; name: string; playerIndex?: number };
export type ChatMessage = {
_id?: string;
author?: string;
authorId?: string;
playerIndex?: number;
createdAt?: string;
text: string;
segments?: ChatSegment[];
type: "text" | "system";
editedAt?: string;
};
export class Chat {
enabled = $state(false);
mentions: ChatMention[] = $state([]);
open = $state(true);
messages: ChatMessage[] = $state([]);
canSend = $state(false);
disabled = $state(false);
reason = $state("");
draft = $state("");
error = $state("");
pending = $state("");
private sent = "";
private sequence = 0;
private timer: ReturnType<typeof setTimeout> | undefined;
send: (data: { text: string; requestId: string }) => void = () => {};
read: (messageId: string) => void = () => {};
private newestRead = "";
unreadIds: string[] = $state([]);
playerIndex: number | undefined;
get unread() {
return this.unreadIds.filter((id) => this.messages.some((m) => m._id === id)).length;
}
private readTimer: ReturnType<typeof setTimeout> | undefined;
markRead(messageId: string) {
const index = this.messages.findIndex((m) => m._id === messageId);
if (index >= 0) {
const seen = new Set(this.messages.slice(0, index + 1).map((m) => m._id));
this.unreadIds = this.unreadIds.filter((id) => !seen.has(id));
}
// BGS message IDs are time-ordered ObjectIds. Keep the watermark even when
// older messages are deleted, history is replaced, or the panel is collapsed.
if (!/^[0-9a-f]{24}$/i.test(messageId)) return;
const id = messageId.toLowerCase();
if (id <= this.newestRead) return;
this.newestRead = id;
// Coalesce newly visible messages without postponing indefinitely while scrolling.
if (this.readTimer) return;
this.readTimer = setTimeout(() => {
this.readTimer = undefined;
this.read(this.newestRead);
}, 500);
}
replace(messages: ChatMessage[]) {
this.enabled = true;
this.messages = messages;
this.unreadIds = [];
}
append(messages: ChatMessage[]) {
this.unreadIds = [
...this.unreadIds,
...messages
.filter(
(m) =>
m._id &&
!this.messages.some((old) => old._id === m._id) &&
(m.playerIndex === undefined || m.playerIndex !== this.playerIndex)
)
.map((m) => m._id!),
];
this.messages = [
...this.messages,
...messages.filter((m) => !m._id || !this.messages.some((old) => old._id === m._id)),
];
}
submit() {
if (!this.canSend || this.disabled || this.pending || !this.draft.trim()) return;
this.error = "";
this.sent = this.draft;
this.pending = `fuji-chat-${Date.now()}-${++this.sequence}`;
this.timer = setTimeout(() => {
this.pending = "";
this.error = "Delivery could not be confirmed. Check the chat before retrying.";
}, 20000);
this.send({ text: this.sent.trim(), requestId: this.pending });
}
result(result: { requestId: string; ok: boolean; error?: string }) {
if (result.requestId !== this.pending) return;
clearTimeout(this.timer);
this.pending = "";
if (result.ok) {
if (this.draft === this.sent) this.draft = "";
} else this.error = result.error || "Message could not be sent. Please try again.";
}
destroy() {
clearTimeout(this.readTimer);
clearTimeout(this.timer);
}
}

View file

@ -1,34 +0,0 @@
export type Listener<T = unknown> = (payload: T) => void;
export class Emitter {
private listeners = new Map<string, Set<Listener>>();
on<T = unknown>(event: string, listener: Listener<T>): () => void {
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
const wrapped = listener as Listener;
set.add(wrapped);
return () => set.delete(wrapped);
}
once<T = unknown>(event: string, listener: Listener<T>): () => void {
const off = this.on<T>(event, (payload) => {
off();
listener(payload);
});
return off;
}
emit<T = unknown>(event: string, payload?: T): void {
for (const listener of this.listeners.get(event) ?? []) {
try {
listener(payload);
} catch (error) {
console.error(`[fuji-viewer] listener for "${event}" failed`, error);
}
}
}
}

View file

@ -1,153 +0,0 @@
// Mention parsing for chat (@username): rendering + autocomplete query state.
//
// Syntax: `@name` for plain-word usernames ([A-Za-z0-9_.-]+), and `@"name with
// spaces"` when the name isn't a plain word (the autocomplete always inserts the
// right form). Usernames forbid "@" by schema (packages/models user.ts), so "@"
// is an unambiguous trigger. The quote form never spans a line break.
//
// Rendering is roster-based: segments resolve against the room's known users, so
// an "@foo" that matches nobody stays plain text (no dead profile link). The
// roster is assembled per room by ChatRoom (game players + chat authors).
export type MentionCandidate = {
/** User id — the rendered link routes to the profile. */
id: string;
/** The username exactly as stored (mention text matches this). */
name: string;
};
export type MentionSegment = { kind: "text"; text: string } | { kind: "mention"; name: string; id: string };
// Plain-word usernames: letters, digits, underscore, dot, hyphen. Everything
// else (spaces, unicode, …) needs the quoted form.
const PLAIN_NAME = /^[A-Za-z0-9_.-]+$/;
// Matches a mention anywhere: `@word` or `@"quoted name"`.
const MENTION_RE = /@([A-Za-z0-9_.-]+)|@"([^"\n]+)"/g;
/**
* Split message text into text and mention segments, resolving mentions against
* the roster (id by name). Unresolvable @-references stay plain text — no dead
* links, and no way for a message author to fabricate a link to an arbitrary
* profile that isn't in the room.
*/
export function parseMentions(text: string, roster: Map<string, string>): MentionSegment[] {
const byName = new Map<string, string>();
for (const [id, name] of roster) {
byName.set(name.toLowerCase(), id);
}
const segments: MentionSegment[] = [];
let last = 0;
for (const match of text.matchAll(MENTION_RE)) {
const name = match[1] ?? match[2]!;
const id = byName.get(name.toLowerCase());
// A word char before the @ (emails, emoji codes) disqualifies the mention.
if (!id || (match.index > 0 && /\S/.test(text[match.index - 1]!))) continue;
if (match.index > last) {
segments.push({ kind: "text", text: text.slice(last, match.index) });
}
segments.push({ kind: "mention", name, id });
last = match.index + match[0].length;
}
if (last < text.length) {
segments.push({ kind: "text", text: text.slice(last) });
}
return segments;
}
/**
* Whether a username needs the quoted mention form (anything outside
* [A-Za-z0-9_.-] — spaces, unicode, …).
*/
export function needsQuotedMention(name: string): boolean {
return !PLAIN_NAME.test(name);
}
/**
* The literal text for a mention of `name` — `@name` or `@"full name"`, with a
* trailing space so typing continues right after it.
*/
export function mentionText(name: string): string {
return needsQuotedMention(name) ? `@"${name}" ` : `@${name} `;
}
/** A live autocomplete query: the mention being typed at the caret, if any. */
export type MentionQuery = {
/** Text typed after the @ (or inside the quotes) so far. */
query: string;
/** Index where the whole reference starts (the @). */
start: number;
/** Index where the reference ends (== caret). */
end: number;
/** Quote form: the reference started as `@"` and is not closed yet. */
quoted: boolean;
};
/**
* Find the mention being typed at `caret`, or null when the caret is not inside
* a @-reference. Trigger rules:
* - caret right after a fresh `@` (empty query), or
* - caret inside/after `@word…` plain-name chars, or
* - caret inside an unclosed `@"…`.
* A non-space char before the @ disqualifies the trigger — a mid-word @ (emails,
* emoji codes) is not a mention.
*/
export function mentionQueryAt(text: string, caret: number): MentionQuery | null {
// Quote form: an `@"` opened before the caret and not yet closed — the next
// quote (if any) is at/after the caret. indexOf === -1 means no closer at all
// (still being typed), which counts as open.
const open = text.lastIndexOf('@"', caret);
const closer = open >= 0 ? text.indexOf('"', open + 2) : -2;
if (open >= 0 && (closer === -1 || closer >= caret)) {
if (open > 0 && /\S/.test(text[open - 1]!)) return null;
return { query: text.slice(open + 2, caret), start: open, end: caret, quoted: true };
}
// Plain form: scan back over name chars, then require the @ before them.
let i = caret;
while (i > 0 && PLAIN_NAME.test(text[i - 1]!)) {
i--;
}
// The @ must be followed immediately by the caret's name chars — but a plain
// name can't contain "l" then space… the scan is over PLAIN_NAME chars only.
if (i === caret && i > 0 && text[i - 1]! === "@") {
return { query: "", start: i - 1, end: caret, quoted: false };
}
if (i === 0 || text[i - 1]! !== "@") {
return null;
}
const start = i - 1;
if (start > 0 && /\S/.test(text[start - 1]!)) {
return null;
}
return { query: text.slice(start + 1, caret), start, end: caret, quoted: false };
}
/**
* Filter the roster for the autocomplete list: prefix match, case-insensitive,
* exact match first, then alphabetical. Caller decides who's in the roster
* (bots are not offered).
*/
export function filterMentionCandidates(roster: MentionCandidate[], query: string, limit = 8): MentionCandidate[] {
const q = query.toLowerCase();
return roster
.filter((c) => c.name.toLowerCase().startsWith(q))
.sort((a, b) => {
const ax = a.name.toLowerCase();
const bx = b.name.toLowerCase();
if (ax === q) return -1;
if (bx === q) return 1;
return ax < bx ? -1 : ax > bx ? 1 : 0;
})
.slice(0, limit);
}
/**
* Replace the query being typed (the [start, end) span from mentionQueryAt) with
* the chosen mention's literal text, returning the new full text and the caret
* position right after the inserted mention (before its trailing space).
*/
export function applyMention(text: string, q: MentionQuery, name: string): { text: string; caret: number } {
const literal = needsQuotedMention(name) ? `@"${name}"` : `@${name}`;
const next = text.slice(0, q.start) + literal + " " + text.slice(q.end);
return { text: next, caret: q.start + literal.length };
}

View file

@ -1,8 +1,12 @@
import { Chat } from "./chat.svelte";
import { ChatController } from "@boardgamers/protocol/chat";
import { SoundDesign, type SoundCue } from "./sound";
import type { View, Move } from "fuji-engine";
export class Store {
chat = new Chat();
chat = new ChatController();
chatState = $state.raw(this.chat.snapshot);
private unsubscribeChat = this.chat.subscribe((snapshot) => {
this.chatState = snapshot;
});
state: View | null = $state(null);
avatars: string[] = $state([]);
clickPlayer: (index: number) => void = () => {};
@ -17,6 +21,7 @@ export class Store {
}
destroy() {
this.dispose();
this.unsubscribeChat();
this.chat.destroy();
this.audio.destroy();
}

View file

@ -1,66 +1,40 @@
import { mount, tick } from "svelte";
import { mount, tick, unmount } from "svelte";
import { registerViewer } from "@boardgamers/protocol/viewer";
import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import { Emitter } from "./lib/emitter";
import type { ChatMessage, ChatMention } from "./lib/chat.svelte";
import type { View } from "fuji-engine";
import type { View, Move } from "fuji-engine";
import "./lib/theme.css";
export function launch(selector: string) {
const target = document.querySelector(selector);
if (!target) throw Error("Viewer mount point not found.");
const events = new Emitter();
const store = new Store();
let ready = false;
const chat = store.chat;
chat.send = (data) => events.emit("chat:send", data);
chat.read = (messageId) => events.emit("chat:read", { messageId });
events.on<ChatMessage[]>("chat:messages", (messages) => chat.replace(messages));
events.on<ChatMessage[]>("chat:appended", (messages) => chat.append(messages));
events.on<ChatMessage[]>("chat:updated", (messages) => {
chat.messages = chat.messages.map((m) => messages.find((update) => update._id === m._id) ?? m);
});
events.on<string[]>("chat:deleted", (ids) => {
chat.messages = chat.messages.filter((m) => !m._id || !ids.includes(m._id));
});
events.on<boolean>("chat:disabled", (disabled) => {
chat.disabled = disabled;
});
events.on<{ canSend: boolean; reason?: string; mentions?: ChatMention[] }>("chat:state", (state) => {
chat.enabled = true;
chat.canSend = state.canSend;
chat.reason = state.reason ?? "";
chat.mentions = state.mentions ?? [];
});
events.on<{ requestId: string; ok: boolean; error?: string }>("chat:result", (result) => chat.result(result));
store.savePreference = (name, value) => events.emit("update:preference", { name, value });
events.on<Record<string, unknown>>("preferences", (preferences) => {
store.colorblind = preferences?.colorblind === true;
store.setSound(preferences?.sound !== false);
});
events.on<string[]>("avatars", (avatars) => {
store.avatars = avatars;
});
store.clickPlayer = (index) => events.emit("player:clicked", { index });
store.send = (move) => events.emit("move", move);
events.on<View>("state", async (state) => {
store.receive(state);
events.emit(
"replaceLog",
state.log.map((e) => e.text)
);
await tick();
if (!ready) {
ready = true;
setTimeout(() => events.emit("ready"), 0);
}
});
events.on<{ index?: number }>("player", (p) => {
store.seat = p?.index;
});
events.on("state:updated", () => events.emit("fetchState"));
events.on("gamelog", () => events.emit("fetchState"));
mount(App, { target, props: { store } });
return events;
}
if (typeof window !== "undefined") (window as unknown as { fuji: unknown }).fuji = { launch };
registerViewer<View, Move>("fuji", ({ target, move, openPlayer, updatePreference, replaceLog }) => {
const store = new Store();
store.send = move;
store.clickPlayer = openPlayer;
store.savePreference = updatePreference;
const app = mount(App, { target, props: { store } });
return {
chat: store.chat,
async onState(state) {
store.receive(state);
replaceLog(state.log.map((entry) => entry.text));
await tick();
},
onPlayer({ index }) {
store.seat = index;
},
onPreferences(preferences) {
store.colorblind = preferences.colorblind === true;
store.setSound(preferences.sound !== false);
},
onAvatars(avatars) {
store.avatars = avatars;
},
onError(error) {
store.error = error instanceof Error ? error.message : String(error);
store.waiting = false;
},
destroy() {
store.destroy();
void unmount(app);
},
};
});

View file

@ -8,7 +8,8 @@ export default defineConfig({
},
build: {
cssCodeSplit: false,
lib: { entry: "src/viewer.ts", name: "fuji", formats: ["iife"], fileName: () => "fuji-viewer.iife.js" },
// Vite requires a bundle name; registerViewer owns the fuji global.
lib: { name: "fujiBundle", entry: "src/viewer.ts", formats: ["iife"], fileName: () => "fuji-viewer.iife.js" },
rolldownOptions: { output: { assetFileNames: "fuji-viewer.[ext]" } },
},
});

15
pnpm-lock.yaml generated
View file

@ -33,6 +33,9 @@ importers:
packages/viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.1.0
version: 0.1.0
fuji-engine:
specifier: workspace:*
version: link:../engine
@ -58,6 +61,9 @@ importers:
packages:
'@boardgamers/protocol@0.1.0':
resolution: {integrity: sha512-Gl5oPb6v+FoE9Lyj6rg98o3UQmRKGl61XVouMryUcQ33C+blhQ0azH4UH5NuoJUILR+xQDDpcZC+U6pal+07aQ==}
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@ -620,8 +626,15 @@ packages:
zimmerframe@1.1.5:
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
zod@4.6.2:
resolution: {integrity: sha512-lh5RCAGFa1Cm2hjtNwLQhSs/AsqdWnTQaBER9fEwN/88pSh7KOtJavtBx/0VlkN/uFd61SwYmljLMDAsHlvzBQ==}
snapshots:
'@boardgamers/protocol@0.1.0':
dependencies:
zod: 4.6.2
'@jridgewell/gen-mapping@0.3.13':
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
@ -1006,3 +1019,5 @@ snapshots:
vite: 8.2.0(@types/node@24.10.1)
zimmerframe@1.1.5: {}
zod@4.6.2: {}

View file

@ -1,2 +1,4 @@
packages:
- packages/*
minimumReleaseAgeExclude:
- "@boardgamers/protocol@0.1.0"

View file

@ -0,0 +1,50 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { initGame, stripSecret } from "../packages/engine/dist/index.js";
const browser = await chromium.launch({ executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
try {
const page = await browser.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.setContent('<div id="app"></div>');
await page.addStyleTag({ path: "packages/viewer/dist/fuji-viewer.css" });
await page.addScriptTag({ path: "packages/viewer/dist/fuji-viewer.iife.js" });
const state = stripSecret(initGame(3, {}, "protocol-lifecycle"), 0);
await page.evaluate((state) => {
window.old = fuji.launch("#app");
old.emit("state", state);
old.emit("chat:state", { canSend: true });
window.events = [];
window.current = fuji.launch("#app");
for (const event of ["ready", "move", "chat:send"]) {
current.on(event, (payload) => events.push({ event, payload }));
}
current.emit("player", { index: 0 });
current.emit("state", state);
old.emit("chat:messages", [{ type: "text", text: "Old game" }]);
current.emit("chat:state", { canSend: true });
current.emit("chat:messages", [{ _id: "000000000000000000000001", type: "text", text: "New game" }]);
}, state);
await page.waitForFunction(() => events.filter((e) => e.event === "ready").length === 1);
assert.equal(await page.getByText("Old game", { exact: true }).count(), 0);
assert.equal(await page.getByText("New game", { exact: true }).count(), 1);
assert.equal(await page.getByRole("textbox", { name: "Chat message" }).count(), 1);
assert.equal(await page.evaluate(() => fuji.diagnostics().compatible), true);
assert.equal(await page.evaluate(() => old.emit("state:updated")), false);
const input = page.getByRole("textbox", { name: "Chat message" });
await input.fill("Original draft");
await input.press("Enter");
await input.fill("Edited while sending");
await page.evaluate(() => {
const request = events.find((e) => e.event === "chat:send").payload;
current.emit("chat:result", { requestId: request.requestId, ok: true });
});
assert.equal(await input.inputValue(), "Edited while sending");
await page.evaluate(() => fuji.destroy());
assert.equal(await page.locator("#app").innerHTML(), "");
assert.equal(await page.evaluate(() => current.emit("state:updated")), false);
assert.deepEqual(errors, []);
console.log("Fuji protocol: relaunch cleanup, readiness, diagnostics and pending draft preservation passed.");
} finally {
await browser.close();
}