# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Commands ```bash npm run dev # start dev server on :3000 npm run build # prisma generate + migrate deploy + next build npm run lint # next lint npm run db:migrate # prisma migrate dev (create + apply a new migration) npm run db:push # prisma db push (apply schema without creating migration files) npm run db:studio # open Prisma Studio GUI ``` There are no automated tests. Verification is done by running `npm run build` (TypeScript + Next.js compilation) and manual browser testing. ## Required environment variables (`.env`) ``` DATABASE_URL="file:./dev.db" SESSION_SECRET="" ``` `SESSION_SECRET` is validated at startup in `src/lib/session.ts` — the server will refuse to start without it. ## Architecture ### Stack - **Next.js 14.2** App Router, TypeScript, no test framework - **Prisma 5.22** + **SQLite** (`prisma/dev.db`) - **iron-session** for cookie auth (`florthoritania_session`) - **bcryptjs** for password hashing ### Auth model Two roles: `"dm"` and `"player"`. DM sees everything; players see only entries where `isPublic = true` OR an `EntryReveal` record exists linking that entry to one of the player's campaigns. `src/lib/session.ts` exports three helpers used throughout API routes: - `getSession()` — reads the iron-session cookie (no auth required) - `requireAuth()` — throws a `Response(401)` if no session - `requireDm()` — throws a `Response(403)` if role ≠ "dm" Both throw `Response` objects deliberately — `asResponse()` in `src/lib/api.ts` catches and re-returns them. ### API route conventions Every route file must have `export const dynamic = "force-dynamic"` (required because all routes call `cookies()`). Route handlers follow this pattern: ```ts export async function GET(req: Request) { try { await requireDm(); // or requireAuth() or getSession() // ... return json(data); // NextResponse.json wrapper } catch (e) { return asResponse(e); // handles thrown Response + unknown errors } } ``` `json()`, `err()`, and `asResponse()` are all in `src/lib/api.ts`. Never pass a bare status number to `json()` — it takes `ResponseInit`: `json(data, { status: 201 })`. ### Client-side data fetching All client components fetch via `src/lib/client.ts`'s `api(url, init?)` helper. It sets `Content-Type: application/json`, `cache: "no-store"`, and throws on non-OK responses with the `error` field from the JSON body. ### Context / providers `src/components/ClientProviders.tsx` is the single React context for the whole app. It provides: - `world` / `setWorld` — world settings (name, theme, accent colour, etc.) - `session` / `setSession` — authenticated user state - `lang` / `setLang` — current language ("en" | "ru"), persisted in `florte_lang` cookie - `t(key)` — i18n lookup function; dictionaries are in `src/lib/i18n.ts` - `refresh()` — re-fetches `/api/auth/me` and `/api/world` and updates both states `ClientProviders` is initialised server-side in `src/app/layout.tsx` with `initialWorld` and `initialSession` props (fetched via Prisma + iron-session before the page renders). ### Rendering shell `src/components/RootBody.tsx` decides whether to render the full `AppShell` (sidebar + topbar) or a bare layout (for `/login`, `/setup`, `/register`). `AppShell` also wires the `/` keyboard shortcut to navigate to search. ### Entry model The central model is `Entry`. JSON columns (`fields`, `tags`, `stats`, `abilities`) are stored as JSON strings in SQLite and deserialized by `entryToDTO()` in `src/lib/serialize.ts`. Always go through `entryToDTO()` before returning entries from API routes. Valid `kind` values are defined in `src/lib/kinds.ts` as `KindId`. Use `isKind(s)` to validate. Entry body syntax (parsed client-side in the article page): - `## Heading` — section heading - `> Quote text` — blockquote (last line starting with `—` becomes attribution) - `[[Entry Title]]` — wikilink, resolved to `/article/` - `::secret … ::end` — DM-only block, invisible to players ### Wikilinks / backlinks `src/lib/links.ts` exports `syncLinks(fromId, body)`. Call it after every create or update of an entry's body. It re-derives all `[[wikilinks]]` in the body, deletes old `Link` records for that entry, and inserts new ones. The `Link` table powers the "Mentioned in" backlinks on article pages. ### Campaigns and visibility - `Campaign` has many `CampaignMember` (users) and many `EntryReveal` (entries revealed to that campaign) - `InviteCode` is DM-created; on registration the code is consumed and the new user is added to the associated campaign - Player entry visibility check in `GET /api/entries`: `isPublic OR reveals.some(r => campaignIds.includes(r.campaignId))` ### Import system `src/lib/import.ts` defines `ImportPlan` and `applyPlan()`. Parsers for each source live in `src/app/api/import/{donjon,azgaar,fantasytown}/route.ts`. Each import route supports `?action=preview` (returns the plan as JSON) and `?action=apply` (commits it). `applyPlan()` calls `sanitize()` on all string fields before insertion to strip lone surrogate code points that Azgaar JSONs sometimes contain. ### Map The map page (`src/app/map/page.tsx`) is fully client-side. Pan/zoom state (`scale`, `tx`, `ty`) is stored in React state; the CSS transform is applied to `.flo-map-stage`. Wheel zoom anchors to the cursor position. Pin positions are stored as 0..1 relative coordinates so they work at any scale. Map layers store background images as data: URLs in `MapLayer.imageData`. ### Styling Three CSS files loaded globally via `src/styles/globals.css`: - `florthoritania.css` — design system (CSS vars, layout primitives, all `.flo-*` classes) - `extras.css` — additions: auth cards, modals, map overlays, theme switcher, responsive collapse Themes (`midnight`, `parchment`, etc.) are applied as `data-theme` on ``. Accent colour is a CSS var `--brass` overridden inline. Never use Tailwind — the entire design system is custom CSS classes. ### World model `World` is a singleton (always `id = 1`). `src/lib/world.ts` exports `getOrCreateWorld()` which upserts it on first access. ### OpenAPI / Swagger The spec is hand-authored in `src/lib/openapi.ts` and served at `/api/openapi.json`. The Swagger UI at `/api-docs` loads `swagger-ui-bundle.js` (not the standalone preset — the standalone preset crashes with a `specActions` error before the spec loads).