Compare commits

...

17 commits

Author SHA1 Message Date
lila
fd9667c1fd updating documentation
Some checks failed
Build and Deploy / build-and-deploy (push) Failing after 1m27s
2026-04-28 17:26:01 +02:00
lila
98c59f33c5 formatting + adding issues 2026-04-28 16:39:36 +02:00
lila
648c5d2979 fix: improve error semantics, clarify answer key type 2026-04-28 16:07:19 +02:00
lila
6eaf282651 fix: sanitise Zod validation error messages in game controller 2026-04-28 15:51:57 +02:00
lila
c081e632cf fix: explicit store update in evaluateAnswer, remove mutation through reference 2026-04-28 15:47:53 +02:00
lila
a02d3b3335 fix: deduplicate distractors against each other, guard thin distractor pool 2026-04-28 15:44:29 +02:00
lila
a02f3b139d fix: deduplicate distractors, replace tautological test, add distractor failure test 2026-04-28 15:17:31 +02:00
lila
3d16ab0fff feat: guard against empty terms in createGameSession 2026-04-28 15:08:06 +02:00
lila
1e30f04e81 feat: add ownership check to evaluateAnswer, AuthenticatedRequest type 2026-04-28 14:39:13 +02:00
lila
fdeb769640 feat: add TTL to GameSessionStore, replay protection and session cleanup to evaluateAnswer 2026-04-28 14:03:15 +02:00
lila
54705943fa adding ticket for refactor: dependency injection for GameSessionStore via composition root 2026-04-28 13:50:56 +02:00
lila
a4a4bfff57 refactor: dependency injection for GameSessionStore via composition root 2026-04-28 13:48:50 +02:00
lila
4f59f3bc14 formatting 2026-04-28 13:18:18 +02:00
lila
2ff7d1759e refactor: extract shuffleArray to lib/utils, rename correctAnswers to terms 2026-04-28 13:17:24 +02:00
lila
c46729f365 formatting 2026-04-28 12:32:44 +02:00
lila
02ccc88d24 fix: change GAME_ROUNDS from strings to numbers 2026-04-28 12:29:46 +02:00
lila
7d3c456efe formatting 2026-04-28 12:29:32 +02:00
46 changed files with 2412 additions and 3828 deletions

View file

@ -10,27 +10,27 @@ Live at [lilastudy.com](https://lilastudy.com).
## Stack ## Stack
| Layer | Technology | | Layer | Technology |
|---|---| | ------------ | ---------------------------------- |
| Monorepo | pnpm workspaces | | Monorepo | pnpm workspaces |
| Frontend | React 18, Vite, TypeScript | | Frontend | React 18, Vite, TypeScript |
| Routing | TanStack Router | | Routing | TanStack Router |
| Server state | TanStack Query | | Server state | TanStack Query |
| Styling | Tailwind CSS | | Styling | Tailwind CSS |
| Backend | Node.js, Express, TypeScript | | Backend | Node.js, Express, TypeScript |
| Database | PostgreSQL + Drizzle ORM | | Database | PostgreSQL + Drizzle ORM |
| Validation | Zod (shared schemas) | | Validation | Zod (shared schemas) |
| Auth | Better Auth (Google + GitHub) | | Auth | Better Auth (Google + GitHub) |
| Realtime | WebSockets (`ws` library) | | Realtime | WebSockets (`ws` library) |
| Testing | Vitest, supertest | | Testing | Vitest, supertest |
| Deployment | Docker Compose, Caddy, Hetzner VPS | | Deployment | Docker Compose, Caddy, Hetzner VPS |
| CI/CD | Forgejo Actions | | CI/CD | Forgejo Actions |
--- ---
## Repository Structure ## Repository Structure
``` ```tree
lila/ lila/
├── apps/ ├── apps/
│ ├── api/ — Express backend │ ├── api/ — Express backend
@ -50,7 +50,7 @@ lila/
Requests flow through a strict layered architecture: Requests flow through a strict layered architecture:
``` ```text
HTTP Request → Router → Controller → Service → Model → Database HTTP Request → Router → Controller → Service → Model → Database
``` ```
@ -71,7 +71,7 @@ Vocabulary data is sourced from WordNet and the Open Multilingual Wordnet (OMW).
## API ## API
``` ```text
POST /api/v1/game/start — start a quiz session (auth required) POST /api/v1/game/start — start a quiz session (auth required)
POST /api/v1/game/answer — submit an answer (auth required) POST /api/v1/game/answer — submit an answer (auth required)
GET /api/v1/health — health check (public) GET /api/v1/health — health check (public)
@ -90,7 +90,7 @@ Rooms are created via REST, then managed over WebSockets. Messages are typed via
## Infrastructure ## Infrastructure
``` ```tree
Internet → Caddy (HTTPS) Internet → Caddy (HTTPS)
├── lilastudy.com → web (nginx, static files) ├── lilastudy.com → web (nginx, static files)
├── api.lilastudy.com → api (Express) ├── api.lilastudy.com → api (Express)
@ -156,15 +156,15 @@ pnpm --filter web test
## Roadmap ## Roadmap
| Phase | Description | Status | | Phase | Description | Status |
|---|---|---| | ----- | ---------------------------------------------------------------------- | ------ |
| 0 | Foundation — monorepo, tooling, dev environment | ✅ | | 0 | Foundation — monorepo, tooling, dev environment | ✅ |
| 1 | Vocabulary data pipeline + REST API | ✅ | | 1 | Vocabulary data pipeline + REST API | ✅ |
| 2 | Singleplayer quiz UI | ✅ | | 2 | Singleplayer quiz UI | ✅ |
| 3 | Auth (Google + GitHub) | ✅ | | 3 | Auth (Google + GitHub) | ✅ |
| 4 | Multiplayer lobby (WebSockets) | ✅ | | 4 | Multiplayer lobby (WebSockets) | ✅ |
| 5 | Multiplayer game (real-time, server timer) | ✅ | | 5 | Multiplayer game (real-time, server timer) | ✅ |
| 6 | Production deployment + CI/CD | ✅ | | 6 | Production deployment + CI/CD | ✅ |
| 7 | Hardening (rate limiting, error boundaries, monitoring, accessibility) | 🔄 | | 7 | Hardening (rate limiting, error boundaries, monitoring, accessibility) | 🔄 |
See `documentation/roadmap.md` for task-level detail. See `documentation/roadmap.md` for task-level detail.

View file

@ -4,7 +4,8 @@ import { toNodeHandler } from "better-auth/node";
import cors from "cors"; import cors from "cors";
import helmet from "helmet"; import helmet from "helmet";
import { auth } from "./lib/auth.js"; import { auth } from "./lib/auth.js";
import { apiRouter } from "./routes/apiRouter.js"; import { createApiRouter } from "./routes/apiRouter.js";
import { InMemoryGameSessionStore } from "./gameSessionStore/index.js";
import { errorHandler } from "./middleware/errorHandler.js"; import { errorHandler } from "./middleware/errorHandler.js";
import { authLimiter } from "./middleware/rateLimiters.js"; import { authLimiter } from "./middleware/rateLimiters.js";
@ -23,7 +24,10 @@ export function createApp() {
app.use("/api/auth", authLimiter); app.use("/api/auth", authLimiter);
app.all("/api/auth/*splat", toNodeHandler(auth)); app.all("/api/auth/*splat", toNodeHandler(auth));
app.use(express.json()); app.use(express.json());
app.use("/api/v1", apiRouter);
const store = new InMemoryGameSessionStore();
app.use("/api/v1", createApiRouter(store));
app.use(errorHandler); app.use(errorHandler);
return app; return app;

View file

@ -60,7 +60,7 @@ const validBody = {
target_language: "it", target_language: "it",
pos: "noun", pos: "noun",
difficulty: "easy", difficulty: "easy",
rounds: "3", rounds: 3,
}; };
const fakeTerms = [ const fakeTerms = [
@ -110,6 +110,26 @@ describe("POST /api/v1/game/start", () => {
expect(res.status).toBe(400); expect(res.status).toBe(400);
expect(body.success).toBe(false); expect(body.success).toBe(false);
}); });
it("returns 422 when no terms are found for the given filters", async () => {
mockGetGameTerms.mockResolvedValue([]);
const res = await request(app).post("/api/v1/game/start").send(validBody);
const body = res.body as ErrorResponse;
expect(res.status).toBe(422);
expect(body.success).toBe(false);
});
it("returns a sanitised error message when the body is invalid", async () => {
const res = await request(app)
.post("/api/v1/game/start")
.send({ ...validBody, difficulty: "impossible" });
const body = res.body as ErrorResponse;
expect(res.status).toBe(400);
expect(body.error).toBe("Invalid game settings");
expect(body.error).not.toContain("Invalid literal value");
expect(body.error).not.toContain("Invalid enum value");
});
}); });
describe("POST /api/v1/game/answer", () => { describe("POST /api/v1/game/answer", () => {
@ -158,7 +178,7 @@ describe("POST /api/v1/game/answer", () => {
expect(body.error).toContain("Game session not found"); expect(body.error).toContain("Game session not found");
}); });
it("returns 404 when the question does not exist in the session", async () => { it("returns 409 when the question does not exist in the session", async () => {
const startRes = await request(app) const startRes = await request(app)
.post("/api/v1/game/start") .post("/api/v1/game/start")
.send(validBody); .send(validBody);
@ -173,8 +193,26 @@ describe("POST /api/v1/game/answer", () => {
selectedOptionId: 0, selectedOptionId: 0,
}); });
const body = res.body as ErrorResponse; const body = res.body as ErrorResponse;
expect(res.status).toBe(404); expect(res.status).toBe(409);
expect(body.success).toBe(false);
expect(body.error).toContain("Question already answered");
});
it("returns 400 when a field has an invalid value", async () => {
const res = await request(app)
.post("/api/v1/game/start")
.send({ ...validBody, difficulty: "impossible" });
const body = res.body as ErrorResponse;
expect(res.status).toBe(400);
expect(body.success).toBe(false);
});
it("returns 400 when rounds has an invalid value", async () => {
const res = await request(app)
.post("/api/v1/game/start")
.send({ ...validBody, rounds: "invalid" });
const body = res.body as ErrorResponse;
expect(res.status).toBe(400);
expect(body.success).toBe(false); expect(body.success).toBe(false);
expect(body.error).toContain("Question not found");
}); });
}); });

View file

@ -1,42 +1,50 @@
import type { Request, Response, NextFunction } from "express"; import type { Response, NextFunction } from "express";
import type { AuthenticatedRequest } from "../types/express.js";
import { GameRequestSchema, AnswerSubmissionSchema } from "@lila/shared"; import { GameRequestSchema, AnswerSubmissionSchema } from "@lila/shared";
import { createGameSession, evaluateAnswer } from "../services/gameService.js"; import { createGameSession, evaluateAnswer } from "../services/gameService.js";
import { ValidationError } from "../errors/AppError.js"; import { ValidationError } from "../errors/AppError.js";
import type { GameSessionStore } from "../gameSessionStore/index.js";
export const createGame = async ( export const createGameController = (store: GameSessionStore) => ({
req: Request, createGame: async (
res: Response, req: AuthenticatedRequest,
next: NextFunction, res: Response,
) => { next: NextFunction,
try { ) => {
const gameSettings = GameRequestSchema.safeParse(req.body); try {
const gameSettings = GameRequestSchema.safeParse(req.body);
if (!gameSettings.success) { if (!gameSettings.success) {
throw new ValidationError(gameSettings.error.message); throw new ValidationError("Invalid game settings");
}
const gameQuestions = await createGameSession(
gameSettings.data,
store,
req.session.user.id,
);
res.json({ success: true, data: gameQuestions });
} catch (error) {
next(error);
} }
},
const gameQuestions = await createGameSession(gameSettings.data); submitAnswer: async (
res.json({ success: true, data: gameQuestions }); req: AuthenticatedRequest,
} catch (error) { res: Response,
next(error); next: NextFunction,
} ) => {
}; try {
const submission = AnswerSubmissionSchema.safeParse(req.body);
export const submitAnswer = async ( if (!submission.success) {
req: Request, throw new ValidationError("Invalid answer submission");
res: Response, }
next: NextFunction, const result = await evaluateAnswer(
) => { submission.data,
try { store,
const submission = AnswerSubmissionSchema.safeParse(req.body); req.session.user.id,
);
if (!submission.success) { res.json({ success: true, data: result });
throw new ValidationError(submission.error.message); } catch (error) {
next(error);
} }
},
const result = await evaluateAnswer(submission.data); });
res.json({ success: true, data: result });
} catch (error) {
next(error);
}
};

View file

@ -25,3 +25,9 @@ export class ConflictError extends AppError {
super(message, 409); super(message, 409);
} }
} }
export class UnprocessableEntityError extends AppError {
constructor(message: string) {
super(message, 422);
}
}

View file

@ -1,7 +1,15 @@
export type GameSessionData = { answers: Map<string, number> }; export type GameSessionData = {
answers: Map<string, { correctOptionId: number }>;
userId: string;
};
export interface GameSessionStore { export interface GameSessionStore {
create(sessionId: string, data: GameSessionData): Promise<void>; create(
sessionId: string,
data: GameSessionData,
ttlMs: number,
): Promise<void>;
get(sessionId: string): Promise<GameSessionData | null>; get(sessionId: string): Promise<GameSessionData | null>;
update(sessionId: string, data: GameSessionData): Promise<void>;
delete(sessionId: string): Promise<void>; delete(sessionId: string): Promise<void>;
} }

View file

@ -0,0 +1,75 @@
import { describe, it, expect, beforeEach } from "vitest";
import { InMemoryGameSessionStore } from "./InMemoryGameSessionStore.js";
describe("InMemoryGameSessionStore", () => {
let store: InMemoryGameSessionStore;
beforeEach(() => {
store = new InMemoryGameSessionStore();
});
it("returns null for a non-existent session", async () => {
const result = await store.get("00000000-0000-0000-0000-000000000000");
expect(result).toBeNull();
});
it("returns session data after creation", async () => {
const data = {
answers: new Map([["q1", { correctOptionId: 2 }]]),
userId: "user-1",
};
await store.create("session-1", data, 60_000);
const result = await store.get("session-1");
expect(result).toEqual(data);
});
it("returns null after the session is deleted", async () => {
const data = {
answers: new Map([["q1", { correctOptionId: 2 }]]),
userId: "user-1",
};
await store.create("session-1", data, 60_000);
await store.delete("session-1");
const result = await store.get("session-1");
expect(result).toBeNull();
});
it("returns null after TTL expires", async () => {
const data = {
answers: new Map([["q1", { correctOptionId: 2 }]]),
userId: "user-1",
};
await store.create("session-1", data, 1);
await new Promise((resolve) => setTimeout(resolve, 10));
const result = await store.get("session-1");
expect(result).toBeNull();
});
it("returns session data before TTL expires", async () => {
const data = {
answers: new Map([["q1", { correctOptionId: 2 }]]),
userId: "user-1",
};
await store.create("session-1", data, 60_000);
const result = await store.get("session-1");
expect(result).not.toBeNull();
});
it("update persists modified session data", async () => {
const data = {
answers: new Map([["q1", { correctOptionId: 2 }]]),
userId: "user-1",
};
await store.create("session-1", data, 60_000);
const updated = {
answers: new Map([["q2", { correctOptionId: 1 }]]),
userId: "user-1",
};
await store.update("session-1", updated);
const result = await store.get("session-1");
expect(result).toEqual(updated);
});
});

View file

