/// The X-Haven web server: static file serving for the built SPA, the /// session endpoint, and the game WebSocket endpoint at `/ws`. library; import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_router/shelf_router.dart'; import 'package:shelf_static/shelf_static.dart'; import 'game_server.dart'; import 'sessions.dart'; import 'ws_upgrade.dart'; final _log = Logger('server'); /// Builds the HTTP handler for the game server. /// /// [dataDir] (e.g. `assets/data/`) is served read-only at `/data/` when /// non-null: the client's menus read the campaign/scenario/character/section /// JSON from it (the same files the engine loads). [imageDir] (e.g. /// `assets/images/`) is served at `/images/` when non-null — character and /// monster artwork for the main list. [i18nDir] (e.g. `assets/i18n/`) is /// served at `/i18n/` when non-null — the in-game ability-text translations /// the client's card renderer resolves (the reference app's /// `TranslationService`, PLAN.md Phase 4). Handler createHandler({ required String staticDir, required GameServer gameServer, String? dataDir, String? imageDir, String? i18nDir, }) { final router = Router(); router.get('/ws', createWebSocketUpgradeHandler(gameServer)); router.get('/healthz', (Request request) => Response.ok( jsonEncode({'status': 'ok'}), headers: {'content-type': 'application/json; charset=utf-8'}, )); if (dataDir != null) { router.mount('/data/', _createStaticHandler(dataDir, plain: true)); } if (imageDir != null) { router.mount('/images/', _createStaticHandler(imageDir, plain: true)); } if (i18nDir != null) { router.mount('/i18n/', _createStaticHandler(i18nDir, plain: true)); } // Session endpoint (PLAN.md section 3.3): returns the caller's persistent // session id, setting the `x-haven-session` cookie when the caller has // none yet. Browsers then carry the cookie on every same-origin request, // including the `/ws` upgrade — so a player keeps their seat across page // refreshes. router.get('/session', (Request request) { final existing = _validSessionIdFrom(request); final Map headers = { 'content-type': 'application/json; charset=utf-8', }; if (existing != null) { return Response.ok(jsonEncode({'session': existing}), headers: headers); } final id = SessionManager.newSessionId(); headers['set-cookie'] = '$sessionCookieName=$id; Path=/; HttpOnly; SameSite=Lax'; return Response.ok(jsonEncode({'session': id}), headers: headers); }); router.mount('/', _createStaticHandler(staticDir)); return const Pipeline().addMiddleware(_logRequests()).addHandler(router); } /// Starts the server on [port] (0 for an ephemeral port). Future startServer({ required int port, required String staticDir, required GameServer gameServer, String? dataDir, String? imageDir, String? i18nDir, }) { return shelf_io.serve( createHandler( staticDir: staticDir, gameServer: gameServer, dataDir: dataDir, imageDir: imageDir, i18nDir: i18nDir, ), '0.0.0.0', port, ); } /// The session id from [request]'s cookie, when well-formed. String? _validSessionIdFrom(Request request) { final cookie = request.headers['Cookie']; if (cookie == null) return null; for (final part in cookie.split(';')) { final trimmed = part.trim(); if (trimmed.startsWith('$sessionCookieName=')) { final value = trimmed.substring(sessionCookieName.length + 1).trim(); if (SessionManager.isKnownFormat(value)) return value; } } return null; } /// Serves [staticDir] as static files. When [plain] is true (data/image /// directories) it is plain static serving with a cache header and a plain /// 404; otherwise (the SPA build) a 404 on an extensionless path falls back /// to `index.html` so client-side routes resolve. Handler _createStaticHandler(String staticDir, {bool plain = false}) { final directory = Directory(staticDir); if (!directory.existsSync()) { if (plain) { _log.info('data dir $staticDir not found; serving 404'); return (Request request) => Response.notFound('not found'); } _log.info('static dir $staticDir not found; serving stub page'); return (Request request) => Response.ok( '' 'X-Haven' '' '

X-Haven server

' '

Running, but the web app is not built yet. ' 'Run npm run build in web/ and restart ' 'with --static-dir ../web/dist.

', ); } if (plain) { // Plain static serving (no SPA fallback) with long-lived caching — // the JSON and images are immutable build inputs. return createStaticHandler( directory.path, maxAge: const Duration(days: 1), ); } final staticHandler = createStaticHandler( directory.path, defaultDocument: 'index.html', ); return (Request request) async { final response = await staticHandler(request); if (response.statusCode == 404 && request.method == 'GET' && !request.url.path.contains('.')) { // SPA fallback: routes without a file extension get index.html. final indexFile = File(p.join(directory.path, 'index.html')); if (await indexFile.exists()) { return Response.ok( await indexFile.readAsString(), headers: {'content-type': 'text/html; charset=utf-8'}, ); } } return response; }; } Middleware _logRequests() { return (Handler inner) { return (Request request) async { final stopwatch = Stopwatch()..start(); final response = await inner(request); stopwatch.stop(); _log.info( '${request.method} ${request.requestedUri.path} -> ' '${response.statusCode} (${stopwatch.elapsedMilliseconds}ms)', ); return response; }; }; }