# Architecture How starfleet-ui is put together and what to watch out for when changing it. The game API reference is https://starfleet.glo.quebec/docs. ## Layers ``` src/lib/game/ Pure TypeScript game logic. No Svelte, no DOM. Unit-tested with `bun test`. src/lib/scenes/ Threlte/Three.js scenes (galaxy, system) and their geometry helpers. src/lib/hud/ HUD components and state: canvas, fleet rail, command dock, forms, cards. src/lib/ui/ Generic primitives: Panel, Button, Meter, Tabs, Countdown. src/lib/server/ Server-only: API client, TTL cache, galaxy-wide cached reads. src/routes/(hud)/ Every logged-in page. All of them share one canvas and the HUD shell. ``` Keep game rules in `lib/game`. Components should call those modules rather than re-implement formulas, so the rules stay testable and live in one place. ## The HUD shell `routes/(hud)/+layout.svelte` renders, in this order: 1. **One ``** (`hud/World.svelte`) fixed behind everything. It is never torn down. Galaxy and system scenes swap inside it according to `hud.mode`. 2. **Top bar**: navigation, live galaxy events, animated credits. 3. **Fleet rail** (left) and **captain's log** (bottom-left, fed by the server load plus live SSE). 4. **Side panel** (right). The current page renders into it. The drawer routes (contracts, postings, federation, factions, messages, codex, market) get a wide drawer instead. Pages *declare* what the map shows: `hud.showSystem(detail)` or `hud.showGalaxy()`. They read selections back from the `Hud` object (`lib/hud/hud.svelte.ts`). That object is passed through Svelte context, never a module global. The ship page also renders a `MapDock` (the command dock), which sits between the rail and the panel using the CSS variables `--rail-w` and `--panel-w`. The HUD routes use `ssr = false` (WebGL). Their server `load`s still run. ## Actions (HATEOAS) The API's `actions` list on each envelope is the only source of truth for what is legal. `lib/game/actions.ts` adds presentation only: label, group, hotkey, help, field inputs, and "why is this unavailable?" for the core ship actions. An action missing from the registry still renders with a humanised name, so new API features appear without code changes. `hud/run.ts` executes actions. It handles idempotency keys (federation money moves), learns which actions refuse dry runs, plays sounds, shows toasts and refreshes data. It returns errors to the caller, so forms can highlight the field named by the error's `path` and the dock can offer the fix (`lib/game/errors.ts`). ## Guidance - **Advisor** (`lib/game/advisor.ts`): `adviseShip(ctx)` turns a ship's state into at most three ranked hints. A hint's button is only attached when that action is actually on offer. - **Trade helper** (`lib/game/trade.ts`, `navigation.ts`, `rules.ts`): ranks cargo runs between known markets by profit per minute, with per-unit price impact, route planning over lanes, fuel cost and feasibility. Market snapshots come from `/intel/markets`, which reads every visible station server-side and caches the result. ### Assumptions to review These are documented in each module's header. Check them against the server before relying on the numbers: | Assumption | Where | |---|---| | Price of the i-th unit = p₀·s₀/(s₀∓i). The clamp is ignored, and prices don't drift back during a trip | `trade.ts` | | Jumps burn 1 fuel per 10 of lane distance (the docs give no rate) | `rules.ts` | | Fuel rounds up | `rules.ts` | | Nebula slow-down is unknown, so it's flagged rather than estimated | `rules.ts`, `navigation.ts` | ## API budget The API allows 120 requests per minute per captain. `lib/server/galaxy.ts` sets the refresh intervals (details every 10 min, influence 5 min, markets 2 min, events 1 min). Every read is stale-while-revalidate and fans out with at most 6 requests in flight. If you add a galaxy-wide read, budget for it there. ## When the API fails A failed API call must never become a bare 500. Each case is handled in one place: | Case | Where | What the player sees | |---|---|---| | Key unknown or revoked (401) | root `+layout.server.ts`, which runs on every page | Cookie cleared, back to `/login?expired=1` | | Other API error in a `load` | `handleError` in `hooks.server.ts` | `+error.svelte`: the API's message, its 4xx status (5xx becomes 502), Try again / Log out | | An error in the root layout itself | `src/error.html` (the root layout has no error page above it) | Static page with Log out | | Not the API answering (a firewall's HTML page, an empty body) | `lib/server/api.ts` | "answered 403 Forbidden without an explanation". The server log records `server`, `cf-ray` and the start of the body | | API unreachable | `lib/server/api.ts`, the `/api` proxy | 502 `unreachable` | The `/api` proxy forwards an allowlist of request headers. The browser's and the host's own headers (`origin`, `sec-fetch-*`, `x-forwarded-*`) can trip a firewall in front of the API. When the API renames things (0.2 → the "captain" revision moved `/v1/agent/*` to `/v1/captain/*`), its old paths answer a non-envelope 404 "There is nothing here." Look for that message in the logs first. ## 3D gotchas - **Labels:** Threlte's `` only applies in `transform` mode. Every label must also carry `class="pointer-events-none"`, otherwise it swallows clicks meant for the scene. - **Rigged models:** clone them with `SkeletonUtils.clone`, not `scene.clone()`. The derelict is skinned. - **Disposal:** dispose geometries and materials you create, in an `$effect` cleanup. - **Camera:** it is driven imperatively by `CameraRig` while a flight runs. Don't bind its position to reactive state. - **Movement:** use `damp()` (`scenes/motion.ts`) for frame-rate independent motion. ## Testing ```sh bun run test # pure logic: rules, navigation, trade, advisor, forms, errors, cache, scene math bun run check # svelte-check (types + a11y) ``` To test against a local API, point the app at it with `STARFLEET_API_URL=http://127.0.0.1:8080 bun run dev`.