@ -1,15 +1,34 @@
import type { GameSessionStore, GameSessionData } from "./GameSessionStore.js"; import type { GameSessionStore, GameSessionData } from "./GameSessionStore.js";
export class InMemoryGameSessionStore implements GameSessionStore { type SessionEntry = { data: GameSessionData; expiresAt: number };
private sessions = new Map<string, GameSessionData>();
create(sessionId: string, data: GameSessionData): Promise<void> { export class InMemoryGameSessionStore implements GameSessionStore {
this.sessions.set(sessionId, data); private sessions = new Map<string, SessionEntry>();
create(
sessionId: string,
data: GameSessionData,
ttlMs: number,
): Promise<void> {
this.sessions.set(sessionId, { data, expiresAt: Date.now() + ttlMs });
return Promise.resolve(); return Promise.resolve();
} }
get(sessionId: string): Promise<GameSessionData | null> { get(sessionId: string): Promise<GameSessionData | null> {
return Promise.resolve(this.sessions.get(sessionId) ?? null); const entry = this.sessions.get(sessionId);
if (!entry) return Promise.resolve(null);
if (Date.now() > entry.expiresAt) {
this.sessions.delete(sessionId);
return Promise.resolve(null);
}
return Promise.resolve(entry.data);
}
update(sessionId: string, data: GameSessionData): Promise<void> {
const entry = this.sessions.get(sessionId);
if (!entry) return Promise.resolve();
this.sessions.set(sessionId, { data, expiresAt: entry.expiresAt });
return Promise.resolve();
} }
delete(sessionId: string): Promise<void> { delete(sessionId: string): Promise<void> {

10
apps/api/src/lib/utils.ts Normal file
View file

@ -0,0 +1,10 @@
export const shuffleArray = <T>(array: T[]): T[] => {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = result[i]!;
result[i] = result[j]!;
result[j] = temp;
}
return result;
};

View file

@ -1,11 +1,16 @@
import express from "express"; import express from "express";
import { Router } from "express"; import type { Router } from "express";
import { healthRouter } from "./healthRouter.js"; import { healthRouter } from "./healthRouter.js";
import { gameRouter } from "./gameRouter.js"; import { createGameRouter } from "./gameRouter.js";
import { lobbyRouter } from "./lobbyRouter.js"; import { lobbyRouter } from "./lobbyRouter.js";
import type { GameSessionStore } from "../gameSessionStore/index.js";
export const apiRouter: Router = express.Router(); export const createApiRouter = (store: GameSessionStore): Router => {
const router = express.Router();
apiRouter.use("/health", healthRouter); router.use("/health", healthRouter);
apiRouter.use("/game", gameRouter); router.use("/game", createGameRouter(store));
apiRouter.use("/lobbies", lobbyRouter); router.use("/lobbies", lobbyRouter);
return router;
};

View file

@ -1,13 +1,19 @@
import express from "express"; import express from "express";
import type { Router } from "express"; import type { Router } from "express";
import { createGame, submitAnswer } from "../controllers/gameController.js"; import { createGameController } from "../controllers/gameController.js";
import { requireAuth } from "../middleware/authMiddleware.js"; import { requireAuth } from "../middleware/authMiddleware.js";
import { gameLimiter } from "../middleware/rateLimiters.js"; import { gameLimiter } from "../middleware/rateLimiters.js";
import type { GameSessionStore } from "../gameSessionStore/index.js";
export const gameRouter: Router = express.Router(); export const createGameRouter = (store: GameSessionStore): Router => {
const router = express.Router();
const controller = createGameController(store);
gameRouter.use(requireAuth); router.use(requireAuth);
gameRouter.use(gameLimiter); router.use(gameLimiter);
gameRouter.post("/start", createGame); router.post("/start", controller.createGame as express.RequestHandler);
gameRouter.post("/answer", submitAnswer); router.post("/answer", controller.submitAnswer as express.RequestHandler);
return router;
};

View file

@ -5,6 +5,7 @@ vi.mock("@lila/db", () => ({ getGameTerms: vi.fn(), getDistractors: vi.fn() }));
import { getGameTerms, getDistractors } from "@lila/db"; import { getGameTerms, getDistractors } from "@lila/db";
import { createGameSession, evaluateAnswer } from "./gameService.js"; import { createGameSession, evaluateAnswer } from "./gameService.js";
import { InMemoryGameSessionStore } from "../gameSessionStore/index.js";
const mockGetGameTerms = vi.mocked(getGameTerms); const mockGetGameTerms = vi.mocked(getGameTerms);
const mockGetDistractors = vi.mocked(getDistractors); const mockGetDistractors = vi.mocked(getDistractors);
@ -14,7 +15,7 @@ const validRequest: GameRequest = {
target_language: "it", target_language: "it",
pos: "noun", pos: "noun",
difficulty: "easy", difficulty: "easy",
rounds: "3", rounds: 3,
}; };
const fakeTerms = [ const fakeTerms = [
@ -31,19 +32,32 @@ const fakeTerms = [
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
mockGetGameTerms.mockResolvedValue(fakeTerms); mockGetGameTerms.mockResolvedValue(fakeTerms);
mockGetDistractors.mockResolvedValue(["wrong1", "wrong2", "wrong3"]); mockGetDistractors.mockResolvedValue([
"wrong1",
"wrong2",
"wrong3",
"wrong4",
"wrong5",
"wrong6",
]);
}); });
describe("createGameSession", () => { describe("createGameSession", () => {
let store: InMemoryGameSessionStore;
beforeEach(() => {
store = new InMemoryGameSessionStore();
});
it("returns a session with the correct number of questions", async () => { it("returns a session with the correct number of questions", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
expect(session.sessionId).toBeDefined(); expect(session.sessionId).toBeDefined();
expect(session.questions).toHaveLength(3); expect(session.questions).toHaveLength(3);
}); });
it("each question has exactly 4 options", async () => { it("each question has exactly 4 options", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
for (const question of session.questions) { for (const question of session.questions) {
expect(question.options).toHaveLength(4); expect(question.options).toHaveLength(4);
@ -51,14 +65,14 @@ describe("createGameSession", () => {
}); });
it("each question has a unique questionId", async () => { it("each question has a unique questionId", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
const ids = session.questions.map((q) => q.questionId); const ids = session.questions.map((q) => q.questionId);
expect(new Set(ids).size).toBe(ids.length); expect(new Set(ids).size).toBe(ids.length);
}); });
it("options have sequential optionIds 0-3", async () => { it("options have sequential optionIds 0-3", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
for (const question of session.questions) { for (const question of session.questions) {
const optionIds = question.options.map((o) => o.optionId); const optionIds = question.options.map((o) => o.optionId);
@ -67,7 +81,7 @@ describe("createGameSession", () => {
}); });
it("the correct answer is always among the options", async () => { it("the correct answer is always among the options", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
for (let i = 0; i < session.questions.length; i++) { for (let i = 0; i < session.questions.length; i++) {
const question = session.questions[i]!; const question = session.questions[i]!;
@ -78,24 +92,26 @@ describe("createGameSession", () => {
} }
}); });
it("distractors are never the correct answer", async () => { it("correct answer appears exactly once even if getDistractors returns a duplicate", async () => {
const session = await createGameSession(validRequest); mockGetDistractors.mockResolvedValueOnce([
"cane",
"wrong2",
"wrong3",
"wrong4",
"wrong5",
"wrong6",
]);
for (let i = 0; i < session.questions.length; i++) { const session = await createGameSession(validRequest, store, "user-1");
const question = session.questions[i]!; const question = session.questions[0]!;
const correctText = fakeTerms[i]!.targetText; const optionTexts = question.options.map((o) => o.text);
const distractorTexts = question.options
.map((o) => o.text)
.filter((t) => t !== correctText);
for (const text of distractorTexts) { expect(optionTexts.filter((t) => t === "cane")).toHaveLength(1);
expect(text).not.toBe(correctText); expect(question.options).toHaveLength(4);
}
}
}); });
it("sets the prompt from the source text", async () => { it("sets the prompt from the source text", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
expect(session.questions[0]!.prompt).toBe("dog"); expect(session.questions[0]!.prompt).toBe("dog");
expect(session.questions[1]!.prompt).toBe("cat"); expect(session.questions[1]!.prompt).toBe("cat");
@ -103,14 +119,14 @@ describe("createGameSession", () => {
}); });
it("passes gloss through (null or string)", async () => { it("passes gloss through (null or string)", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
expect(session.questions[0]!.gloss).toBeNull(); expect(session.questions[0]!.gloss).toBeNull();
expect(session.questions[2]!.gloss).toBe("a building for living in"); expect(session.questions[2]!.gloss).toBe("a building for living in");
}); });
it("calls getGameTerms with the correct arguments", async () => { it("calls getGameTerms with the correct arguments", async () => {
await createGameSession(validRequest); await createGameSession(validRequest, store, "user-1");
expect(mockGetGameTerms).toHaveBeenCalledWith( expect(mockGetGameTerms).toHaveBeenCalledWith(
"en", "en",
@ -122,7 +138,7 @@ describe("createGameSession", () => {
}); });
it("calls getDistractors once per question", async () => { it("calls getDistractors once per question", async () => {
await createGameSession(validRequest); await createGameSession(validRequest, store, "user-1");
expect(mockGetDistractors).toHaveBeenCalledTimes(3); expect(mockGetDistractors).toHaveBeenCalledTimes(3);
}); });
@ -130,24 +146,75 @@ describe("createGameSession", () => {
it("propagates unexpected errors from getGameTerms", async () => { it("propagates unexpected errors from getGameTerms", async () => {
mockGetGameTerms.mockRejectedValue(new Error("connection refused")); mockGetGameTerms.mockRejectedValue(new Error("connection refused"));
await expect(createGameSession(validRequest)).rejects.toThrow( await expect(
"connection refused", createGameSession(validRequest, store, "user-1"),
); ).rejects.toThrow("connection refused");
});
it("propagates getDistractors failure", async () => {
mockGetDistractors.mockRejectedValue(new Error("db timeout"));
await expect(
createGameSession(validRequest, store, "user-1"),
).rejects.toThrow("db timeout");
});
it("throws when fewer than 3 unique distractors remain after deduplication", async () => {
mockGetDistractors.mockResolvedValueOnce([
"cane",
"cane",
"cane",
"cane",
"cane",
"cane",
]);
await expect(
createGameSession(validRequest, store, "user-1"),
).rejects.toThrow("Not enough unique distractors");
});
it("duplicate distractors are deduplicated against each other", async () => {
mockGetDistractors.mockResolvedValueOnce([
"wrong1",
"wrong1",
"wrong1",
"wrong2",
"wrong3",
"wrong4",
]);
const session = await createGameSession(validRequest, store, "user-1");
const question = session.questions[0]!;
const optionTexts = question.options.map((o) => o.text);
expect(new Set(optionTexts).size).toBe(4);
expect(question.options).toHaveLength(4);
}); });
}); });
describe("evaluateAnswer", () => { describe("evaluateAnswer", () => {
let store: InMemoryGameSessionStore;
beforeEach(() => {
store = new InMemoryGameSessionStore();
});
it("returns isCorrect: true when the correct option is selected", async () => { it("returns isCorrect: true when the correct option is selected", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
const question = session.questions[0]!; const question = session.questions[0]!;
const correctText = fakeTerms[0]!.targetText; const correctText = fakeTerms[0]!.targetText;
const correctOption = question.options.find((o) => o.text === correctText)!; const correctOption = question.options.find((o) => o.text === correctText)!;
const result = await evaluateAnswer({ const result = await evaluateAnswer(
sessionId: session.sessionId, {
questionId: question.questionId, sessionId: session.sessionId,
selectedOptionId: correctOption.optionId, questionId: question.questionId,
}); selectedOptionId: correctOption.optionId,
},
store,
"user-1",
);
expect(result.isCorrect).toBe(true); expect(result.isCorrect).toBe(true);
expect(result.correctOptionId).toBe(correctOption.optionId); expect(result.correctOptionId).toBe(correctOption.optionId);
@ -155,17 +222,21 @@ describe("evaluateAnswer", () => {
}); });
it("returns isCorrect: false when a wrong option is selected", async () => { it("returns isCorrect: false when a wrong option is selected", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
const question = session.questions[0]!; const question = session.questions[0]!;
const correctText = fakeTerms[0]!.targetText; const correctText = fakeTerms[0]!.targetText;
const correctOption = question.options.find((o) => o.text === correctText)!; const correctOption = question.options.find((o) => o.text === correctText)!;
const wrongOption = question.options.find((o) => o.text !== correctText)!; const wrongOption = question.options.find((o) => o.text !== correctText)!;
const result = await evaluateAnswer({ const result = await evaluateAnswer(
sessionId: session.sessionId, {
questionId: question.questionId, sessionId: session.sessionId,
selectedOptionId: wrongOption.optionId, questionId: question.questionId,
}); selectedOptionId: wrongOption.optionId,
},
store,
"user-1",
);
expect(result.isCorrect).toBe(false); expect(result.isCorrect).toBe(false);
expect(result.correctOptionId).toBe(correctOption.optionId); expect(result.correctOptionId).toBe(correctOption.optionId);
@ -179,13 +250,13 @@ describe("evaluateAnswer", () => {
selectedOptionId: 0, selectedOptionId: 0,
}; };
await expect(evaluateAnswer(submission)).rejects.toThrow( await expect(evaluateAnswer(submission, store, "user-1")).rejects.toThrow(
"Game session not found", "Game session not found",
); );
}); });
it("throws NotFoundError for a non-existent question", async () => { it("throws ConflictError for a non-existent question", async () => {
const session = await createGameSession(validRequest); const session = await createGameSession(validRequest, store, "user-1");
const submission: AnswerSubmission = { const submission: AnswerSubmission = {
sessionId: session.sessionId, sessionId: session.sessionId,
@ -193,8 +264,71 @@ describe("evaluateAnswer", () => {
selectedOptionId: 0, selectedOptionId: 0,
}; };
await expect(evaluateAnswer(submission)).rejects.toThrow( await expect(
"Question not found", evaluateAnswer(submission, store, "user-1"),
).rejects.toMatchObject({ statusCode: 409 });
});
it("throws ConflictError when the same question is submitted twice", async () => {
const session = await createGameSession(validRequest, store, "user-1");
const question = session.questions[0]!;
await evaluateAnswer(
{
sessionId: session.sessionId,
questionId: question.questionId,
selectedOptionId: 0,
},
store,
"user-1",
); );
await expect(
evaluateAnswer(
{
sessionId: session.sessionId,
questionId: question.questionId,
selectedOptionId: 0,
},
store,
"user-1",
),
).rejects.toMatchObject({ statusCode: 409 });
});
it("deletes the session after the last question is answered", async () => {
const session = await createGameSession(validRequest, store, "user-1");
for (const question of session.questions) {
await evaluateAnswer(
{
sessionId: session.sessionId,
questionId: question.questionId,
selectedOptionId: 0,
},
store,
"user-1",
);
}
await expect(
evaluateAnswer(
{
sessionId: session.sessionId,
questionId: session.questions[0]!.questionId,
selectedOptionId: 0,
},
store,
"user-1",
),
).rejects.toThrow("Game session not found");
});
it("throws UnprocessableEntityError when getGameTerms returns no terms", async () => {
mockGetGameTerms.mockResolvedValue([]);
await expect(
createGameSession(validRequest, store, "user-1"),
).rejects.toMatchObject({ statusCode: 422 });
}); });
}); });

View file

@ -8,38 +8,57 @@ import type {
AnswerSubmission, AnswerSubmission,
AnswerResult, AnswerResult,
} from "@lila/shared"; } from "@lila/shared";
import { InMemoryGameSessionStore } from "../gameSessionStore/index.js"; import type { GameSessionStore } from "../gameSessionStore/index.js";
import { NotFoundError } from "../errors/AppError.js"; import {
NotFoundError,
const gameSessionStore = new InMemoryGameSessionStore(); ConflictError,
UnprocessableEntityError,
} from "../errors/AppError.js";
import { shuffleArray } from "../lib/utils.js";
export const createGameSession = async ( export const createGameSession = async (
request: GameRequest, request: GameRequest,
store: GameSessionStore,
userId: string,
): Promise<GameSession> => { ): Promise<GameSession> => {
const correctAnswers = await getGameTerms( const terms = await getGameTerms(
request.source_language, request.source_language,
request.target_language, request.target_language,
request.pos, request.pos,
request.difficulty, request.difficulty,
Number(request.rounds), request.rounds,
); );
const answerKey = new Map<string, number>(); if (terms.length === 0) {
throw new UnprocessableEntityError("No terms found for the given filters");
}
const answerKey = new Map<string, { correctOptionId: number }>();
const questions: GameQuestion[] = await Promise.all( const questions: GameQuestion[] = await Promise.all(
correctAnswers.map(async (correctAnswer) => { terms.map(async (term) => {
const distractorTexts = await getDistractors( const distractorTexts = await getDistractors(
correctAnswer.termId, term.termId,
correctAnswer.targetText, term.targetText,
request.target_language, request.target_language,
request.pos, request.pos,
request.difficulty, request.difficulty,
3, 6,
); );
const optionTexts = [correctAnswer.targetText, ...distractorTexts]; const uniqueDistractors = [
const shuffledTexts = shuffle(optionTexts); ...new Set(distractorTexts.filter((t) => t !== term.targetText)),
const correctOptionId = shuffledTexts.indexOf(correctAnswer.targetText); ];
if (uniqueDistractors.length < 3) {
throw new Error(
`Not enough unique distractors for term: ${term.targetText}`,
);
}
const optionTexts = [term.targetText, ...uniqueDistractors.slice(0, 3)];
const shuffledTexts = shuffleArray(optionTexts);
const correctOptionId = shuffledTexts.indexOf(term.targetText);
const options: AnswerOption[] = shuffledTexts.map((text, index) => ({ const options: AnswerOption[] = shuffledTexts.map((text, index) => ({
optionId: index, optionId: index,
@ -47,53 +66,58 @@ export const createGameSession = async (
})); }));
const questionId = randomUUID(); const questionId = randomUUID();
answerKey.set(questionId, correctOptionId); answerKey.set(questionId, { correctOptionId });
return { return {
questionId, questionId,
prompt: correctAnswer.sourceText, prompt: term.sourceText,
gloss: correctAnswer.sourceGloss, gloss: term.sourceGloss,
options, options,
}; };
}), }),
); );
const sessionId = randomUUID(); const sessionId = randomUUID();
await gameSessionStore.create(sessionId, { answers: answerKey }); await store.create(sessionId, { answers: answerKey, userId }, 30 * 60 * 1000);
return { sessionId, questions }; return { sessionId, questions };
}; };
const shuffle = <T>(array: T[]): T[] => {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = result[i]!;
result[i] = result[j]!;
result[j] = temp;
}
return result;
};
export const evaluateAnswer = async ( export const evaluateAnswer = async (
submission: AnswerSubmission, submission: AnswerSubmission,
store: GameSessionStore,
userId: string,
): Promise<AnswerResult> => { ): Promise<AnswerResult> => {
const session = await gameSessionStore.get(submission.sessionId); const session = await store.get(submission.sessionId);
if (!session) { if (!session || session.userId !== userId) {
throw new NotFoundError(`Game session not found: ${submission.sessionId}`); throw new NotFoundError(`Game session not found: ${submission.sessionId}`);
} }
const correctOptionId = session.answers.get(submission.questionId); const answer = session.answers.get(submission.questionId);
if (correctOptionId === undefined) { if (answer === undefined) {
throw new NotFoundError(`Question not found: ${submission.questionId}`); throw new ConflictError(
`Question already answered: ${submission.questionId}`,
);
}
const updatedAnswers = new Map(session.answers);
updatedAnswers.delete(submission.questionId);
if (updatedAnswers.size === 0) {
await store.delete(submission.sessionId);
} else {
await store.update(submission.sessionId, {
answers: updatedAnswers,
userId: session.userId,
});
} }
return { return {
questionId: submission.questionId, questionId: submission.questionId,
isCorrect: submission.selectedOptionId === correctOptionId, isCorrect: submission.selectedOptionId === answer.correctOptionId,
correctOptionId, correctOptionId: answer.correctOptionId,
selectedOptionId: submission.selectedOptionId, selectedOptionId: submission.selectedOptionId,
}; };
}; };

View file

@ -1,3 +1,4 @@
import type { Request } from "express";
import type { Session, User } from "better-auth"; import type { Session, User } from "better-auth";
declare global { declare global {
@ -14,4 +15,6 @@ declare module "ws" {
} }
} }
export {}; export type AuthenticatedRequest = Request & {
session: { session: Session; user: User };
};

View file

@ -24,19 +24,19 @@ const LABELS: Record<string, string> = {
type GameSetupProps = { onStart: (settings: GameRequest) => void }; type GameSetupProps = { onStart: (settings: GameRequest) => void };
type SettingGroupProps = { type SettingGroupProps<T extends string | number> = {
label: string; label: string;
options: readonly string[]; options: readonly T[];
selected: string; selected: T;
onSelect: (value: string) => void; onSelect: (value: T) => void;
}; };
const SettingGroup = ({ const SettingGroup = <T extends string | number>({
label, label,
options, options,
selected, selected,
onSelect, onSelect,
}: SettingGroupProps) => ( }: SettingGroupProps<T>) => (
<div className="w-full"> <div className="w-full">
<p className="text-xs font-bold tracking-widest uppercase text-(--color-primary) mb-2"> <p className="text-xs font-bold tracking-widest uppercase text-(--color-primary) mb-2">
{label} {label}
@ -52,7 +52,7 @@ const SettingGroup = ({
: "bg-white text-(--color-primary-dark) border-(--color-primary-light) hover:bg-(--color-surface) hover:-translate-y-0.5 active:translate-y-0" : "bg-white text-(--color-primary-dark) border-(--color-primary-light) hover:bg-(--color-surface) hover:-translate-y-0.5 active:translate-y-0"
}`} }`}
> >
{LABELS[option] ?? option} {LABELS[String(option)] ?? option}
</button> </button>
))} ))}
</div> </div>
@ -68,7 +68,7 @@ export const GameSetup = ({ onStart }: GameSetupProps) => {
); );
const [pos, setPos] = useState<string>(SUPPORTED_POS[0]); const [pos, setPos] = useState<string>(SUPPORTED_POS[0]);
const [difficulty, setDifficulty] = useState<string>(DIFFICULTY_LEVELS[0]); const [difficulty, setDifficulty] = useState<string>(DIFFICULTY_LEVELS[0]);
const [rounds, setRounds] = useState<string>(GAME_ROUNDS[0]); const [rounds, setRounds] = useState<number>(GAME_ROUNDS[0]);
const handleSourceLanguage = (value: string) => { const handleSourceLanguage = (value: string) => {
if (value === targetLanguage) { if (value === targetLanguage) {

View file

@ -53,7 +53,11 @@ export const QuestionCard = ({
Round {questionNumber}/{totalQuestions} Round {questionNumber}/{totalQuestions}
</div> </div>
<div className="text-xs font-semibold text-(--color-text-muted)"> <div className="text-xs font-semibold text-(--color-text-muted)">
{currentResult ? "Checked" : selectedOptionId !== null ? "Ready" : "Pick one"} {currentResult
? "Checked"
: selectedOptionId !== null
? "Ready"
: "Pick one"}
</div> </div>
</div> </div>
@ -73,14 +77,14 @@ export const QuestionCard = ({
<div className="w-full rounded-3xl border border-(--color-primary-light) bg-white/55 dark:bg-black/10 backdrop-blur shadow-sm p-4"> <div className="w-full rounded-3xl border border-(--color-primary-light) bg-white/55 dark:bg-black/10 backdrop-blur shadow-sm p-4">
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
{question.options.map((option) => ( {question.options.map((option) => (
<OptionButton <OptionButton
key={option.optionId} key={option.optionId}
text={option.text} text={option.text}
state={getOptionState(option.optionId)} state={getOptionState(option.optionId)}
onSelect={() => handleSelect(option.optionId)} onSelect={() => handleSelect(option.optionId)}
/> />
))} ))}
</div> </div>
</div> </div>

View file

@ -69,7 +69,9 @@ export const MultiplayerScoreScreen = ({
</span> </span>
<span <span
className={`text-sm font-semibold ${ className={`text-sm font-semibold ${
isCurrentUser ? "text-(--color-text)" : "text-(--color-text)" isCurrentUser
? "text-(--color-text)"
: "text-(--color-text)"
}`} }`}
> >
{player.user.name} {player.user.name}

View file

@ -6,10 +6,7 @@ type ConfettiBurstProps = {
count?: number; count?: number;
}; };
type Piece = { type Piece = { id: number; style: React.CSSProperties & ConfettiVars };
id: number;
style: React.CSSProperties & ConfettiVars;
};
type ConfettiVars = { type ConfettiVars = {
["--x0"]: string; ["--x0"]: string;
@ -56,7 +53,9 @@ export const ConfettiBurst = ({
}, []); }, []);
const pieces = useMemo<Piece[]>(() => { const pieces = useMemo<Piece[]>(() => {
const seed = hashStringToUint32(`${instanceId}:${count}:${colors.join(",")}`); const seed = hashStringToUint32(
`${instanceId}:${count}:${colors.join(",")}`,
);
const rand = mulberry32(seed); const rand = mulberry32(seed);
const rnd = (min: number, max: number) => min + rand() * (max - min); const rnd = (min: number, max: number) => min + rand() * (max - min);
@ -100,4 +99,3 @@ export const ConfettiBurst = ({
</div> </div>
); );
}; };

View file

@ -108,7 +108,9 @@ function MultiplayerPage() {
{/* Join lobby */} {/* Join lobby */}
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<h2 className="text-lg font-bold text-(--color-text)">Join a lobby</h2> <h2 className="text-lg font-bold text-(--color-text)">
Join a lobby
</h2>
<p className="text-sm text-(--color-text-muted)"> <p className="text-sm text-(--color-text-muted)">
Enter the code shared by your host. Enter the code shared by your host.
</p> </p>

File diff suppressed because it is too large Load diff

View file

@ -5,8 +5,8 @@
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"outDir": "dist", "outDir": "dist",
"rootDir": ".", "rootDir": ".",
"types": ["node"], "types": ["node"]
}, },
"references": [{ "path": "../packages/shared" }], "references": [{ "path": "../packages/shared" }],
"include": ["./**/*"], "include": ["./**/*"]
} }

View file

@ -8,21 +8,21 @@ Labels: `[feature]` `[infra]` `[security]` `[ux]` `[debt]`
Things that are actively in progress or should be picked up immediately. Mostly operational risk and the remaining phase 7 hardening work. Things that are actively in progress or should be picked up immediately. Mostly operational risk and the remaining phase 7 hardening work.
- **Google OAuth publishing** `[infra]`
Only test users can currently log in via Google. Publish the OAuth consent screen so any Google user can sign in — requires branding verification in Google Cloud Console.
- **Hetzner domain migration check** `[infra]` - **Hetzner domain migration check** `[infra]`
Verify whether the lilastudy.com domain needs to be migrated following a Hetzner DNS change. Check Hetzner dashboard for any pending migration notice. Verify whether the lilastudy.com domain needs to be migrated following a Hetzner DNS change. Check Hetzner dashboard for any pending migration notice.
- **Conditionally register OAuth providers** `[debt]`
Better Auth logs warnings when social providers are registered without credentials (`Social provider google is missing clientId or clientSecret`). Instead of registering all providers unconditionally, only add a provider to the config when its credentials are present in the environment. Keeps local dev clean for contributors who don't have OAuth apps set up.
--- ---
## next ## next
Clearly planned work, not yet started. No hard ordering — sequence based on what unblocks real users first. Clearly planned work, not yet started. No hard ordering — sequence based on what unblocks real users first.
- **Batch distractor queries to eliminate N+1** `[debt]`
createGameSession calls getDistractors once per term in parallel — 3 queries for 3 rounds, 10 for 10. Each query does ORDER BY RANDOM() which can't use an index and gets slower as the translations table grows. Fix: add a getDistractorsForTerms(termIds[], ...) function to @lila/db that batches all distractor fetches into a single query and returns results grouped by term. The service distributes the results per question. Prerequisite: none. Blocked by: nothing, but coordinate with any ongoing @lila/db changes.
- **Atomic session creation** `[debt]`
createGameSession reads from Postgres (getGameTerms, getDistractors) then writes to the session store (in-memory/Valkey). A crash between the two leaves the terms consumed with no session created — the user gets an error and retries, no data is corrupted, but the work is wasted. A true transaction boundary isn't achievable across two different systems (Postgres + Valkey have no shared coordinator). Options when revisiting: store sessions in Postgres instead of Valkey (full transactionality, higher latency), or accept the current behaviour and add retry logic on the client. Revisit after Valkey is in production and actual failure rates are observable.
- **Guest / try-now flow** `[feature]` - **Guest / try-now flow** `[feature]`
Allow users to play a quiz without signing in so they can see what the app offers before creating an account. Make auth middleware optional on game routes, add a "Try without account" button on the landing/login page. Allow users to play a quiz without signing in so they can see what the app offers before creating an account. Make auth middleware optional on game routes, add a "Try without account" button on the landing/login page.
@ -63,6 +63,9 @@ Clearly planned work, not yet started. No hard ordering — sequence based on wh
- **Tighten CSP to remove unsafe-inline** `[security]` - **Tighten CSP to remove unsafe-inline** `[security]`
Current script-src uses 'unsafe-inline' to accommodate framework-injected inline scripts (likely TanStack Router hydration). Tightening this would require nonce-based CSP, which needs server-rendered HTML or a Caddy layer that injects per-request nonces. Not urgent — pragmatic CSP with 'unsafe-inline' is mainstream for SPAs at this scale. Revisit if the app handles more sensitive data or grows a meaningful user base Current script-src uses 'unsafe-inline' to accommodate framework-injected inline scripts (likely TanStack Router hydration). Tightening this would require nonce-based CSP, which needs server-rendered HTML or a Caddy layer that injects per-request nonces. Not urgent — pragmatic CSP with 'unsafe-inline' is mainstream for SPAs at this scale. Revisit if the app handles more sensitive data or grows a meaningful user base
- **Publish Google OAuth consent screen** `[infra]`
App is currently in testing mode, which caps OAuth sign-ins at 100 users. Before hitting that limit, publish the consent screen in Google Cloud Console. Basic scopes (email, profile, openid) require no Google review — just fill in branding fields (app name, logo, support email, privacy policy URL) and click publish. Trigger: do this before reaching 80 users.
--- ---
## later ## later
@ -103,10 +106,10 @@ Directionally right, timing is unclear. Revisit when the next/now work is done.
Shipped milestones, newest first. Shipped milestones, newest first.
- **04 - 2026 - t00001 - Docker credential helper** - **04 - 2026 - t00001 - Docker credential helper**
- **04 - 2026 - Pin dependencies in package.json** - Unpinned deps in a CI/CD pipeline are a real risk. - **04 - 2026 - Pin dependencies in package.json** - Unpinned deps in a CI/CD pipeline are a real risk.
- **04 - 2026 - React error boundaries** - Catch and display runtime errors gracefully instead of crashing the entire app. - **04 - 2026 - React error boundaries** - Catch and display runtime errors gracefully instead of crashing the entire app.
- **04 - 2026 - 404 and redirect handling** - Unknown routes return raw errors. Add a catch-all route on the frontend for client-side 404s. - **04 - 2026 - 404 and redirect handling** - Unknown routes return raw errors. Add a catch-all route on the frontend for client-side 404s.
- **04 - 2026 - Multiplayer GameService unit tests** - round evaluation, scoring, tie-breaking, timeout handling - **04 - 2026 - Multiplayer GameService unit tests** - round evaluation, scoring, tie-breaking, timeout handling
- **04 - 2026 - Security headers with helmet** - Add helmet middleware to set secure HTTP response headers. - **04 - 2026 - Security headers with helmet** - Add helmet middleware to set secure HTTP response headers.
- **04 - 2026 - Rate limiting on API endpoints** - At minimum: auth endpoints (brute force prevention) and game endpoints (spam prevention) - **04 - 2026 - Rate limiting on API endpoints** - At minimum: auth endpoints (brute force prevention) and game endpoints (spam prevention)
- **04 - 2026 — Migrations in deploy pipeline** — Drizzle migrate runs as a CI/CD step before the API container restarts - **04 - 2026 — Migrations in deploy pipeline** — Drizzle migrate runs as a CI/CD step before the API container restarts

View file

@ -55,13 +55,13 @@ See **Setup** for download instructions.
Per-language JSON files in `sources/cefr/` provide the initial CEFR level annotations. These files do not cover the full vocabulary extracted from OMW — coverage varies by language. Gaps and disagreements are handled by the enrich stage. Per-language JSON files in `sources/cefr/` provide the initial CEFR level annotations. These files do not cover the full vocabulary extracted from OMW — coverage varies by language. Gaps and disagreements are handled by the enrich stage.
| Language | File | | Language | File |
|---|---| | -------- | ---------------------- |
| English | `sources/cefr/en.json` | | English | `sources/cefr/en.json` |
| Italian | `sources/cefr/it.json` | | Italian | `sources/cefr/it.json` |
| Spanish | `sources/cefr/es.json` | | Spanish | `sources/cefr/es.json` |
| German | `sources/cefr/de.json` | | German | `sources/cefr/de.json` |
| French | `sources/cefr/fr.json` | | French | `sources/cefr/fr.json` |
These files are committed to git. For per-language coverage detail see `COVERAGE.md`. These files are committed to git. For per-language coverage detail see `COVERAGE.md`.
@ -102,13 +102,13 @@ See `LLM-SETUP.md`.
The pipeline runs in five stages. Each stage is independent and can be re-run without affecting the others. The pipeline runs in five stages. Each stage is independent and can be re-run without affecting the others.
| Stage | What it does | | Stage | What it does |
|---|---| | ----------- | -------------------------------------------------------------------- |
| 1. Extract | Reads OMW SQLite database, outputs normalized JSON per language | | 1. Extract | Reads OMW SQLite database, outputs normalized JSON per language |
| 2. Annotate | Merges CEFR source files into extracted data, adds source file votes | | 2. Annotate | Merges CEFR source files into extracted data, adds source file votes |
| 3. Enrich | Runs local LLMs in two rounds — generation then voting | | 3. Enrich | Runs local LLMs in two rounds — generation then voting |
| 4. Merge | Resolves votes, derives difficulty, splits into final and flagged | | 4. Merge | Resolves votes, derives difficulty, splits into final and flagged |
| 5. Compare | Generates COVERAGE.md with detailed quality report | | 5. Compare | Generates COVERAGE.md with detailed quality report |
### 1. Extract ### 1. Extract
@ -137,11 +137,11 @@ Each record in the output looks like this:
"fr": ["comptable"] "fr": ["comptable"]
}, },
"glosses": { "glosses": {
"en": ["(usually followed by 'to') having the necessary means or skill or know-how or authority to do something"] "en": [
"(usually followed by 'to') having the necessary means or skill or know-how or authority to do something"
]
}, },
"examples": { "examples": { "en": ["able to swim", "she was able to program her computer"] }
"en": ["able to swim", "she was able to program her computer"]
}
} }
``` ```
@ -158,6 +158,7 @@ Words appearing in the CEFR source file multiple times with different CEFR level
**Input:** `stage-1-extract/output/omw.json` + `stage-2-annotate/sources/cefr/{lang}.json` **Input:** `stage-1-extract/output/omw.json` + `stage-2-annotate/sources/cefr/{lang}.json`
**Output:** **Output:**
- `stage-2-annotate/output/{lang}.json` — one per language - `stage-2-annotate/output/{lang}.json` — one per language
- `stage-2-annotate/output/conflicts.json` — cross-language conflicts for review - `stage-2-annotate/output/conflicts.json` — cross-language conflicts for review
@ -177,20 +178,14 @@ Each record in the output extends the OMW record with a `votes` field and any ad
"es": ["capaz"], "es": ["capaz"],
"fr": ["comptable"] "fr": ["comptable"]
}, },
"glosses": { "glosses": { "en": ["having the necessary means or skill to do something"] },
"en": ["having the necessary means or skill to do something"]
},
"examples": { "examples": {
"en": [ "en": [
{ "text": "able to swim", "source": "omw" }, { "text": "able to swim", "source": "omw" },
{ "text": "She was able to finish the task.", "source": "cefr" } { "text": "She was able to finish the task.", "source": "cefr" }
] ]
}, },
"votes": { "votes": { "en": { "able": { "cefr_source": "B1" } } }
"en": {
"able": { "cefr_source": "B1" }
}
}
} }
``` ```
@ -297,9 +292,7 @@ Each record in the votes file looks like this:
} }
}, },
"examples": { "examples": {
"en": [ "en": [{ "text": "the dog barked at the stranger", "source": "omw" }],
{ "text": "the dog barked at the stranger", "source": "omw" }
],
"fr": { "fr": {
"candidates": [ "candidates": [
{ "text": "le chien a aboyé", "source": "model_1" }, { "text": "le chien a aboyé", "source": "model_1" },
@ -311,8 +304,14 @@ Each record in the votes file looks like this:
"descriptions": { "descriptions": {
"en": { "en": {
"candidates": [ "candidates": [
{ "text": "a common household pet known for loyalty", "source": "model_1" }, {
{ "text": "a domesticated animal and loyal companion", "source": "model_2" } "text": "a common household pet known for loyalty",
"source": "model_1"
},
{
"text": "a domesticated animal and loyal companion",
"source": "model_2"
}
], ],
"votes": { "model_1": 2, "model_2": 1 } "votes": { "model_1": 2, "model_2": 1 }
} }
@ -334,14 +333,15 @@ Reads the votes file per language and resolves the final value for every field.
**Difficulty mapping:** **Difficulty mapping:**
| CEFR | Difficulty | | CEFR | Difficulty |
|---|---| | ------ | ------------ |
| A1, A2 | easy | | A1, A2 | easy |
| B1, B2 | intermediate | | B1, B2 | intermediate |
| C1, C2 | hard | | C1, C2 | hard |
**Input:** `stage-3-enrich/output/votes/{lang}_votes.json` **Input:** `stage-3-enrich/output/votes/{lang}_votes.json`
**Output:** **Output:**
- `stage-4-merge/output/final/{lang}.json` — fully resolved, ready for seeding - `stage-4-merge/output/final/{lang}.json` — fully resolved, ready for seeding
- `stage-4-merge/output/flagged/{lang}.json` — CEFR majority not reached, needs manual review before seeding - `stage-4-merge/output/flagged/{lang}.json` — CEFR majority not reached, needs manual review before seeding
@ -360,21 +360,15 @@ Each record in `final/{lang}.json` looks like this:
{ "text": "dog", "cefr_level": "A1", "difficulty": "easy" }, { "text": "dog", "cefr_level": "A1", "difficulty": "easy" },
{ "text": "canine", "cefr_level": "B2", "difficulty": "intermediate" } { "text": "canine", "cefr_level": "B2", "difficulty": "intermediate" }
], ],
"it": [ "it": [{ "text": "cane", "cefr_level": "A1", "difficulty": "easy" }]
{ "text": "cane", "cefr_level": "A1", "difficulty": "easy" }
]
}, },
"glosses": { "glosses": {
"en": { "text": "a domesticated carnivorous mammal", "source": "omw" }, "en": { "text": "a domesticated carnivorous mammal", "source": "omw" },
"fr": { "text": "un mammifère carnivore domestiqué", "source": "model_1" } "fr": { "text": "un mammifère carnivore domestiqué", "source": "model_1" }
}, },
"examples": { "examples": {
"en": [ "en": [{ "text": "the dog barked at the stranger", "source": "omw" }],
{ "text": "the dog barked at the stranger", "source": "omw" } "fr": [{ "text": "le chien a aboyé", "source": "model_1" }]
],
"fr": [
{ "text": "le chien a aboyé", "source": "model_1" }
]
}, },
"descriptions": { "descriptions": {
"en": { "en": {
@ -400,6 +394,7 @@ output quality per language. Run this after merge to verify output before
seeding the database. seeding the database.
**Input:** **Input:**
- `stage-4-merge/output/final/{lang}.json` - `stage-4-merge/output/final/{lang}.json`
- `stage-4-merge/output/flagged/{lang}.json` - `stage-4-merge/output/flagged/{lang}.json`
@ -436,12 +431,12 @@ pnpm --filter @lila/pipeline compare
These values are defined in `packages/shared/src/constants.ts` and enforced by database check constraints. The pipeline filters out any entries that violate them. These values are defined in `packages/shared/src/constants.ts` and enforced by database check constraints. The pipeline filters out any entries that violate them.
| Constant | Values | | Constant | Values |
|---|---| | --------------- | ------------------------------------- |
| Languages | `en`, `it`, `de`, `es`, `fr` | | Languages | `en`, `it`, `de`, `es`, `fr` |
| Parts of speech | `noun`, `verb`, `adjective`, `adverb` | | Parts of speech | `noun`, `verb`, `adjective`, `adverb` |
| CEFR levels | `A1`, `A2`, `B1`, `B2`, `C1`, `C2` | | CEFR levels | `A1`, `A2`, `B1`, `B2`, `C1`, `C2` |
| Difficulty | `easy`, `intermediate`, `hard` | | Difficulty | `easy`, `intermediate`, `hard` |
Adding a new value to any of these requires a constants update and a database migration before re-running the pipeline. See **Adding a new language** for the full steps — the same process applies for new parts of speech. Adding a new value to any of these requires a constants update and a database migration before re-running the pipeline. See **Adding a new language** for the full steps — the same process applies for new parts of speech.

View file

@ -243,13 +243,13 @@ Automated build and deploy via Forgejo Actions. On every push to `main`, the pip
### Secrets (stored in Forgejo repo settings → Actions → Secrets) ### Secrets (stored in Forgejo repo settings → Actions → Secrets)
| Secret | Value | | Secret | Value |
|---|---| | ----------------- | ----------------------------------------- |
| REGISTRY_USER | Forgejo username | | REGISTRY_USER | Forgejo username |
| REGISTRY_PASSWORD | Forgejo password | | REGISTRY_PASSWORD | Forgejo password |
| SSH_PRIVATE_KEY | Contents of `~/.ssh/ci-runner` on the VPS | | SSH_PRIVATE_KEY | Contents of `~/.ssh/ci-runner` on the VPS |
| SSH_HOST | VPS IP address | | SSH_HOST | VPS IP address |
| SSH_USER | `lila` | | SSH_USER | `lila` |
### Runner Configuration ### Runner Configuration

View file

@ -9,12 +9,12 @@ and production scripts.
## Hardware (dev machine) ## Hardware (dev machine)
| Component | Spec | | Component | Spec |
|---|---| | --------- | --------------------------------------------------------------- |
| CPU | Intel Core i7-6500U (2 cores / 4 threads @ 3.10 GHz) | | CPU | Intel Core i7-6500U (2 cores / 4 threads @ 3.10 GHz) |
| RAM | 8 GB | | RAM | 8 GB |
| GPU | NVIDIA GeForce GTX 950M — 4 GB VRAM (Maxwell, CUDA compute 5.0) | | GPU | NVIDIA GeForce GTX 950M — 4 GB VRAM (Maxwell, CUDA compute 5.0) |
| OS | Debian GNU/Linux 13 (trixie) x86_64 | | OS | Debian GNU/Linux 13 (trixie) x86_64 |
**Local inference verdict:** viable for small/quantized models, not for **Local inference verdict:** viable for small/quantized models, not for
production runs. See the [Local inference](#local-inference-llamacpp) section production runs. See the [Local inference](#local-inference-llamacpp) section
@ -28,12 +28,12 @@ The enrich script uses a single, swappable provider config. All providers
except Anthropic expose an OpenAI-compatible API, so the same client code except Anthropic expose an OpenAI-compatible API, so the same client code
works across all of them — only `baseURL`, `apiKey`, and `model` change. works across all of them — only `baseURL`, `apiKey`, and `model` change.
| Provider | Use case | Cost | Rate limits | | Provider | Use case | Cost | Rate limits |
|---|---|---|---| | ---------------------- | --------------------------------------------- | ------------------ | ---------------------- |
| llama.cpp (local) | Quality testing, overnight dev runs | Free (electricity) | None | | llama.cpp (local) | Quality testing, overnight dev runs | Free (electricity) | None |
| OpenRouter (free tier) | Quality comparison, multi-model evaluation | Free | 50 req/day, 20 req/min | | OpenRouter (free tier) | Quality comparison, multi-model evaluation | Free | 50 req/day, 20 req/min |
| OpenRouter (paid) | Production runs if local quality insufficient | Pay-per-token | None | | OpenRouter (paid) | Production runs if local quality insufficient | Pay-per-token | None |
| Anthropic API | Quality baseline / reference | Pay-per-token | Standard | | Anthropic API | Quality baseline / reference | Pay-per-token | Standard |
--- ---
@ -58,12 +58,12 @@ in hybrid mode, slower than full-GPU but much faster than pure CPU.
Practical estimates for this hardware (~3.5 GB VRAM usable after drivers): Practical estimates for this hardware (~3.5 GB VRAM usable after drivers):
| Model size | Q4 VRAM | Mode | Est. speed | | Model size | Q4 VRAM | Mode | Est. speed |
|---|---|---|---| | ---------- | ------- | ----------------------------- | ------------ |
| 3B | ~2.0 GB | Full GPU | ~1520 tok/s | | 3B | ~2.0 GB | Full GPU | ~1520 tok/s |
| 4B | ~2.5 GB | Full GPU | ~1218 tok/s | | 4B | ~2.5 GB | Full GPU | ~1218 tok/s |
| 7B | ~4.5 GB | Hybrid (~26/32 layers on GPU) | ~812 tok/s | | 7B | ~4.5 GB | Hybrid (~26/32 layers on GPU) | ~812 tok/s |
| 13B+ | ~8 GB+ | CPU-heavy hybrid | too slow | | 13B+ | ~8 GB+ | CPU-heavy hybrid | too slow |
### Recommended local models ### Recommended local models
@ -71,6 +71,7 @@ Two candidates worth testing, covering different points on the size/quality
tradeoff: tradeoff:
**Gemma 4 E4B Instruct (Q4 / UD-Q4_K_XL)** **Gemma 4 E4B Instruct (Q4 / UD-Q4_K_XL)**
- GGUF file: `gemma-4-E4B-it-UD-Q4_K_XL.gguf` (~2.5 GB) - GGUF file: `gemma-4-E4B-it-UD-Q4_K_XL.gguf` (~2.5 GB)
- Source: https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF - Source: https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF
- Runs fully on GPU. Brand new (April 2025), built for edge hardware, 140+ - Runs fully on GPU. Brand new (April 2025), built for edge hardware, 140+
@ -78,6 +79,7 @@ tradeoff:
to test. to test.
**Qwen2.5 7B Instruct (Q4_K_M)** **Qwen2.5 7B Instruct (Q4_K_M)**
- GGUF file: `Qwen2.5-7B-Instruct-Q4_K_M.gguf` (~4.5 GB) - GGUF file: `Qwen2.5-7B-Instruct-Q4_K_M.gguf` (~4.5 GB)
- Source: https://huggingface.co/Qwen/Qwen2.5-7B-Instruct-GGUF - Source: https://huggingface.co/Qwen/Qwen2.5-7B-Instruct-GGUF
- Runs in hybrid mode (~26 of 32 layers on GPU, rest on CPU), ~812 tok/s. - Runs in hybrid mode (~26 of 32 layers on GPU, rest on CPU), ~812 tok/s.
@ -107,6 +109,7 @@ wget -O models/qwen2.5-3b-instruct-q4_k_m.gguf \
### Starting the server ### Starting the server
**Gemma 4 E4B** (full GPU): **Gemma 4 E4B** (full GPU):
```bash ```bash
./build/bin/llama-server \ ./build/bin/llama-server \
--model models/gemma-4-e4b-it-ud-q4_k_xl.gguf \ --model models/gemma-4-e4b-it-ud-q4_k_xl.gguf \
@ -117,6 +120,7 @@ wget -O models/qwen2.5-3b-instruct-q4_k_m.gguf \
``` ```
**Qwen2.5 7B** (hybrid — tune `--n-gpu-layers` to fit your VRAM): **Qwen2.5 7B** (hybrid — tune `--n-gpu-layers` to fit your VRAM):
```bash ```bash
./build/bin/llama-server \ ./build/bin/llama-server \
--model models/qwen2.5-7b-instruct-q4_k_m.gguf \ --model models/qwen2.5-7b-instruct-q4_k_m.gguf \
@ -163,15 +167,16 @@ object changes.
Ranked by expected multilingual generation quality for en/it/de/fr/es: Ranked by expected multilingual generation quality for en/it/de/fr/es:
| Model ID | Params | Notes | | Model ID | Params | Notes |
|---|---|---| | ---------------------------------------- | --------------------- | ------------------------------------------------------------------------------------ |
| `qwen/qwen3-coder:free` | 480B MoE (35B active) | Best free option. Strong multilingual despite "coder" label. Use as quality ceiling. | | `qwen/qwen3-coder:free` | 480B MoE (35B active) | Best free option. Strong multilingual despite "coder" label. Use as quality ceiling. |
| `qwen/qwen3-next-80b-a3b-instruct:free` | 80B MoE (3B active) | Smaller Qwen, useful comparison point. | | `qwen/qwen3-next-80b-a3b-instruct:free` | 80B MoE (3B active) | Smaller Qwen, useful comparison point. |
| `nvidia/nemotron-3-super-120b-a12b:free` | 120B MoE (12B active) | 262K context, supports structured output. | | `nvidia/nemotron-3-super-120b-a12b:free` | 120B MoE (12B active) | 262K context, supports structured output. |
| `google/gemma-4-31b-it:free` | 31B | 140+ language support, good European language coverage. | | `google/gemma-4-31b-it:free` | 31B | 140+ language support, good European language coverage. |
| `zhipuai/glm-4.5-air:free` | MoE | Multilingual-focused. | | `zhipuai/glm-4.5-air:free` | MoE | Multilingual-focused. |
**Skip for this pipeline:** **Skip for this pipeline:**
- Llama models — weaker European language generation than Qwen/Gemma - Llama models — weaker European language generation than Qwen/Gemma
- Mistral free tier — requests may be used for model training - Mistral free tier — requests may be used for model training
@ -194,7 +199,7 @@ change this object and re-run.
// config.ts // config.ts
export type ProviderConfig = { export type ProviderConfig = {
name: string; // used for output folder naming name: string; // used for output folder naming
baseURL: string; baseURL: string;
apiKey: string; apiKey: string;
model: string; model: string;
@ -205,8 +210,8 @@ export type ProviderConfig = {
export const LOCAL_QWEN3B: ProviderConfig = { export const LOCAL_QWEN3B: ProviderConfig = {
name: "local-qwen2.5-3b", name: "local-qwen2.5-3b",
baseURL: "http://127.0.0.1:8080/v1", baseURL: "http://127.0.0.1:8080/v1",
apiKey: "none", // llama.cpp ignores this apiKey: "none", // llama.cpp ignores this
model: "qwen2.5-3b", // llama.cpp ignores model name, uses loaded model model: "qwen2.5-3b", // llama.cpp ignores model name, uses loaded model
maxTokens: 512, maxTokens: 512,
}; };
@ -231,7 +236,7 @@ export const OR_GEMMA4_31B: ProviderConfig = {
// Anthropic (reference baseline — different adapter required) // Anthropic (reference baseline — different adapter required)
export const ANTHROPIC_SONNET: ProviderConfig = { export const ANTHROPIC_SONNET: ProviderConfig = {
name: "anthropic-sonnet", name: "anthropic-sonnet",
baseURL: "https://api.anthropic.com/v1", // adapter handles format difference baseURL: "https://api.anthropic.com/v1", // adapter handles format difference
apiKey: process.env.ANTHROPIC_API_KEY!, apiKey: process.env.ANTHROPIC_API_KEY!,
model: "claude-sonnet-4-6", model: "claude-sonnet-4-6",
maxTokens: 512, maxTokens: 512,
@ -239,6 +244,7 @@ export const ANTHROPIC_SONNET: ProviderConfig = {
``` ```
Output from each run lands in: Output from each run lands in:
``` ```
stage-3-enrich/test/output/{provider.name}/results.json stage-3-enrich/test/output/{provider.name}/results.json
stage-3-enrich/test/output/{provider.name}/metrics.json stage-3-enrich/test/output/{provider.name}/metrics.json
@ -252,21 +258,21 @@ The evaluate script compares all `metrics.json` files side by side.
The test script measures the following per provider run: The test script measures the following per provider run:
| Metric | What it measures | | Metric | What it measures |
|---|---| | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| **JSON parse rate** | % of responses that are valid, schema-compliant JSON. Critical — a failed parse is a wasted call. Target: >97% | | **JSON parse rate** | % of responses that are valid, schema-compliant JSON. Critical — a failed parse is a wasted call. Target: >97% |
| **Field coverage** | % of records where all required fields are present (cefr votes for all translations, descriptions for all languages, glosses/examples for fr/es) | | **Field coverage** | % of records where all required fields are present (cefr votes for all translations, descriptions for all languages, glosses/examples for fr/es) |
| **CEFR agreement** | For records that have a `cefr_source` vote, % where the model agrees. Measures calibration. | | **CEFR agreement** | For records that have a `cefr_source` vote, % where the model agrees. Measures calibration. |
| **Language correctness** | Manual spot-check only — automated detection not reliable enough | | **Language correctness** | Manual spot-check only — automated detection not reliable enough |
| **Tokens/second** | Local only. Indicates overnight run feasibility | | **Tokens/second** | Local only. Indicates overnight run feasibility |
### Decision thresholds ### Decision thresholds
| Metric | Threshold | Action if below | | Metric | Threshold | Action if below |
|---|---|---| | --------------- | --------- | ---------------------------------------------- |
| JSON parse rate | < 97% | Do not use this model for production | | JSON parse rate | < 97% | Do not use this model for production |
| Field coverage | < 95% | Prompt needs revision before production | | Field coverage | < 95% | Prompt needs revision before production |
| CEFR agreement | < 70% | Model lacks vocabulary knowledge for this task | | CEFR agreement | < 70% | Model lacks vocabulary knowledge for this task |
--- ---

View file

@ -1,6 +1,5 @@
# notes # notes
## prompt ## prompt
ive attached the readme of my project. this is my current task: ive attached the readme of my project. this is my current task:
@ -46,7 +45,7 @@ laptop: verify if docker containers run on startup (they shouldnt)
### vps setup ### vps setup
- monitoring and logging (eg via chrootkit or rkhunter, logwatch/monit => mails daily with summary) - monitoring and logging (eg via chrootkit or rkhunter, logwatch/monit => mails daily with summary)
<<<<<<< HEAD <<<<<<< HEAD
- ~~keep the vps clean (e.g. old docker images/containers)~~ ✅ CI/CD pipeline runs `docker image prune -f` after deploy - ~~keep the vps clean (e.g. old docker images/containers)~~ ✅ CI/CD pipeline runs `docker image prune -f` after deploy
### ~~cd/ci pipeline~~ ✅ RESOLVED ### ~~cd/ci pipeline~~ ✅ RESOLVED
@ -55,9 +54,9 @@ Forgejo Actions with runner on VPS, Forgejo built-in container registry. See `de
### ~~postgres backups~~ ✅ RESOLVED ### ~~postgres backups~~ ✅ RESOLVED
Daily pg_dump cron job, 7-day retention, dev laptop auto-sync via rsync. See `deployment.md`. # Daily pg_dump cron job, 7-day retention, dev laptop auto-sync via rsync. See `deployment.md`.
=======
>>>>>>> dev > > > > > > > dev
### try now option ### try now option

View file

@ -1,397 +1,348 @@
# `gameService.ts` — Code Review & Fixes # 🔥 GameService Roast: `apps/api/src/services/gameService.ts`
> *"It works on my machine" is not a scalability strategy.*
**Project:** lila — Vocabulary Trainer
**File Roasted:** `gameService.ts`
**Date:** $(date)
**Roaster:** Qwen3.6
--- ---
## 1. Hardcoded singleton kills the abstraction ## 📋 Executive Summary
**Problem** | Metric | Score | Notes |
| ------------- | -------- | ---------------------------------------------------- |
A `GameSessionStore` interface exists, an `InMemoryGameSessionStore` implements it, and then the concrete class is immediately hardcoded as a module-level singleton. The interface is decorative — nothing can inject an alternative implementation without editing this file. | Code Quality | 8/10 | Clean layering, good types, consistent style |
| Correctness | 6/10 | Race condition + N+1 query are critical |
```ts | Test Coverage | 7/10 | Good happy-path tests, missing concurrency tests |
// ❌ current — store is unreachable from outside | Scalability | 5/10 | Will choke at ~100 concurrent users without fixes |
const gameSessionStore = new InMemoryGameSessionStore(); | **Overall** | **7/10** | Solid foundation, but fix the footguns before launch |
export const createGameSession = async (request: GameRequest) => { ... };
export const evaluateAnswer = async (submission: AnswerSubmission) => { ... };
```
**Fix — inject the store**
Accept the store as a parameter (or use a factory). The simplest approach that requires no framework:
```ts
// ✅ inject the store
export const createGameSession = async (
request: GameRequest,
store: GameSessionStore,
): Promise<GameSession> => { ... };
export const evaluateAnswer = async (
submission: AnswerSubmission,
store: GameSessionStore,
): Promise<AnswerResult> => { ... };
```
The call site (controller) owns the store instance and passes it in. Tests can pass a fresh `InMemoryGameSessionStore` per test — no mocking required, no shared state.
```ts
// gameController.ts
const store = new InMemoryGameSessionStore();
// later, swap for ValKeyGameSessionStore with one line change
```
--- ---
## 2. Sessions are never deleted — memory leak ## 🚨 Critical Issues (Fix Before Production)
**Problem** ### 1. Race Condition: Lost Update in `evaluateAnswer`
`GameSessionStore.delete()` is defined and implemented but never called. Every session ever created stays in the Map until the process restarts. Under real traffic this is a slow memory leak; under a spike it's a fast one. **Location:** `gameService.ts:45-58` + `InMemoryGameSessionStore.ts:update()`
**Fix — delete after answer, or add a TTL** // Current flow (VULNERABLE):
const session = await store.get(submission.sessionId); // READ
const updatedAnswers = new Map(session.answers); // MODIFY (local copy)
updatedAnswers.delete(submission.questionId);
await store.update(submission.sessionId, { answers: updatedAnswers }); // WRITE
The simplest fix: delete the session once the last question is answered. If partial completion is needed, add a TTL on creation instead. The Attack:
```ts Client submits answer A and answer B for the same question (network retry, bug, or malice)
// ✅ option A — delete on answer Both requests read the same session.answers Map (question still present)
export const evaluateAnswer = async ( Both delete the question from their local copy
submission: AnswerSubmission, Both write back → second write overwrites first
store: GameSessionStore, Result: One answer is silently lost, session state desyncs
): Promise<AnswerResult> => {
const session = await store.get(submission.sessionId);
if (!session) throw new NotFoundError(`Game session not found: ${submission.sessionId}`);
const correctOptionId = session.answers.get(submission.questionId); Why Tests Missed It: Vitest runs tests synchronously. Race conditions require deliberate concurrency testing.
if (correctOptionId === undefined) throw new NotFoundError(`Question not found: ${submission.questionId}`); Fix Options:
// delete answered question; delete session when all questions are answered // Option A: Add atomic operation to store interface
session.answers.delete(submission.questionId); interface GameSessionStore {
if (session.answers.size === 0) { deleteAnswer(sessionId: string, questionId: string): Promise<boolean>;
await store.delete(submission.sessionId); }
}
// Option B: Use Valkey Lua script for atomic read-modify-write
// Option C: Optimistic locking with version numbers
Priority: 🔴 CRITICAL — Data integrity issue
2. N+1 Query: Database Performance Bomb
Location: gameService.ts:24-26 + termModel.ts:getDistractors()
// For each of N terms, we call getDistractors():
const questions: GameQuestion[] = await Promise.all(
terms.map(async (term) => {
const distractorTexts = await getDistractors(term.termId, ...); // 🚩 N queries!
})
);
Impact Analysis:
Rounds
DB Queries
At 50 concurrent users
3
1 + 3 = 4
200 queries/min
10
1 + 10 = 11
550 queries/min
20
1 + 20 = 21
1,050 queries/min
Each getDistractors() runs:
SELECT text FROM terms
JOIN translations ON ...
WHERE pos = $1 AND difficulty = $2 AND term_id != $3 AND text != $4
ORDER BY RANDOM() LIMIT 6
Fix: Batch Fetch Distractors
// Fetch all distractors in ONE query
const allDistractors = await db
.select({ termId: terms.id, text: translations.text })
.from(terms)
.innerJoin(translations, /* ... */)
.where(and(
eq(terms.pos, pos),
eq(translations.difficulty, difficulty),
inArray(terms.id, termIds), // Batch!
))
.limit(DISTRACTOR_FETCH_COUNT * termIds.length);
// Group by termId in JS, then slice to 3 unique distractors per term
const distractorsByTerm = groupByTermId(allDistractors);
Priority: 🔴 CRITICAL — Performance/scalability issue
3. Error Handling Inconsistency
Location: gameService.ts:33-36
if (uniqueDistractors.length < 3) {
throw new Error(`Not enough unique distractors for term: ${term.targetText}`); // 🚩
}
Problem: Raw Error bypasses your errorHandler middleware:
No HTTP status mapping (defaults to 500)
No structured logging
Inconsistent API responses
Fix:
import { UnprocessableEntityError } from "../errors/AppError.js";
if (uniqueDistractors.length < 3) {
logger.warn({ termId: term.termId, uniqueCount: uniqueDistractors.length },
"insufficient_distractors");
throw new UnprocessableEntityError(
`Not enough unique distractors for term: ${term.targetText}`
);
}
Priority: 🟡 HIGH — Observability & UX issue
⚠️ High-Severity Smells
4. Code Duplication: Singleplayer vs Multiplayer
Compare: gameService.ts vs multiplayerGameService.ts
// gameService.ts
const optionTexts = [term.targetText, ...uniqueDistractors.slice(0, 3)];
const shuffledTexts = shuffleArray(optionTexts);
const correctOptionId = shuffledTexts.indexOf(term.targetText);
// multiplayerGameService.ts (lines 35-45)
const optionTexts = [correctAnswer.targetText, ...distractorTexts];
const shuffledTexts = shuffle(optionTexts); // Different function, same logic!
const correctOptionId = shuffledTexts.indexOf(correctAnswer.targetText);
Risks:
Fix shuffle bias in one place, forget the other
Add new option type (e.g., etymology hint), update one service only
Harder to test core game logic in isolation
Fix: Extract pure function to @lila/shared or new @lila/game-logic:
// packages/shared/src/game-logic.ts
export const buildQuestionOptions = (
correctAnswer: string,
distractors: string[],
optionCount: number = 4
): { options: AnswerOption[]; correctOptionId: number } => {
const uniqueDistractors = [...new Set(distractors.filter(d => d !== correctAnswer))];
const optionTexts = [correctAnswer, ...uniqueDistractors.slice(0, optionCount - 1)];
const shuffled = shuffleSecure(optionTexts);
const correctOptionId = shuffled.indexOf(correctAnswer);
return { return {
questionId: submission.questionId, options: shuffled.map((text, idx) => ({ optionId: idx, text })),
isCorrect: submission.selectedOptionId === correctOptionId, correctOptionId
correctOptionId,
selectedOptionId: submission.selectedOptionId,
}; };
}; };
```
```ts Priority: 🟡 HIGH — Maintainability issue
// ✅ option B — TTL in InMemoryGameSessionStore 5. Shuffle Bias: Math.random() Trap
export class InMemoryGameSessionStore implements GameSessionStore { Location: utils.ts:shuffleArray() + multiplayerGameService.ts:shuffle()
private sessions = new Map<string, { data: GameSessionData; expiresAt: number }>();
private readonly ttlMs: number;
constructor(ttlMs = 30 * 60 * 1000) { // 30 minutes default export const shuffleArray = <T>(array: T[]): T[] => {
this.ttlMs = ttlMs; for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // 🚩 Modulo bias + non-crypto RNG
// ...
} }
create(sessionId: string, data: GameSessionData): Promise<void> {
this.sessions.set(sessionId, { data, expiresAt: Date.now() + this.ttlMs });
return Promise.resolve();
}
get(sessionId: string): Promise<GameSessionData | null> {
const entry = this.sessions.get(sessionId);
if (!entry) return Promise.resolve(null);
if (Date.now() > entry.expiresAt) {
this.sessions.delete(sessionId);
return Promise.resolve(null);
}
return Promise.resolve(entry.data);
}
delete(sessionId: string): Promise<void> {
this.sessions.delete(sessionId);
return Promise.resolve();
}
}
```
---
## 3. `shuffle` is defined after it's used
**Problem**
`shuffle` is called inside `createGameSession` but defined below it. It works at runtime (module evaluation order), but reads as if the file was written top-to-bottom without a plan.
```ts
// ❌ shuffle appears after the function that calls it
export const createGameSession = async (...) => {
const shuffledTexts = shuffle(optionTexts); // used here
}; };
const shuffle = <T>(array: T[]): T[] => { ... }; // defined down here The Math:
```
**Fix — move helpers to the top, exports to the bottom** Math.random() has ~53 bits of entropy (fine for vocab)
Math.floor(rand * n) has modulo bias when n isn't a power of 2
For n=4: bias is ~0.01% (tiny, but non-zero)
```ts When It Matters:
// ✅ utilities first, then exported functions
const shuffle = <T>(array: T[]): T[] => { Competitive leaderboards ("option 0 is correct 26% of the time")
Achievement systems based on answer patterns
Security-sensitive features (not applicable here, but principle matters)
Fix (if needed):
import { randomBytes } from "crypto";
const shuffleSecure = <T>(array: T[]): T[] => {
const result = [...array]; const result = [...array];
for (let i = result.length - 1; i > 0; i--) { for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // Use crypto.getRandomValues for better randomness
const temp = result[i]!; const rand = randomBytes(4).readUInt32LE(0);
result[i] = result[j]!; const j = rand % (i + 1);
result[j] = temp; [result[i], result[j]] = [result[j], result[i]];
} }
return result; return result;
}; };
export const createGameSession = async (...) => { ... }; Priority: 🟢 LOW — Document tradeoff and move on for now
export const evaluateAnswer = async (...) => { ... };
```
--- 6. Test Coverage Gaps
File: gameService.test.ts
✅ Well Tested:
## 4. `rounds` is typed as a string Happy path: session creation, answer evaluation
Edge cases: duplicate distractors, empty results, invalid inputs
Error propagation from DB layer
**Problem** ❌ Missing Tests:
`GameRequest.rounds` is typed as `string` in `@lila/shared`, forcing the service to cast it every time: // 1. Concurrency test (race condition)
it("rejects duplicate answers for same question under concurrent load", async () => {
```ts const session = await createGameSession(validRequest, store, "user-1");
// ❌ why is a round count a string?
Number(request.rounds)
```
**Fix — fix the schema in `@lila/shared`**
```ts
// ✅ in packages/shared
export const GameRequestSchema = z.object({
source_language: z.string(),
target_language: z.string(),
pos: z.string(),
difficulty: z.string(),
rounds: z.coerce.number().int().min(1).max(50), // coerce handles form inputs, validates range
});
export type GameRequest = z.infer<typeof GameRequestSchema>;
```
The `z.coerce.number()` handles the case where the value arrives as a string from a query param or form — Zod does the conversion at the boundary so the rest of the system never sees a string.
---
## 5. `correctAnswers` is a misleading variable name
**Problem**
The variable holds `terms` — word pairs fetched from the database. Calling them `correctAnswers` jumps ahead semantically; they only become "correct answers" once options are constructed around them.
```ts
// ❌ these are terms, not answers yet
const correctAnswers = await getGameTerms(...);
```
**Fix**
```ts
// ✅
const terms = await getGameTerms(...);
// and inside the map:
terms.map(async (term) => {
const distractorTexts = await getDistractors(
term.termId,
term.targetText,
...
);
...
const correctOptionId = shuffledTexts.indexOf(term.targetText);
...
});
```
---
## 6. Tautological test: `"distractors are never the correct answer"`
**Problem**
The test filters the correct answer out of the options array, then asserts the remaining items are not the correct answer. It is testing that `Array.filter` works.
```ts
// ❌ this cannot fail
it("distractors are never the correct answer", async () => {
const distractorTexts = question.options
.map((o) => o.text)
.filter((t) => t !== correctText); // removes correct answer...
for (const text of distractorTexts) {
expect(text).not.toBe(correctText); // ...then checks they're not the correct answer
}
});
```
**What to actually test**
The real concern is that `getDistractors` doesn't return the target word. Test that the service handles it correctly if it does:
```ts
// ✅ test that the correct answer appears exactly once even if a distractor collides
it("correct answer appears exactly once in options even if distractor matches", async () => {
// simulate getDistractors returning the correct answer as one of the distractors
mockGetDistractors.mockResolvedValueOnce(["cane", "wrong2", "wrong3"]);
const session = await createGameSession(validRequest, new InMemoryGameSessionStore());
const question = session.questions[0]!; const question = session.questions[0]!;
const optionTexts = question.options.map((o) => o.text);
// Submit two answers simultaneously
// "cane" should only appear once regardless of the duplicate from getDistractors const [result1, result2] = await Promise.allSettled([
expect(optionTexts.filter((t) => t === "cane")).toHaveLength(1); evaluateAnswer({ sessionId, questionId, selectedOptionId: 0 }, store, "user-1"),
expect(question.options).toHaveLength(4); evaluateAnswer({ sessionId, questionId, selectedOptionId: 1 }, store, "user-1"),
]);
// Exactly one should succeed, one should throw ConflictError
expect([result1, result2].filter(r => r.status === "fulfilled")).toHaveLength(1);
}); });
```
> **Note:** the current implementation doesn't actually handle this case — a duplicate distractor would produce a 4-option list where the correct answer appears twice and one distractor slot is wasted. Worth fixing in `createGameSession` alongside the test. // 2. TTL expiration test
it("deletes session after TTL expires", async () => {
--- vi.useFakeTimers();
const session = await createGameSession(validRequest, store, "user-1");
## 7. Store not reset between tests
vi.advanceTimersByTime(31 * 60 * 1000); // 31 minutes
**Problem**
await expect(store.get(session.sessionId)).resolves.toBeNull();
`beforeEach` calls `vi.clearAllMocks()` which resets mock functions, but the `gameSessionStore` module-level singleton is never cleared. Ghost sessions from earlier tests persist for the entire test run.
It doesn't bite today because each session gets a unique UUID and tests don't share IDs — but it's one non-UUID lookup away from a very confusing afternoon.
**Fix — a consequence of fixing issue #1**
Once the store is injected rather than module-level, each test creates its own instance:
```ts
// ✅ no shared state, no ghost sessions
describe("evaluateAnswer", () => {
it("returns isCorrect: true for correct option", async () => {
const store = new InMemoryGameSessionStore();
const session = await createGameSession(validRequest, store);
...
const result = await evaluateAnswer({ ... }, store);
...
});
}); });
```
No `beforeEach` cleanup needed — the store simply doesn't outlive the test that created it. // 3. Distractor fallback strategy test
it("uses fallback when <3 unique distractors available", async () => {
mockGetDistractors.mockResolvedValue(["same", "same", "same", "same"]);
// Should either: (a) fetch from broader pool, or (b) reduce rounds gracefully
});
--- Priority: 🟡 HIGH — Prevents regression on critical fixes
🧼 Code Quality Nitpicks
7. Magic Numbers
## 8. No answer replay protection // gameService.ts:52
await store.create(sessionId, {...}, 30 * 60 * 1000); // What is this?
**Problem** // termModel.ts:65
.limit(count); // count=6, but why?
`evaluateAnswer` can be called multiple times with the same `questionId`. The // shared/schemas/game.ts:15
service will evaluate it every time. In multiplayer this could be abused to optionId: z.number().int().min(0).max(3), // Why 4 options?
farm points or desync state.
**Fix — delete the question from the answer key after first evaluation** Fix: Centralize in @lila/shared/constants.ts:
```ts export const GAME_SESSION_TTL_MS = 30 * 60 * 1000;
// ✅ inside evaluateAnswer, after retrieving correctOptionId export const DISTRACTOR_FETCH_COUNT = 6;
session.answers.delete(submission.questionId); export const GAME_OPTION_COUNT = 4;
export const MIN_UNIQUE_DISTRACTORS = 3;
if (submission.selectedOptionId !== correctOptionId) { 8. Mutable Reference Leakage
// already removed — can't retry Location: InMemoryGameSessionStore.ts:get()
get(sessionId: string): Promise<GameSessionData | null> {
return Promise.resolve(entry.data); // 🚩 Returns mutable reference to internal state
} }
```
Once the question key is deleted, a second submission hits the Risk: Any code that does session.answers.delete(...) mutates the store's internal Map directly.
`correctOptionId === undefined` branch and throws `NotFoundError`. One shot Fix:
per question.
--- // Option A: Deep clone (simple, works for this data shape)
return Promise.resolve(structuredClone(entry.data));
## 9. No ownership check in `evaluateAnswer` // Option B: Return readonly view (TypeScript-only protection)
return Promise.resolve(entry.data as Readonly<GameSessionData>);
**Problem** // Option C: Use immutable data structures (overkill for now)
The service accepts any `sessionId` without verifying it belongs to the 9. Zero Observability
requesting user. If auth middleware doesn't tie sessions to users at a higher Problem: No logging, no metrics. You're flying blind in production.
layer, Alice can submit answers for Bob's session by guessing or intercepting Minimal Fix (5 minutes):
his `sessionId`.
**Fix — store `userId` alongside the session and assert it on retrieval**
```ts
// GameSessionStore.ts
export type GameSessionData = {
answers: Map<string, number>;
userId: string;
};
// evaluateAnswer // apps/api/src/lib/logger.ts
const session = await store.get(submission.sessionId); import pino from "pino";
export const logger = pino({
if (!session) throw new NotFoundError(`Game session not found`); level: process.env.LOG_LEVEL || "info",
if (session.userId !== requestingUserId) throw new NotFoundError(`Game session not found`); transport: process.env.NODE_ENV === "production"
// ^^^ same error — don't confirm the session exists to the wrong user ? { target: "pino-pretty" }
``` : undefined
Pass `requestingUserId` in from the controller, where it's already available
via auth middleware.
---
## 10. No test for empty `getGameTerms` result
**Problem**
If the database returns zero terms (no words match the difficulty/language/pos
filter), `createGameSession` happily returns a session with an empty
`questions` array. The frontend receives it, tries to render question 1, and
crashes. The user sees nothing useful.
**Fix — guard in the service and add a test**
```ts
// ✅ inside createGameSession, after fetching terms
if (terms.length === 0) {
throw new AppError("No terms found for the given filters", 404);
}
```
```ts
// ✅ test
it("throws when getGameTerms returns no terms", async () => {
mockGetGameTerms.mockResolvedValue([]);
await expect(createGameSession(validRequest, new InMemoryGameSessionStore()))
.rejects.toThrow("No terms found");
}); });
```
--- // In gameService.ts:
import { logger } from "../lib/logger.js";
## 11. No test for `getDistractors` rejection logger.info(
{ userId, sourceLang, targetLang, termCount: terms.length },
"game_session_created"
);
**Problem** logger.debug(
{ sessionId, questionId, isCorrect, responseTimeMs },
"answer_evaluated"
);
`createGameSession` uses `Promise.all` over the terms array. If Bonus: Export a Prometheus histogram for game_service_duration_seconds.
`getDistractors` rejects for any single term, the entire `Promise.all` rejects
— no session is created, no partial recovery, the user gets a 500 with
"connection refused" leaking through.
**Fix — test the failure path and consider a fallback** 10. ORDER BY RANDOM() Time Bomb
Location: termModel.ts:getGameTerms() + getDistractors()
```ts .orderBy(sql`RANDOM()`) // 🚩 Fine for 10k rows, slow for 1M
// ✅ test
it("propagates getDistractors failure", async () => {
mockGetDistractors.mockRejectedValue(new Error("db timeout"));
await expect(createGameSession(validRequest, new InMemoryGameSessionStore())) The Comment Admits It:
.rejects.toThrow("db timeout");
});
```
For resilience, consider catching per-term distractor failures and falling back // TODO(post-mvp): ORDER BY RANDOM() sorts the entire filtered result set...
to random terms from the already-fetched set rather than collapsing the whole
session. Reality Check: "Post-MVP" never comes without a ticket.
Fix Options:
-- Option A: Pre-computed random_seed column (updated nightly)
WHERE ... AND random_seed >= random()
ORDER BY random_seed
LIMIT $1
-- Option B: TABLESAMPLE for approximate sampling (Postgres 9.5+)
FROM terms TABLESAMPLE SYSTEM(10)
WHERE ...
LIMIT $1
-- Option C: Random offset (simple, but still scans)
OFFSET floor(random() * (SELECT count(*) FROM terms WHERE ...))
Action: Add a ticket to documentation/tickets/t00009.md now.

View file

@ -51,9 +51,9 @@ This is the full vision. The current implementation already covers most of it; r
### What is CUT from the MVP ### What is CUT from the MVP
| Feature | Why cut | | Feature | Why cut |
| ------------------------------- | -------------------------------------- | | --------------------- | ---------- |
| User stats / profiles | Needs auth | | User stats / profiles | Needs auth |
These are not deleted from the plan — they are deferred. The architecture is already designed to support them. See Section 11 (Post-MVP Ladder). These are not deleted from the plan — they are deferred. The architecture is already designed to support them. See Section 11 (Post-MVP Ladder).
@ -63,22 +63,22 @@ These are not deleted from the plan — they are deferred. The architecture is a
The monorepo structure and tooling are already set up. This is the full stack. The monorepo structure and tooling are already set up. This is the full stack.
| Layer | Technology | Status | | Layer | Technology | Status |
| ------------ | ------------------------------ | ----------- | | ------------ | ------------------------------ | ------------------------------------------------------ |
| Monorepo | pnpm workspaces | ✅ | | Monorepo | pnpm workspaces | ✅ |
| Frontend | React 18, Vite, TypeScript | ✅ | | Frontend | React 18, Vite, TypeScript | ✅ |
| Routing | TanStack Router | ✅ | | Routing | TanStack Router | ✅ |
| Server state | TanStack Query | ✅ | | Server state | TanStack Query | ✅ |
| Client state | Zustand | ✅ | | Client state | Zustand | ✅ |
| Styling | Tailwind CSS + shadcn/ui | ✅ | | Styling | Tailwind CSS + shadcn/ui | ✅ |
| Backend | Node.js, Express, TypeScript | ✅ | | Backend | Node.js, Express, TypeScript | ✅ |
| Database | PostgreSQL + Drizzle ORM | ✅ | | Database | PostgreSQL + Drizzle ORM | ✅ |
| Validation | Zod (shared schemas) | ✅ | | Validation | Zod (shared schemas) | ✅ |
| Testing | Vitest, supertest | ✅ | | Testing | Vitest, supertest | ✅ |
| Auth | Better Auth (Google + GitHub) | ✅ | | Auth | Better Auth (Google + GitHub) | ✅ |
| Deployment | Docker Compose, Caddy, Hetzner | ✅ | | Deployment | Docker Compose, Caddy, Hetzner | ✅ |
| CI/CD | Forgejo Actions | ✅ | | CI/CD | Forgejo Actions | ✅ |
| Realtime | WebSockets (`ws` library) | ✅ | | Realtime | WebSockets (`ws` library) | ✅ |
| Cache | Valkey | ⚠️ optional (used locally; production/state hardening) | | Cache | Valkey | ⚠️ optional (used locally; production/state hardening) |
--- ---
@ -288,26 +288,27 @@ After completing a task: share the code, ask what to refactor and why. The LLM s
## 11. Post-MVP Ladder ## 11. Post-MVP Ladder
<<<<<<< HEAD <<<<<<< HEAD
| Phase | What it adds | Status | | Phase | What it adds | Status |
| ----------------- | ------------------------------------------------------------------------------- | ------ | | ----------------- | ------------------------------------------------------------------------------- | ------ |
| Auth | Better Auth (Google + GitHub), embedded in Express API, user rows in DB | ✅ | | Auth | Better Auth (Google + GitHub), embedded in Express API, user rows in DB | ✅ |
| Deployment | Docker Compose, Caddy, Forgejo, CI/CD, Hetzner VPS | ✅ | | Deployment | Docker Compose, Caddy, Forgejo, CI/CD, Hetzner VPS | ✅ |
| Hardening (partial) | CI/CD pipeline, DB backups | ✅ | | Hardening (partial) | CI/CD pipeline, DB backups | ✅ |
| User Stats | Games played, score history, profile page | ❌ | | User Stats | Games played, score history, profile page | ❌ |
| Multiplayer Lobby | Room creation, join by code, WebSocket connection | ❌ | | Multiplayer Lobby | Room creation, join by code, WebSocket connection | ❌ |
| Multiplayer Game | Simultaneous answers, server timer, live scores, winner screen | ❌ | | Multiplayer Game | Simultaneous answers, server timer, live scores, winner screen | ❌ |
| Hardening (rest) | Rate limiting, error boundaries, monitoring, accessibility | ❌ | | Hardening (rest) | Rate limiting, error boundaries, monitoring, accessibility | ❌ |
======= =======
| Phase | What it adds | Status | | Phase | What it adds | Status |
| ------------------- | ----------------------------------------------------------------------- | ------ | | ------------------- | ----------------------------------------------------------------------- | ------ |
| Auth | Better Auth (Google + GitHub), embedded in Express API, user rows in DB | ✅ | | Auth | Better Auth (Google + GitHub), embedded in Express API, user rows in DB | ✅ |
| Deployment | Docker Compose, Caddy, Forgejo, CI/CD, Hetzner VPS | ✅ | | Deployment | Docker Compose, Caddy, Forgejo, CI/CD, Hetzner VPS | ✅ |
| Hardening (partial) | CI/CD pipeline, DB backups | ✅ | | Hardening (partial) | CI/CD pipeline, DB backups | ✅ |
| User Stats | Games played, score history, profile page | ❌ | | User Stats | Games played, score history, profile page | ❌ |
| Multiplayer Lobby | Room creation, join by code, WebSocket connection | ✅ | | Multiplayer Lobby | Room creation, join by code, WebSocket connection | ✅ |
| Multiplayer Game | Simultaneous answers, server timer, live scores, winner screen | ✅ | | Multiplayer Game | Simultaneous answers, server timer, live scores, winner screen | ✅ |
| Hardening (rest) | Rate limiting, error boundaries, monitoring, accessibility | ❌ | | Hardening (rest) | Rate limiting, error boundaries, monitoring, accessibility | ❌ |
>>>>>>> dev
> > > > > > > dev
### Future Data Model Extensions (deferred, additive) ### Future Data Model Extensions (deferred, additive)

View file

@ -1,11 +1,12 @@
# Ticket Blueprint # Ticket Blueprint
Two formats depending on task type. Choose based on whether a meaningful Two formats depending on task type. Choose based on whether a meaningful
decision between options was made. decision between options was made.
--- ---
## Format A — ADR (architectural/infrastructural decisions) ## Format A — ADR (architectural/infrastructural decisions)
Use when: you chose between options with long-term consequences. Use when: you chose between options with long-term consequences.
Prefix: `adr-` Prefix: `adr-`
@ -14,45 +15,56 @@ Prefix: `adr-`
# ADR: <title> # ADR: <title>
## Status ## Status
Accepted | Superseded by | Deprecated Accepted | Superseded by | Deprecated
## Date ## Date
YYYY-MM-DD YYYY-MM-DD
## Context ## Context
What is the problem? Why does it need to be solved? What is the problem? Why does it need to be solved?
## Decision ## Decision
What was chosen and why in one or two sentences. What was chosen and why in one or two sentences.
## Options considered ## Options considered
### Option A — <name> ### Option A — <name>
Description. Why it was chosen. Description. Why it was chosen.
### Option B — <name> ### Option B — <name>
Description. Why it was rejected. Description. Why it was rejected.
## Consequences ## Consequences
- What gets better - What gets better
- What gets worse or more complex - What gets worse or more complex
- Operational implications - Operational implications
- What breaks if this needs to be redone - What breaks if this needs to be redone
## Affected files / machines ## Affected files / machines
- List files, servers, or systems touched - List files, servers, or systems touched
## References ## References
- Links to relevant docs - Links to relevant docs
--- ---
## Setup guide / implementation notes ## Setup guide / implementation notes
Step-by-step of what was actually done. Step-by-step of what was actually done.
--- ---
## Format B — Task (features, fixes, chores) ## Format B — Task (features, fixes, chores)
Use when: routine task with a clear solution. Use when: routine task with a clear solution.
Prefix: `feat-` / `fix-` / `chore-` Prefix: `feat-` / `fix-` / `chore-`
@ -61,17 +73,23 @@ Prefix: `feat-` / `fix-` / `chore-`
# <prefix>: <title> # <prefix>: <title>
## Problem ## Problem
What was wrong or missing? What was wrong or missing?
## Options considered ## Options considered
### Option A — <name> ### Option A — <name>
### Option B — <name> ### Option B — <name>
## Solution ## Solution
What was done and why. What was done and why.
## Files changed ## Files changed
- `path/to/file.ts` - `path/to/file.ts`
## Commit ## Commit
`<type>: <message>` `<type>: <message>`

View file

@ -1,49 +1,52 @@
# ADR: Docker Credential Helper Setup # ADR: Docker Credential Helper Setup
## Status ## Status
Accepted Accepted
## Date ## Date
2026-04-26 2026-04-26
## Context ## Context
Docker credentials for `git.lilastudy.com` and `dhi.io` were stored as
base64-encoded strings in `~/.docker/config.json` on both the dev laptop Docker credentials for `git.lilastudy.com` and `dhi.io` were stored as base64-encoded strings in `~/.docker/config.json` on both the dev laptop and the VPS. Base64 is not encryption — anyone with read access to the file can decode the credentials instantly.
and the VPS. Base64 is not encryption — anyone with read access to the
file can decode the credentials instantly.
## Decision ## Decision
Use `pass` (GPG-backed password store) as the Docker credential helper
on both machines. Use `pass` (GPG-backed password store) as the Docker credential helper on both machines.
## Options considered ## Options considered
### Option A — `pass` (GPG-backed) ✅ ### Option A — `pass` (GPG-backed) ✅
Stores credentials encrypted with a GPG key. Works on headless servers
and desktops without GNOME. Industry standard for Linux servers. Stores credentials encrypted with a GPG key. Works on headless servers and desktops without GNOME. Industry standard for Linux servers.
### Option B — `secretservice` (GNOME keyring) ### Option B — `secretservice` (GNOME keyring)
Uses the desktop keyring daemon. Not suitable for a headless VPS, and
not suitable for an i3 desktop without running `gnome-keyring-daemon` Uses the desktop keyring daemon. Not suitable for a headless VPS, and not suitable for an i3 desktop without running `gnome-keyring-daemon` manually.
manually.
### Option C — `gnome-libsecret` ### Option C — `gnome-libsecret`
Same limitations as Option B. Same limitations as Option B.
## Consequences ## Consequences
- Credentials are now GPG-encrypted at rest on both machines - Credentials are now GPG-encrypted at rest on both machines
- Requires GPG passphrase entry when Docker needs to pull credentials - Requires GPG passphrase entry when Docker needs to pull credentials
in a new session in a new session
- Must be set up manually on each machine — not reproducible via the repo - Must be set up manually on each machine — not reproducible via the repo
- VPS setup must be repeated if the server is reprovisioned - VPS setup must be repeated if the server is reprovisioned
## Affected machines ## Affected machines
- Dev laptop (Debian 13, i3) - Dev laptop (Debian 13, i3)
- VPS (Debian 13, ARM64, headless) - VPS (Debian 13, ARM64, headless)
## References ## References
- https://docs.docker.com/reference/cli/docker/login/#credential-stores
- https://www.passwordstore.org/ - [docker docs](https://docs.docker.com/reference/cli/docker/login/#credential-stores)
- [pass docs](https://www.passwordstore.org/)
--- ---
@ -52,36 +55,43 @@ Same limitations as Option B.
Repeat these steps on each machine. Repeat these steps on each machine.
### 1. Install dependencies ### 1. Install dependencies
```bash ```bash
sudo apt-get install -y pass gnupg2 golang-docker-credential-helpers sudo apt-get install -y pass gnupg2 golang-docker-credential-helpers
``` ```
### 2. Generate a GPG key ### 2. Generate a GPG key
```bash ```bash
gpg --full-generate-key gpg --full-generate-key
``` ```
Choose RSA, 4096 bits, no expiry. Set a strong passphrase. Choose RSA, 4096 bits, no expiry. Set a strong passphrase.
### 3. Get the key ID ### 3. Get the key ID
```bash ```bash
gpg --list-secret-keys --keyid-format LONG gpg --list-secret-keys --keyid-format LONG
``` ```
Copy the hex string after the `/` on the `sec` line. Copy the hex string after the `/` on the `sec` line.
### 4. Initialise pass ### 4. Initialise pass
```bash ```bash
pass init <your-key-id> pass init <your-key-id>
``` ```
### 5. Update `~/.docker/config.json` ### 5. Update `~/.docker/config.json`
Replace the entire file contents with: Replace the entire file contents with:
```json ```json
{ { "credsStore": "pass" }
"credsStore": "pass"
}
``` ```
### 6. Re-login to registries ### 6. Re-login to registries
```bash ```bash
docker login git.lilastudy.com docker login git.lilastudy.com
# dev laptop only: # dev laptop only:
@ -89,7 +99,9 @@ docker login dhi.io
``` ```
### 7. Verify ### 7. Verify
```bash ```bash
cat ~/.docker/config.json cat ~/.docker/config.json
``` ```
Should show only `"credsStore": "pass"` with no `auths` block. Should show only `"credsStore": "pass"` with no `auths` block.

View file

@ -0,0 +1,149 @@
# ADR: Change GAME_ROUNDS from strings to numbers
## Status
Accepted
## Date
2026-04-28
## Context
`GAME_ROUNDS` in `packages/shared/src/constants.ts` was typed as `["3", "10"] as const`, making `GameRounds` a string union (`"3" | "10"`). This meant `gameService.ts` had to cast the value with `Number(request.rounds)` deep in business logic — a type conversion happening far from the boundary where data enters the system. The type system was lying: `rounds` was described as a string everywhere but used as a number where it mattered.
## Decision
Change `GAME_ROUNDS` to `[3, 10] as const` and update the Zod schema to use `z.literal(GAME_ROUNDS)` instead of `z.enum(GAME_ROUNDS)`. The single source of truth remains `constants.ts` — adding a new round count (e.g. `20`) requires only editing that file.
## Options considered
### Option A — Numbers everywhere ✅
Change `GAME_ROUNDS` to `[3, 10] as const`. Use `z.literal(GAME_ROUNDS)` in the schema. Update the frontend component state and `SettingGroup` props. Drop `Number()` cast in the service.
Chosen because: JSON carries numbers natively, both ends of the wire are owned by this codebase, and type conversions belong at the boundary — not inside business logic.
### Option B — Keep strings, accept the cast
Leave `GAME_ROUNDS` as `["3", "10"]`. The `Number()` cast stays in `gameService.ts`.
Rejected because: it pushes type conversion into business logic and makes the inferred `GameRequest` type misleading. The cast has to live somewhere — the schema boundary is the right place.
### Option C — Coerce at the schema boundary
Keep `GAME_ROUNDS` as numbers but use `z.coerce.number().pipe(z.literal(GAME_ROUNDS))` so the frontend can keep sending strings.
Rejected because: coercion is for untrusted or uncontrolled inputs (form fields, query params, third-party clients). We control both ends of the wire. Coercing a self-inflicted type mismatch is treating a wound we gave ourselves.
## Consequences
- `GameRounds` is now `3 | 10` instead of `"3" | "10"`
- `Number(request.rounds)` cast removed from `gameService.ts`
- `SettingGroup` in `GameSetup.tsx` now accepts `string | number` options
- `useState<string>` for rounds changed to `useState<number>`
- Adding a new round count requires only editing `GAME_ROUNDS` in `constants.ts`
- `z.enum` cannot be used for number literals — `z.literal` must be used instead (this is a Zod constraint, not a project convention)
## Affected files
- `packages/shared/src/constants.ts`
- `packages/shared/src/schemas/game.ts`
- `apps/api/src/services/gameService.ts`
- `apps/api/src/services/gameService.test.ts`
- `apps/api/src/controllers/gameController.test.ts`
- `apps/web/src/components/game/GameSetup.tsx`
## References
- [Zod literals](https://zod.dev/?id=literals)
---
## Setup guide / implementation notes
1. In `packages/shared/src/constants.ts`, change:
```ts
export const GAME_ROUNDS = ["3", "10"] as const;
```
to:
```ts
export const GAME_ROUNDS = [3, 10] as const;
```
2. In `packages/shared/src/schemas/game.ts`, change:
```ts
rounds: z.enum(GAME_ROUNDS),
```
to:
```ts
rounds: z.literal(GAME_ROUNDS),
```
3. In `apps/api/src/services/gameService.ts`, change:
```ts
Number(request.rounds),
```
to:
```ts
request.rounds,
```
4. In `apps/api/src/services/gameService.test.ts`, change:
```ts
rounds: "3",
```
to:
```ts
rounds: 3,
```
5. In `apps/api/src/controllers/gameController.test.ts`, change:
```ts
rounds: "3",
```
to:
```ts
rounds: 3,
```
Also add a pinning test before the refactor:
```ts
it("returns 400 when rounds has an invalid value", async () => {
const res = await request(app)
.post("/api/v1/game/start")
.send({ ...validBody, rounds: "invalid" });
expect(res.status).toBe(400);
expect(res.body.success).toBe(false);
});
```
6. In `apps/web/src/components/game/GameSetup.tsx`:
- Update `SettingGroup` props to accept `string | number`:
```ts
type SettingGroupProps = {
options: readonly (string | number)[];
selected: string | number;
onSelect: (value: string | number) => void;
};
```
- Update `LABELS` lookup to `LABELS[String(option)]`
- Change rounds state from `useState<string>` to `useState<number>`

View file

@ -0,0 +1,37 @@
# refactor: extract shuffleArray to lib/utils, rename correctAnswers to terms
## Problem
Two readability issues in `gameService.ts`:
1. `shuffle` was defined as a private function at the bottom of `gameService.ts`, after the function that calls it. It is a pure generic utility with no dependency on game domain logic, so it had no business living there.
2. The variable holding terms fetched from the database was named `correctAnswers`. These are word pairs — they only become "correct answers" once options are built around them. The name was premature and misleading.
## Options considered
### Option A — Move `shuffle` up in the same file
Simple, no new files. Fixes the ordering issue but keeps a generic utility buried in domain code.
### Option B — Extract to `lib/utils.ts`
Move `shuffle` (renamed `shuffleArray`) to `apps/api/src/lib/utils.ts` and import it. Cleaner separation: domain logic stays in services, generic utilities live in `lib/`.
Chosen because `lib/` already exists, the function is reusable, and it gives future utilities a home.
## Solution
- Created `apps/api/src/lib/utils.ts` with `shuffleArray`
- Renamed `shuffle``shuffleArray` for clarity at the call site
- Removed the inline `shuffle` from `gameService.ts` and imported from `lib/utils.ts`
- Renamed `correctAnswers``terms` and `correctAnswer``term` throughout `gameService.ts`
## Files changed
- `apps/api/src/lib/utils.ts` — created
- `apps/api/src/services/gameService.ts` — removed `shuffle`, updated import, renamed variables
## Commit
`refactor: extract shuffleArray to lib/utils, rename correctAnswers to terms`

View file

@ -0,0 +1,110 @@
# ADR: Dependency injection for GameSessionStore via composition root
## Status
Accepted
## Date
2026-04-28
## Context
`gameService.ts` had a module-level singleton:
```ts
const gameSessionStore = new InMemoryGameSessionStore();
```
This made the store invisible to anything outside the file. The `GameSessionStore` interface existed to make the store swappable — but the singleton made that impossible without editing the service itself. Tests shared the same instance across every test run, creating the potential for ghost sessions leaking between tests. The controller also briefly owned the singleton during an intermediate step, which violated the principle that controllers should only handle HTTP concerns.
## Decision
Adopt a composition root pattern. The store is created once in `createApp()` and passed down through factory functions: `createApiRouter(store)``createGameRouter(store)``createGameController(store)` → service calls. Neither the controller nor the service knows which implementation they're working with — they both see `GameSessionStore`.
## Options considered
### Option A — Composition root ✅
Convert routers and controllers to factory functions. Create the store in `createApp()` and pass it down. The store is created once, at the top, and injected through the call chain.
Chosen because: clean separation of concerns, no layer below `createApp()` needs to know the concrete implementation, swapping to `ValKeyGameSessionStore` is a one-line change in `app.ts`, and tests get fresh isolated store instances.
### Option B — Keep singleton in controller
Leave the store as a module-level singleton in `gameController.ts`. Controllers own the store lifetime.
Rejected because: controllers should only handle HTTP concerns. Owning infrastructure lifetime is not an HTTP concern.
### Option C — DI framework (tsyringe, inversify)
Use a proper dependency injection container.
Rejected because: overkill for the current scale. The composition root pattern achieves the same result with zero dependencies and no magic.
## Consequences
- Swapping `InMemoryGameSessionStore` for `ValKeyGameSessionStore` requires editing one line in `app.ts`
- Tests create fresh `InMemoryGameSessionStore` instances per test — no shared state, no ghost sessions
- Routers and controllers are now factory functions instead of module-level singletons — slightly more verbose but explicitly testable
- `gameController.test.ts` uses `createApp()` which owns the store — controller tests remain integration-style and unaffected
- All layers below `createApp()` depend only on the `GameSessionStore` interface, never the concrete implementation
## Affected files
- `apps/api/src/app.ts` — creates the store, passes to `createApiRouter`
- `apps/api/src/routes/apiRouter.ts` — converted to `createApiRouter(store)` factory
- `apps/api/src/routes/gameRouter.ts` — converted to `createGameRouter(store)` factory
- `apps/api/src/controllers/gameController.ts` — converted to `createGameController(store)` factory
- `apps/api/src/services/gameService.ts``store` parameter added to both functions, singleton removed
- `apps/api/src/services/gameService.test.ts` — fresh store per describe block via `beforeEach`
## References
- [Composition root pattern](https://blog.ploeh.dk/2011/07/28/CompositionRoot/)
---
## Setup guide / implementation notes
1. `gameService.ts` — remove module-level singleton, add `store: GameSessionStore` parameter to `createGameSession` and `evaluateAnswer`
2. `gameController.ts` — convert exported functions to a factory:
```ts
export const createGameController = (store: GameSessionStore) => ({
createGame: async (req, res, next) => { ... },
submitAnswer: async (req, res, next) => { ... },
});
```
3. `gameRouter.ts` — convert to factory:
```ts
export const createGameRouter = (store: GameSessionStore): Router => {
const router = express.Router();
const controller = createGameController(store);
router.post("/start", controller.createGame);
router.post("/answer", controller.submitAnswer);
return router;
};
```
4. `apiRouter.ts` — convert to factory:
```ts
export const createApiRouter = (store: GameSessionStore): Router => {
const router = express.Router();
router.use("/game", createGameRouter(store));
return router;
};
```
5. `app.ts` — create the store at the composition root:
```ts
const store = new InMemoryGameSessionStore();
app.use("/api/v1", createApiRouter(store));
```
6. `gameService.test.ts` — add `let store: InMemoryGameSessionStore` to each `describe` block, reset in `beforeEach`, pass to every service call

View file

@ -0,0 +1,93 @@
# ADR: Session lifecycle — TTL and replay protection
## Status
Accepted
## Date
2026-04-28
## Context
`InMemoryGameSessionStore` had no TTL and no cleanup mechanism. Every session created stayed in memory until the process restarted. Additionally, `evaluateAnswer` never removed a question from the answer key after evaluating it, meaning the same question could be submitted multiple times and receive a valid result each time — a potential exploit in multiplayer and a correctness bug in singleplayer.
## Decision
Add a `ttlMs` parameter to `GameSessionStore.create()` so both the in-memory and future Valkey implementations handle expiry consistently. Delete questions from the answer key after evaluation. Delete the session when the last question is answered.
## Options considered
### Option A — Delete on last answer only
Simple. Covers replay protection and normal session completion. Abandoned sessions (player starts game, never finishes) still leak memory.
### Option B — Delete on last answer + TTL on the interface ✅
Delete on answer covers normal flow. TTL covers abandoned sessions. TTL on the interface means `ValKeyGameSessionStore` can use Redis-native `EXPIRE` without any interface changes during migration.
Chosen because it closes the memory leak entirely and makes the Valkey migration a zero-interface-change operation.
### Option C — TTL hardcoded inside InMemoryGameSessionStore only
Simpler short-term. But the interface wouldn't carry the TTL parameter, so `ValKeyGameSessionStore` would need a different mechanism — inconsistency between implementations.
## Consequences
- Sessions expire after 30 minutes of inactivity regardless of completion state
- Submitting the same question twice throws `NotFoundError` on the second attempt
- Sessions are deleted automatically when the last question is answered
- `GameSessionStore.create()` now requires a `ttlMs` argument — any future implementation must honour it
- `ValKeyGameSessionStore` can implement TTL via Redis `EXPIRE` with no interface changes
- `InMemoryGameSessionStore` stores `{ data, expiresAt }` entries instead of raw `GameSessionData` — expiry is checked lazily on `get()`
## Affected files
- `apps/api/src/gameSessionStore/GameSessionStore.ts``ttlMs` added to `create`
- `apps/api/src/gameSessionStore/InMemoryGameSessionStore.ts` — TTL implementation
- `apps/api/src/gameSessionStore/InMemoryGameSessionStore.test.ts` — new test file
- `apps/api/src/services/gameService.ts` — passes TTL to `store.create`, deletes question after evaluation, deletes session when empty
- `apps/api/src/services/gameService.test.ts` — replay protection and session cleanup tests added
## References
- [Redis EXPIRE command](https://redis.io/commands/expire/)
---
## Setup guide / implementation notes
1. `GameSessionStore.ts` — add `ttlMs` to `create`:
```ts
create(sessionId: string, data: GameSessionData, ttlMs: number): Promise<void>;
```
2. `InMemoryGameSessionStore.ts` — wrap stored data with expiry:
```ts
type SessionEntry = { data: GameSessionData; expiresAt: number };
```
Check expiry on `get()`, delete expired entries lazily.
3. `gameService.ts` — pass TTL when creating session:
```ts
await store.create(sessionId, { answers: answerKey }, 30 * 60 * 1000);
```
After evaluating an answer:
```ts
session.answers.delete(submission.questionId);
if (session.answers.size === 0) {
await store.delete(submission.sessionId);
}
```
4. When implementing `ValKeyGameSessionStore`, pass `ttlMs` to Redis `EXPIRE`:
```ts
await valkey.set(sessionId, serialize(data), "EX", Math.ceil(ttlMs / 1000));
```

View file

@ -0,0 +1,125 @@
# ADR: Session ownership check and AuthenticatedRequest type
## Status
Accepted
## Date
2026-04-28
## Context
`evaluateAnswer` accepted any `sessionId` without verifying it belonged to the requesting user. The only protection was the unguessability of a UUID — security through obscurity. If a user intercepted or guessed another user's `sessionId`, they could submit answers on their behalf.
Additionally, protected controller handlers typed their `req` parameter as `Request`, making `session` optional even though `requireAuth` middleware guarantees it is present. This required non-null assertions (`req.session!`) in business logic — a type assertion that could cause a runtime crash if middleware ordering ever changed.
## Decision
Store `userId` in `GameSessionData`. Pass `userId` from the controller into both `createGameSession` and `evaluateAnswer`. Assert ownership on evaluation — if the session's `userId` doesn't match the requesting user's ID, throw `NotFoundError`. Introduce `AuthenticatedRequest` to eliminate non-null assertions in protected handlers.
## Options considered
### Option A — AuthenticatedRequest type ✅
Define `AuthenticatedRequest = Request & { session: { session: Session; user: User } }` in `types/express.d.ts`. Use it in protected controller handlers instead of `Request`. Requires a single `as express.RequestHandler` cast at route registration due to Express's type limitations.
Chosen because: eliminates dangerous non-null assertions in business logic. The cast at route registration is a necessary cast caused by a third-party library limitation, not uncertain logic.
### Option B — Non-null assertion (`req.session!`)
Keep `Request` on all handlers. Assert `req.session!` at every usage.
Rejected because: non-null assertions in business logic are dangerous — if middleware ordering ever changes, the assertion silently passes and crashes at runtime.
---
### Option C — NotFoundError (404) on ownership failure ✅
When a session exists but belongs to a different user, throw `NotFoundError` with the same message as a missing session.
Chosen because: session IDs are opaque secrets. Returning 403 would confirm to the caller that the session ID is valid and belongs to someone else — information they shouldn't have. This pattern is used by GitHub, AWS, and most security-conscious APIs.
### Option D — ForbiddenError (403) on ownership failure
Explicit error that distinguishes "not found" from "not allowed".
Rejected because: for user-owned resources identified by opaque IDs, confirming existence to an unauthorised caller is an information leak. 404 is the industry standard for this case.
## Consequences
- Alice cannot submit answers for Bob's session — ownership is verified at the service layer
- `req.session.user.id` is accessible without non-null assertions in protected handlers
- `GameSessionData` now carries `userId` — any future `GameSessionStore` implementation must store and return it
- Route registration requires `as express.RequestHandler` cast for protected handlers — one cast per route, in wiring code only
- `ValKeyGameSessionStore` must serialise and deserialise `userId` alongside `answers`
## Affected files
- `apps/api/src/types/express.d.ts``AuthenticatedRequest` type added
- `apps/api/src/gameSessionStore/GameSessionStore.ts``userId` added to `GameSessionData`
- `apps/api/src/gameSessionStore/InMemoryGameSessionStore.test.ts` — updated data fixtures
- `apps/api/src/services/gameService.ts``userId` parameter added to both functions, ownership assertion in `evaluateAnswer`
- `apps/api/src/services/gameService.test.ts` — updated all calls, ownership test added
- `apps/api/src/controllers/gameController.ts` — extracts `userId` from `req.session.user.id`, passes to service calls
- `apps/api/src/routes/gameRouter.ts``as express.RequestHandler` cast at route registration
## References
- [OWASP: Insecure Direct Object Reference](https://owasp.org/www-community/attacks/Insecure_Direct_Object_Reference)
- [HTTP 403 vs 404 for authorization failures](https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses)
---
## Setup guide / implementation notes
1. `types/express.d.ts` — add:
```ts
export type AuthenticatedRequest = Request & {
session: { session: Session; user: User };
};
```
2. `GameSessionStore.ts` — add `userId` to `GameSessionData`:
```ts
export type GameSessionData = { answers: Map<string, number>; userId: string };
```
3. `gameService.ts` — add `userId` to both function signatures:
```ts
export const createGameSession = async (
request: GameRequest,
store: GameSessionStore,
userId: string,
): Promise<GameSession>
```
Store it on create:
```ts
await store.create(sessionId, { answers: answerKey, userId }, 30 * 60 * 1000);
```
Assert on evaluate:
```ts
if (!session || session.userId !== userId) {
throw new NotFoundError(`Game session not found: ${submission.sessionId}`);
}
```
4. `gameController.ts` — extract from authenticated request:
```ts
req.session.user.id
```
5. `gameRouter.ts` — cast at registration:
```ts
router.post("/start", controller.createGame as express.RequestHandler);
router.post("/answer", controller.submitAnswer as express.RequestHandler);
```

View file

@ -0,0 +1,41 @@
# feat: guard against empty terms in createGameSession
## Problem
If `getGameTerms` returned an empty array — no vocabulary data matched the requested language, difficulty, and part of speech combination — `createGameSession` would create a session with zero questions and return it. The frontend would receive an empty `questions` array, attempt to render the first question, find nothing, and crash with no useful error message shown to the user.
## Options considered
### Option A — `NotFoundError` (404) ✅
Throw when `terms.length === 0` before any session is created. The combination of filters yielded no data — that's a "not found" situation.
Chosen because: the request is technically valid (all filter values are recognised), but the combination has no matching data. 404 is the correct semantic response.
### Option B — `ValidationError` (400)
Treat empty results as a bad request.
Rejected because: the client sent valid input. The problem is missing data, not invalid input. 400 would be misleading.
## Solution
Added a guard in `createGameSession` immediately after `getGameTerms`:
```ts
if (terms.length === 0) {
throw new NotFoundError("No terms found for the given filters");
}
```
The error propagates through the controller's `try/catch` to the error handler, which returns a clean 404 response. No session is created.
## Files changed
- `apps/api/src/services/gameService.ts` — empty terms guard added
- `apps/api/src/services/gameService.test.ts` — pinning test added
- `apps/api/src/controllers/gameController.test.ts` — pinning test added at HTTP layer
## Commit
`feat: guard against empty terms in createGameSession`

View file

@ -0,0 +1,54 @@
# fix: deduplicate distractors, replace tautological test
## Problem
Two issues in `createGameSession` and its test suite:
1. If `getDistractors` returned the correct answer as one of the distractors, `createGameSession` would include it in the options array without filtering it out. `indexOf` would then find the first occurrence, which might not be the one intended as the correct answer — producing a question where the correct answer appears twice and the stored `correctOptionId` is wrong.
2. The test `"distractors are never the correct answer"` was tautological — it filtered the correct answer out of the options array, then asserted the remaining items were not the correct answer. It was testing that `Array.filter()` works. It could never fail.
## Options considered
### Option A — Filter duplicates after fetching, request extra distractors as buffer ✅
Filter out any distractor that matches the correct answer after fetching. Request 6 distractors instead of 3 to ensure enough remain after deduplication. Take the first 3 valid ones with `slice(0, 3)`.
Chosen because: deduplication at the service layer is the right place — `getDistractors` shouldn't need to know what the correct answer is. Requesting extra provides a buffer against collisions.
### Option B — Fix `getDistractors` to never return the correct answer
Add a NOT filter in the database query.
Not chosen for this ticket — the database query is in `@lila/db` and is a separate concern. The service layer should be defensive regardless of what the model layer returns.
## Solution
- Filter distractors against the correct answer before building options:
```ts
const uniqueDistractors = distractorTexts.filter((t) => t !== term.targetText);
const optionTexts = [term.targetText, ...uniqueDistractors.slice(0, 3)];
```
- Request 6 distractors instead of 3 to account for potential duplicates
- Replaced tautological test with a test that actually exercises the duplicate case:
```ts
it("correct answer appears exactly once even if getDistractors returns a duplicate", ...)
```
- Added distractor failure propagation test:
```ts
it("propagates getDistractors failure", ...)
```
## Files changed
- `apps/api/src/services/gameService.ts` — deduplication logic, distractor count increased to 6
- `apps/api/src/services/gameService.test.ts` — tautological test replaced, failure test added
## Commit
`fix: deduplicate distractors, replace tautological test, add distractor failure test`

View file

@ -110,12 +110,8 @@
"name": "account_user_id_user_id_fk", "name": "account_user_id_user_id_fk",
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -149,12 +145,8 @@
"name": "deck_terms_deck_id_decks_id_fk", "name": "deck_terms_deck_id_decks_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "decks", "tableTo": "decks",
"columnsFrom": [ "columnsFrom": ["deck_id"],
"deck_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -162,12 +154,8 @@
"name": "deck_terms_term_id_terms_id_fk", "name": "deck_terms_term_id_terms_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -175,10 +163,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"deck_terms_deck_id_term_id_pk": { "deck_terms_deck_id_term_id_pk": {
"name": "deck_terms_deck_id_term_id_pk", "name": "deck_terms_deck_id_term_id_pk",
"columns": [ "columns": ["deck_id", "term_id"]
"deck_id",
"term_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -265,10 +250,7 @@
"unique_deck_name": { "unique_deck_name": {
"name": "unique_deck_name", "name": "unique_deck_name",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["name", "source_language"]
"name",
"source_language"
]
} }
}, },
"policies": {}, "policies": {},
@ -336,12 +318,8 @@
"name": "lobbies_host_user_id_user_id_fk", "name": "lobbies_host_user_id_user_id_fk",
"tableFrom": "lobbies", "tableFrom": "lobbies",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["host_user_id"],
"host_user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -351,9 +329,7 @@
"lobbies_code_unique": { "lobbies_code_unique": {
"name": "lobbies_code_unique", "name": "lobbies_code_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["code"]
"code"
]
} }
}, },
"policies": {}, "policies": {},
@ -402,12 +378,8 @@
"name": "lobby_players_lobby_id_lobbies_id_fk", "name": "lobby_players_lobby_id_lobbies_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "lobbies", "tableTo": "lobbies",
"columnsFrom": [ "columnsFrom": ["lobby_id"],
"lobby_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -415,12 +387,8 @@
"name": "lobby_players_user_id_user_id_fk", "name": "lobby_players_user_id_user_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -428,10 +396,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"lobby_players_lobby_id_user_id_pk": { "lobby_players_lobby_id_user_id_pk": {
"name": "lobby_players_lobby_id_user_id_pk", "name": "lobby_players_lobby_id_user_id_pk",
"columns": [ "columns": ["lobby_id", "user_id"]
"lobby_id",
"user_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -515,12 +480,8 @@
"name": "session_user_id_user_id_fk", "name": "session_user_id_user_id_fk",
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -530,9 +491,7 @@
"session_token_unique": { "session_token_unique": {
"name": "session_token_unique", "name": "session_token_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["token"]
"token"
]
} }
}, },
"policies": {}, "policies": {},
@ -588,12 +547,8 @@
"name": "term_glosses_term_id_terms_id_fk", "name": "term_glosses_term_id_terms_id_fk",
"tableFrom": "term_glosses", "tableFrom": "term_glosses",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -603,10 +558,7 @@
"unique_term_gloss": { "unique_term_gloss": {
"name": "unique_term_gloss", "name": "unique_term_gloss",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code"]
"term_id",
"language_code"
]
} }
}, },
"policies": {}, "policies": {},
@ -641,12 +593,8 @@
"name": "term_topics_term_id_terms_id_fk", "name": "term_topics_term_id_terms_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -654,12 +602,8 @@
"name": "term_topics_topic_id_topics_id_fk", "name": "term_topics_topic_id_topics_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "topics", "tableTo": "topics",
"columnsFrom": [ "columnsFrom": ["topic_id"],
"topic_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -667,10 +611,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"term_topics_term_id_topic_id_pk": { "term_topics_term_id_topic_id_pk": {
"name": "term_topics_term_id_topic_id_pk", "name": "term_topics_term_id_topic_id_pk",
"columns": [ "columns": ["term_id", "topic_id"]
"term_id",
"topic_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -744,10 +685,7 @@
"unique_source_id": { "unique_source_id": {
"name": "unique_source_id", "name": "unique_source_id",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["source", "source_id"]
"source",
"source_id"
]
} }
}, },
"policies": {}, "policies": {},
@ -803,9 +741,7 @@
"topics_slug_unique": { "topics_slug_unique": {
"name": "topics_slug_unique", "name": "topics_slug_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["slug"]
"slug"
]
} }
}, },
"policies": {}, "policies": {},
@ -901,12 +837,8 @@
"name": "translations_term_id_terms_id_fk", "name": "translations_term_id_terms_id_fk",
"tableFrom": "translations", "tableFrom": "translations",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -916,11 +848,7 @@
"unique_translations": { "unique_translations": {
"name": "unique_translations", "name": "unique_translations",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -997,9 +925,7 @@
"user_email_unique": { "user_email_unique": {
"name": "user_email_unique", "name": "user_email_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["email"]
"email"
]
} }
}, },
"policies": {}, "policies": {},
@ -1080,9 +1006,5 @@
"roles": {}, "roles": {},
"policies": {}, "policies": {},
"views": {}, "views": {},
"_meta": { "_meta": { "columns": {}, "schemas": {}, "tables": {} }
"columns": {}, }
"schemas": {},
"tables": {}
}
}

View file

@ -110,12 +110,8 @@
"name": "account_user_id_user_id_fk", "name": "account_user_id_user_id_fk",
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -149,12 +145,8 @@
"name": "deck_terms_deck_id_decks_id_fk", "name": "deck_terms_deck_id_decks_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "decks", "tableTo": "decks",
"columnsFrom": [ "columnsFrom": ["deck_id"],
"deck_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -162,12 +154,8 @@
"name": "deck_terms_term_id_terms_id_fk", "name": "deck_terms_term_id_terms_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -175,10 +163,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"deck_terms_deck_id_term_id_pk": { "deck_terms_deck_id_term_id_pk": {
"name": "deck_terms_deck_id_term_id_pk", "name": "deck_terms_deck_id_term_id_pk",
"columns": [ "columns": ["deck_id", "term_id"]
"deck_id",
"term_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -265,10 +250,7 @@
"unique_deck_name": { "unique_deck_name": {
"name": "unique_deck_name", "name": "unique_deck_name",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["name", "source_language"]
"name",
"source_language"
]
} }
}, },
"policies": {}, "policies": {},
@ -336,12 +318,8 @@
"name": "lobbies_host_user_id_user_id_fk", "name": "lobbies_host_user_id_user_id_fk",
"tableFrom": "lobbies", "tableFrom": "lobbies",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["host_user_id"],
"host_user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -351,9 +329,7 @@
"lobbies_code_unique": { "lobbies_code_unique": {
"name": "lobbies_code_unique", "name": "lobbies_code_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["code"]
"code"
]
} }
}, },
"policies": {}, "policies": {},
@ -402,12 +378,8 @@
"name": "lobby_players_lobby_id_lobbies_id_fk", "name": "lobby_players_lobby_id_lobbies_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "lobbies", "tableTo": "lobbies",
"columnsFrom": [ "columnsFrom": ["lobby_id"],
"lobby_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -415,12 +387,8 @@
"name": "lobby_players_user_id_user_id_fk", "name": "lobby_players_user_id_user_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -428,10 +396,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"lobby_players_lobby_id_user_id_pk": { "lobby_players_lobby_id_user_id_pk": {
"name": "lobby_players_lobby_id_user_id_pk", "name": "lobby_players_lobby_id_user_id_pk",
"columns": [ "columns": ["lobby_id", "user_id"]
"lobby_id",
"user_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -515,12 +480,8 @@
"name": "session_user_id_user_id_fk", "name": "session_user_id_user_id_fk",
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -530,9 +491,7 @@
"session_token_unique": { "session_token_unique": {
"name": "session_token_unique", "name": "session_token_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["token"]
"token"
]
} }
}, },
"policies": {}, "policies": {},
@ -604,12 +563,8 @@
"name": "term_examples_term_id_terms_id_fk", "name": "term_examples_term_id_terms_id_fk",
"tableFrom": "term_examples", "tableFrom": "term_examples",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -619,11 +574,7 @@
"unique_term_example": { "unique_term_example": {
"name": "unique_term_example", "name": "unique_term_example",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -684,12 +635,8 @@
"name": "term_glosses_term_id_terms_id_fk", "name": "term_glosses_term_id_terms_id_fk",
"tableFrom": "term_glosses", "tableFrom": "term_glosses",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -699,10 +646,7 @@
"unique_term_gloss": { "unique_term_gloss": {
"name": "unique_term_gloss", "name": "unique_term_gloss",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code"]
"term_id",
"language_code"
]
} }
}, },
"policies": {}, "policies": {},
@ -737,12 +681,8 @@
"name": "term_topics_term_id_terms_id_fk", "name": "term_topics_term_id_terms_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -750,12 +690,8 @@
"name": "term_topics_topic_id_topics_id_fk", "name": "term_topics_topic_id_topics_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "topics", "tableTo": "topics",
"columnsFrom": [ "columnsFrom": ["topic_id"],
"topic_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -763,10 +699,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"term_topics_term_id_topic_id_pk": { "term_topics_term_id_topic_id_pk": {
"name": "term_topics_term_id_topic_id_pk", "name": "term_topics_term_id_topic_id_pk",
"columns": [ "columns": ["term_id", "topic_id"]
"term_id",
"topic_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -840,10 +773,7 @@
"unique_source_id": { "unique_source_id": {
"name": "unique_source_id", "name": "unique_source_id",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["source", "source_id"]
"source",
"source_id"
]
} }
}, },
"policies": {}, "policies": {},
@ -899,9 +829,7 @@
"topics_slug_unique": { "topics_slug_unique": {
"name": "topics_slug_unique", "name": "topics_slug_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["slug"]
"slug"
]
} }
}, },
"policies": {}, "policies": {},
@ -997,12 +925,8 @@
"name": "translations_term_id_terms_id_fk", "name": "translations_term_id_terms_id_fk",
"tableFrom": "translations", "tableFrom": "translations",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -1012,11 +936,7 @@
"unique_translations": { "unique_translations": {
"name": "unique_translations", "name": "unique_translations",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -1093,9 +1013,7 @@
"user_email_unique": { "user_email_unique": {
"name": "user_email_unique", "name": "user_email_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["email"]
"email"
]
} }
}, },
"policies": {}, "policies": {},
@ -1176,9 +1094,5 @@
"roles": {}, "roles": {},
"policies": {}, "policies": {},
"views": {}, "views": {},
"_meta": { "_meta": { "columns": {}, "schemas": {}, "tables": {} }
"columns": {}, }
"schemas": {},
"tables": {}
}
}

View file

@ -110,12 +110,8 @@
"name": "account_user_id_user_id_fk", "name": "account_user_id_user_id_fk",
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -149,12 +145,8 @@
"name": "deck_terms_deck_id_decks_id_fk", "name": "deck_terms_deck_id_decks_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "decks", "tableTo": "decks",
"columnsFrom": [ "columnsFrom": ["deck_id"],
"deck_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -162,12 +154,8 @@
"name": "deck_terms_term_id_terms_id_fk", "name": "deck_terms_term_id_terms_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -175,10 +163,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"deck_terms_deck_id_term_id_pk": { "deck_terms_deck_id_term_id_pk": {
"name": "deck_terms_deck_id_term_id_pk", "name": "deck_terms_deck_id_term_id_pk",
"columns": [ "columns": ["deck_id", "term_id"]
"deck_id",
"term_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -265,10 +250,7 @@
"unique_deck_name": { "unique_deck_name": {
"name": "unique_deck_name", "name": "unique_deck_name",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["name", "source_language"]
"name",
"source_language"
]
} }
}, },
"policies": {}, "policies": {},
@ -355,12 +337,8 @@
"name": "lobbies_host_user_id_user_id_fk", "name": "lobbies_host_user_id_user_id_fk",
"tableFrom": "lobbies", "tableFrom": "lobbies",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["host_user_id"],
"host_user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -370,9 +348,7 @@
"lobbies_code_unique": { "lobbies_code_unique": {
"name": "lobbies_code_unique", "name": "lobbies_code_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["code"]
"code"
]
} }
}, },
"policies": {}, "policies": {},
@ -421,12 +397,8 @@
"name": "lobby_players_lobby_id_lobbies_id_fk", "name": "lobby_players_lobby_id_lobbies_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "lobbies", "tableTo": "lobbies",
"columnsFrom": [ "columnsFrom": ["lobby_id"],
"lobby_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -434,12 +406,8 @@
"name": "lobby_players_user_id_user_id_fk", "name": "lobby_players_user_id_user_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -447,10 +415,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"lobby_players_lobby_id_user_id_pk": { "lobby_players_lobby_id_user_id_pk": {
"name": "lobby_players_lobby_id_user_id_pk", "name": "lobby_players_lobby_id_user_id_pk",
"columns": [ "columns": ["lobby_id", "user_id"]
"lobby_id",
"user_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -534,12 +499,8 @@
"name": "session_user_id_user_id_fk", "name": "session_user_id_user_id_fk",
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -549,9 +510,7 @@
"session_token_unique": { "session_token_unique": {
"name": "session_token_unique", "name": "session_token_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["token"]
"token"
]
} }
}, },
"policies": {}, "policies": {},
@ -623,12 +582,8 @@
"name": "term_examples_term_id_terms_id_fk", "name": "term_examples_term_id_terms_id_fk",
"tableFrom": "term_examples", "tableFrom": "term_examples",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -638,11 +593,7 @@
"unique_term_example": { "unique_term_example": {
"name": "unique_term_example", "name": "unique_term_example",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -703,12 +654,8 @@
"name": "term_glosses_term_id_terms_id_fk", "name": "term_glosses_term_id_terms_id_fk",
"tableFrom": "term_glosses", "tableFrom": "term_glosses",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -718,10 +665,7 @@
"unique_term_gloss": { "unique_term_gloss": {
"name": "unique_term_gloss", "name": "unique_term_gloss",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code"]
"term_id",
"language_code"
]
} }
}, },
"policies": {}, "policies": {},
@ -756,12 +700,8 @@
"name": "term_topics_term_id_terms_id_fk", "name": "term_topics_term_id_terms_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -769,12 +709,8 @@
"name": "term_topics_topic_id_topics_id_fk", "name": "term_topics_topic_id_topics_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "topics", "tableTo": "topics",
"columnsFrom": [ "columnsFrom": ["topic_id"],
"topic_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -782,10 +718,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"term_topics_term_id_topic_id_pk": { "term_topics_term_id_topic_id_pk": {
"name": "term_topics_term_id_topic_id_pk", "name": "term_topics_term_id_topic_id_pk",
"columns": [ "columns": ["term_id", "topic_id"]
"term_id",
"topic_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -859,10 +792,7 @@
"unique_source_id": { "unique_source_id": {
"name": "unique_source_id", "name": "unique_source_id",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["source", "source_id"]
"source",
"source_id"
]
} }
}, },
"policies": {}, "policies": {},
@ -918,9 +848,7 @@
"topics_slug_unique": { "topics_slug_unique": {
"name": "topics_slug_unique", "name": "topics_slug_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["slug"]
"slug"
]
} }
}, },
"policies": {}, "policies": {},
@ -1016,12 +944,8 @@
"name": "translations_term_id_terms_id_fk", "name": "translations_term_id_terms_id_fk",
"tableFrom": "translations", "tableFrom": "translations",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -1031,11 +955,7 @@
"unique_translations": { "unique_translations": {
"name": "unique_translations", "name": "unique_translations",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -1112,9 +1032,7 @@
"user_email_unique": { "user_email_unique": {
"name": "user_email_unique", "name": "user_email_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["email"]
"email"
]
} }
}, },
"policies": {}, "policies": {},
@ -1195,9 +1113,5 @@
"roles": {}, "roles": {},
"policies": {}, "policies": {},
"views": {}, "views": {},
"_meta": { "_meta": { "columns": {}, "schemas": {}, "tables": {} }
"columns": {}, }
"schemas": {},
"tables": {}
}
}

View file

@ -110,12 +110,8 @@
"name": "account_user_id_user_id_fk", "name": "account_user_id_user_id_fk",
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -149,12 +145,8 @@
"name": "deck_terms_deck_id_decks_id_fk", "name": "deck_terms_deck_id_decks_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "decks", "tableTo": "decks",
"columnsFrom": [ "columnsFrom": ["deck_id"],
"deck_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -162,12 +154,8 @@
"name": "deck_terms_term_id_terms_id_fk", "name": "deck_terms_term_id_terms_id_fk",
"tableFrom": "deck_terms", "tableFrom": "deck_terms",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -175,10 +163,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"deck_terms_deck_id_term_id_pk": { "deck_terms_deck_id_term_id_pk": {
"name": "deck_terms_deck_id_term_id_pk", "name": "deck_terms_deck_id_term_id_pk",
"columns": [ "columns": ["deck_id", "term_id"]
"deck_id",
"term_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -265,10 +250,7 @@
"unique_deck_name": { "unique_deck_name": {
"name": "unique_deck_name", "name": "unique_deck_name",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["name", "source_language"]
"name",
"source_language"
]
} }
}, },
"policies": {}, "policies": {},
@ -336,12 +318,8 @@
"name": "lobbies_host_user_id_user_id_fk", "name": "lobbies_host_user_id_user_id_fk",
"tableFrom": "lobbies", "tableFrom": "lobbies",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["host_user_id"],
"host_user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -351,9 +329,7 @@
"lobbies_code_unique": { "lobbies_code_unique": {
"name": "lobbies_code_unique", "name": "lobbies_code_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["code"]
"code"
]
} }
}, },
"policies": {}, "policies": {},
@ -402,12 +378,8 @@
"name": "lobby_players_lobby_id_lobbies_id_fk", "name": "lobby_players_lobby_id_lobbies_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "lobbies", "tableTo": "lobbies",
"columnsFrom": [ "columnsFrom": ["lobby_id"],
"lobby_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -415,12 +387,8 @@
"name": "lobby_players_user_id_user_id_fk", "name": "lobby_players_user_id_user_id_fk",
"tableFrom": "lobby_players", "tableFrom": "lobby_players",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -428,10 +396,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"lobby_players_lobby_id_user_id_pk": { "lobby_players_lobby_id_user_id_pk": {
"name": "lobby_players_lobby_id_user_id_pk", "name": "lobby_players_lobby_id_user_id_pk",
"columns": [ "columns": ["lobby_id", "user_id"]
"lobby_id",
"user_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -515,12 +480,8 @@
"name": "session_user_id_user_id_fk", "name": "session_user_id_user_id_fk",
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["user_id"],
"user_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -530,9 +491,7 @@
"session_token_unique": { "session_token_unique": {
"name": "session_token_unique", "name": "session_token_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["token"]
"token"
]
} }
}, },
"policies": {}, "policies": {},
@ -604,12 +563,8 @@
"name": "term_examples_term_id_terms_id_fk", "name": "term_examples_term_id_terms_id_fk",
"tableFrom": "term_examples", "tableFrom": "term_examples",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -619,11 +574,7 @@
"unique_term_example": { "unique_term_example": {
"name": "unique_term_example", "name": "unique_term_example",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -684,12 +635,8 @@
"name": "term_glosses_term_id_terms_id_fk", "name": "term_glosses_term_id_terms_id_fk",
"tableFrom": "term_glosses", "tableFrom": "term_glosses",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -699,10 +646,7 @@
"unique_term_gloss": { "unique_term_gloss": {
"name": "unique_term_gloss", "name": "unique_term_gloss",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code"]
"term_id",
"language_code"
]
} }
}, },
"policies": {}, "policies": {},
@ -737,12 +681,8 @@
"name": "term_topics_term_id_terms_id_fk", "name": "term_topics_term_id_terms_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@ -750,12 +690,8 @@
"name": "term_topics_topic_id_topics_id_fk", "name": "term_topics_topic_id_topics_id_fk",
"tableFrom": "term_topics", "tableFrom": "term_topics",
"tableTo": "topics", "tableTo": "topics",
"columnsFrom": [ "columnsFrom": ["topic_id"],
"topic_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -763,10 +699,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"term_topics_term_id_topic_id_pk": { "term_topics_term_id_topic_id_pk": {
"name": "term_topics_term_id_topic_id_pk", "name": "term_topics_term_id_topic_id_pk",
"columns": [ "columns": ["term_id", "topic_id"]
"term_id",
"topic_id"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@ -840,10 +773,7 @@
"unique_source_id": { "unique_source_id": {
"name": "unique_source_id", "name": "unique_source_id",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["source", "source_id"]
"source",
"source_id"
]
} }
}, },
"policies": {}, "policies": {},
@ -899,9 +829,7 @@
"topics_slug_unique": { "topics_slug_unique": {
"name": "topics_slug_unique", "name": "topics_slug_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["slug"]
"slug"
]
} }
}, },
"policies": {}, "policies": {},
@ -997,12 +925,8 @@
"name": "translations_term_id_terms_id_fk", "name": "translations_term_id_terms_id_fk",
"tableFrom": "translations", "tableFrom": "translations",
"tableTo": "terms", "tableTo": "terms",
"columnsFrom": [ "columnsFrom": ["term_id"],
"term_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@ -1012,11 +936,7 @@
"unique_translations": { "unique_translations": {
"name": "unique_translations", "name": "unique_translations",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["term_id", "language_code", "text"]
"term_id",
"language_code",
"text"
]
} }
}, },
"policies": {}, "policies": {},
@ -1093,9 +1013,7 @@
"user_email_unique": { "user_email_unique": {
"name": "user_email_unique", "name": "user_email_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["email"]
"email"
]
} }
}, },
"policies": {}, "policies": {},
@ -1176,9 +1094,5 @@
"roles": {}, "roles": {},
"policies": {}, "policies": {},
"views": {}, "views": {},
"_meta": { "_meta": { "columns": {}, "schemas": {}, "tables": {} }
"columns": {}, }
"schemas": {},
"tables": {}
}
}

View file

@ -80,4 +80,4 @@
"breakpoints": true "breakpoints": true
} }
] ]
} }

View file

@ -5,11 +5,11 @@
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"outDir": "./dist", "outDir": "./dist",
"resolveJsonModule": true, "resolveJsonModule": true,
"types": ["vitest/globals"], "types": ["vitest/globals"]
}, },
"include": [ "include": [
"src", "src",
"vitest.config.ts", "vitest.config.ts",
"../../data-pipeline/archive/packages-db-src-old-seeding-scripts/data", "../../data-pipeline/archive/packages-db-src-old-seeding-scripts/data"
], ]
} }

View file

@ -4,7 +4,7 @@ export type SupportedLanguageCode = (typeof SUPPORTED_LANGUAGE_CODES)[number];
export const SUPPORTED_POS = ["noun", "verb", "adjective", "adverb"] as const; export const SUPPORTED_POS = ["noun", "verb", "adjective", "adverb"] as const;
export type SupportedPos = (typeof SUPPORTED_POS)[number]; export type SupportedPos = (typeof SUPPORTED_POS)[number];
export const GAME_ROUNDS = ["3", "10"] as const; export const GAME_ROUNDS = [3, 10] as const;
export type GameRounds = (typeof GAME_ROUNDS)[number]; export type GameRounds = (typeof GAME_ROUNDS)[number];
export const CEFR_LEVELS = ["A1", "A2", "B1", "B2", "C1", "C2"] as const; export const CEFR_LEVELS = ["A1", "A2", "B1", "B2", "C1", "C2"] as const;

View file

@ -12,7 +12,7 @@ export const GameRequestSchema = z.object({
target_language: z.enum(SUPPORTED_LANGUAGE_CODES), target_language: z.enum(SUPPORTED_LANGUAGE_CODES),
pos: z.enum(SUPPORTED_POS), pos: z.enum(SUPPORTED_POS),
difficulty: z.enum(DIFFICULTY_LEVELS), difficulty: z.enum(DIFFICULTY_LEVELS),
rounds: z.enum(GAME_ROUNDS), rounds: z.literal(GAME_ROUNDS),
}); });
export type GameRequest = z.infer<typeof GameRequestSchema>; export type GameRequest = z.infer<typeof GameRequestSchema>;

View file

@ -4,7 +4,7 @@
{ "path": "./packages/db" }, { "path": "./packages/db" },
{ "path": "./apps/web" }, { "path": "./apps/web" },
{ "path": "./apps/api" }, { "path": "./apps/api" },
{ "path": "./data-pipeline" }, { "path": "./data-pipeline" }
], ],
"files": [], "files": []
} }