feat: client shell, sign-in and protocol client (#67)

New `client/` package (Vite + TypeScript + PixiJS v8, plain DOM overlay):
the pure reducer seam (no Pixi import), an append-only slice registry
build-time glob, the `proto` 2 WS client with envelope/ack/closing mapping,
the sign-in door (`POST /join`, one "Key not recognised." for wrong and
unknown), the DOM shell/HUD and a minimal Pixi stage created only after a
live `hello`. `hello` resets every slice so a reconnect cannot show stale
state; `proto-mismatch` shows reload; `revoked` returns to the sign-in page
and stops.

The browser e2e moves into the client package (`client/e2e/`, owning
playwright-core) and runs the real Vite build through the TLS/HTTP2 test
nginx: join -> canvas -> hello/roster for GM and player, no data before
join, identical wrong/unknown key refusal, proto mismatch, revoked.
`devbox run client-test` adds the Vitest seam; `devbox run e2e` builds the
client first. The #66 stub dist stays local to `tools/vhost.test.mjs`, so
`devbox run test` still needs no npm install.

Refs #67
This commit is contained in:
2026-11-20 23:57:16 +01:00
parent 97f618c5ad
commit 3c0258ea31
37 changed files with 3439 additions and 178 deletions
+74
View File
@@ -0,0 +1,74 @@
# FFF VTT client
Vite + TypeScript + PixiJS v8, plain DOM overlay, `proto` 2 (DESIGN §7, ADR-0011). No framework.
## Run and gates
All through devbox, from the repo root:
```sh
devbox run client-test # Vitest: pure reducer + protocol client + envelope (no DOM, no GPU)
devbox run e2e # builds client/dist, then Chromium against the real server through the
# TLS/HTTP2 test nginx (client/e2e/*.test.mjs, playwright-core)
devbox run test # the server gate; unaffected by the client
devbox run -- bash -c 'cd client && npm run dev' # local dev (Vite, no server API on :5173)
```
`npm run build` = `tsc --noEmit && vite build` into `client/dist`, which the test/production nginx
serves at `/` (DESIGN §11.1). `client/dist` and `client/node_modules` are not committed.
## The one seam that matters
`src/reducer.ts` is pure: server frames and connection events in, state out. **It must never import
Pixi, the DOM, or the socket.** Its unit tests (`test/*.test.ts`) are the contract. Everything else
is wiring:
| File | Owns |
|---|---|
| `src/protocol.ts` | Wire types, envelope/ack/closing guards, intent encoding, `/ws?proto=2` URL. Pure. |
| `src/reducer.ts` | `RootState`, phase machine (`boot/connecting/signin/live/reload/offline`), `hello` reset, slice registry. Pure. |
| `src/slices/*.ts` | Append-only domain state (roster today; fog, tokens, walls, panels later). |
| `src/ws.ts` | Socket, `reqId` counter, pending map, close-code mapping. No DOM. |
| `src/shell.ts` | Sign-in, HUD/roster, fatal screens. Plain DOM, `textContent` only. |
| `src/render/stage.ts` | One Pixi `Application`, one world container, fixed layers. Pixi lives here and in modules only. |
| `src/render/modules/*.ts` | Append-only render modules. |
| `src/main.ts` | Wiring: store -> shell/stage, `/join`, connect. |
## Convention for the M4 fan-out (T7, T8/T9, T10, T11/T12)
The registry is a **build-time glob**, so parallel tickets are file-disjoint: no shared import list
to merge and no registry file to edit.
- **State slice**: add `src/slices/<feature>.ts` exporting `export const slice: Slice<YourState>`
(`name`, `init()`, `reduce(state, event, root)`). It is registered automatically. Read it with
`sliceOf<YourState>(state, '<name>')`. `hello` resets every slice for you (DESIGN §6.3): never
keep server-derived state outside a slice or the core session.
- **Render module**: add `src/render/modules/<feature>.ts` exporting
`export const renderModule: RenderModule` (`name`, `mount(context)`, optional teardown). Draw into
your layer: `tiles`, `grid`, `tokens`, `fog` (players), `gm` (GM only), `dom`.
- **Panel/DOM**: add `src/panels/<feature>.ts` and mount under the existing `#panels` host; do not
rewrite the sign-in flow. Server strings go through `textContent` (never `innerHTML`); token
labels use `BitmapText` with the pre-installed `BitmapFont` (DESIGN §7.2).
- **No per-frame full redraw**: subscribe to the store and touch only entities that changed
(DESIGN §7.2). Keep the DOM overlay work per frame minimal.
- **Protocol**: only the catalogue in DESIGN §6.1. The client ignores unknown frame types/fields
(§6.2). `closing` reasons map through `closeOutcome`: `proto-mismatch` -> reload, `revoked` ->
sign-in, `evicted`/`malformed-flood` -> offline. Do not invent wire fields; server-side additions
are separate tickets (e.g. `seen_by`, T12).
Suggested ownership (no file overlap): T7 fog = `slices/fog.ts` + `render/modules/fog.ts`; T8/T9
tokens/drag = `slices/tokens.ts`, `slices/move.ts`, `render/modules/tokens.ts`; T10 walls =
`slices/walls.ts` + `render/modules/walls.ts`; T11/T12 GM panels = `slices/admin.ts` +
`src/panels/*.ts`. `src/reducer.ts`, `src/main.ts` and `src/render/stage.ts` are already generic;
change them only if a slice needs a new *core* event, and say so in the PR.
## Protocol notes already encoded
- `/ws?proto=2`; a mismatch is `closing{reason:"proto-mismatch",code:4003}` then close. The reason
is read from the last `closing` frame because browsers report 1005 at the mummy pin (ADR-0019).
- `hello` resets all state; the resync after it rebuilds the view. Pending `reqId`s survive a
`hello` on a live connection and die with the socket (DESIGN §6.3).
- Sign-in is `POST /join` (form body, key never in the URL). A `401` for a wrong key and for an
unknown key is shown as the same "Key not recognised." (DESIGN §3.2, story 3).
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
only sees the sign-in page.
+55
View File
@@ -0,0 +1,55 @@
// The browser half of the vhost gate (#66, TESTING 10.3): real Chromium loads the real client build
// from `/` through the TLS/HTTP2 test nginx and reports h2 for the document and its hashed assets.
// The client bundle replaces the throwaway `tools/distfixture.mjs` of #66; `client/e2e/run.sh`
// builds it before this test runs.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, withStack } from './stack.mjs'
test('e2e: headless chromium loads the real client build and the page reports h2', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const loaded = []
page.on('response', response => loaded.push({ url: response.url(), status: response.status() }))
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
// The boot probe's refused WebSocket upgrade is the expected no-session path (the browser
// logs it); it is not a page error. Everything else must be silent.
if (message.type() === 'error' && !message.text().includes('WebSocket connection')) {
errors.push(message.text())
}
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
assert.equal(await page.title(), 'FFF VTT')
await page.locator('#app').waitFor({ state: 'attached' })
// A visitor with no session gets the sign-in door; the canvas is created only after `hello`.
await page.locator('#signin').waitFor({ state: 'visible', timeout: 20000 })
assert.deepEqual(errors, [])
const assets = loaded.filter(response => new URL(response.url).pathname.startsWith('/assets/'))
assert.ok(assets.length > 0, `the page loaded hashed assets: ${JSON.stringify(loaded)}`)
assert.ok(assets.every(response => response.status === 200))
const proto = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0]
const resources = performance
.getEntriesByType('resource')
.map(entry => ({ name: entry.name, protocol: entry.nextHopProtocol }))
return { scheme: location.protocol, navigation: navigation.nextHopProtocol, resources }
})
assert.equal(proto.scheme, 'https:')
assert.equal(proto.navigation, 'h2', 'the document came over HTTP/2')
assert.ok(
proto.resources.some(resource => resource.protocol === 'h2' && resource.name.endsWith('.js')),
`subresources are h2 too: ${JSON.stringify(proto.resources)}`,
)
} finally {
await browser.close()
}
})
})
+38
View File
@@ -0,0 +1,38 @@
// Story 9 / DR 6.2 (#67): a proto mismatch completes the upgrade, sends closing{proto-mismatch}
// and closes; the client must show "reload" and stop, not sign in and not retry.
//
// The real server's mismatch path is already proven by tools/protocol.test.mjs (it takes a build
// whose proto differs). Here the browser's own WebSocket is intercepted and given exactly that
// documented frame sequence, so the assertion is about the client's UI and close-code mapping.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, waitForText, waitForVisible, withStack } from './stack.mjs'
test('protocol mismatch: the client shows reload and does not reconnect', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
let sockets = 0
await page.routeWebSocket(/\/ws\?proto=2$/, ws => {
sockets += 1
// DESIGN 6.5 row 5: closing then the close frame; no hello, no state.
ws.send(JSON.stringify({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 }))
ws.close()
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#fatal')
await waitForText(page, '#fatal-text', /out of date.*reload/i)
const reload = page.locator('#reload')
assert.equal(await reload.isVisible(), true)
assert.equal(await page.locator('#signin').isVisible(), false)
assert.equal(await page.locator('#stage canvas').count(), 0)
await new Promise(resolve => setTimeout(resolve, 400))
assert.equal(sockets, 1, 'a mismatch is terminal: exactly one connection attempt')
} finally {
await browser.close()
}
})
})
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# devbox run e2e: the headless-browser gate (TESTING 10.3). Builds the real client, then runs the
# browser suite against the real server through the TLS/HTTP2 test nginx. Separate from
# `devbox run test` so the fast server gate stays fast (TESTING 11.1); the client's own unit tests
# are `devbox run client-test`.
set -euo pipefail
cd "$(dirname "$0")/../.." || exit 1
mkdir -p results
export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}"
if [ -z "$CHROMIUM" ]; then
echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2
exit 1
fi
# npm deps stay out of tools/ (TESTING 10.4) and out of git; install once per checkout.
( cd client && { [ -d node_modules ] || npm ci --no-audit --no-fund; } )
( cd client && npm run build )
node --test --test-concurrency=1 --test-reporter=spec client/e2e/*.test.mjs > results/e2e.log 2>&1
rc=$?
cat results/e2e.log
exit $rc
+103
View File
@@ -0,0 +1,103 @@
// T4 client shell (#67, TESTING 10.3): join -> canvas -> hello/roster for the GM and a player, no
// data before join, one plain refusal for a wrong and an unknown key, and a revoked session
// returning to sign-in. The server, the nginx vhost and the client are the real ones.
import test from 'node:test'
import assert from 'node:assert/strict'
import { sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
makePlayer,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
const KEY_REFUSED = 'Key not recognised.'
async function canvasAndRoster(page, expectedNames) {
await waitForVisible(page, '#stage canvas')
await waitForVisible(page, '#hud')
const roster = await waitForText(page, '#roster', new RegExp(expectedNames[0]))
for (const name of expectedNames) assert.match(roster, new RegExp(name))
return roster
}
test('no session: only the sign-in page, and a wrong and an unknown key look identical', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const joins = []
page.on('response', response => {
if (new URL(response.url()).pathname === '/join') joins.push(response.status())
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
// Story 1: a stranger gets the door and no game data.
assert.equal(await page.locator('#stage').isVisible(), false)
assert.equal(await page.locator('#hud').isVisible(), false)
assert.equal(await page.locator('#roster li').count(), 0)
// Story 3: the same answer for a well-formed but wrong key and for an unknown one.
await signIn(page, 'ABCD-EFGH-JKMN-PQRS')
await waitForVisible(page, '#signin-error')
const wrong = await page.textContent('#signin-error')
await signIn(page, 'not-a-key')
await waitForVisible(page, '#signin-error')
const unknown = await page.textContent('#signin-error')
assert.equal(wrong, KEY_REFUSED)
assert.equal(unknown, KEY_REFUSED)
assert.deepEqual(joins, [401, 401])
// No map request was made before a session existed.
assert.equal(await page.locator('#stage canvas').count(), 0)
} finally {
await browser.close()
}
})
})
test('GM and player: join -> canvas -> hello and roster; revoked returns to sign-in', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const player = await makePlayer(origin, gmKey, 'Alice')
const browser = await launchBrowser()
try {
const gmView = await newPage(browser)
await gmView.page.goto(`${origin}/`)
await waitForVisible(gmView.page, '#signin')
await signIn(gmView.page, gmKey)
const gmRoster = await canvasAndRoster(gmView.page, ['GM', 'Alice'])
assert.equal(await gmView.page.textContent('#role'), 'GM')
assert.match(gmRoster, /connected/)
const playerView = await newPage(browser)
await playerView.page.goto(`${origin}/`)
await waitForVisible(playerView.page, '#signin')
await signIn(playerView.page, player.key)
await canvasAndRoster(playerView.page, ['GM', 'Alice'])
assert.equal(await playerView.page.textContent('#role'), 'Player')
assert.equal(await playerView.page.textContent('#me'), 'Alice')
// Story 10: the GM replaces the key, the server revokes the session, and the browser stops
// at the sign-in door instead of hammering a dead socket.
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const ack = await gm.ws.request({ t: 'key.replace', id: player.id })
assert.equal(ack.ok, true)
gm.ws.close()
await waitForVisible(playerView.page, '#signin')
await waitForText(playerView.page, '#signin-notice', /session has ended/i)
assert.equal(await playerView.page.locator('#stage canvas').count(), 0)
assert.equal(await playerView.page.locator('#roster li').count(), 0)
// No automatic reconnection: still on the sign-in page a moment later.
await sleep(300)
assert.equal(await playerView.page.locator('#signin').isVisible(), true)
} finally {
await browser.close()
}
})
})
+96
View File
@@ -0,0 +1,96 @@
// Shared stack for the client e2e (TESTING 10.3): the real client build served by the TLS/HTTP2
// test nginx in front of the real server binary. Never a fixture, never a mocked protocol.
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright-core'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot, sleep } from '../../tools/lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import { startTestNginx, stopTestNginx } from '../../tools/nginx.mjs'
export const CHROMIUM = process.env.CHROMIUM ?? 'chromium'
export const LAUNCH_ARGS = [
'--no-sandbox',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'--ignore-gpu-blocklist',
]
export const CLIENT_DIST = path.join(projectRoot, 'client', 'dist')
export function assertClientBuild() {
assert.ok(
fs.existsSync(path.join(CLIENT_DIST, 'index.html')),
`client build missing at ${CLIENT_DIST}: run \`npm run build\` in client/ (client/e2e/run.sh does)`,
)
}
export async function withStack(fn) {
assertClientBuild()
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let nginx
try {
nginx = await startTestNginx({
backendPort: server.port,
stateDir,
port: nginxPort,
distDir: CLIENT_DIST,
})
return await fn({ stateDir, server, nginx, origin: nginx.origin, gmKey })
} finally {
if (nginx) await stopTestNginx(nginx)
await stopServer(server)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
export async function launchBrowser() {
return chromium.launch({ executablePath: CHROMIUM, args: LAUNCH_ARGS })
}
export async function newPage(browser) {
// The certificate is generated per run by tools/tlsdev.mjs; trusting it in the browser is the
// one concession, the rest of the page is the real https/h2 path.
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
return { context, page: await context.newPage() }
}
/** A named player created the way the product creates one: a GM key.create, then player.setname. */
export async function makePlayer(origin, gmKey, name) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const created = await createPlayer(gm.ws)
await namePlayer(origin, created.key, name)
gm.ws.close()
await gm.ws.closed
return { id: created.id, key: created.key, name }
}
export async function signIn(page, key) {
await page.fill('#key', key)
await page.click('#signin-submit')
}
export async function waitForVisible(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'visible', timeout })
}
export async function waitForHidden(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'hidden', timeout })
}
export async function waitForText(page, selector, pattern, timeout = 20000) {
const deadline = Date.now() + timeout
let last = ''
while (Date.now() < deadline) {
last = (await page.locator(selector).textContent()) ?? ''
if (pattern.test(last)) return last
await sleep(50)
}
throw new Error(`${selector} never matched ${pattern}: last was ${JSON.stringify(last)}`)
}
export { sleep }
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>FFF VTT</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1342
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "fff-vtt-client",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "FFF VTT browser client: Vite + TypeScript + PixiJS v8, plain DOM overlay (DESIGN 7).",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"test": "vitest run --reporter=dot"
},
"dependencies": {
"pixi.js": "8.23.0"
},
"devDependencies": {
"playwright-core": "1.65.1",
"typescript": "5.9.3",
"vite": "8.3.8",
"vitest": "5.1.1"
}
}
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# devbox run client-test: the pure reducer/protocol-client seam (TESTING 10.3 "Client reducer",
# spec #63 decision 13). No server, no browser, no GPU: these run in a second.
set -euo pipefail
cd "$(dirname "$0")/.." || exit 1
mkdir -p results
{ [ -d client/node_modules ] || ( cd client && npm ci --no-audit --no-fund ); }
( cd client && npm test ) > results/client-test.log 2>&1
rc=$?
cat results/client-test.log
exit $rc
+103
View File
@@ -0,0 +1,103 @@
// Client bootstrap: one store, one WS client, one DOM shell, one Pixi stage created only once the
// session is live. Every network/UI decision goes through the pure reducer; this file is wiring.
import './style.css'
import { ProtocolClient } from './ws.ts'
import { Store } from './store.ts'
import { mountShell } from './shell.ts'
import type { Stage } from './render/stage.ts'
import { createStage } from './render/stage.ts'
import type { RootState } from './reducer.ts'
const KEY_REFUSED = 'Key not recognised.'
const host = document.querySelector<HTMLElement>('#app')
if (!host) throw new Error('#app is missing')
const store = new Store()
let client: ProtocolClient | null = null
let stage: Stage | null = null
let startingStage: Promise<void> | null = null
const shell = mountShell(host, {
onSubmitKey: key => {
void signIn(key)
},
onReload: () => location.reload(),
})
const stageHost = document.querySelector<HTMLElement>('#stage')
if (!stageHost) throw new Error('#stage is missing')
const stageRoot: HTMLElement = stageHost
async function signIn(key: string): Promise<void> {
shell.setBusy(true)
let accepted = false
try {
// DESIGN 3.2/6.6: POST /join, key in the body. `redirect: 'manual'` turns the 303 into an
// opaque redirect the client cannot mistake for a body; a 401 (wrong or unknown key alike)
// is a readable same-origin response.
const response = await fetch('/join', {
method: 'POST',
credentials: 'same-origin',
redirect: 'manual',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ key }).toString(),
})
accepted = response.type === 'opaqueredirect' || response.status === 303
} catch {
accepted = false
}
if (!accepted) {
// Story 3: one plain answer, whatever the reason. No key existence oracle.
store.dispatch({ type: 'signin-failed', message: KEY_REFUSED })
return
}
client?.close()
store.dispatch({ type: 'connecting' })
connect()
}
function connect(): void {
client = new ProtocolClient({
onEvent: event => {
store.dispatch(event)
},
})
client.connect()
}
function syncStage(state: RootState): void {
const live = state.connection.phase === 'live'
if (!live) {
stage?.destroy()
stage = null
return
}
if (stage || startingStage) return
startingStage = createStage(stageRoot, store)
.then(created => {
if (store.state.connection.phase !== 'live') {
created.destroy()
return
}
stage = created
})
.catch(error => {
console.error('stage init failed', error)
})
.finally(() => {
startingStage = null
})
}
store.subscribe(state => {
shell.render(state)
syncStage(state)
})
// Boot: show the neutral connecting screen and probe for a session. A visitor without a session
// gets a refused `/ws` upgrade and lands on the sign-in page; no map data is ever created.
store.dispatch({ type: 'connecting' })
shell.render(store.state)
connect()
+181
View File
@@ -0,0 +1,181 @@
// The wire contract (DESIGN 6). This module is pure: no Pixi, no DOM, no socket. The client speaks
// `proto` 2 (ADR-0011) and ignores unknown server message types and unknown fields (6.2).
/** Compiled into the client exactly as into the server (DESIGN 6.2, ADR-0011). */
export const PROTO = 2
export type Role = 'gm' | 'player'
export type Vec2 = [number, number]
/** `hello.scene` (DESIGN 6.1; views.sceneBlock). No counts, no wall data, no owned ids. */
export interface SceneInfo {
id: number
name: string
w: number
h: number
tile_size: number
cell: number
grid_size: number
vision_radius_default: number
token_radius_default: number
art_version: number
}
export interface RosterEntry {
id: number
name: string | null
role: Role
colour: string
connected: boolean
}
export interface Me {
id: number
name: string | null
}
/** Every server frame carries the per-connection counter `n` (DESIGN 6, 6.4). */
export interface ServerFrame {
t: string
n: number
[field: string]: unknown
}
export interface HelloFrame extends ServerFrame {
t: 'hello'
proto: number
role: Role
me: Me
scene?: SceneInfo
extra?: unknown
}
export interface AckFrame extends ServerFrame {
t: 'ack'
reqId: number
ok: boolean
code?: string
id?: number
key?: string
pos?: Vec2
ts?: number
}
export const CLOSE_REASONS = [
'revoked',
'evicted',
'proto-mismatch',
'malformed-flood',
'server-shutdown',
] as const
export type CloseReason = (typeof CLOSE_REASONS)[number]
export interface ClosingFrame extends ServerFrame {
t: 'closing'
reason: CloseReason
code: number
}
/** What the shell does when a connection outcome arrives (DESIGN 6.5). */
export type CloseOutcome = 'signin' | 'reload' | 'offline'
export function closeOutcome(reason: CloseReason | null): CloseOutcome {
switch (reason) {
case 'revoked':
return 'signin'
case 'proto-mismatch':
return 'reload'
case 'evicted':
case 'malformed-flood':
case 'server-shutdown':
return 'offline'
case null:
return 'offline'
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Parse one text frame into a server envelope. Binary frames and anything that is not a JSON
* object with a string `t` and an integer `n >= 1` are not frames (DESIGN 6: a binary frame counts
* as malformed server input; the client ignores it, exactly as 6.2 says for unknown shapes).
*/
export function parseServerFrame(raw: unknown): ServerFrame | null {
if (typeof raw !== 'string') return null
let value: unknown
try {
value = JSON.parse(raw)
} catch {
return null
}
if (!isRecord(value)) return null
const t = value['t']
const n = value['n']
if (typeof t !== 'string' || t.length === 0) return null
if (typeof n !== 'number' || !Number.isInteger(n) || n < 1) return null
return value as ServerFrame
}
function isRole(value: unknown): value is Role {
return value === 'gm' || value === 'player'
}
function isMe(value: unknown): value is Me {
if (!isRecord(value)) return false
const name = value['name']
return (
typeof value['id'] === 'number' &&
Number.isInteger(value['id']) &&
(name === null || typeof name === 'string')
)
}
export function isHello(frame: ServerFrame): frame is HelloFrame {
if (frame.t !== 'hello') return false
if (typeof frame['proto'] !== 'number' || !Number.isInteger(frame['proto'])) return false
if (!isRole(frame['role'])) return false
if (!isMe(frame['me'])) return false
const scene = frame['scene']
if (scene !== undefined && !isRecord(scene)) return false
return true
}
export function isAck(frame: ServerFrame): frame is AckFrame {
return (
frame.t === 'ack' &&
typeof frame['reqId'] === 'number' &&
Number.isInteger(frame['reqId']) &&
typeof frame['ok'] === 'boolean'
)
}
function isCloseReason(value: unknown): value is CloseReason {
return typeof value === 'string' && (CLOSE_REASONS as readonly string[]).includes(value)
}
export function isClosing(frame: ServerFrame): frame is ClosingFrame {
return (
frame.t === 'closing' &&
isCloseReason(frame['reason']) &&
typeof frame['code'] === 'number' &&
Number.isInteger(frame['code'])
)
}
/**
* Serialise one intent: envelope `t` plus its `reqId` and fields (DESIGN 6 Conventions). The server
* ignores unknown fields (6.2); the client never invents a `t` outside the catalogue.
*/
export function encodeIntent(t: string, reqId: number, fields: Record<string, unknown> = {}): string {
return JSON.stringify({ ...fields, t, reqId })
}
/** The only place the client spells the `proto` parameter (6.2: absent or non-integer is 400). */
export function wsUrl(location: Pick<Location, 'protocol' | 'host'> = window.location): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
return `${scheme}://${location.host}/ws?proto=${PROTO}`
}
+218
View File
@@ -0,0 +1,218 @@
// The client's one pure reducer (DESIGN 7.1, spec #63 decision 11): server frames and connection
// events in, state out. No Pixi import here, ever: this module is the unit-test seam.
//
// Domain slices are *append-only*: every file in ./slices/ that exports `slice` is picked up by the
// build-time glob below and registered automatically, so a later ticket (fog, tokens, walls, GM
// panels) adds one file and touches no other slice. `hello` resets every slice (DESIGN 6.3: a
// reconnect is a full resync), which is why the registry owns the reset rather than each slice.
import type {
CloseReason,
Me,
Role,
RosterEntry,
SceneInfo,
ServerFrame,
} from './protocol.ts'
import { closeOutcome, isClosing, isHello } from './protocol.ts'
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reload' | 'offline'
export interface ConnectionState {
phase: Phase
/** Server frames seen on this connection (`n` is per connection, starts at 1). */
frames: number
lastN: number
/** Human text for the shell; never game data. */
notice: string | null
/** Sign-in failure text ("Key not recognised.") or a transport message. */
error: string | null
}
export interface SessionState {
role: Role | null
me: Me | null
proto: number | null
scene: SceneInfo | null
}
export interface RootState {
connection: ConnectionState
session: SessionState
/**
* Append-only domain state, keyed by slice name. Later tickets read `slices.tokens`, `slices.fog`
* and so on; core connection/session/handshake state stays in this file.
*/
slices: Record<string, unknown>
}
export type ReducerEvent =
| { type: 'connecting' }
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
| { type: 'signin-failed'; message: string }
| { type: 'signed-out' }
/**
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
* root reducer clones before dispatching, so the previous state is never touched).
*/
export interface Slice<S = unknown> {
readonly name: string
init(): S
reduce(state: S, event: ReducerEvent, root: RootState): void
}
interface SliceModule {
slice: Slice
}
// Build-time registry: no shared import list to merge, so parallel tickets never edit one file.
const modules = import.meta.glob<SliceModule>('./slices/*.ts', { eager: true })
export const SLICES: readonly Slice[] = Object.keys(modules)
.sort()
.map(path => {
const module = modules[path]
if (!module || !module.slice) throw new Error(`slice ${path} has no \`slice\` export`)
return module.slice
})
const sliceNames = new Set(SLICES.map(slice => slice.name))
if (sliceNames.size !== SLICES.length) throw new Error('duplicate slice name')
export function sliceOf<S>(state: RootState, name: string): S {
return state.slices[name] as S
}
function initialConnection(): ConnectionState {
return { phase: 'boot', frames: 0, lastN: 0, notice: null, error: null }
}
function initialSession(): SessionState {
return { role: null, me: null, proto: null, scene: null }
}
export function initialState(): RootState {
const slices: Record<string, unknown> = {}
for (const slice of SLICES) slices[slice.name] = slice.init()
return { connection: initialConnection(), session: initialSession(), slices }
}
/** Reset everything that came from the server; keep the connection envelope. */
function resetDomain(state: RootState): void {
state.session = initialSession()
const slices: Record<string, unknown> = {}
for (const slice of SLICES) slices[slice.name] = slice.init()
state.slices = slices
}
function onFrame(state: RootState, frame: ServerFrame): void {
state.connection.frames += 1
state.connection.lastN = frame.n
if (isHello(frame)) {
// DESIGN 6.1/6.3: `hello` means "start clean". The resync that follows rebuilds the view; a
// client that kept the previous connection's state would show stale tokens after a reconnect.
resetDomain(state)
state.session.role = frame.role
state.session.me = frame.me
state.session.proto = frame.proto
state.session.scene = frame.scene ?? null
state.connection.phase = 'live'
state.connection.notice = null
state.connection.error = null
} else if (isClosing(frame)) {
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
const outcome = closeOutcome(frame.reason)
state.connection.notice =
frame.reason === 'revoked'
? 'Your session has ended. Sign in again.'
: frame.reason === 'proto-mismatch'
? 'This client is out of date.'
: frame.reason === 'evicted'
? 'This tab was replaced by a newer connection.'
: 'The connection was closed by the server.'
if (outcome === 'signin') {
resetDomain(state)
state.connection.phase = 'signin'
} else if (outcome === 'reload') {
state.connection.phase = 'reload'
} else {
state.connection.phase = 'offline'
}
}
}
export function reduce(previous: RootState, event: ReducerEvent): RootState {
const state: RootState = {
connection: { ...previous.connection },
session: { ...previous.session },
slices: { ...previous.slices },
}
switch (event.type) {
case 'connecting':
resetDomain(state)
state.connection.phase = 'connecting'
state.connection.frames = 0
state.connection.lastN = 0
state.connection.notice = null
state.connection.error = null
break
case 'open':
// An open socket is not a view: stay on the boot/connecting screen until `hello` (6.3).
break
case 'frame':
onFrame(state, event.frame)
break
case 'close': {
// A `closing` frame already decided the outcome (6.5); a close without one is a transport
// failure. Before the first `hello` that means "no session" (the `/ws` upgrade was refused).
if (state.connection.phase === 'live') {
const outcome = closeOutcome(event.reason)
if (outcome === 'signin') {
resetDomain(state)
state.connection.phase = 'signin'
state.connection.notice = 'Your session has ended. Sign in again.'
} else if (outcome === 'reload') {
state.connection.phase = 'reload'
state.connection.notice = 'This client is out of date.'
} else {
state.connection.phase = 'offline'
state.connection.notice = 'Connection lost.'
}
} else if (state.connection.phase === 'connecting' || state.connection.phase === 'boot') {
resetDomain(state)
state.connection.phase = 'signin'
}
break
}
case 'signin-failed':
resetDomain(state)
state.connection.phase = 'signin'
state.connection.error = event.message
break
case 'signed-out':
resetDomain(state)
state.connection.phase = 'signin'
state.connection.notice = null
state.connection.error = null
break
}
for (const slice of SLICES) {
slice.reduce(state.slices[slice.name], event, state)
}
return state
}
/** `roster` lives in its own slice (append-only), read through here by the shell. */
export interface RosterState {
players: RosterEntry[]
}
export function rosterOf(state: RootState): RosterEntry[] {
return sliceOf<RosterState>(state, 'roster').players
}
+19
View File
@@ -0,0 +1,19 @@
# Render modules: append-only
Every `*.ts` file here that exports `renderModule` is registered by the build-time glob in
`../stage.ts`. Add one file per feature; never edit the registry.
```ts
import type { RenderModule } from '../stage.ts'
export const renderModule: RenderModule = {
name: 'tiles', // unique
mount({ app, world, layers, store }) {
// create your objects in `layers.*`, subscribe to `store` for state changes,
// return a teardown only for global resources you install.
},
}
```
Layers bottom to top: `tiles`, `grid`, `tokens`, `fog`, `gm`, `dom` (DESIGN 7.1). Update only the
entities that changed (DESIGN 7.2); no per-frame full redraw.
+105
View File
@@ -0,0 +1,105 @@
// The Pixi stage (DESIGN 7.1): one Application, one world container under pan/zoom, fixed layers
// bottom to top. Render modules are append-only, exactly like reducer slices: every file in
// ./modules/ that exports `renderModule` is picked up by the glob, so a later ticket (tiles/grid
// T6, fog T7, tokens T8, walls T10, GM overlays) adds one file and touches no other module.
//
// Pixi is imported here (and in modules/) only. The reducer, the WS client and the DOM shell stay
// Pixi-free so their unit tests run without a GPU or a DOM.
import { Application, Container } from 'pixi.js'
import type { Store } from '../store.ts'
import { PROTO } from '../protocol.ts'
export interface RenderLayers {
tiles: Container
grid: Container
tokens: Container
fog: Container
gm: Container
dom: Container
}
export interface RenderContext {
app: Application
world: Container
layers: RenderLayers
store: Store
}
export interface RenderModule {
readonly name: string
/** Start drawing. Return a teardown for anything global the module installed. */
mount(context: RenderContext): void | (() => void)
}
interface ModuleExport {
renderModule: RenderModule
}
const modules = import.meta.glob<ModuleExport>('./modules/*.ts', { eager: true })
const RENDER_MODULES: readonly RenderModule[] = Object.keys(modules)
.sort()
.map(path => {
const module = modules[path]
if (!module || !module.renderModule) {
throw new Error(`render module ${path} has no \`renderModule\` export`)
}
return module.renderModule
})
const moduleNames = new Set(RENDER_MODULES.map(module => module.name))
if (moduleNames.size !== RENDER_MODULES.length) throw new Error('duplicate render module name')
export interface Stage {
readonly app: Application
readonly context: RenderContext
destroy(): void
}
/**
* Create the stage inside `host`. The caller creates it only when the session is live, so a
* visitor without a session never gets a canvas (story 1). `PROTO` is touched here so the build
* keeps the constant referenced even before an intent module exists.
*/
export async function createStage(host: HTMLElement, store: Store): Promise<Stage> {
const app = new Application()
await app.init({
resizeTo: window,
background: 0x000000,
antialias: true,
autoDensity: true,
resolution: Math.min(window.devicePixelRatio || 1, 2),
preference: 'webgl',
})
app.canvas.id = 'stage-canvas'
app.canvas.dataset['proto'] = String(PROTO)
host.replaceChildren(app.canvas)
const world = new Container()
const layers: RenderLayers = {
tiles: new Container(),
grid: new Container(),
tokens: new Container(),
fog: new Container(),
gm: new Container(),
dom: new Container(),
}
world.addChild(layers.tiles, layers.grid, layers.tokens, layers.fog, layers.gm, layers.dom)
app.stage.addChild(world)
// A v1 scene is large and the camera starts at the origin until T6 adds pan/zoom; scaling the
// world down is not a map feature, so the world simply sits under the camera transform.
const context: RenderContext = { app, world, layers, store }
const teardowns = RENDER_MODULES.map(module => module.mount(context))
return {
app,
context,
destroy() {
for (const teardown of teardowns) teardown?.()
app.destroy(true, { children: true })
host.replaceChildren()
},
}
}
+173
View File
@@ -0,0 +1,173 @@
// The plain-DOM overlay (DESIGN 7.1 layer 6, spec #63 decision 15). No framework, no `innerHTML`:
// every server-supplied string goes through `textContent`, so a name can never become markup.
//
// The shell is the only module that owns page structure; later panels (roster/keys/tokens T11,
// characters/reveals T12) add their DOM under `#panels` or as their own file next to this one,
// never by rewriting the sign-in flow.
import type { RootState } from './reducer.ts'
import { rosterOf } from './reducer.ts'
import type { RosterEntry } from './protocol.ts'
export interface ShellHandlers {
onSubmitKey(key: string): void
onReload(): void
}
export interface Shell {
render(state: RootState): void
setBusy(busy: boolean): void
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
node.id = id
if (text !== undefined) node.textContent = text
return node
}
function rosterName(entry: RosterEntry): string {
return entry.name ?? '(unnamed)'
}
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
const stage = element('div', 'stage')
stage.hidden = true
const boot = element('section', 'boot')
const bootText = element('p', 'boot-text', 'Connecting…')
boot.append(bootText)
const signin = element('section', 'signin')
signin.hidden = true
const title = element('h1', 'signin-title', 'FFF VTT')
const notice = element('p', 'signin-notice')
notice.hidden = true
const form = element('form', 'signin-form')
const label = element('label', 'signin-label', 'Player or GM key')
label.htmlFor = 'key'
const input = element('input', 'key')
input.name = 'key'
input.type = 'text'
input.autocomplete = 'off'
input.autocapitalize = 'characters'
input.spellcheck = false
input.required = true
const submit = element('button', 'signin-submit', 'Sign in')
submit.type = 'submit'
form.append(label, input, submit)
const error = element('p', 'signin-error')
error.hidden = true
error.setAttribute('role', 'alert')
signin.append(title, notice, form, error)
const hud = element('header', 'hud')
hud.hidden = true
const role = element('span', 'role')
const scene = element('span', 'scene')
const me = element('span', 'me')
const roster = element('ul', 'roster')
hud.append(role, scene, me, roster)
const fatal = element('section', 'fatal')
fatal.hidden = true
const fatalText = element('p', 'fatal-text')
const reload = element('button', 'reload', 'Reload')
reload.type = 'button'
reload.addEventListener('click', () => handlers.onReload())
fatal.append(fatalText, reload)
const panels = element('div', 'panels')
root.replaceChildren(stage, hud, signin, boot, fatal, panels)
form.addEventListener('submit', event => {
event.preventDefault()
const key = input.value.trim()
if (key.length === 0) return
handlers.onSubmitKey(key)
})
let busy = false
function setBusy(next: boolean): void {
busy = next
submit.disabled = next
input.disabled = next
bootText.textContent = next ? 'Signing in…' : 'Connecting…'
if (next) showOnly(boot)
}
function showOnly(active: HTMLElement): void {
for (const node of [boot, signin, hud, fatal]) node.hidden = node !== active
}
function renderRoster(players: RosterEntry[]): void {
roster.replaceChildren(
...players.map(entry => {
const item = document.createElement('li')
item.dataset['player'] = String(entry.id)
const name = element('span', 'roster-name', rosterName(entry))
const state = element('span', 'roster-state', entry.connected ? 'connected' : 'offline')
item.append(name, state)
return item
}),
)
}
function render(state: RootState): void {
const phase = state.connection.phase
notice.textContent = state.connection.notice ?? ''
notice.hidden = state.connection.notice === null
error.textContent = state.connection.error ?? ''
error.hidden = state.connection.error === null
stage.hidden = phase !== 'live'
// Leaving the live phase clears every server-derived DOM text, so a revoked session cannot
// leave a roster (or names) behind the sign-in page.
if (phase !== 'live') {
role.textContent = ''
scene.textContent = ''
me.textContent = ''
roster.replaceChildren()
}
switch (phase) {
case 'boot':
case 'connecting':
if (!busy) bootText.textContent = 'Connecting…'
showOnly(boot)
break
case 'signin':
busy = false
submit.disabled = false
input.disabled = false
showOnly(signin)
input.focus()
break
case 'live':
busy = false
showOnly(hud)
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
scene.textContent = state.session.scene?.name ?? ''
me.textContent = state.session.me?.name ?? ''
renderRoster(rosterOf(state))
break
case 'reload':
showOnly(fatal)
fatalText.textContent = 'This client is out of date. Reload the page to get the matching version.'
break
case 'offline':
showOnly(fatal)
fatalText.textContent = state.connection.notice ?? 'Connection lost. Reload to reconnect.'
break
}
}
return { render, setBusy }
}
+25
View File
@@ -0,0 +1,25 @@
// Roster slice (DESIGN 6.1 `roster`). Append-only registration: adding this file was enough; the
// reducer's glob picked it up and `hello` reset it with every other slice.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { RosterEntry } from '../protocol.ts'
export interface RosterState {
/** Always the full list the server sent; the client never merges (6.1). */
players: RosterEntry[]
}
function rosterList(value: unknown): RosterEntry[] | null {
if (!Array.isArray(value)) return null
return value as RosterEntry[]
}
export const slice: Slice<RosterState> = {
name: 'roster',
init: () => ({ players: [] }),
reduce(state: RosterState, event: ReducerEvent, _root: RootState): void {
if (event.type !== 'frame' || event.frame.t !== 'roster') return
const players = rosterList(event.frame['players'])
if (players) state.players = players
},
}
+35
View File
@@ -0,0 +1,35 @@
// The store is the tiny bridge between the pure reducer and the renderer/DOM shell. It owns the
// current state and notifies subscribers once per dispatch; render modules update only the
// entities they saw change (DESIGN 7.2), so no module may assume a frame-by-frame redraw.
import type { ReducerEvent, RootState } from './reducer.ts'
import { initialState, reduce } from './reducer.ts'
export type Listener = (state: RootState, event: ReducerEvent) => void
export class Store {
#state: RootState
#listeners = new Set<Listener>()
constructor(state: RootState = initialState()) {
this.#state = state
}
get state(): RootState {
return this.#state
}
dispatch(event: ReducerEvent): RootState {
const next = reduce(this.#state, event)
this.#state = next
for (const listener of this.#listeners) listener(next, event)
return next
}
subscribe(listener: Listener): () => void {
this.#listeners.add(listener)
return () => {
this.#listeners.delete(listener)
}
}
}
+104
View File
@@ -0,0 +1,104 @@
html,
body {
margin: 0;
height: 100%;
overflow: hidden;
background: #000;
color: #eee;
font: 14px/1.4 system-ui, sans-serif;
}
#app {
position: fixed;
inset: 0;
}
[hidden] {
display: none !important;
}
#stage {
position: absolute;
inset: 0;
}
#stage canvas {
display: block;
}
#boot,
#signin,
#fatal {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 24px;
text-align: center;
}
#signin form {
display: flex;
flex-direction: column;
gap: 8px;
width: min(360px, 90vw);
}
#key {
font: inherit;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid #555;
background: #111;
color: inherit;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#signin button,
#fatal button {
font: inherit;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid #777;
background: #222;
color: inherit;
}
#signin-error {
color: #ff8a8a;
}
#hud {
position: absolute;
top: 0;
left: 0;
right: 0;
display: flex;
gap: 16px;
align-items: baseline;
padding: 6px 12px;
background: rgb(0 0 0 / 65%);
pointer-events: none;
font: 12px/1.4 ui-monospace, monospace;
}
#roster {
display: flex;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
}
#roster li {
display: flex;
gap: 4px;
}
#roster-state {
opacity: 0.6;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+143
View File
@@ -0,0 +1,143 @@
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
// counter and the pending-request map; it emits reducer events and never touches the DOM. The
// socket factory and clock-free design make it unit-testable without a browser.
//
// Close mapping (6.5, FIXED #18): a server-initiated close is `closing {reason, code}` and then a
// close frame the browser reports as 1005, so the reason always comes from the last `closing` frame.
// `revoked` and `proto-mismatch` are terminal: this client does not reconnect to them. Reconnect
// with backoff is T5 (#68); T4 only proves the outcome mapping.
import type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
export interface SocketLike {
send(data: string): void
close(code?: number, reason?: string): void
onopen: (() => void) | null
onmessage: ((event: { data: unknown }) => void) | null
onclose: ((event: { code: number; reason: string }) => void) | null
onerror: ((event: unknown) => void) | null
}
export type ClientEvent =
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
export interface ProtocolClientOptions {
url?: string
createSocket?: (url: string) => SocketLike
onEvent: (event: ClientEvent) => void
}
type Pending = {
resolve: (ack: AckFrame) => void
reject: (error: Error) => void
}
function defaultSocket(url: string): SocketLike {
return new WebSocket(url) as unknown as SocketLike
}
export class ProtocolClient {
#url: string
#createSocket: (url: string) => SocketLike
#onEvent: (event: ClientEvent) => void
#socket: SocketLike | null = null
#nextReqId = 1
#pending = new Map<number, Pending>()
#lastClosing: { reason: CloseReason; code: number } | null = null
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
constructor(options: ProtocolClientOptions) {
this.#url = options.url ?? wsUrl()
this.#createSocket = options.createSocket ?? defaultSocket
this.#onEvent = options.onEvent
}
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
return this.#state
}
get pendingCount(): number {
return this.#pending.size
}
connect(): void {
if (this.#state !== 'idle') return
this.#state = 'connecting'
const socket = this.#createSocket(this.#url)
this.#socket = socket
socket.onopen = () => {
if (this.#state !== 'connecting') return
this.#state = 'open'
this.#onEvent({ type: 'open' })
}
socket.onmessage = event => {
if (this.#state === 'closed') return // a frame in flight after the client closed
const frame = parseServerFrame(event.data)
if (!frame) return // binary or unreadable: 6.2 says ignore what cannot be read
if (isClosing(frame)) this.#lastClosing = { reason: frame.reason, code: frame.code }
if (isAck(frame)) {
const pending = this.#pending.get(frame.reqId)
if (pending) {
this.#pending.delete(frame.reqId)
pending.resolve(frame)
}
}
this.#onEvent({ type: 'frame', frame })
}
socket.onerror = () => {
// The browser follows an error with a close; mapping the outcome there keeps it single.
}
socket.onclose = event => {
if (this.#state === 'closed') return
this.#state = 'closed'
const reason = this.#lastClosing?.reason ?? null
const code = this.#lastClosing?.code ?? event.code ?? null
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
this.#onEvent({ type: 'close', reason, code })
}
}
/**
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
* `hello` on a live connection does not drop them.
*/
send(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame> {
const socket = this.#socket
if (this.#state !== 'open' || !socket) {
return Promise.reject(new Error('not connected'))
}
const reqId = this.#nextReqId++
const frame = encodeIntent(t, reqId, fields)
return new Promise<AckFrame>((resolve, reject) => {
this.#pending.set(reqId, { resolve, reject })
try {
socket.send(frame)
} catch (error) {
this.#pending.delete(reqId)
reject(error instanceof Error ? error : new Error(String(error)))
}
})
}
close(): void {
if (this.#state === 'closed') return
this.#state = 'closed'
try {
this.#socket?.close()
} catch {
// A socket that is already gone is the outcome we wanted.
}
this.#failPending(new Error('connection closed by the client'))
}
#failPending(error: Error): void {
const pending = [...this.#pending.values()]
this.#pending.clear()
for (const entry of pending) entry.reject(error)
}
}
+137
View File
@@ -0,0 +1,137 @@
import { describe, expect, it } from 'vitest'
import {
CLOSE_REASONS,
PROTO,
closeOutcome,
encodeIntent,
isAck,
isClosing,
isHello,
parseServerFrame,
wsUrl,
} from '../src/protocol.ts'
const scene = {
id: 1,
name: 'Cellar',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
}
describe('server envelope', () => {
it('parses a JSON object with a string t and an integer n >= 1', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'roster', n: 3, players: [] }))
expect(frame).toEqual({ t: 'roster', n: 3, players: [] })
})
it('ignores unknown frame types without dropping them (6.2: additive only)', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'future_frame', n: 2, x: 1 }))
expect(frame?.t).toBe('future_frame')
})
it.each([
['binary', new Uint8Array([1, 2, 3])],
['non-JSON', '{not json'],
['array', '[]'],
['null', 'null'],
['no t', JSON.stringify({ n: 1 })],
['empty t', JSON.stringify({ t: '', n: 1 })],
['no n', JSON.stringify({ t: 'hello' })],
['n = 0', JSON.stringify({ t: 'hello', n: 0 })],
['fractional n', JSON.stringify({ t: 'hello', n: 1.5 })],
['string n', JSON.stringify({ t: 'hello', n: '1' })],
])('rejects %s', (_name, raw) => {
expect(parseServerFrame(raw)).toBeNull()
})
})
describe('hello', () => {
it('accepts the DESIGN 6.1 shape and carries the scene block', () => {
const frame = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: 'Ann' }, scene }),
)
expect(frame && isHello(frame)).toBe(true)
if (frame && isHello(frame)) {
expect(frame.proto).toBe(2)
expect(frame.scene?.w).toBe(4096)
}
})
it('accepts the unnamed-player minimum (proto, role, me only)', () => {
const frame = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: null } }),
)
expect(frame && isHello(frame)).toBe(true)
})
it('rejects a wrong role or proto', () => {
const badRole = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'admin', me: { id: 1, name: null } }),
)
const badProto = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: '2', role: 'gm', me: { id: 1, name: null } }),
)
expect(badRole && isHello(badRole)).toBe(false)
expect(badProto && isHello(badProto)).toBe(false)
})
})
describe('ack', () => {
it('is the envelope plus reqId and ok', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'ack', n: 2, reqId: 7, ok: true, pos: [1, 2] }))
expect(frame && isAck(frame)).toBe(true)
if (frame && isAck(frame)) expect(frame.pos).toEqual([1, 2])
})
it('is not an ack without an integer reqId or a boolean ok', () => {
for (const body of [
{ t: 'ack', n: 1, ok: true },
{ t: 'ack', n: 1, reqId: '7', ok: true },
{ t: 'ack', n: 1, reqId: 7, ok: 'yes' },
]) {
const frame = parseServerFrame(JSON.stringify(body))
expect(frame && isAck(frame)).toBe(false)
}
})
})
describe('closing and outcomes', () => {
it('accepts every static reason of DESIGN 6.5', () => {
for (const reason of CLOSE_REASONS) {
const frame = parseServerFrame(
JSON.stringify({ t: 'closing', n: 9, reason, code: 4001 }),
)
expect(frame && isClosing(frame)).toBe(true)
}
})
it('maps reasons to the shell outcome', () => {
expect(closeOutcome('proto-mismatch')).toBe('reload')
expect(closeOutcome('revoked')).toBe('signin')
expect(closeOutcome('evicted')).toBe('offline')
expect(closeOutcome('malformed-flood')).toBe('offline')
expect(closeOutcome(null)).toBe('offline')
})
})
describe('intents', () => {
it('always carry t and reqId and nothing secret', () => {
const raw = encodeIntent('conn.ping', 3, { ts: 99 })
expect(JSON.parse(raw)).toEqual({ t: 'conn.ping', reqId: 3, ts: 99 })
})
it('builds the /ws URL with the required proto parameter', () => {
expect(wsUrl({ protocol: 'https:', host: 'table.example' })).toBe(
`wss://table.example/ws?proto=${PROTO}`,
)
expect(wsUrl({ protocol: 'http:', host: '127.0.0.1:8080' })).toBe(
`ws://127.0.0.1:8080/ws?proto=${PROTO}`,
)
})
})
+184
View File
@@ -0,0 +1,184 @@
import { describe, expect, it } from 'vitest'
import { SLICES, initialState, reduce, rosterOf } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import type { RosterEntry } from '../src/protocol.ts'
const scene = (name: string) => ({
id: 1,
name,
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
})
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number, extra: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'hello',
n,
proto: 2,
role: 'player',
me: { id: 2, name: 'Ann' },
scene: scene('Cellar'),
...extra,
})
const roster = (n: number, players: RosterEntry[]): ReducerEvent =>
frame({ t: 'roster', n, players })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
describe('hello resets the whole view (6.1/6.3)', () => {
it('clears every slice and replaces session fields on a second hello', () => {
const first = run(
{ type: 'connecting' },
hello(1),
roster(2, [
{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true },
{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true },
]),
)
expect(first.connection.phase).toBe('live')
expect(first.session.role).toBe('player')
expect(first.session.me).toEqual({ id: 2, name: 'Ann' })
expect(first.session.scene?.name).toBe('Cellar')
expect(rosterOf(first)).toHaveLength(2)
// Reconnect: the server sends hello first, then the resync. Nothing from the old connection
// may survive, otherwise a token that left the view would stay on screen.
const second = reduce(first, hello(9, { role: 'gm', me: { id: 1, name: 'GM' }, scene: scene('Attic') }))
expect(rosterOf(second)).toEqual([])
expect(second.session.role).toBe('gm')
expect(second.session.scene?.name).toBe('Attic')
expect(second.connection.phase).toBe('live')
expect(second.connection.frames).toBe(3)
expect(second.connection.lastN).toBe(9)
})
it('stays on the other slices while a hello resets them', () => {
const state = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
hello(3),
)
expect(Object.keys(state.slices).sort()).toEqual(SLICES.map(slice => slice.name).sort())
expect(rosterOf(state)).toEqual([])
})
})
describe('no data before join', () => {
it('connecting clears session and slices, so a stranger is shown nothing', () => {
const live = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]),
)
const cleared = reduce(live, { type: 'connecting' })
expect(cleared.connection.phase).toBe('connecting')
expect(cleared.session).toEqual({ role: null, me: null, proto: null, scene: null })
expect(rosterOf(cleared)).toEqual([])
})
it('a refused upgrade (close before hello) lands on sign-in', () => {
const state = run({ type: 'connecting' }, { type: 'close', reason: null, code: 1006 })
expect(state.connection.phase).toBe('signin')
expect(state.session.me).toBeNull()
})
it('a failed key shows a sign-in error and no session', () => {
const state = run({ type: 'connecting' }, { type: 'signin-failed', message: 'Key not recognised.' })
expect(state.connection.phase).toBe('signin')
expect(state.connection.error).toBe('Key not recognised.')
expect(state.session.me).toBeNull()
})
})
describe('connection outcomes (6.5)', () => {
it('proto-mismatch asks for a reload', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'closing', n: 2, reason: 'proto-mismatch', code: 4003 }),
{ type: 'close', reason: 'proto-mismatch', code: 4003 },
)
expect(state.connection.phase).toBe('reload')
})
it('revoked returns to sign-in and clears the view', () => {
const state = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
frame({ t: 'closing', n: 3, reason: 'revoked', code: 4001 }),
{ type: 'close', reason: 'revoked', code: 4001 },
)
expect(state.connection.phase).toBe('signin')
expect(state.connection.notice).toMatch(/session has ended/i)
expect(state.session.me).toBeNull()
expect(rosterOf(state)).toEqual([])
})
it('evicted goes offline but keeps the tab usable', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'closing', n: 2, reason: 'evicted', code: 4002 }),
)
expect(state.connection.phase).toBe('offline')
})
it('a transport close while live is offline, not a silent sign-out', () => {
const state = run({ type: 'connecting' }, hello(1), { type: 'close', reason: null, code: 1006 })
expect(state.connection.phase).toBe('offline')
})
})
describe('frames', () => {
it('ignores an unknown server message type (6.2) without touching the view', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'future_frame', n: 2, payload: 42 }),
)
expect(state.connection.phase).toBe('live')
expect(state.connection.lastN).toBe(2)
})
it('a roster frame replaces the list instead of merging', () => {
const a: RosterEntry = { id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }
const b: RosterEntry = { id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }
const state = run({ type: 'connecting' }, hello(1), roster(2, [a, b]), roster(3, [b]))
expect(rosterOf(state)).toEqual([b])
})
it('keeps the session intact when a non-hello frame arrives', () => {
const state = run({ type: 'connecting' }, hello(1), frame({ t: 'error', n: 2, code: 'malformed' }))
expect(state.session.me).toEqual({ id: 2, name: 'Ann' })
})
})
describe('registry', () => {
it('registers the roster slice without an import list', () => {
expect(SLICES.map(slice => slice.name)).toContain('roster')
})
it('rotates every server frame through the slice too', () => {
const state = run({ type: 'connecting' }, hello(1))
const withRoster = reduce(state, roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]))
expect(rosterOf(withRoster)).toHaveLength(1)
})
})
+147
View File
@@ -0,0 +1,147 @@
import { describe, expect, it } from 'vitest'
import { ProtocolClient } from '../src/ws.ts'
import type { ClientEvent, SocketLike } from '../src/ws.ts'
class FakeSocket implements SocketLike {
onopen: (() => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onclose: ((event: { code: number; reason: string }) => void) | null = null
onerror: ((event: unknown) => void) | null = null
sent: string[] = []
closed = false
send(data: string): void {
if (this.closed) throw new Error('socket is closed')
this.sent.push(data)
}
close(): void {
this.closed = true
}
open(): void {
this.onopen?.()
}
receive(body: unknown): void {
this.onmessage?.({ data: typeof body === 'string' ? body : JSON.stringify(body) })
}
serverClose(code = 1005, reason = ''): void {
this.closed = true
this.onclose?.({ code, reason })
}
}
function connect(): {
client: ProtocolClient
socket: FakeSocket
events: ClientEvent[]
} {
const socket = new FakeSocket()
const events: ClientEvent[] = []
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: event => events.push(event),
})
client.connect()
socket.open()
return { client, socket, events }
}
describe('protocol client', () => {
it('parses text frames and ignores binary or unreadable ones', () => {
const { socket, events } = connect()
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
socket.receive('not json')
socket.onmessage?.({ data: new Uint8Array([1, 2]) })
expect(events.filter(event => event.type === 'frame')).toHaveLength(1)
})
it('correlates one ack per reqId and ignores an unknown ack', async () => {
const { client, socket } = connect()
const first = client.send('conn.ping', { ts: 11 })
const second = client.send('conn.ping', { ts: 12 })
expect(client.pendingCount).toBe(2)
const sent = socket.sent.map(raw => JSON.parse(raw) as { t: string; reqId: number; ts: number })
expect(sent.map(intent => intent.t)).toEqual(['conn.ping', 'conn.ping'])
expect(sent[0]?.reqId).toBe(1)
expect(sent[1]?.reqId).toBe(2)
socket.receive({ t: 'ack', n: 1, reqId: 2, ok: true, ts: 12 })
socket.receive({ t: 'ack', n: 2, reqId: 99, ok: true })
expect(client.pendingCount).toBe(1)
await expect(second).resolves.toMatchObject({ reqId: 2, ok: true })
socket.receive({ t: 'ack', n: 3, reqId: 1, ok: false, code: 'invalid' })
await expect(first).resolves.toMatchObject({ reqId: 1, ok: false, code: 'invalid' })
expect(client.pendingCount).toBe(0)
})
it('keeps pending requests across a hello on a live connection (6.3)', async () => {
const { client, socket } = connect()
const pending = client.send('player.setname', { name: 'Ann' })
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } })
expect(client.pendingCount).toBe(1)
socket.receive({ t: 'ack', n: 2, reqId: 1, ok: true })
await expect(pending).resolves.toMatchObject({ ok: true })
})
it('drops pending requests with the connection (6.3)', async () => {
const { client, socket } = connect()
const pending = client.send('conn.ping', { ts: 1 })
socket.serverClose(1006)
expect(client.pendingCount).toBe(0)
await expect(pending).rejects.toThrow(/closed/)
})
it('reads a server close reason from the last closing frame (6.5, FIXED #18)', () => {
const { socket, events } = connect()
socket.receive({ t: 'closing', n: 2, reason: 'revoked', code: 4001 })
socket.serverClose(1005)
expect(events.at(-1)).toEqual({ type: 'close', reason: 'revoked', code: 4001 })
})
it('treats a close without a closing frame as a transport failure', () => {
const { socket, events } = connect()
socket.serverClose(1006)
expect(events.at(-1)).toEqual({ type: 'close', reason: null, code: 1006 })
})
it('does not reconnect to a terminal outcome (single connect)', () => {
const socket = new FakeSocket()
const sockets: FakeSocket[] = [socket]
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: () => {},
})
client.connect()
socket.open()
socket.receive({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 })
socket.serverClose(1005)
client.connect() // a no-op once closed
expect(sockets).toHaveLength(1)
expect(client.state).toBe('closed')
})
it('ignores a frame that arrives after the client closed the socket', () => {
const { client, socket, events } = connect()
client.close()
const before = events.length
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
expect(events).toHaveLength(before)
})
it('refuses to send before the socket opens', async () => {
const socket = new FakeSocket()
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: () => {},
})
client.connect()
await expect(client.send('conn.ping', { ts: 1 })).rejects.toThrow(/not connected/)
})
})
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"allowImportingTsExtensions": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"types": ["vite/client"]
},
"include": ["src", "test"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vitest/config'
// The client is served from `/` by the nginx vhost (DESIGN 11.1, #66), so assets are absolute
// (`/assets/...`) and content-hashed. Tests are pure modules (no DOM): the reducer seam has no
// Pixi import, so Vitest needs no browser environment.
export default defineConfig({
base: '/',
build: { target: 'es2022' },
test: {
include: ['test/**/*.test.ts'],
environment: 'node',
},
})