commit e2e085b34145b5ee634e3663440679ea9a96d542 Author: tyuXX Date: Sun Nov 22 18:18:15 2026 +0300 Implement ChessUp server, vanilla TS UI, Stockfish analytics, and Docker/Cloudflared setup diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b605eab --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +node_modules +dist +data +.git +.env +*.db +*.db-wal +*.db-shm diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4a7d1d1 --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +# Required: Cloudflare Tunnel token from Zero Trust -> Networks -> Tunnels +CLOUDFLARED_TOKEN= + +# Set to 1 behind HTTPS (Cloudflare Tunnel); set to 0 only for plain local HTTP +COOKIE_SECURE=1 + +# Optional Stockfish & game settings +STOCKFISH_WORKERS=2 +ANALYSIS_DEPTH=12 +MULTIPV_DEPTH=14 +DISCONNECT_FORFEIT_MS=60000 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b587bf9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +dist/ +data/ +.env +*.db +*.db-wal +*.db-shm diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..57a70d7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +# syntax=docker/dockerfile:1 + +FROM node:24-slim AS builder +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY tsconfig.json build.mjs ./ +COPY src ./src + +RUN npm run typecheck && npm run build + +FROM node:24-slim AS runner +WORKDIR /app + +ENV NODE_ENV=production \ + PORT=3000 \ + HOST=0.0.0.0 \ + DB_PATH=/app/data/chessup.db + +COPY package.json package-lock.json ./ +# Retain only the lite-single Stockfish JS+WASM files used by ChessUp (~7MB vs ~245MB full package) +RUN npm ci --omit=dev && \ + find node_modules/stockfish/bin -type f ! -name '*-lite-single.*' -delete && \ + npm cache clean --force + +COPY --from=builder /app/dist ./dist + +RUN mkdir -p /app/data && chown -R node:node /app + +USER node + +VOLUME ["/app/data"] + +HEALTHCHECK --interval=15s --timeout=5s --start-period=10s --retries=3 \ + CMD ["node", "-e", "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] + +CMD ["node", "dist/server/index.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..1f53ab5 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# ChessUp + +Lightweight Lichess-style chess server and Stockfish analysis web app built with **vanilla TypeScript**, **esbuild**, **Node.js (`node:http`, `node:sqlite`)**, **`ws`**, and **`stockfish`** — zero UI or server frameworks. + +## Features + +- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap + mouse/touch drag, single premove, Web Audio sounds (ES2017 / Safari 12+ compatible). +- **Accounts (no email required)**: Username + password registration (`crypto.scrypt` + `HttpOnly` session cookies). +- **Glicko-2 Ratings**: Separate ratings for Bullet, Blitz, Rapid, and Classical, with rating history charts and leaderboards. +- **Multiplayer & Social**: Live Open Lobby seeks, shareable invite links (`/invite/`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat. +- **8 Stockfish Levels**: Play Stockfish Lv 1 (~800) through Lv 8 (~2800+) with selectable color, timed/unlimited clocks, and unlimited takebacks. +- **Game History & Stockfish Analytics**: Filterable game history, cached post-game analysis (eval bar, clickable SVG eval graph, accuracy %, ACPL, `?!` / `?` / `??` annotations), plus an interactive variation explorer with live MultiPV lines and PGN/FEN import/export. + +## Local Development + +Requires **Node.js 22+** (built on Node 24/26 with native `node:sqlite`). + +```bash +npm install +npm run build +npm start +``` + +Server listens on `http://0.0.0.0:3000` by default and persists SQLite data in `./data/chessup.db`. + +Run checks and tests: + +```bash +npm run typecheck +npm test +``` + +## Docker + Cloudflare Tunnel Deployment (Zero Host Ports Exposed) + +The included [docker-compose.yml](docker-compose.yml) runs `chessup` and `cloudflared` on a private bridge network (`chessup_bridge`) with no host ports published. + +1. Copy the example environment file and add your Cloudflare Tunnel token: + + ```bash + cp .env.example .env + ``` + + Edit `.env` and set `CLOUDFLARED_TOKEN=...`. + +2. In the Cloudflare Zero Trust dashboard (**Networks -> Tunnels -> Public Hostname**), configure your hostname to forward HTTP traffic to: + + ```text + http://chessup:3000 + ``` + +3. Build and start both containers: + + ```bash + docker compose up -d --build + ``` + +SQLite data is persisted in the named Docker volume `chessup_data`. diff --git a/build.mjs b/build.mjs new file mode 100644 index 0000000..f858562 --- /dev/null +++ b/build.mjs @@ -0,0 +1,112 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import esbuild from 'esbuild'; + +const args = process.argv.slice(2); +const watch = args.includes('--watch'); +const buildTests = args.includes('--tests'); + +const rootDir = process.cwd(); +const distPublicDir = path.join(rootDir, 'dist', 'public'); +const distServerDir = path.join(rootDir, 'dist', 'server'); +const distTestsDir = path.join(rootDir, 'dist', 'tests'); + +function copyHtml() { + fs.mkdirSync(distPublicDir, { recursive: true }); + const srcHtml = path.join(rootDir, 'src', 'client', 'index.html'); + const destHtml = path.join(distPublicDir, 'index.html'); + if (fs.existsSync(srcHtml)) { + fs.copyFileSync(srcHtml, destHtml); + } +} + +async function main() { + fs.mkdirSync(distPublicDir, { recursive: true }); + fs.mkdirSync(distServerDir, { recursive: true }); + + const serverOptions = { + entryPoints: [path.join(rootDir, 'src', 'server', 'index.ts')], + outfile: path.join(distServerDir, 'index.js'), + bundle: true, + platform: 'node', + format: 'cjs', + target: 'node22', + packages: 'external', + sourcemap: true, + logLevel: 'info' + }; + + const clientOptions = { + entryPoints: [path.join(rootDir, 'src', 'client', 'main.ts')], + outfile: path.join(distPublicDir, 'app.js'), + bundle: true, + platform: 'browser', + format: 'iife', + target: ['es2017', 'safari12', 'chrome60'], + minify: !watch, + sourcemap: watch, + logLevel: 'info' + }; + + const cssOptions = { + entryPoints: [path.join(rootDir, 'src', 'client', 'styles.css')], + outfile: path.join(distPublicDir, 'styles.css'), + bundle: true, + target: ['safari12', 'chrome60'], + minify: !watch, + logLevel: 'info' + }; + + if (watch) { + copyHtml(); + const contexts = await Promise.all([ + esbuild.context(serverOptions), + esbuild.context(clientOptions), + esbuild.context(cssOptions) + ]); + await Promise.all(contexts.map((ctx) => ctx.watch())); + const htmlPath = path.join(rootDir, 'src', 'client', 'index.html'); + fs.watchFile(htmlPath, { interval: 500 }, () => { + copyHtml(); + console.log('[build] Copied index.html'); + }); + console.log('[build] Watching for changes...'); + return; + } + + copyHtml(); + await Promise.all([ + esbuild.build(serverOptions), + esbuild.build(clientOptions), + esbuild.build(cssOptions) + ]); + + if (buildTests) { + const testsDir = path.join(rootDir, 'tests'); + if (fs.existsSync(testsDir)) { + const testFiles = fs + .readdirSync(testsDir) + .filter((f) => f.endsWith('.test.ts')) + .map((f) => path.join(testsDir, f)); + if (testFiles.length > 0) { + fs.mkdirSync(distTestsDir, { recursive: true }); + await esbuild.build({ + entryPoints: testFiles, + outdir: distTestsDir, + bundle: true, + platform: 'node', + format: 'cjs', + target: 'node22', + packages: 'external', + sourcemap: true, + logLevel: 'info' + }); + } + } + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..b2c19d9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,58 @@ +# ChessUp + Cloudflare Tunnel (zero host ports exposed) +# +# In the Cloudflare Zero Trust dashboard (Networks -> Tunnels -> Public Hostname), +# point your domain's Public Hostname to: +# Service Type: HTTP +# URL: chessup:3000 + +services: + chessup: + build: + context: . + dockerfile: Dockerfile + restart: unless-stopped + environment: + NODE_ENV: production + PORT: "3000" + HOST: "0.0.0.0" + DB_PATH: /app/data/chessup.db + COOKIE_SECURE: ${COOKIE_SECURE:-1} + STOCKFISH_WORKERS: ${STOCKFISH_WORKERS:-2} + ANALYSIS_DEPTH: ${ANALYSIS_DEPTH:-12} + MULTIPV_DEPTH: ${MULTIPV_DEPTH:-14} + DISCONNECT_FORFEIT_MS: ${DISCONNECT_FORFEIT_MS:-60000} + volumes: + - chessup_data:/app/data + networks: + - chessup_bridge + healthcheck: + test: + [ + "CMD", + "node", + "-e", + "fetch('http://127.0.0.1:3000/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" + ] + interval: 15s + timeout: 5s + retries: 3 + start_period: 10s + + cloudflared: + image: cloudflare/cloudflared:latest + restart: unless-stopped + command: tunnel --no-autoupdate run + environment: + TUNNEL_TOKEN: ${CLOUDFLARED_TOKEN:?Set CLOUDFLARED_TOKEN in .env} + depends_on: + chessup: + condition: service_healthy + networks: + - chessup_bridge + +networks: + chessup_bridge: + driver: bridge + +volumes: + chessup_data: diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..5564b15 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,579 @@ +{ + "name": "chessup", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "chessup", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "stockfish": "^18.0.0", + "ws": "^8.18.0" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "@types/ws": "^8.5.14", + "esbuild": "^0.25.0", + "typescript": "^5.7.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/stockfish": { + "version": "18.0.8", + "resolved": "https://registry.npmjs.org/stockfish/-/stockfish-18.0.8.tgz", + "integrity": "sha512-z+f2UMPXLylDBGjv9e9zU8QulY7hUl8MYHesLRrdddewlOXjJrUSmtNmbtID1/F72EPhq0CCkCNxgWS5MQVWtQ==", + "hasInstallScript": true, + "license": "GPL-3.0", + "bin": { + "stockfish": "scripts/cli.js" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3a6cdfb --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "name": "chessup", + "version": "1.0.0", + "description": "Small chess server+analytics thingy with multiplayer and bot support as well as accounts and history + elo and stuff", + "license": "MIT", + "author": "[tyuXX]", + "type": "commonjs", + "main": "dist/server/index.js", + "scripts": { + "build": "node build.mjs", + "build:watch": "node build.mjs --watch", + "typecheck": "tsc --noEmit", + "start": "node dist/server/index.js", + "dev": "node build.mjs && node dist/server/index.js", + "test": "node build.mjs --tests && node --test dist/tests/*.test.js" + }, + "dependencies": { + "stockfish": "^18.0.0", + "ws": "^8.18.0" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "@types/ws": "^8.5.14", + "esbuild": "^0.25.0", + "typescript": "^5.7.0" + } +} diff --git a/src/client/api.ts b/src/client/api.ts new file mode 100644 index 0000000..20f0551 --- /dev/null +++ b/src/client/api.ts @@ -0,0 +1,170 @@ +import type { ClientWsMessage, ServerWsMessage } from '../shared/types'; + +export class ApiError extends Error { + constructor( + public readonly status: number, + message: string + ) { + super(message); + } +} + +export async function apiRequest(url: string, options: RequestInit = {}): Promise { + const headers: Record = {}; + if (options.body && typeof options.body === 'string') { + headers['Content-Type'] = 'application/json'; + } + const resp = await fetch(url, { + credentials: 'same-origin', + ...options, + headers: { + ...headers, + ...(options.headers as Record | undefined) + } + }); + + const text = await resp.text(); + let data: Record = {}; + if (text) { + try { + data = JSON.parse(text) as Record; + } catch { + if (!resp.ok) { + throw new ApiError(resp.status, text); + } + } + } + + if (!resp.ok) { + throw new ApiError(resp.status, String(data['error'] || `HTTP ${resp.status}`)); + } + + return data as unknown as T; +} + +type WsListener = (msg: ServerWsMessage) => void; + +export class WsClient { + private ws: WebSocket | null = null; + private listeners = new Set(); + private reconnectAttempt = 0; + private reconnectTimer: number | null = null; + private pingTimer: number | null = null; + private subscriptions: { + lobby: boolean; + games: Set; + analyses: Set; + } = { + lobby: false, + games: new Set(), + analyses: new Set() + }; + + connect(): void { + if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) { + return; + } + const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const url = `${proto}//${window.location.host}/ws`; + const ws = new WebSocket(url); + this.ws = ws; + + ws.onopen = () => { + this.reconnectAttempt = 0; + if (this.subscriptions.lobby) { + this.send({ type: 'lobby:subscribe' }); + } + this.subscriptions.games.forEach((gameId) => { + this.send({ type: 'game:subscribe', gameId }); + }); + this.subscriptions.analyses.forEach((gameId) => { + this.send({ type: 'analysis:subscribe', gameId }); + }); + this.startPing(); + }; + + ws.onmessage = (ev) => { + try { + const msg = JSON.parse(String(ev.data)) as ServerWsMessage; + this.listeners.forEach((fn) => fn(msg)); + } catch { + // Ignore malformed + } + }; + + ws.onclose = () => { + this.stopPing(); + this.ws = null; + this.scheduleReconnect(); + }; + + ws.onerror = () => { + // onclose handles reconnect + }; + } + + reconnectNow(): void { + if (this.reconnectTimer !== null) { + window.clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + this.stopPing(); + if (this.ws) { + try { + this.ws.onclose = null; + this.ws.close(); + } catch { + // Ignore + } + this.ws = null; + } + this.reconnectAttempt = 0; + this.connect(); + } + + private startPing(): void { + this.stopPing(); + this.pingTimer = window.setInterval(() => { + this.send({ type: 'ping' }); + }, 20_000); + } + + private stopPing(): void { + if (this.pingTimer !== null) { + window.clearInterval(this.pingTimer); + this.pingTimer = null; + } + } + + private scheduleReconnect(): void { + if (this.reconnectTimer !== null) return; + const delay = Math.min(10_000, 1000 * Math.pow(2, Math.min(4, this.reconnectAttempt))); + this.reconnectAttempt++; + this.reconnectTimer = window.setTimeout(() => { + this.reconnectTimer = null; + this.connect(); + }, delay); + } + + onMessage(fn: WsListener): () => void { + this.listeners.add(fn); + return () => { + this.listeners.delete(fn); + }; + } + + send(msg: ClientWsMessage): void { + if (msg.type === 'lobby:subscribe') this.subscriptions.lobby = true; + if (msg.type === 'lobby:unsubscribe') this.subscriptions.lobby = false; + if (msg.type === 'game:subscribe') this.subscriptions.games.add(msg.gameId); + if (msg.type === 'game:unsubscribe') this.subscriptions.games.delete(msg.gameId); + if (msg.type === 'analysis:subscribe') this.subscriptions.analyses.add(msg.gameId); + if (msg.type === 'analysis:unsubscribe') this.subscriptions.analyses.delete(msg.gameId); + + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify(msg)); + } + } +} + +export const wsClient = new WsClient(); diff --git a/src/client/components/board.ts b/src/client/components/board.ts new file mode 100644 index 0000000..f8acf51 --- /dev/null +++ b/src/client/components/board.ts @@ -0,0 +1,644 @@ +import { Chess, algToSq, sqToAlg } from '../../shared/chess'; +import type { Color, Piece, PromotionPiece } from '../../shared/types'; +import { createPieceNode } from '../pieces'; +import { clearNode, el } from '../dom'; + +export type BoardMode = 'play' | 'analyze' | 'readonly'; + +export interface BoardArrow { + from: string; + to: string; + color?: string; +} + +export interface BoardOptions { + orientation?: Color; + mode?: BoardMode; + playerColor?: Color; + onMove?: (uci: string) => void; +} + +export class ChessBoard { + public readonly root: HTMLElement; + private readonly wrap: HTMLElement; + private readonly grid: HTMLElement; + private readonly svgArrows: SVGSVGElement; + private readonly promoOverlay: HTMLElement; + private readonly squareEls: HTMLElement[] = []; + + private chess = new Chess(); + private orientation: Color = 'w'; + private mode: BoardMode = 'readonly'; + private playerColor: Color = 'w'; + private onMoveCallback?: (uci: string) => void; + + private selectedSq: number = -1; + private legalTargets = new Map(); + private lastMoveFrom: number = -1; + private lastMoveTo: number = -1; + private premove: { from: number; to: number; promotion?: PromotionPiece } | null = null; + private arrows: BoardArrow[] = []; + private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null; + + // Drag state + private pointerDownSq: number = -1; + private dragActive = false; + private dragStartX = 0; + private dragStartY = 0; + private dragGhost: HTMLElement | null = null; + private dragTouchId: number | null = null; + + private readonly boundMouseMove: (e: MouseEvent) => void; + private readonly boundMouseUp: (e: MouseEvent) => void; + private readonly boundTouchMove: (e: TouchEvent) => void; + private readonly boundTouchEnd: (e: TouchEvent) => void; + + constructor(opts: BoardOptions = {}) { + this.orientation = opts.orientation || 'w'; + this.mode = opts.mode || 'readonly'; + this.playerColor = opts.playerColor || 'w'; + this.onMoveCallback = opts.onMove; + + this.root = el('div', { className: 'board-outer' }); + this.wrap = el('div', { className: 'board-wrap' }); + this.grid = el('div', { className: 'board-grid' }); + + this.svgArrows = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svgArrows.setAttribute('viewBox', '0 0 800 800'); + this.svgArrows.setAttribute('class', 'board-arrows'); + + this.promoOverlay = el('div', { className: 'promo-overlay hidden' }); + + for (let i = 0; i < 64; i++) { + const sqEl = el('div', { className: 'sq' }); + this.squareEls.push(sqEl); + this.grid.appendChild(sqEl); + } + + this.wrap.appendChild(this.grid); + this.wrap.appendChild(this.svgArrows); + this.wrap.appendChild(this.promoOverlay); + this.root.appendChild(this.wrap); + + this.grid.addEventListener('contextmenu', (e) => { + e.preventDefault(); + this.clearSelectionAndPremove(); + }); + + this.grid.addEventListener('mousedown', (e) => this.onMouseDown(e)); + this.grid.addEventListener('touchstart', (e) => this.onTouchStart(e), { passive: false }); + + this.boundMouseMove = (e) => this.onMouseMove(e); + this.boundMouseUp = (e) => this.onMouseUp(e); + this.boundTouchMove = (e) => this.onTouchMove(e); + this.boundTouchEnd = (e) => this.onTouchEnd(e); + + window.addEventListener('mousemove', this.boundMouseMove); + window.addEventListener('mouseup', this.boundMouseUp); + window.addEventListener('touchmove', this.boundTouchMove, { passive: false }); + window.addEventListener('touchend', this.boundTouchEnd); + window.addEventListener('touchcancel', this.boundTouchEnd); + + this.render(); + } + + destroy(): void { + this.endDragGhost(); + window.removeEventListener('mousemove', this.boundMouseMove); + window.removeEventListener('mouseup', this.boundMouseUp); + window.removeEventListener('touchmove', this.boundTouchMove); + window.removeEventListener('touchend', this.boundTouchEnd); + window.removeEventListener('touchcancel', this.boundTouchEnd); + } + + setMode(mode: BoardMode, playerColor?: Color): void { + this.mode = mode; + if (playerColor) this.playerColor = playerColor; + this.selectedSq = -1; + this.legalTargets.clear(); + this.pendingPromotion = null; + if (mode !== 'play') this.premove = null; + this.render(); + } + + setOrientation(color: Color): void { + this.orientation = color; + this.render(); + } + + getOrientation(): Color { + return this.orientation; + } + + flip(): void { + this.orientation = this.orientation === 'w' ? 'b' : 'w'; + this.render(); + } + + setArrows(arrows: BoardArrow[]): void { + this.arrows = arrows.slice(); + this.renderArrows(); + } + + clearPremove(): void { + if (this.premove) { + this.premove = null; + this.render(); + } + } + + private clearSelectionAndPremove(): void { + this.selectedSq = -1; + this.legalTargets.clear(); + this.premove = null; + this.pendingPromotion = null; + this.render(); + } + + setPosition(fen: string, lastMoveUci?: string | null): void { + try { + this.chess.loadFen(fen); + } catch { + return; + } + + if (lastMoveUci && lastMoveUci.length >= 4) { + this.lastMoveFrom = algToSq(lastMoveUci.slice(0, 2)); + this.lastMoveTo = algToSq(lastMoveUci.slice(2, 4)); + } else { + this.lastMoveFrom = -1; + this.lastMoveTo = -1; + } + + this.selectedSq = -1; + this.legalTargets.clear(); + this.pendingPromotion = null; + + // Auto-execute queued premove if it's now our turn in play mode + if (this.mode === 'play' && this.premove && this.chess.turn() === this.playerColor) { + const pm = this.premove; + this.premove = null; + const uci = sqToAlg(pm.from) + sqToAlg(pm.to) + (pm.promotion || ''); + const legal = this.chess.legalMoves(pm.from); + if (legal.some((m) => m.uci === uci)) { + this.render(); + if (this.onMoveCallback) { + this.onMoveCallback(uci); + } + return; + } + } + + this.render(); + } + + private visualIndexToSq(visualIdx: number): number { + const vr = visualIdx >> 3; + const vc = visualIdx & 7; + const r = this.orientation === 'w' ? vr : 7 - vr; + const c = this.orientation === 'w' ? vc : 7 - vc; + return (r << 3) | c; + } + + private sqToVisualCoords(sq: number): { vr: number; vc: number } { + const r = sq >> 3; + const c = sq & 7; + return { + vr: this.orientation === 'w' ? r : 7 - r, + vc: this.orientation === 'w' ? c : 7 - c + }; + } + + private clientPointToSq(clientX: number, clientY: number): number { + const rect = this.grid.getBoundingClientRect(); + if (clientX < rect.left || clientX > rect.right || clientY < rect.top || clientY > rect.bottom) { + return -1; + } + const vc = Math.min(7, Math.max(0, Math.floor(((clientX - rect.left) / rect.width) * 8))); + const vr = Math.min(7, Math.max(0, Math.floor(((clientY - rect.top) / rect.height) * 8))); + return this.visualIndexToSq((vr << 3) | vc); + } + + private isPieceInteractive(piece: Piece | null): boolean { + if (!piece || this.mode === 'readonly') return false; + if (this.mode === 'analyze') { + return piece.color === this.chess.turn(); + } + return piece.color === this.playerColor; + } + + private computeTargetsForSquare(fromSq: number): Map { + const map = new Map(); + const piece = this.chess.get(fromSq); + if (!piece) return map; + + if (this.mode === 'analyze' || this.chess.turn() === piece.color) { + const legal = this.chess.legalMoves(fromSq); + for (let i = 0; i < legal.length; i++) { + const m = legal[i]!; + const list = map.get(m.to) || []; + if (m.promotion && list.indexOf(m.promotion) === -1) { + list.push(m.promotion); + } + map.set(m.to, list); + } + return map; + } + + // Premove geometric targets (only in 'play' mode when waiting for opponent) + if (this.mode === 'play' && piece.color === this.playerColor) { + const r = fromSq >> 3; + const c = fromSq & 7; + for (let to = 0; to < 64; to++) { + if (to === fromSq) continue; + const tr = to >> 3; + const tc = to & 7; + const dr = tr - r; + const dc = tc - c; + const adr = Math.abs(dr); + const adc = Math.abs(dc); + let ok = false; + + if (piece.type === 'p') { + const forward = piece.color === 'w' ? -1 : 1; + const startRank = piece.color === 'w' ? 6 : 1; + if (dr === forward && adc <= 1) ok = true; + else if (r === startRank && dr === forward * 2 && dc === 0) ok = true; + if (ok) { + const promoRank = piece.color === 'w' ? 0 : 7; + map.set(to, tr === promoRank ? ['q', 'r', 'b', 'n'] : []); + continue; + } + } else if (piece.type === 'n') { + ok = (adr === 2 && adc === 1) || (adr === 1 && adc === 2); + } else if (piece.type === 'b') { + ok = adr === adc; + } else if (piece.type === 'r') { + ok = dr === 0 || dc === 0; + } else if (piece.type === 'q') { + ok = dr === 0 || dc === 0 || adr === adc; + } else if (piece.type === 'k') { + ok = (adr <= 1 && adc <= 1) || (dr === 0 && adc === 2 && ((piece.color === 'w' && r === 7 && c === 4) || (piece.color === 'b' && r === 0 && c === 4))); + } + + if (ok) map.set(to, []); + } + } + + return map; + } + + private selectSquare(sq: number): void { + const piece = this.chess.get(sq); + if (!this.isPieceInteractive(piece)) { + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + return; + } + this.selectedSq = sq; + this.legalTargets = this.computeTargetsForSquare(sq); + this.render(); + } + + private tryMoveTo(fromSq: number, toSq: number): boolean { + const targets = this.computeTargetsForSquare(fromSq); + if (!targets.has(toSq)) return false; + + const piece = this.chess.get(fromSq); + if (!piece) return false; + const isPremove = this.mode === 'play' && this.chess.turn() !== this.playerColor; + const promos = targets.get(toSq) || []; + + if (promos.length > 0) { + this.pendingPromotion = { from: fromSq, to: toSq, isPremove, color: piece.color }; + this.selectedSq = -1; + this.legalTargets.clear(); + this.renderPromotionPicker(); + return true; + } + + if (isPremove) { + this.premove = { from: fromSq, to: toSq }; + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + return true; + } + + const uci = sqToAlg(fromSq) + sqToAlg(toSq); + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + if (this.onMoveCallback) { + this.onMoveCallback(uci); + } + return true; + } + + private renderPromotionPicker(): void { + clearNode(this.promoOverlay); + if (!this.pendingPromotion) { + this.promoOverlay.className = 'promo-overlay hidden'; + return; + } + this.promoOverlay.className = 'promo-overlay'; + const box = el('div', { className: 'promo-box' }); + const pieces: PromotionPiece[] = ['q', 'r', 'b', 'n']; + const pending = this.pendingPromotion; + + for (const pt of pieces) { + const btn = el('button', { type: 'button', className: 'promo-choice', title: pt.toUpperCase() }); + btn.appendChild(createPieceNode(pending.color, pt)); + btn.addEventListener('click', (e) => { + e.stopPropagation(); + this.pendingPromotion = null; + this.promoOverlay.className = 'promo-overlay hidden'; + if (pending.isPremove) { + this.premove = { from: pending.from, to: pending.to, promotion: pt }; + this.render(); + } else { + const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt; + this.render(); + if (this.onMoveCallback) this.onMoveCallback(uci); + } + }); + box.appendChild(btn); + } + + const cancelBtn = el('button', { type: 'button', className: 'promo-cancel' }, 'Cancel'); + cancelBtn.addEventListener('click', (e) => { + e.stopPropagation(); + this.pendingPromotion = null; + this.promoOverlay.className = 'promo-overlay hidden'; + }); + box.appendChild(cancelBtn); + + this.promoOverlay.appendChild(box); + } + + private onMouseDown(e: MouseEvent): void { + if (e.button !== 0 || this.pendingPromotion) return; + const sq = this.clientPointToSq(e.clientX, e.clientY); + if (sq < 0) return; + this.handlePointerDown(sq, e.clientX, e.clientY, null); + } + + private onTouchStart(e: TouchEvent): void { + if (this.pendingPromotion || e.touches.length !== 1) return; + const t = e.touches[0]!; + const sq = this.clientPointToSq(t.clientX, t.clientY); + if (sq < 0) return; + this.handlePointerDown(sq, t.clientX, t.clientY, t.identifier); + } + + private handlePointerDown(sq: number, clientX: number, clientY: number, touchId: number | null): void { + if (this.mode === 'readonly') return; + + // If user already selected a piece and clicks a valid destination, execute move immediately + if (this.selectedSq >= 0 && this.selectedSq !== sq && this.legalTargets.has(sq)) { + this.tryMoveTo(this.selectedSq, sq); + return; + } + + const piece = this.chess.get(sq); + if (!this.isPieceInteractive(piece)) { + if (this.selectedSq >= 0 || this.premove) { + this.clearSelectionAndPremove(); + } + return; + } + + this.pointerDownSq = sq; + this.dragStartX = clientX; + this.dragStartY = clientY; + this.dragActive = false; + this.dragTouchId = touchId; + } + + private onMouseMove(e: MouseEvent): void { + if (this.pointerDownSq < 0 || this.dragTouchId !== null) return; + this.handlePointerMove(e.clientX, e.clientY); + } + + private onTouchMove(e: TouchEvent): void { + if (this.pointerDownSq < 0 || this.dragTouchId === null) return; + let touch: Touch | null = null; + for (let i = 0; i < e.touches.length; i++) { + if (e.touches[i]!.identifier === this.dragTouchId) { + touch = e.touches[i]!; + break; + } + } + if (!touch) return; + e.preventDefault(); + this.handlePointerMove(touch.clientX, touch.clientY); + } + + private handlePointerMove(clientX: number, clientY: number): void { + if (!this.dragActive) { + const dx = clientX - this.dragStartX; + const dy = clientY - this.dragStartY; + if (dx * dx + dy * dy < 25) return; + + const piece = this.chess.get(this.pointerDownSq); + if (!piece) { + this.pointerDownSq = -1; + return; + } + + this.dragActive = true; + this.selectedSq = this.pointerDownSq; + this.legalTargets = this.computeTargetsForSquare(this.pointerDownSq); + this.render(); + + const sqSize = this.grid.getBoundingClientRect().width / 8; + const ghost = createPieceNode(piece.color, piece.type); + ghost.className = 'piece drag-ghost'; + ghost.style.width = `${sqSize}px`; + ghost.style.height = `${sqSize}px`; + document.body.appendChild(ghost); + this.dragGhost = ghost; + } + + if (this.dragGhost) { + this.dragGhost.style.left = `${clientX}px`; + this.dragGhost.style.top = `${clientY}px`; + } + } + + private onMouseUp(e: MouseEvent): void { + if (this.pointerDownSq < 0 || this.dragTouchId !== null) return; + this.handlePointerUp(e.clientX, e.clientY); + } + + private onTouchEnd(e: TouchEvent): void { + if (this.pointerDownSq < 0 || this.dragTouchId === null) return; + let touch: Touch | null = null; + for (let i = 0; i < e.changedTouches.length; i++) { + if (e.changedTouches[i]!.identifier === this.dragTouchId) { + touch = e.changedTouches[i]!; + break; + } + } + if (!touch) return; + this.handlePointerUp(touch.clientX, touch.clientY); + } + + private handlePointerUp(clientX: number, clientY: number): void { + const startSq = this.pointerDownSq; + const wasDragging = this.dragActive; + this.pointerDownSq = -1; + this.dragActive = false; + this.dragTouchId = null; + this.endDragGhost(); + + const dropSq = this.clientPointToSq(clientX, clientY); + + if (wasDragging) { + if (dropSq >= 0 && dropSq !== startSq && this.legalTargets.has(dropSq)) { + this.tryMoveTo(startSq, dropSq); + } else { + this.render(); + } + return; + } + + // Tap / Click behavior + if (this.selectedSq === startSq) { + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + } else { + if (this.premove) this.premove = null; + this.selectSquare(startSq); + } + } + + private endDragGhost(): void { + if (this.dragGhost && this.dragGhost.parentNode) { + this.dragGhost.parentNode.removeChild(this.dragGhost); + } + this.dragGhost = null; + } + + private render(): void { + const files = 'abcdefgh'; + const ranks = '87654321'; + const turnInCheck = this.chess.inCheck(); + const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1; + + for (let vi = 0; vi < 64; vi++) { + const sq = this.visualIndexToSq(vi); + const r = sq >> 3; + const c = sq & 7; + const vr = vi >> 3; + const vc = vi & 7; + + const isLight = ((r + c) & 1) === 0; + const sqEl = this.squareEls[vi]!; + let cls = 'sq ' + (isLight ? 'sq-light' : 'sq-dark'); + + if (sq === this.lastMoveFrom || sq === this.lastMoveTo) cls += ' sq-last'; + if (sq === this.selectedSq) cls += ' sq-selected'; + if (sq === checkKingSq) cls += ' sq-check'; + if (this.premove && (sq === this.premove.from || sq === this.premove.to)) cls += ' sq-premove'; + + sqEl.className = cls; + clearNode(sqEl); + + // Rank coordinates on leftmost column (vc === 0) + if (vc === 0) { + sqEl.appendChild(el('span', { className: 'coord-rank' }, ranks.charAt(r))); + } + // File coordinates on bottom row (vr === 7) + if (vr === 7) { + sqEl.appendChild(el('span', { className: 'coord-file' }, files.charAt(c))); + } + + const piece = this.chess.get(sq); + if (piece) { + const pieceNode = createPieceNode(piece.color, piece.type); + if (this.dragActive && sq === this.selectedSq) { + pieceNode.className += ' piece-dragging-origin'; + } + sqEl.appendChild(pieceNode); + } + + if (this.legalTargets.has(sq)) { + const isCapture = piece !== null; + sqEl.appendChild(el('div', { className: isCapture ? 'hint-capture' : 'hint-dot' })); + } + } + + this.renderArrows(); + } + + private renderArrows(): void { + while (this.svgArrows.firstChild) { + this.svgArrows.removeChild(this.svgArrows.firstChild); + } + if (this.arrows.length === 0) return; + + const svgNs = 'http://www.w3.org/2000/svg'; + const defs = document.createElementNS(svgNs, 'defs'); + + for (let i = 0; i < this.arrows.length; i++) { + const arr = this.arrows[i]!; + const fromSq = algToSq(arr.from); + const toSq = algToSq(arr.to); + if (fromSq < 0 || toSq < 0 || fromSq === toSq) continue; + + const color = arr.color || '#629924'; + const markerId = `arrow-${i}`; + + const marker = document.createElementNS(svgNs, 'marker'); + marker.setAttribute('id', markerId); + marker.setAttribute('markerWidth', '4'); + marker.setAttribute('markerHeight', '4'); + marker.setAttribute('refX', '2.4'); + marker.setAttribute('refY', '2'); + marker.setAttribute('orient', 'auto'); + + const head = document.createElementNS(svgNs, 'path'); + head.setAttribute('d', 'M0,0.4 L3.4,2 L0,3.6 Z'); + head.setAttribute('fill', color); + marker.appendChild(head); + defs.appendChild(marker); + } + this.svgArrows.appendChild(defs); + + for (let i = 0; i < this.arrows.length; i++) { + const arr = this.arrows[i]!; + const fromSq = algToSq(arr.from); + const toSq = algToSq(arr.to); + if (fromSq < 0 || toSq < 0 || fromSq === toSq) continue; + + const fc = this.sqToVisualCoords(fromSq); + const tc = this.sqToVisualCoords(toSq); + const x1 = fc.vc * 100 + 50; + const y1 = fc.vr * 100 + 50; + const x2Raw = tc.vc * 100 + 50; + const y2Raw = tc.vr * 100 + 50; + + const dx = x2Raw - x1; + const dy = y2Raw - y1; + const dist = Math.sqrt(dx * dx + dy * dy); + const shorten = 22; + const x2 = x2Raw - (dx / dist) * shorten; + const y2 = y2Raw - (dy / dist) * shorten; + + const line = document.createElementNS(svgNs, 'line'); + line.setAttribute('x1', String(x1)); + line.setAttribute('y1', String(y1)); + line.setAttribute('x2', String(x2)); + line.setAttribute('y2', String(y2)); + line.setAttribute('stroke', arr.color || '#629924'); + line.setAttribute('stroke-width', '15'); + line.setAttribute('stroke-linecap', 'round'); + line.setAttribute('opacity', '0.82'); + line.setAttribute('marker-end', `url(#arrow-${i})`); + this.svgArrows.appendChild(line); + } + } +} diff --git a/src/client/components/clock.ts b/src/client/components/clock.ts new file mode 100644 index 0000000..aaf5d65 --- /dev/null +++ b/src/client/components/clock.ts @@ -0,0 +1,63 @@ +import { formatClock } from '../../shared/timeControl'; +import { el } from '../dom'; + +export class ClockWidget { + public readonly root: HTMLElement; + private baseMs: number = 0; + private syncedAt: number = 0; + private running: boolean = false; + private unlimited: boolean = false; + private timer: number | null = null; + + constructor() { + this.root = el('div', { className: 'clock-box' }, '00:00'); + } + + update(ms: number, running: boolean, unlimited: boolean): void { + this.baseMs = Math.max(0, ms); + this.syncedAt = Date.now(); + this.running = running; + this.unlimited = unlimited; + + if (running && !unlimited) { + this.startTick(); + } else { + this.stopTick(); + } + this.render(); + } + + private startTick(): void { + if (this.timer !== null) return; + this.timer = window.setInterval(() => this.render(), 100); + } + + private stopTick(): void { + if (this.timer !== null) { + window.clearInterval(this.timer); + this.timer = null; + } + } + + private render(): void { + if (this.unlimited) { + this.root.textContent = '∞'; + this.root.className = 'clock-box clock-unlimited'; + return; + } + + const elapsed = this.running ? Math.max(0, Date.now() - this.syncedAt) : 0; + const currentMs = Math.max(0, this.baseMs - elapsed); + this.root.textContent = formatClock(currentMs); + + let cls = 'clock-box'; + if (this.running) cls += ' clock-active'; + if (currentMs <= 15_000 && currentMs > 0) cls += ' clock-low'; + if (currentMs === 0) cls += ' clock-flag'; + this.root.className = cls; + } + + destroy(): void { + this.stopTick(); + } +} diff --git a/src/client/components/evalGraph.ts b/src/client/components/evalGraph.ts new file mode 100644 index 0000000..74dd103 --- /dev/null +++ b/src/client/components/evalGraph.ts @@ -0,0 +1,113 @@ +import type { GameAnalysisReport } from '../../shared/types'; +import { el } from '../dom'; + +export class EvalGraph { + public readonly root: HTMLElement; + private svg: SVGSVGElement; + private totalPlies = 0; + + constructor(private readonly onSelectPly: (ply: number) => void) { + this.root = el('div', { className: 'eval-graph-wrap' }); + this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + this.svg.setAttribute('viewBox', '0 0 400 100'); + this.svg.setAttribute('preserveAspectRatio', 'none'); + this.svg.setAttribute('class', 'eval-graph-svg'); + this.root.appendChild(this.svg); + + this.svg.addEventListener('click', (e) => { + if (this.totalPlies <= 0) return; + const rect = this.svg.getBoundingClientRect(); + if (rect.width <= 0) return; + const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)); + const ply = Math.round(ratio * this.totalPlies); + this.onSelectPly(ply); + }); + } + + render(report: GameAnalysisReport | null, activePly: number): void { + while (this.svg.firstChild) { + this.svg.removeChild(this.svg.firstChild); + } + + const ns = 'http://www.w3.org/2000/svg'; + const bg = document.createElementNS(ns, 'rect'); + bg.setAttribute('x', '0'); + bg.setAttribute('y', '0'); + bg.setAttribute('width', '400'); + bg.setAttribute('height', '100'); + bg.setAttribute('class', 'eval-graph-bg'); + this.svg.appendChild(bg); + + // Midline + const mid = document.createElementNS(ns, 'line'); + mid.setAttribute('x1', '0'); + mid.setAttribute('y1', '50'); + mid.setAttribute('x2', '400'); + mid.setAttribute('y2', '50'); + mid.setAttribute('class', 'eval-graph-mid'); + this.svg.appendChild(mid); + + if (!report || report.status !== 'done' || report.plies.length === 0) { + this.totalPlies = 0; + return; + } + + this.totalPlies = report.plies.length; + const pts: Array<{ x: number; y: number; ply: number; cls: string }> = [ + { + x: 0, + y: 100 - report.initialWinPercent, + ply: 0, + cls: 'none' + } + ]; + + for (let i = 0; i < report.plies.length; i++) { + const p = report.plies[i]!; + const x = ((i + 1) / report.plies.length) * 400; + const y = 100 - p.winPercentAfter; + pts.push({ x, y, ply: p.ply, cls: p.classification }); + } + + // White advantage fill polygon (closed along y=50) + const polyPts = [`0,50`]; + for (let i = 0; i < pts.length; i++) { + polyPts.push(`${pts[i]!.x.toFixed(1)},${pts[i]!.y.toFixed(1)}`); + } + polyPts.push(`400,50`); + + const fillArea = document.createElementNS(ns, 'polygon'); + fillArea.setAttribute('points', polyPts.join(' ')); + fillArea.setAttribute('class', 'eval-graph-area'); + this.svg.appendChild(fillArea); + + const line = document.createElementNS(ns, 'polyline'); + line.setAttribute('points', pts.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ')); + line.setAttribute('fill', 'none'); + line.setAttribute('class', 'eval-graph-line'); + this.svg.appendChild(line); + + // Markers for inaccuracies, mistakes, blunders + for (let i = 1; i < pts.length; i++) { + const p = pts[i]!; + if (p.cls === 'inaccuracy' || p.cls === 'mistake' || p.cls === 'blunder') { + const dot = document.createElementNS(ns, 'circle'); + dot.setAttribute('cx', p.x.toFixed(1)); + dot.setAttribute('cy', p.y.toFixed(1)); + dot.setAttribute('r', p.cls === 'blunder' ? '3.4' : '2.6'); + dot.setAttribute('class', `eval-dot eval-dot-${p.cls}`); + this.svg.appendChild(dot); + } + } + + // Active ply cursor + const cursorX = (Math.min(this.totalPlies, Math.max(0, activePly)) / this.totalPlies) * 400; + const cursor = document.createElementNS(ns, 'line'); + cursor.setAttribute('x1', cursorX.toFixed(1)); + cursor.setAttribute('y1', '0'); + cursor.setAttribute('x2', cursorX.toFixed(1)); + cursor.setAttribute('y2', '100'); + cursor.setAttribute('class', 'eval-graph-cursor'); + this.svg.appendChild(cursor); + } +} diff --git a/src/client/components/moveList.ts b/src/client/components/moveList.ts new file mode 100644 index 0000000..b2eb59b --- /dev/null +++ b/src/client/components/moveList.ts @@ -0,0 +1,172 @@ +import type { Color, MoveClassification } from '../../shared/types'; +import { classificationNag } from '../../shared/winProb'; +import { clearNode, el } from '../dom'; + +export interface MoveListOptions { + onSelectPly: (ply: number) => void; + onFlip: () => void; + enableKeyboard?: boolean; +} + +export class MoveList { + public readonly root: HTMLElement; + private readonly listContainer: HTMLElement; + private totalPlies = 0; + private activePly = 0; + private readonly boundKeyDown: (e: KeyboardEvent) => void; + + constructor(private readonly opts: MoveListOptions) { + this.root = el('div', { className: 'movelist-panel' }); + + const nav = el('div', { className: 'movelist-nav' }); + const btnFirst = el('button', { type: 'button', className: 'btn btn-icon', title: 'Start (Home)' }, '|<'); + const btnPrev = el('button', { type: 'button', className: 'btn btn-icon', title: 'Previous (Left)' }, '<'); + const btnNext = el('button', { type: 'button', className: 'btn btn-icon', title: 'Next (Right)' }, '>'); + const btnLast = el('button', { type: 'button', className: 'btn btn-icon', title: 'End (End)' }, '>|'); + const btnFlip = el('button', { type: 'button', className: 'btn btn-icon', title: 'Flip board (F)' }, 'Flip'); + + btnFirst.addEventListener('click', () => this.opts.onSelectPly(0)); + btnPrev.addEventListener('click', () => this.opts.onSelectPly(Math.max(0, this.activePly - 1))); + btnNext.addEventListener('click', () => this.opts.onSelectPly(Math.min(this.totalPlies, this.activePly + 1))); + btnLast.addEventListener('click', () => this.opts.onSelectPly(this.totalPlies)); + btnFlip.addEventListener('click', () => this.opts.onFlip()); + + nav.appendChild(btnFirst); + nav.appendChild(btnPrev); + nav.appendChild(btnNext); + nav.appendChild(btnLast); + nav.appendChild(btnFlip); + + this.listContainer = el('div', { className: 'movelist-scroll' }); + + this.root.appendChild(nav); + this.root.appendChild(this.listContainer); + + this.boundKeyDown = (e: KeyboardEvent) => { + if (this.opts.enableKeyboard === false) return; + const tag = (e.target as HTMLElement | null)?.tagName || ''; + if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return; + if (e.key === 'ArrowLeft') { + e.preventDefault(); + this.opts.onSelectPly(Math.max(0, this.activePly - 1)); + } else if (e.key === 'ArrowRight') { + e.preventDefault(); + this.opts.onSelectPly(Math.min(this.totalPlies, this.activePly + 1)); + } else if (e.key === 'Home') { + e.preventDefault(); + this.opts.onSelectPly(0); + } else if (e.key === 'End') { + e.preventDefault(); + this.opts.onSelectPly(this.totalPlies); + } else if (e.key === 'f' || e.key === 'F') { + if (!e.ctrlKey && !e.metaKey) { + this.opts.onFlip(); + } + } + }; + + window.addEventListener('keydown', this.boundKeyDown); + } + + destroy(): void { + window.removeEventListener('keydown', this.boundKeyDown); + } + + render( + movesSan: ReadonlyArray, + activePly: number, + options?: { + startMoveNumber?: number; + startTurn?: Color; + classifications?: ReadonlyArray; + } + ): void { + this.totalPlies = movesSan.length; + this.activePly = activePly; + clearNode(this.listContainer); + + if (movesSan.length === 0) { + this.listContainer.appendChild(el('div', { className: 'movelist-empty' }, 'No moves yet')); + return; + } + + const startTurn = options?.startTurn || 'w'; + let moveNum = options?.startMoveNumber || 1; + let activeCell: HTMLElement | null = null; + + const table = el('div', { className: 'movelist-rows' }); + let i = 0; + + if (startTurn === 'b' && movesSan.length > 0) { + const row = el('div', { className: 'movelist-row' }); + row.appendChild(el('span', { className: 'move-num' }, `${moveNum}.`)); + row.appendChild(el('span', { className: 'move-cell move-empty' }, '...')); + const bCell = this.createMoveCell(1, movesSan[0]!, activePly === 1, options?.classifications?.[0]); + if (activePly === 1) activeCell = bCell; + row.appendChild(bCell); + table.appendChild(row); + i = 1; + moveNum++; + } + + while (i < movesSan.length) { + const row = el('div', { className: 'movelist-row' }); + row.appendChild(el('span', { className: 'move-num' }, `${moveNum}.`)); + + const wPly = i + 1; + const wCell = this.createMoveCell(wPly, movesSan[i]!, activePly === wPly, options?.classifications?.[i]); + if (activePly === wPly) activeCell = wCell; + row.appendChild(wCell); + i++; + + if (i < movesSan.length) { + const bPly = i + 1; + const bCell = this.createMoveCell(bPly, movesSan[i]!, activePly === bPly, options?.classifications?.[i]); + if (activePly === bPly) activeCell = bCell; + row.appendChild(bCell); + i++; + } else { + row.appendChild(el('span', { className: 'move-cell move-empty' })); + } + + table.appendChild(row); + moveNum++; + } + + this.listContainer.appendChild(table); + + if (activeCell) { + const top = activeCell.offsetTop; + const height = activeCell.offsetHeight; + const viewTop = this.listContainer.scrollTop; + const viewHeight = this.listContainer.clientHeight; + if (top < viewTop) { + this.listContainer.scrollTop = top; + } else if (top + height > viewTop + viewHeight) { + this.listContainer.scrollTop = top + height - viewHeight; + } + } else if (activePly === 0) { + this.listContainer.scrollTop = 0; + } + } + + private createMoveCell( + ply: number, + san: string, + isActive: boolean, + cls?: MoveClassification + ): HTMLElement { + const nag = cls ? classificationNag(cls) : ''; + let className = 'move-cell'; + if (isActive) className += ' move-active'; + if (cls && nag) className += ` move-cls-${cls}`; + + const cell = el('button', { type: 'button', className }); + cell.appendChild(el('span', null, san)); + if (nag) { + cell.appendChild(el('span', { className: `move-nag nag-${cls}` }, nag)); + } + cell.addEventListener('click', () => this.opts.onSelectPly(ply)); + return cell; + } +} diff --git a/src/client/components/navbar.ts b/src/client/components/navbar.ts new file mode 100644 index 0000000..a629552 --- /dev/null +++ b/src/client/components/navbar.ts @@ -0,0 +1,235 @@ +import type { UserSummary } from '../../shared/types'; +import { + type BoardTheme, + type UiTheme, + applyBoardTheme, + applyUiTheme, + clearNode, + el, + getSavedBoardTheme, + getSavedUiTheme +} from '../dom'; +import { sound } from '../sound'; + +export interface NavbarState { + user: UserSummary | null; + currentPath: string; + friendBadgeCount: number; + activeGameId: string | null; +} + +export interface NavbarActions { + onNavigate: (path: string) => void; + onLogout: () => void; +} + +export class Navbar { + private settingsOpen = false; + private uiTheme: UiTheme = getSavedUiTheme(); + private boardTheme: BoardTheme = getSavedBoardTheme(); + + constructor( + private readonly container: HTMLElement, + private readonly actions: NavbarActions + ) { + applyUiTheme(this.uiTheme); + applyBoardTheme(this.boardTheme); + document.addEventListener('click', (e) => { + if (this.settingsOpen && !this.container.contains(e.target as Node)) { + this.settingsOpen = false; + this.render(this.lastState); + } + }); + } + + private lastState: NavbarState = { + user: null, + currentPath: '/', + friendBadgeCount: 0, + activeGameId: null + }; + + render(state: NavbarState): void { + this.lastState = state; + clearNode(this.container); + + const inner = el('div', { className: 'nav-inner' }); + + // Brand + const brand = el('a', { href: '/', className: 'nav-brand' }, 'ChessUp'); + brand.addEventListener('click', (e) => { + e.preventDefault(); + this.actions.onNavigate('/'); + }); + inner.appendChild(brand); + + // Primary nav links + const links = el('nav', { className: 'nav-links' }); + const navItems: Array<{ href: string; label: string; badge?: number; match: (p: string) => boolean }> = [ + { href: '/', label: 'Lobby', match: (p) => p === '/' }, + { href: '/bots', label: 'Play Bot', match: (p) => p.indexOf('/bots') === 0 }, + { href: '/analysis', label: 'Analysis', match: (p) => p.indexOf('/analysis') === 0 }, + { + href: '/friends', + label: 'Friends', + badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined, + match: (p) => p.indexOf('/friends') === 0 + }, + { href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 0 } + ]; + + for (const item of navItems) { + const a = el('a', { + href: item.href, + className: item.match(state.currentPath) ? 'nav-link active' : 'nav-link' + }); + a.appendChild(document.createTextNode(item.label)); + if (item.badge !== undefined) { + a.appendChild(el('span', { className: 'nav-badge' }, item.badge)); + } + a.addEventListener('click', (e) => { + e.preventDefault(); + this.actions.onNavigate(item.href); + }); + links.appendChild(a); + } + + if (state.activeGameId && state.currentPath !== `/game/${state.activeGameId}`) { + const resume = el('a', { href: `/game/${state.activeGameId}`, className: 'nav-resume' }, 'Resume Game'); + resume.addEventListener('click', (e) => { + e.preventDefault(); + this.actions.onNavigate(`/game/${state.activeGameId}`); + }); + links.appendChild(resume); + } + + inner.appendChild(links); + + // Right side: settings + account + const right = el('div', { className: 'nav-right' }); + + const settingsWrap = el('div', { className: 'nav-settings-wrap' }); + const settingsBtn = el( + 'button', + { type: 'button', className: 'btn btn-sm btn-ghost', title: 'Appearance & Sound' }, + 'Prefs' + ); + settingsBtn.addEventListener('click', (e) => { + e.stopPropagation(); + this.settingsOpen = !this.settingsOpen; + this.render(this.lastState); + }); + settingsWrap.appendChild(settingsBtn); + + if (this.settingsOpen) { + settingsWrap.appendChild(this.buildSettingsPopover()); + } + right.appendChild(settingsWrap); + + if (state.user) { + const profileLink = el( + 'a', + { href: `/u/${encodeURIComponent(state.user.username)}`, className: 'nav-user-link' }, + state.user.username + ); + profileLink.addEventListener('click', (e) => { + e.preventDefault(); + this.actions.onNavigate(`/u/${encodeURIComponent(state.user!.username)}`); + }); + right.appendChild(profileLink); + + const logoutBtn = el('button', { type: 'button', className: 'btn btn-sm btn-ghost' }, 'Sign out'); + logoutBtn.addEventListener('click', () => this.actions.onLogout()); + right.appendChild(logoutBtn); + } else { + const loginLink = el('a', { href: '/login', className: 'btn btn-sm btn-primary' }, 'Sign in'); + loginLink.addEventListener('click', (e) => { + e.preventDefault(); + this.actions.onNavigate('/login'); + }); + right.appendChild(loginLink); + } + + inner.appendChild(right); + this.container.appendChild(inner); + } + + private buildSettingsPopover(): HTMLElement { + const pop = el('div', { className: 'settings-popover' }); + pop.addEventListener('click', (e) => e.stopPropagation()); + + // UI Theme + const themeRow = el('div', { className: 'settings-row' }); + themeRow.appendChild(el('span', { className: 'settings-label' }, 'UI Theme')); + const themeBtns = el('div', { className: 'btn-group' }); + for (const t of ['dark', 'light'] as UiTheme[]) { + const b = el( + 'button', + { + type: 'button', + className: this.uiTheme === t ? 'btn btn-xs btn-primary' : 'btn btn-xs' + }, + t === 'dark' ? 'Dark' : 'Light' + ); + b.addEventListener('click', () => { + this.uiTheme = t; + applyUiTheme(t); + this.render(this.lastState); + }); + themeBtns.appendChild(b); + } + themeRow.appendChild(themeBtns); + pop.appendChild(themeRow); + + // Board Theme + const boardRow = el('div', { className: 'settings-row' }); + boardRow.appendChild(el('span', { className: 'settings-label' }, 'Board')); + const boardBtns = el('div', { className: 'btn-group' }); + const boards: Array<{ id: BoardTheme; label: string }> = [ + { id: 'brown', label: 'Brown' }, + { id: 'green', label: 'Green' }, + { id: 'blue', label: 'Blue' }, + { id: 'mono', label: 'Mono' } + ]; + for (const bt of boards) { + const b = el( + 'button', + { + type: 'button', + className: this.boardTheme === bt.id ? 'btn btn-xs btn-primary' : 'btn btn-xs' + }, + bt.label + ); + b.addEventListener('click', () => { + this.boardTheme = bt.id; + applyBoardTheme(bt.id); + this.render(this.lastState); + }); + boardBtns.appendChild(b); + } + boardRow.appendChild(boardBtns); + pop.appendChild(boardRow); + + // Sound toggle + const soundRow = el('div', { className: 'settings-row' }); + soundRow.appendChild(el('span', { className: 'settings-label' }, 'Sounds')); + const muted = sound.isMuted(); + const soundBtn = el( + 'button', + { + type: 'button', + className: !muted ? 'btn btn-xs btn-primary' : 'btn btn-xs' + }, + muted ? 'Muted' : 'On' + ); + soundBtn.addEventListener('click', () => { + sound.setMuted(!muted); + if (muted) sound.play('move'); + this.render(this.lastState); + }); + soundRow.appendChild(soundBtn); + pop.appendChild(soundRow); + + return pop; + } +} diff --git a/src/client/dom.ts b/src/client/dom.ts new file mode 100644 index 0000000..b490682 --- /dev/null +++ b/src/client/dom.ts @@ -0,0 +1,133 @@ +export type ChildNodeSpec = Node | string | number | null | undefined | false; + +export function el( + tag: K, + attrs?: Record | null, + children?: ChildNodeSpec | ChildNodeSpec[] +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (attrs) { + for (const key in attrs) { + if (!Object.prototype.hasOwnProperty.call(attrs, key)) continue; + const val = attrs[key]; + if (val === undefined || val === false) continue; + if (key === 'className') { + node.className = String(val); + } else if (val === true) { + node.setAttribute(key, ''); + } else { + node.setAttribute(key, String(val)); + } + } + } + if (children !== undefined) { + appendChildren(node, children); + } + return node; +} + +export function appendChildren(parent: Node, children: ChildNodeSpec | ChildNodeSpec[]): void { + const list = Array.isArray(children) ? children : [children]; + for (let i = 0; i < list.length; i++) { + const item = list[i]; + if (item === null || item === undefined || item === false) continue; + if (typeof item === 'string' || typeof item === 'number') { + parent.appendChild(document.createTextNode(String(item))); + } else { + parent.appendChild(item); + } + } +} + +export function clearNode(node: Node): void { + while (node.firstChild) { + node.removeChild(node.firstChild); + } +} + +export function formatRelativeDate(ts: number): string { + const diffSec = Math.floor((Date.now() - ts) / 1000); + if (diffSec < 60) return 'just now'; + if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`; + if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`; + if (diffSec < 604800) return `${Math.floor(diffSec / 86400)}d ago`; + const d = new Date(ts); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +export function formatDateShort(ts: number): string { + const d = new Date(ts); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +export type UiTheme = 'dark' | 'light'; +export type BoardTheme = 'brown' | 'green' | 'blue' | 'mono'; + +export function getSavedUiTheme(): UiTheme { + try { + const v = localStorage.getItem('chessup_theme'); + return v === 'light' ? 'light' : 'dark'; + } catch { + return 'dark'; + } +} + +export function applyUiTheme(theme: UiTheme): void { + document.documentElement.setAttribute('data-theme', theme); + try { + localStorage.setItem('chessup_theme', theme); + } catch { + // Ignore storage restriction + } +} + +export function getSavedBoardTheme(): BoardTheme { + try { + const v = localStorage.getItem('chessup_board'); + if (v === 'green' || v === 'blue' || v === 'mono') return v; + return 'brown'; + } catch { + return 'brown'; + } +} + +export function applyBoardTheme(board: BoardTheme): void { + document.documentElement.setAttribute('data-board', board); + try { + localStorage.setItem('chessup_board', board); + } catch { + // Ignore + } +} + +export function copyTextToClipboard(text: string): Promise { + if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + return navigator.clipboard.writeText(text).then( + () => true, + () => fallbackCopy(text) + ); + } + return Promise.resolve(fallbackCopy(text)); +} + +function fallbackCopy(text: string): boolean { + try { + const ta = document.createElement('textarea'); + ta.value = text; + ta.style.position = 'fixed'; + ta.style.left = '-9999px'; + document.body.appendChild(ta); + ta.select(); + const ok = document.execCommand('copy'); + document.body.removeChild(ta); + return ok; + } catch { + return false; + } +} diff --git a/src/client/index.html b/src/client/index.html new file mode 100644 index 0000000..bdb81de --- /dev/null +++ b/src/client/index.html @@ -0,0 +1,17 @@ + + + + + + ChessUp — Sharp Chess Server & Analysis + + + +
+
+
+
+
+ + + diff --git a/src/client/main.ts b/src/client/main.ts new file mode 100644 index 0000000..b0156d3 --- /dev/null +++ b/src/client/main.ts @@ -0,0 +1,241 @@ +import type { DirectChallenge, ServerWsMessage, UserSummary } from '../shared/types'; +import { apiRequest, wsClient } from './api'; +import { Navbar } from './components/navbar'; +import { clearNode, el } from './dom'; +import { sound } from './sound'; +import { mountAnalysisView } from './views/analysisView'; +import { mountAuthView } from './views/authView'; +import { mountBotView } from './views/botView'; +import type { AppContext, ViewHandle } from './views/context'; +import { mountFriendsView } from './views/friendsView'; +import { mountGameView } from './views/gameView'; +import { mountHomeView } from './views/homeView'; +import { mountInviteView } from './views/inviteView'; +import { mountLeaderboardView } from './views/leaderboardView'; +import { mountProfileView } from './views/profileView'; + +class App { + private user: UserSummary | null = null; + private activeGameId: string | null = null; + private friendBadgeCount = 0; + private activeView: ViewHandle | null = null; + + private readonly navbarEl = document.getElementById('navbar')!; + private readonly mainEl = document.getElementById('main-content')!; + private readonly toastEl = document.getElementById('toast-container')!; + private readonly navbar: Navbar; + + private readonly ctx: AppContext = { + getUser: () => this.user, + getActiveGameId: () => this.activeGameId, + setActiveGameId: (gid) => { + this.activeGameId = gid; + this.renderNavbar(); + }, + refreshSession: () => this.refreshSession(), + navigate: (path, replace) => this.navigate(path, replace), + toast: (msg, kind) => this.toast(msg, kind) + }; + + constructor() { + this.navbar = new Navbar(this.navbarEl, { + onNavigate: (path) => this.navigate(path), + onLogout: () => this.logout() + }); + + window.addEventListener('popstate', () => { + this.renderRoute(); + }); + + wsClient.onMessage((msg) => this.handleGlobalWs(msg)); + } + + async init(): Promise { + await this.refreshSession(); + wsClient.connect(); + this.renderRoute(); + } + + private async refreshSession(): Promise { + try { + const me = await apiRequest<{ user: UserSummary | null; activeGameId: string | null }>('/api/auth/me'); + this.user = me.user; + this.activeGameId = me.activeGameId; + if (this.user) { + this.refreshFriendBadge(); + } else { + this.friendBadgeCount = 0; + } + } catch { + this.user = null; + this.activeGameId = null; + this.friendBadgeCount = 0; + } + this.renderNavbar(); + } + + private async refreshFriendBadge(): Promise { + if (!this.user) { + this.friendBadgeCount = 0; + this.renderNavbar(); + return; + } + try { + const data = await apiRequest<{ + requests: Array<{ direction: string }>; + challenges: DirectChallenge[]; + }>('/api/friends'); + const incomingReqs = data.requests.filter((r) => r.direction === 'incoming').length; + const incomingChals = data.challenges.filter((c) => c.toUserId === this.user!.id).length; + this.friendBadgeCount = incomingReqs + incomingChals; + this.renderNavbar(); + } catch { + // Ignore + } + } + + private async logout(): Promise { + try { + await apiRequest('/api/auth/logout', { method: 'POST' }); + } catch { + // Ignore + } + this.user = null; + this.activeGameId = null; + this.friendBadgeCount = 0; + wsClient.reconnectNow(); + this.renderNavbar(); + this.navigate('/'); + } + + private renderNavbar(): void { + this.navbar.render({ + user: this.user, + currentPath: window.location.pathname, + friendBadgeCount: this.friendBadgeCount, + activeGameId: this.activeGameId + }); + } + + navigate(path: string, replace: boolean = false): void { + if (replace) { + window.history.replaceState(null, '', path); + } else { + window.history.pushState(null, '', path); + } + this.renderRoute(); + } + + private renderRoute(): void { + if (this.activeView) { + this.activeView.destroy(); + this.activeView = null; + } + clearNode(this.mainEl); + this.renderNavbar(); + + const pathname = window.location.pathname; + const search = new URLSearchParams(window.location.search); + const nextParam = search.get('next') || undefined; + + if (pathname === '/' || pathname === '') { + this.activeView = mountHomeView(this.mainEl, this.ctx); + } else if (pathname === '/login') { + this.activeView = mountAuthView(this.mainEl, this.ctx, 'login', nextParam); + } else if (pathname === '/register') { + this.activeView = mountAuthView(this.mainEl, this.ctx, 'register', nextParam); + } else if (pathname === '/bots') { + this.activeView = mountBotView(this.mainEl, this.ctx); + } else if (pathname === '/friends') { + this.activeView = mountFriendsView(this.mainEl, this.ctx); + } else if (pathname === '/leaderboard') { + this.activeView = mountLeaderboardView(this.mainEl, this.ctx); + } else if (pathname === '/analysis') { + this.activeView = mountAnalysisView(this.mainEl, this.ctx); + } else if (pathname.indexOf('/analysis/') === 0) { + const gameId = decodeURIComponent(pathname.slice('/analysis/'.length)); + this.activeView = mountAnalysisView(this.mainEl, this.ctx, gameId); + } else if (pathname.indexOf('/game/') === 0) { + const gameId = decodeURIComponent(pathname.slice('/game/'.length)); + this.activeView = mountGameView(this.mainEl, this.ctx, gameId); + } else if (pathname.indexOf('/u/') === 0) { + const username = decodeURIComponent(pathname.slice('/u/'.length)); + this.activeView = mountProfileView(this.mainEl, this.ctx, username); + } else if (pathname.indexOf('/invite/') === 0) { + const token = decodeURIComponent(pathname.slice('/invite/'.length)); + this.activeView = mountInviteView(this.mainEl, this.ctx, token); + } else { + const card = el('div', { className: 'page-container narrow-page' }, [ + el('div', { className: 'card' }, [ + el('div', { className: 'card-body' }, [ + el('h1', { className: 'card-title' }, 'Page Not Found'), + el('p', { className: 'muted' }, 'That ChessUp page does not exist.'), + el('button', { + type: 'button', + className: 'btn btn-primary' + }, 'Go to Lobby') + ]) + ]) + ]); + const btn = card.querySelector('button')!; + btn.addEventListener('click', () => this.navigate('/')); + this.mainEl.appendChild(card); + } + } + + private handleGlobalWs(msg: ServerWsMessage): void { + if (msg.type === 'session:init') { + this.user = msg.user; + this.activeGameId = msg.activeGameId; + this.refreshFriendBadge(); + this.renderNavbar(); + } else if (msg.type === 'game:started') { + this.activeGameId = msg.gameId; + sound.play('notify'); + this.renderNavbar(); + this.navigate(`/game/${msg.gameId}`); + } else if (msg.type === 'challenge:received') { + sound.play('notify'); + this.refreshFriendBadge(); + this.showChallengeToast(msg.challenge); + } else if (msg.type === 'challenge:removed' || msg.type === 'challenge:list' || msg.type === 'friend:update') { + this.refreshFriendBadge(); + } else if (msg.type === 'error') { + this.toast(msg.message, 'error'); + } + } + + private showChallengeToast(ch: DirectChallenge): void { + const item = el('div', { className: 'toast toast-info' }); + item.appendChild(el('div', { className: 'toast-text' }, `${ch.fromUsername} (${ch.fromRating}) challenged you!`)); + const btns = el('div', { className: 'btn-row' }); + const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept'); + const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline'); + acc.addEventListener('click', () => { + wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: true }); + if (item.parentNode) item.parentNode.removeChild(item); + }); + dec.addEventListener('click', () => { + wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: false }); + if (item.parentNode) item.parentNode.removeChild(item); + }); + btns.appendChild(acc); + btns.appendChild(dec); + item.appendChild(btns); + this.toastEl.appendChild(item); + window.setTimeout(() => { + if (item.parentNode) item.parentNode.removeChild(item); + }, 15_000); + } + + toast(message: string, kind: 'info' | 'success' | 'error' = 'info'): void { + const item = el('div', { className: `toast toast-${kind}` }, message); + this.toastEl.appendChild(item); + window.setTimeout(() => { + if (item.parentNode) item.parentNode.removeChild(item); + }, 4000); + } +} + +const app = new App(); +app.init(); diff --git a/src/client/pieces.ts b/src/client/pieces.ts new file mode 100644 index 0000000..848c651 --- /dev/null +++ b/src/client/pieces.ts @@ -0,0 +1,40 @@ +import type { Color, PieceType } from '../shared/types'; + +// Crisp Staunton-style inline SVGs (45x45 viewBox) inspired by Cburnett public-domain geometry +const WHITE_STROKE = '#1a1a1a'; +const WHITE_FILL = '#ffffff'; +const BLACK_FILL = '#1e1e1e'; +const BLACK_DETAIL = '#ececec'; + +const PIECE_SVGS: Record = { + wp: ``, + + bp: ``, + + wr: ``, + + br: ``, + + wn: ``, + + bn: ``, + + wb: ``, + + bb: ``, + + wq: ``, + + bq: ``, + + wk: ``, + + bk: `` +}; + +export function createPieceNode(color: Color, type: PieceType): HTMLElement { + const wrap = document.createElement('div'); + wrap.className = 'piece'; + wrap.innerHTML = PIECE_SVGS[color + type] || ''; + return wrap; +} diff --git a/src/client/sound.ts b/src/client/sound.ts new file mode 100644 index 0000000..09146e6 --- /dev/null +++ b/src/client/sound.ts @@ -0,0 +1,104 @@ +export type SoundName = 'move' | 'capture' | 'castle' | 'check' | 'notify' | 'gameEnd' | 'lowTime'; + +class SoundManager { + private ctx: AudioContext | null = null; + private muted: boolean; + + constructor() { + this.muted = this.loadMuted(); + } + + private loadMuted(): boolean { + try { + return localStorage.getItem('chessup_muted') === '1'; + } catch { + return false; + } + } + + isMuted(): boolean { + return this.muted; + } + + setMuted(mute: boolean): void { + this.muted = mute; + try { + localStorage.setItem('chessup_muted', mute ? '1' : '0'); + } catch { + // Ignore + } + } + + private ensureCtx(): AudioContext | null { + if (this.muted) return null; + try { + const AC = + window.AudioContext || + (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; + if (!AC) return null; + if (!this.ctx) { + this.ctx = new AC(); + } + if (this.ctx.state === 'suspended') { + this.ctx.resume().catch(() => {}); + } + return this.ctx; + } catch { + return null; + } + } + + private beep(freq: number, durationSec: number, gainLevel: number, type: OscillatorType, delaySec: number = 0): void { + const ctx = this.ensureCtx(); + if (!ctx) return; + try { + const now = ctx.currentTime + delaySec; + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = type; + osc.frequency.setValueAtTime(freq, now); + gain.gain.setValueAtTime(0.001, now); + gain.gain.exponentialRampToValueAtTime(gainLevel, now + 0.008); + gain.gain.exponentialRampToValueAtTime(0.0001, now + durationSec); + osc.connect(gain); + gain.connect(ctx.destination); + osc.start(now); + osc.stop(now + durationSec + 0.01); + } catch { + // Ignore audio errors on old/restricted browsers + } + } + + play(name: SoundName): void { + if (this.muted) return; + switch (name) { + case 'move': + this.beep(260, 0.055, 0.12, 'triangle'); + break; + case 'capture': + this.beep(175, 0.075, 0.18, 'sawtooth'); + this.beep(120, 0.06, 0.12, 'triangle', 0.01); + break; + case 'castle': + this.beep(260, 0.05, 0.12, 'triangle'); + this.beep(310, 0.055, 0.12, 'triangle', 0.07); + break; + case 'check': + this.beep(620, 0.09, 0.14, 'sine'); + break; + case 'notify': + this.beep(520, 0.09, 0.1, 'sine'); + this.beep(680, 0.12, 0.1, 'sine', 0.09); + break; + case 'gameEnd': + this.beep(440, 0.11, 0.12, 'sine'); + this.beep(554, 0.18, 0.12, 'sine', 0.1); + break; + case 'lowTime': + this.beep(880, 0.06, 0.08, 'square'); + break; + } + } +} + +export const sound = new SoundManager(); diff --git a/src/client/styles.css b/src/client/styles.css new file mode 100644 index 0000000..09e18a9 --- /dev/null +++ b/src/client/styles.css @@ -0,0 +1,1624 @@ +:root { + --bg: #161512; + --surface: #21201d; + --surface-2: #2a2825; + --surface-hover: #33312d; + --border: #3a3833; + --text: #e6e4e0; + --muted: #9e9a92; + --accent: #629924; + --accent-hover: #73ad30; + --accent-text: #ffffff; + --danger: #c94040; + --danger-hover: #dd4e4e; + --warn: #d89b28; + --info: #3f87c9; + --sq-light: #f0d9b5; + --sq-dark: #b58863; + --sq-last: rgba(155, 199, 0, 0.42); + --sq-selected: rgba(20, 85, 30, 0.52); + --sq-premove: rgba(35, 105, 175, 0.5); + --coord-light: #9e7350; + --coord-dark: #f0d9b5; +} + +[data-theme="light"] { + --bg: #edebe9; + --surface: #ffffff; + --surface-2: #f6f5f3; + --surface-hover: #eae8e4; + --border: #d0cdc7; + --text: #24221f; + --muted: #66625c; + --accent: #55881e; + --accent-hover: #629924; + --accent-text: #ffffff; + --danger: #bf3434; + --danger-hover: #d64444; + --warn: #c78316; + --info: #2d70b0; +} + +[data-board="green"] { + --sq-light: #eeeed2; + --sq-dark: #769656; + --coord-light: #769656; + --coord-dark: #eeeed2; +} + +[data-board="blue"] { + --sq-light: #dee3e6; + --sq-dark: #8ca2ad; + --coord-light: #6d8591; + --coord-dark: #eef2f5; +} + +[data-board="mono"] { + --sq-light: #e4e4e4; + --sq-dark: #7c7c7c; + --coord-light: #626262; + --coord-dark: #ededed; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.45; + -webkit-font-smoothing: antialiased; +} + +a { + color: inherit; + text-decoration: none; +} + +.hidden { + display: none !important; +} + +.mono { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; +} + +.small-text { + font-size: 12px; +} + +.muted { + color: var(--muted); +} + +.center-text { + text-align: center; +} + +/* Navbar */ +#navbar { + background: var(--surface); + border-bottom: 1px solid var(--border); + position: relative; + z-index: 50; +} + +.nav-inner { + max-width: 1240px; + margin: 0 auto; + padding: 0 12px; + min-height: 46px; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; +} + +.nav-brand { + font-size: 17px; + font-weight: 700; + letter-spacing: 0.3px; + padding: 8px 0; + margin-right: 16px; + color: var(--text); +} + +.nav-links { + display: flex; + flex-wrap: wrap; + align-items: center; + margin-right: auto; +} + +.nav-link { + padding: 12px 10px; + font-size: 13px; + font-weight: 600; + color: var(--muted); + border-bottom: 2px solid transparent; + margin-right: 2px; +} + +.nav-link:hover { + color: var(--text); +} + +.nav-link.active { + color: var(--text); + border-bottom-color: var(--accent); +} + +.nav-badge { + display: inline-block; + margin-left: 5px; + padding: 1px 5px; + font-size: 11px; + line-height: 1.2; + background: var(--accent); + color: var(--accent-text); + border-radius: 2px; +} + +.nav-resume { + margin-left: 8px; + padding: 4px 8px; + font-size: 12px; + font-weight: 700; + background: var(--warn); + color: #111; + border-radius: 2px; +} + +.nav-right { + display: flex; + align-items: center; + padding: 6px 0; +} + +.nav-right > * { + margin-left: 8px; +} + +.nav-settings-wrap { + position: relative; +} + +.settings-popover { + position: absolute; + top: 100%; + right: 0; + margin-top: 6px; + width: 245px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 2px; + padding: 10px; + z-index: 80; +} + +.settings-row { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; +} + +.settings-row:last-child { + margin-bottom: 0; +} + +.settings-label { + font-size: 12px; + font-weight: 600; + color: var(--muted); +} + +.nav-user-link { + font-weight: 600; + font-size: 13px; + padding: 4px 6px; +} + +.nav-user-link:hover { + text-decoration: underline; +} + +/* Main container */ +.main-content { + padding: 14px 12px 32px; +} + +.page-container { + max-width: 1220px; + margin: 0 auto; +} + +.narrow-page { + max-width: 780px; +} + +/* Cards */ +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 2px; + margin-bottom: 14px; +} + +.card-header { + padding: 10px 14px; + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: space-between; +} + +.card-title { + margin: 0; + font-size: 15px; + font-weight: 700; +} + +.card-title-sm { + font-size: 13px; + font-weight: 700; +} + +.card-body { + padding: 14px; +} + +.card-body.compact { + padding: 10px 12px; +} + +.card-body.no-pad { + padding: 0; +} + +.border-top { + border-top: 1px solid var(--border); +} + +/* Buttons */ +.btn { + display: inline-block; + padding: 7px 12px; + font-size: 13px; + font-weight: 600; + font-family: inherit; + color: var(--text); + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 2px; + cursor: pointer; + text-align: center; + line-height: 1.25; +} + +.btn:hover:not(:disabled) { + background: var(--surface-hover); +} + +.btn:disabled { + opacity: 0.45; + cursor: default; +} + +.btn-primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-text); +} + +.btn-primary:hover:not(:disabled) { + background: var(--accent-hover); +} + +.btn-danger { + background: var(--danger); + border-color: var(--danger); + color: #ffffff; +} + +.btn-danger:hover:not(:disabled) { + background: var(--danger-hover); +} + +.btn-ghost { + background: transparent; +} + +.btn-sm { + padding: 5px 9px; + font-size: 12px; +} + +.btn-xs { + padding: 3px 7px; + font-size: 11px; +} + +.btn-lg { + padding: 10px 16px; + font-size: 14px; +} + +.btn-block { + display: block; + width: 100%; +} + +.btn-icon { + padding: 5px 8px; + font-size: 12px; + font-weight: 700; +} + +.btn-row { + display: flex; + flex-wrap: wrap; + align-items: center; +} + +.btn-row > * { + margin-right: 6px; + margin-bottom: 4px; +} + +.btn-col > * { + margin-bottom: 8px; +} + +.btn-col > *:last-child { + margin-bottom: 0; +} + +.btn-group { + display: inline-flex; + flex-wrap: wrap; +} + +.btn-group > .btn { + margin-right: 3px; + margin-bottom: 3px; +} + +/* Inputs & Forms */ +.input, +.select, +.textarea { + width: 100%; + padding: 7px 9px; + font-size: 13px; + font-family: inherit; + color: var(--text); + background: var(--bg); + border: 1px solid var(--border); + border-radius: 2px; +} + +.input-sm { + padding: 5px 7px; + font-size: 12px; +} + +.select { + width: auto; +} + +.textarea { + resize: vertical; + margin-bottom: 8px; +} + +.field-label { + display: block; + font-size: 12px; + font-weight: 600; + color: var(--muted); + margin: 8px 0 4px; +} + +.stack-form .input { + margin-bottom: 8px; +} + +.stack-form .btn { + margin-top: 6px; +} + +.inline-inputs { + display: flex; + align-items: center; + margin: 6px 0 10px; +} + +.inline-inputs > * { + margin-right: 6px; +} + +.inline-inputs .input { + width: 72px; +} + +.options-row { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + margin: 10px 0; +} + +/* Alerts & Toasts */ +.alert { + padding: 9px 12px; + border: 1px solid var(--border); + border-radius: 2px; + margin-bottom: 12px; + font-size: 13px; +} + +.alert-error { + border-color: var(--danger); + background: rgba(201, 64, 64, 0.14); +} + +.alert-info { + border-color: var(--info); + background: rgba(63, 135, 201, 0.14); +} + +.resume-banner { + display: flex; + align-items: center; + justify-content: space-between; +} + +.toast-container { + position: fixed; + top: 56px; + right: 12px; + z-index: 100; + width: 290px; + max-width: 90%; +} + +.toast { + background: var(--surface); + border: 1px solid var(--border); + border-left: 3px solid var(--info); + border-radius: 2px; + padding: 9px 11px; + margin-bottom: 8px; + font-size: 13px; +} + +.toast-success { + border-left-color: var(--accent); +} + +.toast-error { + border-left-color: var(--danger); +} + +.toast-text { + margin-bottom: 6px; + font-weight: 600; +} + +/* Auth */ +.auth-wrap { + max-width: 400px; + margin: 24px auto; +} + +.tab-bar { + display: flex; + border-bottom: 1px solid var(--border); +} + +.tab-btn { + flex: 1; + padding: 10px; + background: var(--surface-2); + color: var(--muted); + border: none; + font-size: 13px; + font-weight: 700; + cursor: pointer; +} + +.tab-btn.active { + background: var(--surface); + color: var(--text); + border-bottom: 2px solid var(--accent); +} + +.small-note { + margin-top: 0; + font-size: 12px; +} + +/* Tables & Lists */ +.data-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.data-table th, +.data-table td { + padding: 8px 12px; + text-align: left; + border-bottom: 1px solid var(--border); +} + +.data-table th { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.4px; + color: var(--muted); + background: var(--surface-2); +} + +.data-table tbody tr:hover { + background: var(--surface-hover); +} + +.col-right { + text-align: right !important; +} + +.col-right > .btn { + margin-left: 4px; +} + +.empty-state { + padding: 24px 14px; + text-align: center; + color: var(--muted); + font-size: 13px; +} + +.user-link { + font-weight: 600; +} + +.user-link:hover { + text-decoration: underline; + color: var(--accent); +} + +.rating-chip { + color: var(--muted); + font-size: 12px; +} + +/* Home / Lobby */ +.hero-title { + margin: 0 0 8px; + font-size: 20px; +} + +.two-col-lobby, +.two-col-friends { + display: flex; + flex-wrap: wrap; + align-items: flex-start; +} + +.lobby-card, +.two-col-friends > .card { + flex: 1 1 520px; + margin-right: 14px; +} + +.side-col { + flex: 0 1 360px; + width: 100%; +} + +.preset-grid { + display: flex; + flex-wrap: wrap; + margin-bottom: 6px; +} + +.preset-btn { + width: 23.5%; + margin: 0 1.5% 6px 0; +} + +.invite-box { + display: flex; + align-items: center; + margin-top: 8px; +} + +.invite-box .input { + flex: 1; + margin-right: 6px; +} + +.invite-headline { + font-size: 16px; + font-weight: 700; + margin: 0 0 6px; +} + +/* Bots */ +.bot-grid { + display: flex; + flex-wrap: wrap; + margin-bottom: 12px; +} + +.bot-level-card { + width: 48.5%; + margin: 0 1.5% 8px 0; + padding: 9px 11px; + text-align: left; + background: var(--surface-2); + color: var(--text); + border: 1px solid var(--border); + border-radius: 2px; + cursor: pointer; +} + +.bot-level-card:hover { + background: var(--surface-hover); +} + +.bot-level-card.active { + border-color: var(--accent); + background: rgba(98, 153, 36, 0.16); +} + +.bot-level-top { + display: flex; + justify-content: space-between; + margin-bottom: 3px; +} + +.bot-level-desc { + font-size: 12px; + color: var(--muted); +} + +.bot-options-split { + margin-bottom: 14px; +} + +.bot-opt-block { + margin-bottom: 10px; +} + +/* Friends & Presence Dots */ +.list-stack { + display: block; +} + +.list-row { + padding: 9px 12px; + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: space-between; +} + +.list-row:last-child { + border-bottom: none; +} + +.dot { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 7px; + vertical-align: middle; +} + +.dot-online { + background: #629924; +} + +.dot-ingame { + background: #d89b28; +} + +.dot-offline { + background: #6e6b65; +} + +.dot-bot { + background: #3f87c9; +} + +.search-results { + margin-top: 8px; + border: 1px solid var(--border); +} + +/* Profile */ +.profile-header-body { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; +} + +.profile-title-row { + display: flex; + align-items: center; + margin-bottom: 4px; +} + +.profile-username { + margin: 0 8px 0 0; + font-size: 20px; +} + +.h2h-line { + margin-top: 3px; + font-weight: 600; +} + +.inline-pw-form { + display: flex; + flex-wrap: wrap; + align-items: center; +} + +.inline-pw-form > * { + margin-right: 8px; + margin-bottom: 6px; + width: auto; +} + +.ratings-grid { + display: flex; + flex-wrap: wrap; + margin-bottom: 6px; +} + +.rating-card { + width: 24%; + margin-right: 1%; +} + +.rating-card:last-child { + margin-right: 0; +} + +.rating-card-top { + display: flex; + justify-content: space-between; + align-items: baseline; + margin-bottom: 4px; +} + +.rating-cat-name { + font-size: 12px; + font-weight: 700; + text-transform: uppercase; + color: var(--muted); +} + +.rating-big { + font-size: 19px; +} + +.sparkline-svg { + width: 100%; + height: 36px; + margin-top: 6px; + display: block; +} + +.sparkline-line { + stroke: var(--accent); + stroke-width: 2; +} + +.sparkline-flat { + stroke: var(--border); + stroke-width: 1; +} + +.filter-bar { + padding: 8px 12px; + border-bottom: 1px solid var(--border); + background: var(--surface-2); + display: flex; + flex-wrap: wrap; + align-items: center; +} + +.filter-bar > * { + margin-right: 6px; + margin-bottom: 4px; +} + +.filter-opp { + width: 150px; +} + +.res-badge { + display: inline-block; + padding: 1px 5px; + font-size: 10px; + font-weight: 700; + border-radius: 2px; +} + +.res-win { + background: rgba(98, 153, 36, 0.25); + color: #8fd147; +} + +.res-loss { + background: rgba(201, 64, 64, 0.25); + color: #f07575; +} + +.res-draw { + background: rgba(150, 150, 150, 0.2); + color: var(--muted); +} + +.pager-bar { + padding: 8px 12px; + display: flex; + align-items: center; + justify-content: center; +} + +.pager-bar > * { + margin: 0 6px; +} + +/* Game & Analysis Layout */ +.game-layout, +.analysis-layout { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: center; +} + +.board-col { + width: 560px; + max-width: 100%; + margin-right: 16px; +} + +.analysis-board-col { + width: 590px; + max-width: 100%; + margin-right: 16px; +} + +.analysis-board-row { + display: flex; + align-items: stretch; +} + +.analysis-board-inner { + flex: 1; + min-width: 0; +} + +.game-side-col, +.analysis-side-col { + flex: 1 1 320px; + max-width: 440px; + min-width: 280px; +} + +/* Player bar & Clock */ +.player-bar { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--surface); + border: 1px solid var(--border); + padding: 6px 10px; + margin: 4px 0; +} + +.player-bar.player-turn { + border-color: var(--accent); +} + +.player-info { + display: flex; + flex-wrap: wrap; + align-items: center; +} + +.player-name { + font-weight: 700; + font-size: 14px; +} + +.rating-diff { + font-size: 12px; + font-weight: 700; + margin-left: 4px; +} + +.diff-pos { + color: #8fd147; +} + +.diff-neg { + color: #f07575; +} + +.disconnect-badge { + margin-left: 8px; + padding: 1px 5px; + font-size: 11px; + font-weight: 700; + background: var(--danger); + color: #fff; + border-radius: 2px; +} + +.clock-box { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 18px; + font-weight: 700; + padding: 3px 9px; + min-width: 78px; + text-align: center; + background: var(--surface-2); + border: 1px solid var(--border); + color: var(--muted); + border-radius: 2px; +} + +.clock-active { + background: var(--text); + color: var(--bg); +} + +.clock-low { + background: var(--warn); + color: #111; + border-color: var(--warn); +} + +.clock-flag { + background: var(--danger); + color: #fff; + border-color: var(--danger); +} + +/* Chessboard (100% old-browser compatible square via padding-bottom) */ +.board-outer { + width: 100%; + user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; +} + +.board-wrap { + position: relative; + width: 100%; + height: 0; + padding-bottom: 100%; + border: 1px solid var(--border); + overflow: hidden; +} + +.board-grid { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + display: flex; + flex-wrap: wrap; +} + +.sq { + position: relative; + width: 12.5%; + height: 12.5%; +} + +.sq-light { + background: var(--sq-light); +} + +.sq-dark { + background: var(--sq-dark); +} + +.sq-last:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: var(--sq-last); + pointer-events: none; +} + +.sq-selected:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: var(--sq-selected); + pointer-events: none; +} + +.sq-premove:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: var(--sq-premove); + pointer-events: none; +} + +.sq-check { + background: radial-gradient(ellipse at center, #ff1111 0%, #c92020 55%, rgba(200, 0, 0, 0) 85%); +} + +.coord-rank { + position: absolute; + top: 2px; + left: 3px; + font-size: 10px; + font-weight: 700; + line-height: 1; + pointer-events: none; + z-index: 2; +} + +.coord-file { + position: absolute; + right: 3px; + bottom: 2px; + font-size: 10px; + font-weight: 700; + line-height: 1; + pointer-events: none; + z-index: 2; +} + +.sq-light .coord-rank, +.sq-light .coord-file { + color: var(--coord-light); +} + +.sq-dark .coord-rank, +.sq-dark .coord-file { + color: var(--coord-dark); +} + +.piece { + position: absolute; + top: 3%; + right: 3%; + bottom: 3%; + left: 3%; + z-index: 3; + cursor: pointer; +} + +.piece-svg { + width: 100%; + height: 100%; + display: block; +} + +.piece-dragging-origin { + opacity: 0.25; +} + +.drag-ghost { + position: fixed; + z-index: 999; + pointer-events: none; + transform: translate(-50%, -50%); +} + +.hint-dot { + position: absolute; + top: 36%; + left: 36%; + width: 28%; + height: 28%; + border-radius: 50%; + background: rgba(20, 85, 30, 0.42); + z-index: 4; + pointer-events: none; +} + +.hint-capture { + position: absolute; + top: 6%; + right: 6%; + bottom: 6%; + left: 6%; + border-radius: 50%; + border: 4px solid rgba(20, 85, 30, 0.48); + z-index: 4; + pointer-events: none; +} + +.board-arrows { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 5; + pointer-events: none; +} + +.promo-overlay { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: rgba(0, 0, 0, 0.58); + z-index: 15; + display: flex; + align-items: center; + justify-content: center; +} + +.promo-box { + background: var(--surface); + border: 1px solid var(--border); + padding: 10px; + display: flex; + flex-wrap: wrap; + align-items: center; +} + +.promo-choice { + position: relative; + width: 56px; + height: 56px; + background: var(--surface-2); + border: 1px solid var(--border); + margin: 4px; + cursor: pointer; +} + +.promo-choice:hover { + background: var(--surface-hover); + border-color: var(--accent); +} + +.promo-cancel { + margin-left: 6px; + padding: 6px 10px; + background: transparent; + color: var(--muted); + border: 1px solid var(--border); + cursor: pointer; +} + +.live-notice { + margin-top: 6px; + padding: 6px 10px; + background: var(--surface-2); + border: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; +} + +.game-meta-line { + font-size: 12px; + color: var(--muted); +} + +.game-status-banner { + margin-top: 8px; + padding: 8px 10px; + background: var(--surface-2); + border: 1px solid var(--border); +} + +.game-status-banner.finished { + border-color: var(--accent); +} + +/* Move list */ +.movelist-nav { + display: flex; + border-bottom: 1px solid var(--border); + padding: 6px; + background: var(--surface-2); +} + +.movelist-nav > .btn { + flex: 1; + margin-right: 4px; +} + +.movelist-nav > .btn:last-child { + margin-right: 0; +} + +.movelist-scroll { + height: 220px; + overflow-y: auto; + position: relative; +} + +.movelist-empty { + padding: 20px; + text-align: center; + color: var(--muted); + font-size: 12px; +} + +.movelist-row { + display: flex; + border-bottom: 1px solid rgba(128, 128, 128, 0.12); +} + +.move-num { + width: 38px; + padding: 4px 6px; + font-size: 12px; + color: var(--muted); + background: var(--surface-2); + text-align: right; + font-family: ui-monospace, monospace; +} + +.move-cell { + flex: 1; + padding: 4px 8px; + font-size: 13px; + font-weight: 600; + text-align: left; + background: transparent; + color: var(--text); + border: none; + cursor: pointer; + font-family: inherit; +} + +.move-cell:hover { + background: var(--surface-hover); +} + +.move-empty { + cursor: default; +} + +.move-active { + background: var(--accent) !important; + color: #ffffff !important; +} + +.move-nag { + margin-left: 3px; + font-size: 11px; + font-weight: 700; +} + +.nag-inaccuracy { + color: #56b4e9; +} + +.nag-mistake { + color: #e69f00; +} + +.nag-blunder { + color: #f06060; +} + +.move-active .move-nag { + color: #ffffff; +} + +.game-actions { + padding: 8px; + border-top: 1px solid var(--border); +} + +.action-row { + display: flex; + flex-wrap: wrap; +} + +.action-row > * { + margin-right: 6px; + margin-bottom: 4px; +} + +.offer-bar { + padding: 6px 8px; + margin-bottom: 6px; + background: var(--surface-2); + border: 1px solid var(--warn); + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; +} + +.offer-bar > .btn { + margin-left: 4px; +} + +/* Chat */ +.chat-messages { + height: 130px; + overflow-y: auto; + padding: 8px 10px; + font-size: 12px; +} + +.chat-line { + margin-bottom: 4px; + word-wrap: break-word; +} + +.chat-author { + color: var(--muted); +} + +.chat-form { + display: flex; + padding: 6px 8px; + border-top: 1px solid var(--border); +} + +.chat-form .input { + flex: 1; + margin-right: 6px; +} + +/* Analysis & Eval Bar & Eval Graph */ +.eval-bar { + width: 26px; + margin-right: 8px; + background: #2b2926; + border: 1px solid var(--border); + position: relative; + overflow: hidden; + flex-shrink: 0; +} + +.eval-fill-white { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 50%; + background: #e8e6e3; +} + +.eval-bar-text { + position: absolute; + top: 4px; + left: 0; + right: 0; + text-align: center; + font-size: 9px; + font-weight: 700; + color: #888; + z-index: 2; +} + +.eval-graph-wrap { + margin-top: 10px; + border: 1px solid var(--border); + background: var(--surface); + height: 82px; + cursor: pointer; +} + +.eval-graph-svg { + width: 100%; + height: 100%; + display: block; +} + +.eval-graph-bg { + fill: #24221f; +} + +.eval-graph-mid { + stroke: #555; + stroke-width: 1; +} + +.eval-graph-area { + fill: rgba(235, 233, 228, 0.3); +} + +.eval-graph-line { + stroke: #e8e6e3; + stroke-width: 1.8; +} + +.eval-graph-cursor { + stroke: var(--accent); + stroke-width: 2; +} + +.eval-dot-inaccuracy { + fill: #56b4e9; +} + +.eval-dot-mistake { + fill: #e69f00; +} + +.eval-dot-blunder { + fill: #df5353; +} + +.variation-bar { + margin-top: 8px; + padding: 8px 10px; + background: var(--surface); + border: 1px solid var(--accent); +} + +.var-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 6px; +} + +.var-moves { + display: flex; + flex-wrap: wrap; +} + +.var-mv { + margin: 0 4px 4px 0; +} + +.move-feedback { + margin-top: 8px; + padding: 8px 10px; + background: var(--surface); + border: 1px solid var(--border); + border-left: 3px solid var(--accent); + font-size: 13px; +} + +.feedback-inaccuracy { + border-left-color: #56b4e9; +} + +.feedback-mistake { + border-left-color: #e69f00; +} + +.feedback-blunder { + border-left-color: #df5353; +} + +.analysis-title-row { + display: flex; + justify-content: space-between; + align-items: center; +} + +.pv-row { + width: 100%; + display: flex; + align-items: baseline; + text-align: left; + padding: 5px 6px; + background: var(--surface-2); + color: var(--text); + border: 1px solid var(--border); + margin-bottom: 4px; + cursor: pointer; + font-size: 12px; +} + +.pv-row:hover { + background: var(--surface-hover); + border-color: var(--accent); +} + +.pv-score { + font-family: ui-monospace, monospace; + font-weight: 700; + min-width: 44px; + margin-right: 6px; +} + +.pv-moves { + color: var(--muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.progress-track { + margin-top: 6px; + height: 8px; + background: var(--bg); + border: 1px solid var(--border); +} + +.progress-fill { + height: 100%; + background: var(--accent); + width: 0; +} + +.summary-table { + width: 100%; + border-collapse: collapse; + font-size: 12px; +} + +.summary-table th, +.summary-table td { + padding: 4px 6px; + border-bottom: 1px solid var(--border); + text-align: left; +} + +/* Mobile breakpoint */ +@media (max-width: 860px) { + .board-col, + .analysis-board-col { + margin-right: 0; + margin-bottom: 12px; + } + + .game-side-col, + .analysis-side-col { + max-width: 100%; + } + + .lobby-card, + .two-col-friends > .card { + margin-right: 0; + } + + .side-col { + flex: 1 1 100%; + } + + .rating-card { + width: 49%; + margin-right: 1%; + } + + .bot-level-card { + width: 100%; + margin-right: 0; + } +} diff --git a/src/client/views/analysisView.ts b/src/client/views/analysisView.ts new file mode 100644 index 0000000..5a9d9db --- /dev/null +++ b/src/client/views/analysisView.ts @@ -0,0 +1,792 @@ +import { Chess, INITIAL_FEN } from '../../shared/chess'; +import { categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { + GameAnalysisReport, + MoveClassification, + MultiPvLine, + ServerWsMessage, + StoredGame +} from '../../shared/types'; +import { classificationNag, cpToWinPercent, formatEvalShort } from '../../shared/winProb'; +import { apiRequest, wsClient } from '../api'; +import { ChessBoard } from '../components/board'; +import { EvalGraph } from '../components/evalGraph'; +import { MoveList } from '../components/moveList'; +import { clearNode, copyTextToClipboard, el } from '../dom'; +import { sound } from '../sound'; +import type { AppContext, ViewHandle } from './context'; + +function classificationBadgeText(c: MoveClassification): string { + switch (c) { + case 'best': + return 'Best'; + case 'good': + return 'Good'; + case 'inaccuracy': + return 'Inaccuracy (?!)'; + case 'mistake': + return 'Mistake (?)'; + case 'blunder': + return 'Blunder (??)'; + } +} + +export function mountAnalysisView( + container: HTMLElement, + ctx: AppContext, + gameId?: string +): ViewHandle { + let storedGame: StoredGame | null = null; + let report: GameAnalysisReport | null = null; + let loadError = ''; + + // Mainline state + let initialFen = INITIAL_FEN; + let mainUci: string[] = []; + let mainSan: string[] = []; + let mainFens: string[] = [INITIAL_FEN]; + let mainPly = 0; + + // Interactive variation state (branched off mainPly) + let branchBasePly = 0; + let branchUci: string[] = []; + let branchSan: string[] = []; + let branchFens: string[] = []; + let branchCursor = 0; // 0 = at branchBasePly, >0 = inside branch + + // Live MultiPV state + let liveEngineOn = !gameId; // auto-on for freeform analysis, toggleable for saved games + let multipvReqCounter = 0; + let activeMultipvReqId = ''; + let activeMultipvFen = ''; + let multipvLines: MultiPvLine[] = []; + let multipvDepth = 0; + let multipvDone = false; + + let destroyed = false; + + const board = new ChessBoard({ + mode: 'analyze', + onMove(uci) { + playInteractiveMove(uci); + } + }); + + const moveList = new MoveList({ + onSelectPly(ply) { + clearBranch(); + mainPly = Math.min(mainUci.length, Math.max(0, ply)); + updateAll(); + }, + onFlip() { + board.flip(); + renderEvalBar(); + } + }); + + const evalGraph = new EvalGraph((ply) => { + clearBranch(); + mainPly = Math.min(mainUci.length, Math.max(0, ply)); + updateAll(); + }); + + // UI elements + const headerInfoEl = el('div', { className: 'analysis-header-card' }); + const evalBarEl = el('div', { className: 'eval-bar' }); + const evalFillWhite = el('div', { className: 'eval-fill-white' }); + const evalTextEl = el('div', { className: 'eval-bar-text' }, '0.0'); + evalBarEl.appendChild(evalFillWhite); + evalBarEl.appendChild(evalTextEl); + + const variationBarEl = el('div', { className: 'variation-bar hidden' }); + const moveFeedbackEl = el('div', { className: 'move-feedback hidden' }); + const analysisControlEl = el('div', { className: 'analysis-control-card' }); + const enginePanelEl = el('div', { className: 'card engine-card' }); + const pgnPanelEl = el('div', { className: 'card' }); + let fenDisplayInput: HTMLInputElement | null = null; + let pgnDisplayArea: HTMLTextAreaElement | null = null; + + function buildSkeleton(): void { + clearNode(container); + const page = el('div', { className: 'page-container analysis-page' }); + const layout = el('div', { className: 'analysis-layout' }); + + const leftCol = el('div', { className: 'analysis-board-col' }); + const boardRow = el('div', { className: 'analysis-board-row' }); + boardRow.appendChild(evalBarEl); + const boardWrap = el('div', { className: 'analysis-board-inner' }); + boardWrap.appendChild(board.root); + boardRow.appendChild(boardWrap); + leftCol.appendChild(boardRow); + leftCol.appendChild(variationBarEl); + leftCol.appendChild(moveFeedbackEl); + leftCol.appendChild(evalGraph.root); + layout.appendChild(leftCol); + + const rightCol = el('div', { className: 'analysis-side-col' }); + rightCol.appendChild(headerInfoEl); + rightCol.appendChild(enginePanelEl); + + const movesCard = el('div', { className: 'card moves-card' }); + movesCard.appendChild(moveList.root); + rightCol.appendChild(movesCard); + + rightCol.appendChild(analysisControlEl); + rightCol.appendChild(pgnPanelEl); + + layout.appendChild(rightCol); + page.appendChild(layout); + container.appendChild(page); + } + + function rebuildMainFens(): void { + const c = new Chess(initialFen); + mainFens = [c.fen()]; + const cleanUci: string[] = []; + const cleanSan: string[] = []; + for (let i = 0; i < mainUci.length; i++) { + const mv = c.moveUci(mainUci[i]!); + if (!mv) break; + cleanUci.push(mv.uci); + cleanSan.push(mv.san); + mainFens.push(c.fen()); + } + mainUci = cleanUci; + mainSan = cleanSan; + if (mainPly > mainUci.length) mainPly = mainUci.length; + } + + function currentFen(): string { + if (branchUci.length > 0 && branchCursor > 0) { + return branchFens[branchCursor - 1]!; + } + return mainFens[mainPly] || initialFen; + } + + function currentLastMoveUci(): string | null { + if (branchUci.length > 0 && branchCursor > 0) { + return branchUci[branchCursor - 1] || null; + } + return mainPly > 0 ? mainUci[mainPly - 1] || null : null; + } + + function clearBranch(): void { + branchBasePly = 0; + branchUci = []; + branchSan = []; + branchFens = []; + branchCursor = 0; + } + + function playInteractiveMove(uci: string): void { + const fen = currentFen(); + const c = new Chess(fen); + const mv = c.moveUci(uci); + if (!mv) return; + + if (mv.san.indexOf('+') >= 0 || mv.san.indexOf('#') >= 0) sound.play('check'); + else if (mv.san.indexOf('x') >= 0) sound.play('capture'); + else sound.play('move'); + + // If on mainline and move matches next mainline move, advance mainline cleanly + if (branchUci.length === 0 && mainPly < mainUci.length && mainUci[mainPly] === mv.uci) { + mainPly++; + updateAll(); + return; + } + + if (branchUci.length === 0) { + branchBasePly = mainPly; + branchCursor = 0; + } else if (branchCursor < branchUci.length) { + branchUci = branchUci.slice(0, branchCursor); + branchSan = branchSan.slice(0, branchCursor); + branchFens = branchFens.slice(0, branchCursor); + } + + branchUci.push(mv.uci); + branchSan.push(mv.san); + branchFens.push(c.fen()); + branchCursor = branchUci.length; + updateAll(); + } + + function requestMultiPvIfEnabled(): void { + const fen = currentFen(); + if (!liveEngineOn) { + wsClient.send({ type: 'analysis:multipv_stop', requestId: activeMultipvReqId }); + activeMultipvReqId = ''; + return; + } + if (fen === activeMultipvFen && activeMultipvReqId) return; + + const reqId = `mpv-${++multipvReqCounter}`; + activeMultipvReqId = reqId; + activeMultipvFen = fen; + multipvLines = []; + multipvDepth = 0; + multipvDone = false; + + const c = new Chess(fen); + if (c.isGameOver()) { + multipvDone = true; + renderEnginePanel(); + return; + } + + wsClient.send({ + type: 'analysis:multipv', + requestId: reqId, + fen, + depth: 14, + multiPv: 3 + }); + renderEnginePanel(); + } + + function getActivePositionEval(): { cp: number | null; mate: number | null; bestUci: string | null } { + const fen = currentFen(); + if (liveEngineOn && activeMultipvFen === fen && multipvLines.length > 0) { + const top = multipvLines[0]!; + return { + cp: top.scoreCp, + mate: top.scoreMate, + bestUci: top.pvUci[0] || null + }; + } + + if (branchUci.length === 0 && report && report.status === 'done') { + if (mainPly === 0) { + return { + cp: report.initialEvalCp, + mate: report.initialEvalMate, + bestUci: report.initialBestMoveUci + }; + } + const prev = report.plies[mainPly - 1]; + const next = report.plies[mainPly]; + return { + cp: prev ? prev.evalCpAfter : 0, + mate: prev ? prev.evalMateAfter : null, + bestUci: next ? next.bestMoveUci : null + }; + } + + return { cp: 0, mate: null, bestUci: null }; + } + + function renderEvalBar(): void { + const ev = getActivePositionEval(); + const whiteWinPct = cpToWinPercent(ev.cp, ev.mate); + evalTextEl.textContent = formatEvalShort(ev.cp, ev.mate); + + const flipped = board.getOrientation() === 'b'; + if (flipped) { + evalFillWhite.style.top = '0'; + evalFillWhite.style.bottom = 'auto'; + evalFillWhite.style.height = `${whiteWinPct.toFixed(1)}%`; + } else { + evalFillWhite.style.top = 'auto'; + evalFillWhite.style.bottom = '0'; + evalFillWhite.style.height = `${whiteWinPct.toFixed(1)}%`; + } + } + + function renderHeader(): void { + clearNode(headerInfoEl); + headerInfoEl.className = 'card'; + const body = el('div', { className: 'card-body compact' }); + + if (storedGame) { + const top = el('div', { className: 'analysis-title-row' }); + top.appendChild( + el( + 'strong', + null, + `${storedGame.whiteUsername}${ + storedGame.whiteRatingBefore ? ` (${storedGame.whiteRatingBefore})` : '' + } vs ${storedGame.blackUsername}${ + storedGame.blackRatingBefore ? ` (${storedGame.blackRatingBefore})` : '' + }` + ) + ); + top.appendChild(el('span', { className: 'rating-chip' }, storedGame.result)); + body.appendChild(top); + body.appendChild( + el( + 'div', + { className: 'small-text muted' }, + `${formatTimeControl(storedGame.initialMs, storedGame.incrementMs)} · ${categoryLabel( + storedGame.category + )} · ${storedGame.termination}` + ) + ); + } else { + body.appendChild(el('strong', null, 'Analysis Board & Variation Explorer')); + body.appendChild( + el('div', { className: 'small-text muted' }, 'Play moves on the board, toggle live Stockfish MultiPV, or import a FEN / PGN below.') + ); + } + + headerInfoEl.appendChild(body); + } + + function renderVariationAndFeedback(): void { + clearNode(variationBarEl); + if (branchUci.length > 0) { + variationBarEl.className = 'variation-bar'; + const head = el('div', { className: 'var-head' }); + head.appendChild(el('strong', { className: 'small-text' }, `Variation from ply ${branchBasePly}: `)); + const exitBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Back to Mainline'); + exitBtn.addEventListener('click', () => { + clearBranch(); + updateAll(); + }); + head.appendChild(exitBtn); + variationBarEl.appendChild(head); + + const line = el('div', { className: 'var-moves' }); + for (let i = 0; i < branchSan.length; i++) { + const idx = i + 1; + const b = el( + 'button', + { + type: 'button', + className: idx === branchCursor ? 'btn btn-xs btn-primary var-mv' : 'btn btn-xs var-mv' + }, + branchSan[i]! + ); + b.addEventListener('click', () => { + branchCursor = idx; + updateAll(); + }); + line.appendChild(b); + } + variationBarEl.appendChild(line); + } else { + variationBarEl.className = 'variation-bar hidden'; + } + + // Move feedback from post-game report + clearNode(moveFeedbackEl); + if (branchUci.length === 0 && report && report.status === 'done' && mainPly > 0) { + const plyInfo = report.plies[mainPly - 1]; + if (plyInfo) { + moveFeedbackEl.className = `move-feedback feedback-${plyInfo.classification}`; + const label = `${plyInfo.moveSan}${classificationNag(plyInfo.classification)} — ${classificationBadgeText( + plyInfo.classification + )} (Accuracy ${plyInfo.accuracy}%)`; + moveFeedbackEl.appendChild(el('div', null, label)); + if (plyInfo.bestMoveSan && plyInfo.bestMoveUci !== plyInfo.moveUci) { + moveFeedbackEl.appendChild( + el('div', { className: 'small-text muted' }, `Best was ${plyInfo.bestMoveSan} · Line: ${plyInfo.pvSan.slice(0, 5).join(' ')}`) + ); + } + return; + } + } + moveFeedbackEl.className = 'move-feedback hidden'; + } + + function renderEnginePanel(): void { + clearNode(enginePanelEl); + const head = el('div', { className: 'card-header' }); + const titleWrap = el('div', { className: 'engine-title-wrap' }); + titleWrap.appendChild(el('span', { className: 'card-title-sm' }, 'Stockfish Live Engine')); + if (liveEngineOn) { + titleWrap.appendChild( + el( + 'span', + { className: 'small-text muted' }, + multipvDepth > 0 ? ` depth ${multipvDepth}${multipvDone ? '' : '...'}` : ' thinking...' + ) + ); + } + head.appendChild(titleWrap); + + const toggleBtn = el( + 'button', + { + type: 'button', + className: liveEngineOn ? 'btn btn-xs btn-primary' : 'btn btn-xs' + }, + liveEngineOn ? 'On' : 'Off' + ); + toggleBtn.addEventListener('click', () => { + liveEngineOn = !liveEngineOn; + activeMultipvFen = ''; + if (!liveEngineOn) { + multipvLines = []; + } + requestMultiPvIfEnabled(); + renderEnginePanel(); + renderArrows(); + renderEvalBar(); + }); + head.appendChild(toggleBtn); + enginePanelEl.appendChild(head); + + const body = el('div', { className: 'card-body compact' }); + if (!liveEngineOn) { + body.appendChild(el('div', { className: 'muted small-text' }, 'Toggle On for live MultiPV (top 3 variations) on any position or branch.')); + } else if (multipvLines.length === 0) { + const c = new Chess(currentFen()); + body.appendChild( + el('div', { className: 'muted small-text' }, c.isGameOver() ? 'Game over position.' : 'Calculating top engine lines...') + ); + } else { + for (const line of multipvLines) { + const row = el('button', { type: 'button', className: 'pv-row' }); + row.appendChild(el('span', { className: 'pv-score' }, formatEvalShort(line.scoreCp, line.scoreMate))); + row.appendChild(el('span', { className: 'pv-moves' }, line.pvSan.slice(0, 7).join(' ') || line.pvUci.slice(0, 7).join(' '))); + if (line.pvUci.length > 0) { + row.addEventListener('click', () => { + playInteractiveMove(line.pvUci[0]!); + }); + } + body.appendChild(row); + } + } + enginePanelEl.appendChild(body); + } + + function renderAnalysisControl(): void { + clearNode(analysisControlEl); + if (!gameId) { + analysisControlEl.className = 'hidden'; + return; + } + + analysisControlEl.className = 'card'; + analysisControlEl.appendChild( + el('div', { className: 'card-header' }, el('span', { className: 'card-title-sm' }, 'Computer Game Report')) + ); + const body = el('div', { className: 'card-body compact' }); + + if (!report || report.status === 'error') { + if (report?.status === 'error') { + body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.')); + } + const reqBtn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-block' }, + 'Request Computer Analysis (Depth 12)' + ); + reqBtn.addEventListener('click', async () => { + try { + const resp = await apiRequest<{ report: GameAnalysisReport }>( + `/api/games/${encodeURIComponent(gameId)}/analysis`, + { method: 'POST', body: JSON.stringify({}) } + ); + report = resp.report; + renderAnalysisControl(); + updateAll(); + } catch (err) { + ctx.toast(err instanceof Error ? err.message : 'Failed to start analysis.', 'error'); + } + }); + body.appendChild(reqBtn); + } else if (report.status === 'running' || report.status === 'pending') { + const pct = report.totalPlies > 0 ? Math.round((report.progressPly / report.totalPlies) * 100) : 0; + body.appendChild( + el( + 'div', + { className: 'small-text' }, + `Analyzing with Stockfish (depth ${report.depth}): ${report.progressPly} / ${report.totalPlies} plies (${pct}%)` + ) + ); + const bar = el('div', { className: 'progress-track' }); + const fill = el('div', { className: 'progress-fill' }); + fill.style.width = `${pct}%`; + bar.appendChild(fill); + body.appendChild(bar); + } else if (report.status === 'done' && report.whiteSummary && report.blackSummary) { + const w = report.whiteSummary; + const b = report.blackSummary; + const table = el('table', { className: 'summary-table' }); + const thead = el('thead'); + const hr = el('tr'); + hr.appendChild(el('th', null, 'Metric')); + hr.appendChild(el('th', { className: 'col-right' }, 'White')); + hr.appendChild(el('th', { className: 'col-right' }, 'Black')); + thead.appendChild(hr); + table.appendChild(thead); + + const tbody = el('tbody'); + const rows: Array<[string, string | number, string | number]> = [ + ['Accuracy', `${w.accuracy}%`, `${b.accuracy}%`], + ['Avg CP Loss', w.acpl, b.acpl], + ['Inaccuracies (?!)', w.inaccuracies, b.inaccuracies], + ['Mistakes (?)', w.mistakes, b.mistakes], + ['Blunders (??)', w.blunders, b.blunders] + ]; + for (const r of rows) { + const tr = el('tr'); + tr.appendChild(el('td', null, r[0])); + tr.appendChild(el('td', { className: 'col-right' }, r[1])); + tr.appendChild(el('td', { className: 'col-right' }, r[2])); + tbody.appendChild(tr); + } + table.appendChild(tbody); + body.appendChild(table); + } + + analysisControlEl.appendChild(body); + } + + function renderPgnPanel(): void { + clearNode(pgnPanelEl); + pgnPanelEl.appendChild( + el('div', { className: 'card-header' }, el('span', { className: 'card-title-sm' }, 'FEN & PGN')) + ); + const body = el('div', { className: 'card-body compact' }); + + body.appendChild(el('div', { className: 'field-label' }, 'Current FEN')); + const fenRow = el('div', { className: 'invite-box' }); + fenDisplayInput = el('input', { + type: 'text', + className: 'input input-sm mono', + value: currentFen(), + readonly: true + }) as HTMLInputElement; + const copyFenBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Copy'); + copyFenBtn.addEventListener('click', async () => { + if (fenDisplayInput) { + const ok = await copyTextToClipboard(fenDisplayInput.value); + ctx.toast(ok ? 'FEN copied!' : 'Copy failed', ok ? 'success' : 'error'); + } + }); + fenRow.appendChild(fenDisplayInput); + fenRow.appendChild(copyFenBtn); + body.appendChild(fenRow); + + body.appendChild(el('div', { className: 'field-label' }, 'PGN (Paste PGN or FEN to load)')); + const c = new Chess(initialFen); + for (let i = 0; i < mainUci.length; i++) c.moveUci(mainUci[i]!); + const exportPgn = storedGame?.pgn || c.toPgn(); + + pgnDisplayArea = el('textarea', { + className: 'textarea mono', + rows: '4' + }) as HTMLTextAreaElement; + pgnDisplayArea.value = exportPgn; + body.appendChild(pgnDisplayArea); + + const pgnBtns = el('div', { className: 'btn-row' }); + const loadBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Load FEN / PGN'); + const copyPgnBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Copy PGN'); + pgnBtns.appendChild(loadBtn); + pgnBtns.appendChild(copyPgnBtn); + if (storedGame) { + const dlLink = el( + 'a', + { href: `/api/games/${storedGame.id}/pgn`, className: 'btn btn-xs', target: '_blank' }, + 'Download .pgn' + ); + pgnBtns.appendChild(dlLink); + } + + loadBtn.addEventListener('click', () => { + if (!pgnDisplayArea) return; + const raw = pgnDisplayArea.value.trim(); + if (!raw) return; + + // Try FEN first if it looks like 1 line without PGN move numbers + if (raw.indexOf('\n') === -1 && raw.split(/\s+/).length >= 4 && raw.split('/').length === 8) { + try { + const test = new Chess(raw); + clearBranch(); + initialFen = test.fen(); + mainUci = []; + mainSan = []; + mainPly = 0; + rebuildMainFens(); + updateAll(); + ctx.toast('Loaded FEN position.', 'success'); + return; + } catch { + // Fall through to PGN parser + } + } + + try { + const parsed = Chess.fromPgn(raw); + clearBranch(); + initialFen = parsed.initialFen; + mainUci = parsed.moves.map((m) => m.uci); + mainSan = parsed.moves.map((m) => m.san); + mainPly = mainUci.length; + rebuildMainFens(); + updateAll(); + ctx.toast(`Loaded PGN (${mainUci.length} plies).`, 'success'); + } catch (err) { + ctx.toast(err instanceof Error ? err.message : 'Invalid FEN or PGN.', 'error'); + } + }); + + copyPgnBtn.addEventListener('click', async () => { + if (pgnDisplayArea) { + const ok = await copyTextToClipboard(pgnDisplayArea.value); + ctx.toast(ok ? 'PGN copied!' : 'Copy failed', ok ? 'success' : 'error'); + } + }); + + body.appendChild(pgnBtns); + pgnPanelEl.appendChild(body); + } + + function renderArrows(): void { + const ev = getActivePositionEval(); + if (ev.bestUci && ev.bestUci.length >= 4) { + board.setArrows([ + { + from: ev.bestUci.slice(0, 2), + to: ev.bestUci.slice(2, 4), + color: '#629924' + } + ]); + } else { + board.setArrows([]); + } + } + + function updateAll(): void { + if (destroyed) return; + if (loadError) { + clearNode(container); + const errPage = el('div', { className: 'page-container narrow-page' }); + const card = el('div', { className: 'card' }); + const body = el('div', { className: 'card-body' }); + body.appendChild(el('div', { className: 'alert alert-error' }, loadError)); + const back = el('button', { type: 'button', className: 'btn' }, 'Open Freeform Analysis'); + back.addEventListener('click', () => ctx.navigate('/analysis')); + body.appendChild(back); + card.appendChild(body); + errPage.appendChild(card); + container.appendChild(errPage); + return; + } + + board.setPosition(currentFen(), currentLastMoveUci()); + const classifications = + report && report.status === 'done' + ? report.plies.map((p) => p.classification) + : undefined; + const initChess = new Chess(initialFen); + moveList.render(mainSan, mainPly, { + startMoveNumber: initChess.fullmove(), + startTurn: initChess.turn(), + classifications + }); + evalGraph.render(report, mainPly); + renderVariationAndFeedback(); + renderEvalBar(); + renderArrows(); + requestMultiPvIfEnabled(); + if (fenDisplayInput) { + fenDisplayInput.value = currentFen(); + } + } + + const unsub = wsClient.onMessage((msg: ServerWsMessage) => { + if (gameId && msg.type === 'analysis:progress' && msg.gameId === gameId) { + if (!report) { + report = { + gameId, + status: 'running', + depth: 12, + progressPly: msg.progressPly, + totalPlies: msg.totalPlies, + whiteSummary: null, + blackSummary: null, + initialEvalCp: null, + initialEvalMate: null, + initialWinPercent: 50, + initialBestMoveUci: null, + initialBestMoveSan: null, + initialPvSan: [], + plies: [], + createdAt: Date.now(), + updatedAt: Date.now() + }; + } else { + report.status = 'running'; + report.progressPly = msg.progressPly; + report.totalPlies = msg.totalPlies; + } + renderAnalysisControl(); + } else if (gameId && msg.type === 'analysis:done' && msg.gameId === gameId) { + report = msg.report; + renderAnalysisControl(); + updateAll(); + ctx.toast('Stockfish analysis complete!', 'success'); + } else if (gameId && msg.type === 'analysis:error' && msg.gameId === gameId) { + if (report) report.status = 'error'; + renderAnalysisControl(); + ctx.toast(msg.message, 'error'); + } else if (msg.type === 'analysis:multipv_result' && msg.requestId === activeMultipvReqId) { + multipvLines = msg.lines; + multipvDepth = msg.depth; + multipvDone = msg.done; + renderEnginePanel(); + renderEvalBar(); + renderArrows(); + } + }); + + buildSkeleton(); + renderHeader(); + renderEnginePanel(); + renderAnalysisControl(); + renderPgnPanel(); + + if (gameId) { + wsClient.send({ type: 'analysis:subscribe', gameId }); + apiRequest< + | { kind: 'active'; game: import('../../shared/types').ActiveGameState } + | { kind: 'stored'; game: StoredGame; analysis: GameAnalysisReport | null } + >(`/api/games/${encodeURIComponent(gameId)}`) + .then((resp) => { + if (destroyed) return; + if (resp.kind === 'active') { + loadError = 'This game is still in progress. Watch it live first!'; + updateAll(); + return; + } + storedGame = resp.game; + report = resp.analysis; + initialFen = resp.game.initialFen; + mainUci = resp.game.movesUci.slice(); + mainSan = resp.game.movesSan.slice(); + mainPly = mainUci.length; + rebuildMainFens(); + renderHeader(); + renderAnalysisControl(); + renderPgnPanel(); + updateAll(); + }) + .catch((err) => { + if (destroyed) return; + loadError = err instanceof Error ? err.message : 'Game not found.'; + updateAll(); + }); + } else { + rebuildMainFens(); + updateAll(); + } + + return { + destroy() { + destroyed = true; + unsub(); + if (gameId) { + wsClient.send({ type: 'analysis:unsubscribe', gameId }); + } + if (activeMultipvReqId) { + wsClient.send({ type: 'analysis:multipv_stop', requestId: activeMultipvReqId }); + } + board.destroy(); + moveList.destroy(); + } + }; +} diff --git a/src/client/views/authView.ts b/src/client/views/authView.ts new file mode 100644 index 0000000..3c91e76 --- /dev/null +++ b/src/client/views/authView.ts @@ -0,0 +1,147 @@ +import type { UserSummary } from '../../shared/types'; +import { apiRequest, wsClient } from '../api'; +import { clearNode, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +export function mountAuthView( + container: HTMLElement, + ctx: AppContext, + initialMode: 'login' | 'register', + nextPath?: string +): ViewHandle { + let mode: 'login' | 'register' = initialMode; + let errorText = ''; + let busy = false; + + function render(): void { + clearNode(container); + const wrap = el('div', { className: 'auth-wrap' }); + const card = el('div', { className: 'card auth-card' }); + + const tabs = el('div', { className: 'tab-bar' }); + const loginTab = el( + 'button', + { type: 'button', className: mode === 'login' ? 'tab-btn active' : 'tab-btn' }, + 'Sign In' + ); + const regTab = el( + 'button', + { type: 'button', className: mode === 'register' ? 'tab-btn active' : 'tab-btn' }, + 'Create Account' + ); + + loginTab.addEventListener('click', () => { + mode = 'login'; + errorText = ''; + render(); + }); + regTab.addEventListener('click', () => { + mode = 'register'; + errorText = ''; + render(); + }); + tabs.appendChild(loginTab); + tabs.appendChild(regTab); + card.appendChild(tabs); + + const body = el('div', { className: 'card-body' }); + body.appendChild( + el( + 'p', + { className: 'muted small-note' }, + mode === 'register' + ? 'No email required. Pick a username and password to play, track Glicko-2 ratings, add friends, and save game analytics.' + : 'Sign in with your ChessUp username and password.' + ) + ); + + if (errorText) { + body.appendChild(el('div', { className: 'alert alert-error' }, errorText)); + } + + const form = el('form', { className: 'stack-form' }); + const usernameInput = el('input', { + type: 'text', + className: 'input', + placeholder: 'Username (3-20 chars, A-Z, 0-9, _, -)', + autocomplete: 'username', + required: true + }) as HTMLInputElement; + + const passwordInput = el('input', { + type: 'password', + className: 'input', + placeholder: 'Password (min 6 characters)', + autocomplete: mode === 'register' ? 'new-password' : 'current-password', + required: true + }) as HTMLInputElement; + + let confirmInput: HTMLInputElement | null = null; + form.appendChild(el('label', { className: 'field-label' }, 'Username')); + form.appendChild(usernameInput); + form.appendChild(el('label', { className: 'field-label' }, 'Password')); + form.appendChild(passwordInput); + + if (mode === 'register') { + confirmInput = el('input', { + type: 'password', + className: 'input', + placeholder: 'Confirm password', + autocomplete: 'new-password', + required: true + }) as HTMLInputElement; + form.appendChild(el('label', { className: 'field-label' }, 'Confirm Password')); + form.appendChild(confirmInput); + } + + const submitBtn = el( + 'button', + { type: 'submit', className: 'btn btn-primary btn-block', disabled: busy }, + busy ? 'Please wait...' : mode === 'login' ? 'Sign In' : 'Create Account' + ); + form.appendChild(submitBtn); + + form.addEventListener('submit', async (e) => { + e.preventDefault(); + if (busy) return; + const username = usernameInput.value.trim(); + const password = passwordInput.value; + + if (mode === 'register' && confirmInput && password !== confirmInput.value) { + errorText = 'Passwords do not match.'; + render(); + return; + } + + busy = true; + errorText = ''; + render(); + + try { + await apiRequest<{ user: UserSummary }>( + mode === 'login' ? '/api/auth/login' : '/api/auth/register', + { + method: 'POST', + body: JSON.stringify({ username, password }) + } + ); + await ctx.refreshSession(); + wsClient.reconnectNow(); + ctx.toast(mode === 'login' ? `Welcome back, ${username}` : `Account created: ${username}`, 'success'); + ctx.navigate(nextPath && nextPath.indexOf('/') === 0 ? nextPath : '/', true); + } catch (err) { + busy = false; + errorText = err instanceof Error ? err.message : 'Authentication failed.'; + render(); + } + }); + + body.appendChild(form); + card.appendChild(body); + wrap.appendChild(card); + container.appendChild(wrap); + } + + render(); + return { destroy() {} }; +} diff --git a/src/client/views/botView.ts b/src/client/views/botView.ts new file mode 100644 index 0000000..708553f --- /dev/null +++ b/src/client/views/botView.ts @@ -0,0 +1,148 @@ +import { BOT_LEVELS } from '../../shared/timeControl'; +import type { ColorPreference } from '../../shared/types'; +import { apiRequest } from '../api'; +import { clearNode, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +const BOT_TIMES: ReadonlyArray<{ label: string; initialMs: number; incrementMs: number }> = [ + { label: 'Unlimited', initialMs: 0, incrementMs: 0 }, + { label: '3+2', initialMs: 180_000, incrementMs: 2_000 }, + { label: '5+0', initialMs: 300_000, incrementMs: 0 }, + { label: '10+0', initialMs: 600_000, incrementMs: 0 }, + { label: '10+5', initialMs: 600_000, incrementMs: 5_000 }, + { label: '15+10', initialMs: 900_000, incrementMs: 10_000 } +]; + +export function mountBotView(container: HTMLElement, ctx: AppContext): ViewHandle { + let selectedLevel = 2; + let colorPref: ColorPreference = 'white'; + let selectedInitialMs = 0; + let selectedIncrementMs = 0; + let starting = false; + + function render(): void { + clearNode(container); + const page = el('div', { className: 'page-container narrow-page' }); + const card = el('div', { className: 'card' }); + card.appendChild(el('div', { className: 'card-header' }, el('h1', { className: 'card-title' }, 'Play vs Stockfish'))); + + const body = el('div', { className: 'card-body' }); + + if (!ctx.getUser()) { + const warn = el('div', { className: 'alert alert-info' }); + warn.appendChild(el('span', null, 'Sign in or create an account (no email needed) to play against Stockfish. ')); + const link = el('a', { href: '/login', className: 'user-link' }, 'Sign in'); + link.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate('/login?next=/bots'); + }); + warn.appendChild(link); + body.appendChild(warn); + } + + body.appendChild(el('div', { className: 'field-label' }, 'Select Difficulty (8 Levels)')); + const levelGrid = el('div', { className: 'bot-grid' }); + for (const b of BOT_LEVELS) { + const active = selectedLevel === b.level; + const item = el('button', { + type: 'button', + className: active ? 'bot-level-card active' : 'bot-level-card' + }); + const top = el('div', { className: 'bot-level-top' }); + top.appendChild(el('strong', null, `Level ${b.level}`)); + top.appendChild(el('span', { className: 'rating-chip' }, `~${b.approxElo}`)); + item.appendChild(top); + item.appendChild(el('div', { className: 'bot-level-desc' }, b.description)); + item.addEventListener('click', () => { + selectedLevel = b.level; + render(); + }); + levelGrid.appendChild(item); + } + body.appendChild(levelGrid); + + const optSplit = el('div', { className: 'bot-options-split' }); + + const colorWrap = el('div', { className: 'bot-opt-block' }); + colorWrap.appendChild(el('div', { className: 'field-label' }, 'Play As')); + const cGrp = el('div', { className: 'btn-group' }); + for (const cp of [ + { id: 'white' as ColorPreference, label: 'White' }, + { id: 'random' as ColorPreference, label: 'Random' }, + { id: 'black' as ColorPreference, label: 'Black' } + ]) { + const btn = el( + 'button', + { type: 'button', className: colorPref === cp.id ? 'btn btn-sm btn-primary' : 'btn btn-sm' }, + cp.label + ); + btn.addEventListener('click', () => { + colorPref = cp.id; + render(); + }); + cGrp.appendChild(btn); + } + colorWrap.appendChild(cGrp); + optSplit.appendChild(colorWrap); + + const timeWrap = el('div', { className: 'bot-opt-block' }); + timeWrap.appendChild(el('div', { className: 'field-label' }, 'Clock')); + const tGrp = el('div', { className: 'btn-group' }); + for (const tc of BOT_TIMES) { + const active = selectedInitialMs === tc.initialMs && selectedIncrementMs === tc.incrementMs; + const btn = el( + 'button', + { type: 'button', className: active ? 'btn btn-sm btn-primary' : 'btn btn-sm' }, + tc.label + ); + btn.addEventListener('click', () => { + selectedInitialMs = tc.initialMs; + selectedIncrementMs = tc.incrementMs; + render(); + }); + tGrp.appendChild(btn); + } + timeWrap.appendChild(tGrp); + optSplit.appendChild(timeWrap); + body.appendChild(optSplit); + + const startBtn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-lg btn-block', disabled: starting }, + starting ? 'Starting Stockfish...' : `Start Game vs Level ${selectedLevel}` + ); + startBtn.addEventListener('click', async () => { + if (!ctx.getUser()) { + ctx.navigate('/login?next=/bots'); + return; + } + starting = true; + render(); + try { + const res = await apiRequest<{ gameId: string }>('/api/games/bot', { + method: 'POST', + body: JSON.stringify({ + level: selectedLevel, + colorPref, + initialMs: selectedInitialMs, + incrementMs: selectedIncrementMs + }) + }); + ctx.setActiveGameId(res.gameId); + ctx.navigate(`/game/${res.gameId}`); + } catch (err) { + starting = false; + ctx.toast(err instanceof Error ? err.message : 'Failed to start bot game.', 'error'); + render(); + } + }); + body.appendChild(startBtn); + + card.appendChild(body); + page.appendChild(card); + container.appendChild(page); + } + + render(); + return { destroy() {} }; +} diff --git a/src/client/views/context.ts b/src/client/views/context.ts new file mode 100644 index 0000000..2bf1a42 --- /dev/null +++ b/src/client/views/context.ts @@ -0,0 +1,14 @@ +import type { UserSummary } from '../../shared/types'; + +export interface ViewHandle { + destroy(): void; +} + +export interface AppContext { + getUser(): UserSummary | null; + getActiveGameId(): string | null; + setActiveGameId(gameId: string | null): void; + refreshSession(): Promise; + navigate(path: string, replace?: boolean): void; + toast(message: string, kind?: 'info' | 'success' | 'error'): void; +} diff --git a/src/client/views/friendsView.ts b/src/client/views/friendsView.ts new file mode 100644 index 0000000..5fcfeb9 --- /dev/null +++ b/src/client/views/friendsView.ts @@ -0,0 +1,420 @@ +import { TIME_PRESETS, categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { + ColorPreference, + DirectChallenge, + FriendEntry, + FriendRequestEntry, + ServerWsMessage, + UserSummary +} from '../../shared/types'; +import { apiRequest, wsClient } from '../api'; +import { clearNode, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +export function mountFriendsView(container: HTMLElement, ctx: AppContext): ViewHandle { + let friends: FriendEntry[] = []; + let requests: FriendRequestEntry[] = []; + let challenges: DirectChallenge[] = []; + let searchQuery = ''; + let searchResults: UserSummary[] = []; + let challengeTarget: FriendEntry | null = null; + let chalInitialMs = 300_000; + let chalIncrementMs = 0; + let chalRated = true; + let chalColor: ColorPreference = 'random'; + let destroyed = false; + + async function loadAll(): Promise { + if (!ctx.getUser()) return; + try { + const data = await apiRequest<{ + friends: FriendEntry[]; + requests: FriendRequestEntry[]; + challenges: DirectChallenge[]; + }>('/api/friends'); + if (destroyed) return; + friends = data.friends; + requests = data.requests; + challenges = data.challenges; + render(); + } catch { + // Ignore + } + } + + async function runSearch(): Promise { + const q = searchQuery.trim(); + if (!q) { + searchResults = []; + render(); + return; + } + try { + const data = await apiRequest<{ users: UserSummary[] }>(`/api/users/search?q=${encodeURIComponent(q)}`); + if (destroyed) return; + searchResults = data.users; + render(); + } catch { + // Ignore + } + } + + function render(): void { + if (destroyed) return; + clearNode(container); + const page = el('div', { className: 'page-container' }); + const user = ctx.getUser(); + + if (!user) { + const card = el('div', { className: 'card' }); + const body = el('div', { className: 'card-body' }); + body.appendChild(el('p', null, 'Sign in to manage friends, see live online status, and send direct challenges.')); + const btn = el('button', { type: 'button', className: 'btn btn-primary' }, 'Sign In'); + btn.addEventListener('click', () => ctx.navigate('/login?next=/friends')); + body.appendChild(btn); + card.appendChild(body); + page.appendChild(card); + container.appendChild(page); + return; + } + + // Challenges card (if any) + if (challenges.length > 0) { + const chalCard = el('div', { className: 'card' }); + chalCard.appendChild(el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, 'Direct Challenges'))); + const cBody = el('div', { className: 'card-body no-pad' }); + const list = el('div', { className: 'list-stack' }); + for (const ch of challenges) { + const isIncoming = ch.toUserId === user.id; + const row = el('div', { className: 'list-row' }); + const info = el('div'); + info.appendChild( + el( + 'strong', + null, + isIncoming ? `From ${ch.fromUsername} (${ch.fromRating})` : `To ${ch.toUsername}` + ) + ); + info.appendChild( + el( + 'div', + { className: 'small-text muted' }, + `${formatTimeControl(ch.initialMs, ch.incrementMs)} · ${categoryLabel(ch.category)} · ${ + ch.rated ? 'Rated' : 'Casual' + }` + ) + ); + row.appendChild(info); + + const acts = el('div', { className: 'btn-row' }); + if (isIncoming) { + const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept'); + const dec = el('button', { type: 'button', className: 'btn btn-xs btn-danger' }, 'Decline'); + acc.addEventListener('click', () => wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: true })); + dec.addEventListener('click', () => wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: false })); + acts.appendChild(acc); + acts.appendChild(dec); + } else { + const cancel = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel'); + cancel.addEventListener('click', () => wsClient.send({ type: 'challenge:cancel', challengeId: ch.id })); + acts.appendChild(cancel); + } + row.appendChild(acts); + list.appendChild(row); + } + cBody.appendChild(list); + chalCard.appendChild(cBody); + page.appendChild(chalCard); + } + + // Challenge modal/panel if targeting a friend + if (challengeTarget) { + const target = challengeTarget; + const box = el('div', { className: 'card challenge-box' }); + const head = el('div', { className: 'card-header' }); + head.appendChild(el('h2', { className: 'card-title' }, `Challenge ${target.username}`)); + const closeBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Close'); + closeBtn.addEventListener('click', () => { + challengeTarget = null; + render(); + }); + head.appendChild(closeBtn); + box.appendChild(head); + + const body = el('div', { className: 'card-body' }); + const tcGrid = el('div', { className: 'preset-grid' }); + for (const p of TIME_PRESETS) { + const active = chalInitialMs === p.initialMs && chalIncrementMs === p.incrementMs; + const b = el('button', { type: 'button', className: active ? 'btn btn-xs btn-primary' : 'btn btn-xs' }, p.label); + b.addEventListener('click', () => { + chalInitialMs = p.initialMs; + chalIncrementMs = p.incrementMs; + if (p.initialMs === 0 && p.incrementMs === 0) chalRated = false; + render(); + }); + tcGrid.appendChild(b); + } + body.appendChild(tcGrid); + + const opts = el('div', { className: 'options-row' }); + const isUnlimited = chalInitialMs === 0 && chalIncrementMs === 0; + const mGrp = el('div', { className: 'btn-group' }); + const rBtn = el('button', { type: 'button', className: chalRated && !isUnlimited ? 'btn btn-xs btn-primary' : 'btn btn-xs', disabled: isUnlimited }, 'Rated'); + const casBtn = el('button', { type: 'button', className: !chalRated || isUnlimited ? 'btn btn-xs btn-primary' : 'btn btn-xs' }, 'Casual'); + rBtn.addEventListener('click', () => { + chalRated = true; + render(); + }); + casBtn.addEventListener('click', () => { + chalRated = false; + render(); + }); + mGrp.appendChild(rBtn); + mGrp.appendChild(casBtn); + opts.appendChild(mGrp); + + const cGrp = el('div', { className: 'btn-group' }); + for (const cp of [ + { id: 'white' as ColorPreference, label: 'White' }, + { id: 'random' as ColorPreference, label: 'Random' }, + { id: 'black' as ColorPreference, label: 'Black' } + ]) { + const b = el('button', { type: 'button', className: chalColor === cp.id ? 'btn btn-xs btn-primary' : 'btn btn-xs' }, cp.label); + b.addEventListener('click', () => { + chalColor = cp.id; + render(); + }); + cGrp.appendChild(b); + } + opts.appendChild(cGrp); + body.appendChild(opts); + + const sendBtn = el('button', { type: 'button', className: 'btn btn-primary' }, `Send Challenge to ${target.username}`); + sendBtn.addEventListener('click', () => { + wsClient.send({ + type: 'challenge:send', + toUserId: target.userId, + initialMs: chalInitialMs, + incrementMs: chalIncrementMs, + rated: isUnlimited ? false : chalRated, + colorPref: chalColor + }); + challengeTarget = null; + ctx.toast(`Challenge sent to ${target.username}`, 'success'); + render(); + }); + body.appendChild(sendBtn); + box.appendChild(body); + page.appendChild(box); + } + + const layout = el('div', { className: 'two-col-friends' }); + + // Friends list + const friendsCard = el('div', { className: 'card' }); + friendsCard.appendChild( + el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, `Friends (${friends.length})`)) + ); + const fBody = el('div', { className: 'card-body no-pad' }); + + if (friends.length === 0) { + fBody.appendChild(el('div', { className: 'empty-state' }, 'No friends yet. Search for players on the right to add friends.')); + } else { + const list = el('div', { className: 'list-stack' }); + for (const f of friends) { + const row = el('div', { className: 'list-row' }); + const left = el('div', { className: 'friend-left' }); + const dotCls = + f.onlineStatus === 'in_game' + ? 'dot dot-ingame' + : f.onlineStatus === 'online' + ? 'dot dot-online' + : 'dot dot-offline'; + left.appendChild(el('span', { className: dotCls })); + + const nameLink = el('a', { href: `/u/${encodeURIComponent(f.username)}`, className: 'user-link' }, f.username); + nameLink.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(f.username)}`); + }); + left.appendChild(nameLink); + left.appendChild( + el( + 'div', + { className: 'small-text muted' }, + `Blitz ${f.ratings.blitz.rating} · Rapid ${f.ratings.rapid.rating} · H2H ${f.headToHead.wins}-${f.headToHead.draws}-${f.headToHead.losses}` + ) + ); + row.appendChild(left); + + const acts = el('div', { className: 'btn-row' }); + if (f.onlineStatus === 'in_game' && f.activeGameId) { + const spec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Spectate'); + spec.addEventListener('click', () => ctx.navigate(`/game/${f.activeGameId}`)); + acts.appendChild(spec); + } + const chalBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Challenge'); + chalBtn.addEventListener('click', () => { + challengeTarget = f; + render(); + }); + const remBtn = el('button', { type: 'button', className: 'btn btn-xs btn-danger' }, 'Remove'); + remBtn.addEventListener('click', async () => { + await apiRequest(`/api/friends/${f.userId}`, { method: 'DELETE' }); + loadAll(); + }); + acts.appendChild(chalBtn); + acts.appendChild(remBtn); + row.appendChild(acts); + list.appendChild(row); + } + fBody.appendChild(list); + } + friendsCard.appendChild(fBody); + layout.appendChild(friendsCard); + + // Right column: Requests + Search + const rightCol = el('div', { className: 'side-col' }); + + const reqCard = el('div', { className: 'card' }); + reqCard.appendChild( + el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, `Friend Requests (${requests.length})`)) + ); + const reqBody = el('div', { className: 'card-body no-pad' }); + if (requests.length === 0) { + reqBody.appendChild(el('div', { className: 'empty-state' }, 'No pending friend requests.')); + } else { + const list = el('div', { className: 'list-stack' }); + for (const req of requests) { + const row = el('div', { className: 'list-row' }); + const nameLink = el('a', { href: `/u/${encodeURIComponent(req.username)}`, className: 'user-link' }, req.username); + nameLink.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(req.username)}`); + }); + row.appendChild(nameLink); + + const acts = el('div', { className: 'btn-row' }); + if (req.direction === 'incoming') { + const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept'); + const dec = el('button', { type: 'button', className: 'btn btn-xs btn-danger' }, 'Decline'); + acc.addEventListener('click', async () => { + await apiRequest('/api/friends/respond', { + method: 'POST', + body: JSON.stringify({ userId: req.userId, accept: true }) + }); + loadAll(); + }); + dec.addEventListener('click', async () => { + await apiRequest('/api/friends/respond', { + method: 'POST', + body: JSON.stringify({ userId: req.userId, accept: false }) + }); + loadAll(); + }); + acts.appendChild(acc); + acts.appendChild(dec); + } else { + const cancel = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel'); + cancel.addEventListener('click', async () => { + await apiRequest(`/api/friends/${req.userId}`, { method: 'DELETE' }); + loadAll(); + }); + acts.appendChild(cancel); + } + row.appendChild(acts); + list.appendChild(row); + } + reqBody.appendChild(list); + } + reqCard.appendChild(reqBody); + rightCol.appendChild(reqCard); + + // Search card + const searchCard = el('div', { className: 'card' }); + searchCard.appendChild(el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, 'Find Players'))); + const sBody = el('div', { className: 'card-body' }); + const sForm = el('form', { className: 'invite-box' }); + const sInput = el('input', { + type: 'text', + className: 'input input-sm', + placeholder: 'Search username...', + value: searchQuery + }) as HTMLInputElement; + const sBtn = el('button', { type: 'submit', className: 'btn btn-sm btn-primary' }, 'Search'); + sForm.appendChild(sInput); + sForm.appendChild(sBtn); + sForm.addEventListener('submit', (e) => { + e.preventDefault(); + searchQuery = sInput.value; + runSearch(); + }); + sBody.appendChild(sForm); + + if (searchResults.length > 0) { + const list = el('div', { className: 'list-stack search-results' }); + for (const u of searchResults) { + const row = el('div', { className: 'list-row' }); + const link = el('a', { href: `/u/${encodeURIComponent(u.username)}`, className: 'user-link' }, u.username); + link.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(u.username)}`); + }); + row.appendChild(link); + + const isFriend = friends.some((f) => f.userId === u.id); + const isPending = requests.some((r) => r.userId === u.id); + if (!isFriend && !isPending) { + const addBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Add Friend'); + addBtn.addEventListener('click', async () => { + try { + await apiRequest('/api/friends/request', { + method: 'POST', + body: JSON.stringify({ userId: u.id }) + }); + ctx.toast(`Friend request sent to ${u.username}`, 'success'); + loadAll(); + } catch (err) { + ctx.toast(err instanceof Error ? err.message : 'Failed.', 'error'); + } + }); + row.appendChild(addBtn); + } else { + row.appendChild(el('span', { className: 'small-text muted' }, isFriend ? 'Friend' : 'Pending')); + } + list.appendChild(row); + } + sBody.appendChild(list); + } + + searchCard.appendChild(sBody); + rightCol.appendChild(searchCard); + layout.appendChild(rightCol); + + page.appendChild(layout); + container.appendChild(page); + } + + const unsub = wsClient.onMessage((msg: ServerWsMessage) => { + if (msg.type === 'friend:presence') { + const target = friends.find((f) => f.userId === msg.userId); + if (target) { + target.onlineStatus = msg.onlineStatus; + target.activeGameId = msg.activeGameId; + render(); + } + } else if (msg.type === 'friend:update' || msg.type === 'challenge:received' || msg.type === 'challenge:removed' || msg.type === 'challenge:list') { + loadAll(); + } + }); + + loadAll(); + render(); + + return { + destroy() { + destroyed = true; + unsub(); + } + }; +} diff --git a/src/client/views/gameView.ts b/src/client/views/gameView.ts new file mode 100644 index 0000000..8850bd6 --- /dev/null +++ b/src/client/views/gameView.ts @@ -0,0 +1,663 @@ +import { Chess } from '../../shared/chess'; +import { categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types'; +import { apiRequest, wsClient } from '../api'; +import { ChessBoard } from '../components/board'; +import { ClockWidget } from '../components/clock'; +import { MoveList } from '../components/moveList'; +import { clearNode, el } from '../dom'; +import { sound } from '../sound'; +import type { AppContext, ViewHandle } from './context'; + +function terminationLabel(term: string | null): string { + switch (term) { + case 'checkmate': + return 'Checkmate'; + case 'resign': + return 'Resignation'; + case 'timeout': + return 'Time out'; + case 'abandonment': + return 'Abandonment (60s disconnect)'; + case 'stalemate': + return 'Stalemate'; + case 'draw_agreement': + return 'Draw by agreement'; + case 'repetition': + return 'Threefold repetition'; + case 'fifty_move': + return '50-move rule'; + case 'insufficient_material': + return 'Insufficient material'; + case 'aborted': + return 'Game aborted'; + default: + return 'Finished'; + } +} + +export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: string): ViewHandle { + let game: ActiveGameState | null = null; + let errorMsg = ''; + let viewPly = 0; + let orientationOverride: Color | null = null; + let confirmResign = false; + let confirmResignTimer: number | null = null; + let destroyed = false; + let lastNotifiedMovesLen = -1; + + const board = new ChessBoard({ + mode: 'readonly', + onMove(uci) { + wsClient.send({ type: 'game:move', gameId, uci }); + } + }); + + const topClock = new ClockWidget(); + const bottomClock = new ClockWidget(); + const moveList = new MoveList({ + onSelectPly(ply) { + viewPly = ply; + syncBoardAndControls(); + }, + onFlip() { + const current = board.getOrientation(); + orientationOverride = current === 'w' ? 'b' : 'w'; + board.setOrientation(orientationOverride); + renderLayout(); + } + }); + + // Dynamic UI refs updated without tearing down Board / Clocks + const topPlayerBar = el('div', { className: 'player-bar' }); + const bottomPlayerBar = el('div', { className: 'player-bar' }); + const liveNoticeEl = el('div', { className: 'live-notice hidden' }); + const statusBannerEl = el('div', { className: 'game-status-banner hidden' }); + const actionsEl = el('div', { className: 'game-actions' }); + const chatMessagesEl = el('div', { className: 'chat-messages' }); + const chatForm = el('form', { className: 'chat-form' }); + const chatInput = el('input', { + type: 'text', + className: 'input input-sm', + placeholder: 'Send a message...', + maxlength: '300' + }) as HTMLInputElement; + const chatSendBtn = el('button', { type: 'submit', className: 'btn btn-sm' }, 'Send'); + chatForm.appendChild(chatInput); + chatForm.appendChild(chatSendBtn); + + chatForm.addEventListener('submit', (e) => { + e.preventDefault(); + const txt = chatInput.value.trim(); + if (!txt) return; + wsClient.send({ type: 'game:chat', gameId, text: txt }); + chatInput.value = ''; + }); + + const specBadgeEl = el('span', { className: 'muted small-text' }); + const headerMetaEl = el('div', { className: 'game-meta-line' }); + + function buildSkeleton(): void { + clearNode(container); + const page = el('div', { className: 'page-container game-page' }); + const layout = el('div', { className: 'game-layout' }); + + const boardCol = el('div', { className: 'board-col' }); + boardCol.appendChild(topPlayerBar); + boardCol.appendChild(board.root); + boardCol.appendChild(bottomPlayerBar); + boardCol.appendChild(liveNoticeEl); + layout.appendChild(boardCol); + + const sideCol = el('div', { className: 'game-side-col' }); + + const infoCard = el('div', { className: 'card' }); + const infoBody = el('div', { className: 'card-body compact' }); + infoBody.appendChild(headerMetaEl); + infoBody.appendChild(statusBannerEl); + infoCard.appendChild(infoBody); + sideCol.appendChild(infoCard); + + const movesCard = el('div', { className: 'card moves-card' }); + movesCard.appendChild(moveList.root); + movesCard.appendChild(actionsEl); + sideCol.appendChild(movesCard); + + const chatCard = el('div', { className: 'card chat-card' }); + const chatHead = el('div', { className: 'card-header' }); + chatHead.appendChild(el('span', { className: 'card-title-sm' }, 'Chat')); + chatHead.appendChild(specBadgeEl); + chatCard.appendChild(chatHead); + chatCard.appendChild(chatMessagesEl); + chatCard.appendChild(chatForm); + sideCol.appendChild(chatCard); + + layout.appendChild(sideCol); + page.appendChild(layout); + container.appendChild(page); + } + + function myColor(g: ActiveGameState): Color | null { + const u = ctx.getUser(); + if (!u) return null; + if (g.white.userId === u.id) return 'w'; + if (g.black.userId === u.id) return 'b'; + return null; + } + + function effectiveOrientation(g: ActiveGameState): Color { + if (orientationOverride) return orientationOverride; + return myColor(g) || 'w'; + } + + function renderPlayerBar( + target: HTMLElement, + clock: ClockWidget, + g: ActiveGameState, + color: Color + ): void { + clearNode(target); + const p = color === 'w' ? g.white : g.black; + const isTurn = !g.finished && g.turn === color; + target.className = isTurn ? 'player-bar player-turn' : 'player-bar'; + + const left = el('div', { className: 'player-info' }); + const dotClass = p.isBot + ? 'dot dot-bot' + : p.connected + ? 'dot dot-online' + : 'dot dot-offline'; + left.appendChild(el('span', { className: dotClass, title: p.connected ? 'Connected' : 'Disconnected' })); + + if (p.userId !== null && !p.isBot) { + const nameLink = el( + 'a', + { href: `/u/${encodeURIComponent(p.username)}`, className: 'player-name' }, + p.username + ); + nameLink.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(p.username)}`); + }); + left.appendChild(nameLink); + } else { + left.appendChild(el('span', { className: 'player-name' }, p.username)); + } + + if (p.rating !== null) { + left.appendChild(el('span', { className: 'rating-chip' }, ` (${p.rating}${p.provisional ? '?' : ''})`)); + } + + const diff = color === 'w' ? g.whiteRatingDiff : g.blackRatingDiff; + if (g.finished && diff !== null) { + const sign = diff >= 0 ? '+' : ''; + const cls = diff > 0 ? 'diff-pos' : diff < 0 ? 'diff-neg' : 'muted'; + left.appendChild(el('span', { className: `rating-diff ${cls}` }, ` ${sign}${diff}`)); + } + + if (!g.finished && p.disconnectDeadlineMs && !p.connected) { + const secs = Math.max(0, Math.ceil((p.disconnectDeadlineMs - Date.now()) / 1000)); + left.appendChild(el('span', { className: 'disconnect-badge' }, `Forfeit in ${secs}s`)); + } + + target.appendChild(left); + target.appendChild(clock.root); + + const ms = color === 'w' ? g.whiteTimeMs : g.blackTimeMs; + clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited'); + } + + function renderLayout(): void { + if (destroyed) return; + if (errorMsg) { + clearNode(container); + const errPage = el('div', { className: 'page-container narrow-page' }); + const card = el('div', { className: 'card' }); + const body = el('div', { className: 'card-body' }); + body.appendChild(el('div', { className: 'alert alert-error' }, errorMsg)); + const back = el('button', { type: 'button', className: 'btn' }, 'Back to Lobby'); + back.addEventListener('click', () => ctx.navigate('/')); + body.appendChild(back); + card.appendChild(body); + errPage.appendChild(card); + container.appendChild(errPage); + return; + } + + if (!game) return; + const g = game; + const orient = effectiveOrientation(g); + const topColor: Color = orient === 'w' ? 'b' : 'w'; + const bottomColor: Color = orient; + + board.setOrientation(orient); + renderPlayerBar(topPlayerBar, topClock, g, topColor); + renderPlayerBar(bottomPlayerBar, bottomClock, g, bottomColor); + + headerMetaEl.textContent = `${formatTimeControl(g.initialMs, g.incrementMs)} · ${categoryLabel(g.category)} · ${ + g.botLevel ? `Stockfish Lv ${g.botLevel}` : g.rated ? 'Rated' : 'Casual' + }`; + specBadgeEl.textContent = g.spectatorCount > 0 ? `${g.spectatorCount} watching` : ''; + + // Status / Result banner + clearNode(statusBannerEl); + if (g.finished) { + statusBannerEl.className = 'game-status-banner finished'; + const title = + g.result === '1-0' + ? 'White wins (1-0)' + : g.result === '0-1' + ? 'Black wins (0-1)' + : g.result === '1/2-1/2' + ? 'Draw (1/2-1/2)' + : 'Game Aborted'; + statusBannerEl.appendChild(el('strong', null, title)); + statusBannerEl.appendChild(el('div', { className: 'small-text muted' }, terminationLabel(g.termination))); + } else if (g.abortDeadlineMs && g.movesUci.length < 2) { + const secs = Math.max(0, Math.ceil((g.abortDeadlineMs - Date.now()) / 1000)); + statusBannerEl.className = 'game-status-banner'; + statusBannerEl.textContent = `Waiting for first moves · auto-abort in ${secs}s`; + } else { + statusBannerEl.className = 'game-status-banner hidden'; + } + + // Action buttons + renderActions(g); + renderChat(g); + syncBoardAndControls(); + } + + function syncBoardAndControls(): void { + if (!game) return; + const g = game; + const mc = myColor(g); + const isLive = viewPly === g.movesUci.length; + + if (mc && !g.finished && isLive) { + board.setMode('play', mc); + } else { + board.setMode('readonly'); + } + + if (isLive) { + const lastUci = g.movesUci.length > 0 ? g.movesUci[g.movesUci.length - 1] : null; + board.setPosition(g.fen, lastUci); + liveNoticeEl.className = 'live-notice hidden'; + } else { + const temp = new Chess(g.initialFen); + for (let i = 0; i < viewPly && i < g.movesUci.length; i++) { + temp.moveUci(g.movesUci[i]!); + } + const lastUci = viewPly > 0 ? g.movesUci[viewPly - 1] : null; + board.setPosition(temp.fen(), lastUci); + clearNode(liveNoticeEl); + liveNoticeEl.className = 'live-notice'; + liveNoticeEl.appendChild(el('span', null, `Viewing move ${viewPly} of ${g.movesUci.length} `)); + const jumpBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Jump to live'); + jumpBtn.addEventListener('click', () => { + viewPly = g.movesUci.length; + syncBoardAndControls(); + }); + liveNoticeEl.appendChild(jumpBtn); + } + + moveList.render(g.movesSan, viewPly); + } + + function renderActions(g: ActiveGameState): void { + clearNode(actionsEl); + const mc = myColor(g); + + if (g.finished) { + const row = el('div', { className: 'action-row' }); + if (g.saved) { + const analyzeBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Analyze Game'); + analyzeBtn.addEventListener('click', () => ctx.navigate(`/analysis/${g.id}`)); + row.appendChild(analyzeBtn); + + const pgnLink = el( + 'a', + { href: `/api/games/${g.id}/pgn`, className: 'btn btn-sm', target: '_blank' }, + 'PGN' + ); + row.appendChild(pgnLink); + } + + if (mc) { + if (g.rematchGameId) { + const goBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Open Rematch'); + goBtn.addEventListener('click', () => ctx.navigate(`/game/${g.rematchGameId}`)); + row.appendChild(goBtn); + } else if (g.rematchOfferFrom && g.rematchOfferFrom !== mc) { + const accBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Accept Rematch'); + const decBtn = el('button', { type: 'button', className: 'btn btn-sm' }, 'Decline'); + accBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_respond', gameId: g.id, accept: true })); + decBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_respond', gameId: g.id, accept: false })); + row.appendChild(accBtn); + row.appendChild(decBtn); + } else { + const remBtn = el( + 'button', + { + type: 'button', + className: 'btn btn-sm', + disabled: g.rematchOfferFrom === mc + }, + g.rematchOfferFrom === mc ? 'Rematch Sent...' : 'Rematch' + ); + remBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_offer', gameId: g.id })); + row.appendChild(remBtn); + } + } + + const lobbyBtn = el('button', { type: 'button', className: 'btn btn-sm' }, 'Lobby'); + lobbyBtn.addEventListener('click', () => ctx.navigate('/')); + row.appendChild(lobbyBtn); + actionsEl.appendChild(row); + return; + } + + if (!mc) { + actionsEl.appendChild(el('div', { className: 'muted small-text center-text' }, 'Spectating live game')); + return; + } + + // Incoming draw offer banner + if (g.drawOfferFrom && g.drawOfferFrom !== mc) { + const offerBar = el('div', { className: 'offer-bar' }); + offerBar.appendChild(el('span', null, 'Opponent offers a draw')); + const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept'); + const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline'); + acc.addEventListener('click', () => wsClient.send({ type: 'game:draw_respond', gameId: g.id, accept: true })); + dec.addEventListener('click', () => wsClient.send({ type: 'game:draw_respond', gameId: g.id, accept: false })); + offerBar.appendChild(acc); + offerBar.appendChild(dec); + actionsEl.appendChild(offerBar); + } + + // Incoming takeback offer banner + if (g.takebackOfferFrom && g.takebackOfferFrom !== mc) { + const offerBar = el('div', { className: 'offer-bar' }); + offerBar.appendChild(el('span', null, 'Opponent requests a takeback')); + const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Allow'); + const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline'); + acc.addEventListener('click', () => wsClient.send({ type: 'game:takeback_respond', gameId: g.id, accept: true })); + dec.addEventListener('click', () => wsClient.send({ type: 'game:takeback_respond', gameId: g.id, accept: false })); + offerBar.appendChild(acc); + offerBar.appendChild(dec); + actionsEl.appendChild(offerBar); + } + + const row = el('div', { className: 'action-row' }); + + if (g.movesUci.length < 2) { + const abortBtn = el('button', { type: 'button', className: 'btn btn-sm btn-danger' }, 'Abort'); + abortBtn.addEventListener('click', () => wsClient.send({ type: 'game:abort', gameId: g.id })); + row.appendChild(abortBtn); + } else { + const resignBtn = el( + 'button', + { type: 'button', className: confirmResign ? 'btn btn-sm btn-danger' : 'btn btn-sm' }, + confirmResign ? 'Confirm Resign?' : 'Resign' + ); + resignBtn.addEventListener('click', () => { + if (!confirmResign) { + confirmResign = true; + renderActions(g); + if (confirmResignTimer !== null) window.clearTimeout(confirmResignTimer); + confirmResignTimer = window.setTimeout(() => { + confirmResign = false; + if (game) renderActions(game); + }, 3500); + } else { + confirmResign = false; + wsClient.send({ type: 'game:resign', gameId: g.id }); + } + }); + row.appendChild(resignBtn); + + if (g.botLevel === null) { + const drawBtn = el( + 'button', + { type: 'button', className: 'btn btn-sm', disabled: g.drawOfferFrom === mc }, + g.drawOfferFrom === mc ? 'Draw Offered' : 'Offer Draw' + ); + drawBtn.addEventListener('click', () => wsClient.send({ type: 'game:draw_offer', gameId: g.id })); + row.appendChild(drawBtn); + } + } + + if (!g.rated && g.movesUci.length >= 1) { + const tbBtn = el( + 'button', + { type: 'button', className: 'btn btn-sm', disabled: g.takebackOfferFrom === mc }, + g.takebackOfferFrom === mc ? 'Takeback Sent' : 'Takeback' + ); + tbBtn.addEventListener('click', () => wsClient.send({ type: 'game:takeback_offer', gameId: g.id })); + row.appendChild(tbBtn); + } + + actionsEl.appendChild(row); + } + + function renderChat(g: ActiveGameState): void { + clearNode(chatMessagesEl); + if (g.chat.length === 0) { + chatMessagesEl.appendChild(el('div', { className: 'muted small-text chat-empty' }, 'No messages yet')); + } else { + for (const m of g.chat) { + const line = el('div', { className: 'chat-line' }); + line.appendChild(el('strong', { className: 'chat-author' }, `${m.username}: `)); + line.appendChild(el('span', null, m.text)); + chatMessagesEl.appendChild(line); + } + chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; + } + const loggedIn = ctx.getUser() !== null; + chatInput.disabled = !loggedIn; + chatSendBtn.disabled = !loggedIn; + chatInput.placeholder = loggedIn ? 'Send a message...' : 'Sign in to chat'; + } + + function playSoundForLastMove(g: ActiveGameState): void { + if (lastNotifiedMovesLen < 0) { + lastNotifiedMovesLen = g.movesSan.length; + return; + } + if (g.movesSan.length <= lastNotifiedMovesLen) { + lastNotifiedMovesLen = g.movesSan.length; + return; + } + lastNotifiedMovesLen = g.movesSan.length; + const san = g.movesSan[g.movesSan.length - 1] || ''; + if (san.indexOf('+') >= 0 || san.indexOf('#') >= 0) { + sound.play('check'); + } else if (san.indexOf('O-O') === 0) { + sound.play('castle'); + } else if (san.indexOf('x') >= 0) { + sound.play('capture'); + } else { + sound.play('move'); + } + } + + // Countdown tick for disconnect / abort banners + const countdownTimer = window.setInterval(() => { + if (!game || game.finished) return; + if (game.white.disconnectDeadlineMs || game.black.disconnectDeadlineMs || (game.abortDeadlineMs && game.movesUci.length < 2)) { + renderLayout(); + } + }, 1000); + + const unsub = wsClient.onMessage((msg: ServerWsMessage) => { + if (msg.type === 'game:state' && msg.game.id === gameId) { + const wasInit = game === null; + game = msg.game; + if (wasInit || viewPly >= game.movesUci.length - 1) { + viewPly = game.movesUci.length; + } + lastNotifiedMovesLen = game.movesSan.length; + if (!game.finished && myColor(game) !== null) { + ctx.setActiveGameId(game.id); + } else if (game.finished && ctx.getActiveGameId() === game.id) { + ctx.setActiveGameId(null); + } + renderLayout(); + } else if (msg.type === 'game:move' && game && msg.gameId === gameId) { + const wasAtLive = viewPly === game.movesUci.length; + game.movesUci.push(msg.uci); + game.movesSan.push(msg.san); + game.moveTimesMs.push(msg.moveTimeMs); + game.fen = msg.fen; + game.turn = msg.turn; + game.whiteTimeMs = msg.whiteTimeMs; + game.blackTimeMs = msg.blackTimeMs; + game.clockRunning = msg.clockRunning; + game.abortDeadlineMs = msg.abortDeadlineMs; + if (wasAtLive) { + viewPly = game.movesUci.length; + } + playSoundForLastMove(game); + renderLayout(); + } else if (msg.type === 'game:takeback' && msg.gameId === gameId) { + game = msg.game; + viewPly = game.movesUci.length; + lastNotifiedMovesLen = game.movesSan.length; + board.clearPremove(); + sound.play('notify'); + renderLayout(); + } else if (msg.type === 'game:offers' && game && msg.gameId === gameId) { + game.drawOfferFrom = msg.drawOfferFrom; + game.takebackOfferFrom = msg.takebackOfferFrom; + game.rematchOfferFrom = msg.rematchOfferFrom; + sound.play('notify'); + renderActions(game); + } else if (msg.type === 'game:presence' && game && msg.gameId === gameId) { + game.white.connected = msg.whiteConnected; + game.white.disconnectDeadlineMs = msg.whiteDisconnectDeadlineMs; + game.black.connected = msg.blackConnected; + game.black.disconnectDeadlineMs = msg.blackDisconnectDeadlineMs; + game.spectatorCount = msg.spectatorCount; + renderLayout(); + } else if (msg.type === 'game:chat' && game && msg.gameId === gameId) { + game.chat.push(msg.message); + renderChat(game); + } else if (msg.type === 'game:over' && game && msg.gameId === gameId) { + game.finished = true; + game.result = msg.result; + game.termination = msg.termination; + game.clockRunning = false; + game.abortDeadlineMs = null; + game.whiteRatingBefore = msg.whiteRatingBefore; + game.blackRatingBefore = msg.blackRatingBefore; + game.whiteRatingDiff = msg.whiteRatingDiff; + game.blackRatingDiff = msg.blackRatingDiff; + game.saved = msg.saved; + game.pgn = msg.pgn; + board.clearPremove(); + if (ctx.getActiveGameId() === game.id) { + ctx.setActiveGameId(null); + } + sound.play('gameEnd'); + renderLayout(); + if (msg.whiteRatingDiff !== null || msg.blackRatingDiff !== null) { + ctx.refreshSession(); + } + } else if (msg.type === 'game:rematch_started' && msg.oldGameId === gameId) { + ctx.setActiveGameId(msg.newGameId); + ctx.navigate(`/game/${msg.newGameId}`); + } + }); + + buildSkeleton(); + wsClient.send({ type: 'game:subscribe', gameId }); + + apiRequest< + | { kind: 'active'; game: ActiveGameState } + | { kind: 'stored'; game: import('../../shared/types').StoredGame } + >(`/api/games/${encodeURIComponent(gameId)}`) + .then((resp) => { + if (destroyed || game !== null) return; + if (resp.kind === 'active') { + game = resp.game; + } else { + const s = resp.game; + game = { + id: s.id, + white: { + userId: s.whiteUserId, + username: s.whiteUsername, + rating: s.whiteRatingBefore, + provisional: false, + isBot: s.botColor === 'w', + botLevel: s.botColor === 'w' ? s.botLevel : null, + connected: false, + disconnectDeadlineMs: null + }, + black: { + userId: s.blackUserId, + username: s.blackUsername, + rating: s.blackRatingBefore, + provisional: false, + isBot: s.botColor === 'b', + botLevel: s.botColor === 'b' ? s.botLevel : null, + connected: false, + disconnectDeadlineMs: null + }, + initialFen: s.initialFen, + fen: s.finalFen, + movesUci: s.movesUci, + movesSan: s.movesSan, + moveTimesMs: s.moveTimesMs, + turn: s.movesUci.length % 2 === 0 ? 'w' : 'b', + initialMs: s.initialMs, + incrementMs: s.incrementMs, + category: s.category, + rated: s.rated, + botLevel: s.botLevel, + whiteTimeMs: 0, + blackTimeMs: 0, + serverTimeMs: Date.now(), + clockRunning: false, + abortDeadlineMs: null, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: null, + rematchGameId: null, + spectatorCount: 0, + chat: [], + finished: true, + result: s.result, + termination: s.termination, + whiteRatingBefore: s.whiteRatingBefore, + blackRatingBefore: s.blackRatingBefore, + whiteRatingDiff: s.whiteRatingDiff, + blackRatingDiff: s.blackRatingDiff, + saved: true, + pgn: s.pgn + }; + } + viewPly = game.movesUci.length; + lastNotifiedMovesLen = game.movesSan.length; + renderLayout(); + }) + .catch((err) => { + if (destroyed || game !== null) return; + errorMsg = err instanceof Error ? err.message : 'Game not found.'; + renderLayout(); + }); + + return { + destroy() { + destroyed = true; + window.clearInterval(countdownTimer); + if (confirmResignTimer !== null) window.clearTimeout(confirmResignTimer); + unsub(); + wsClient.send({ type: 'game:unsubscribe', gameId }); + board.destroy(); + topClock.destroy(); + bottomClock.destroy(); + moveList.destroy(); + } + }; +} diff --git a/src/client/views/homeView.ts b/src/client/views/homeView.ts new file mode 100644 index 0000000..92f542a --- /dev/null +++ b/src/client/views/homeView.ts @@ -0,0 +1,402 @@ +import { TIME_PRESETS, categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { ColorPreference, InviteInfo, LobbySeek, ServerWsMessage } from '../../shared/types'; +import { apiRequest, wsClient } from '../api'; +import { clearNode, copyTextToClipboard, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +export function mountHomeView(container: HTMLElement, ctx: AppContext): ViewHandle { + let seeks: LobbySeek[] = []; + let selectedInitialMs = 300_000; + let selectedIncrementMs = 0; + let customMins = '5'; + let customInc = '3'; + let useCustom = false; + let rated = true; + let colorPref: ColorPreference = 'random'; + let inviteLink: string | null = null; + let destroyed = false; + + function currentTimeValues(): { initialMs: number; incrementMs: number } { + if (useCustom) { + const m = Math.max(0, Math.min(180, Number(customMins) || 0)); + const inc = Math.max(0, Math.min(180, Number(customInc) || 0)); + return { initialMs: Math.round(m * 60_000), incrementMs: Math.round(inc * 1_000) }; + } + return { initialMs: selectedInitialMs, incrementMs: selectedIncrementMs }; + } + + function render(): void { + if (destroyed) return; + clearNode(container); + + const user = ctx.getUser(); + const activeGameId = ctx.getActiveGameId(); + const page = el('div', { className: 'page-container' }); + + if (activeGameId) { + const banner = el('div', { className: 'alert alert-info resume-banner' }); + banner.appendChild(el('span', null, 'You currently have an active game in progress.')); + const btn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-sm' }, + 'Resume Game' + ); + btn.addEventListener('click', () => ctx.navigate(`/game/${activeGameId}`)); + banner.appendChild(btn); + page.appendChild(banner); + } + + if (!user) { + const hero = el('div', { className: 'card hero-card' }); + const body = el('div', { className: 'card-body hero-body' }); + body.appendChild(el('h1', { className: 'hero-title' }, 'Sharp, lightweight chess & Stockfish analysis')); + body.appendChild( + el( + 'p', + { className: 'muted' }, + 'Sign in or register a username (no email required) to play multiplayer games, earn Glicko-2 ratings, challenge friends, battle 8 Stockfish levels, and run engine game analytics.' + ) + ); + const actions = el('div', { className: 'btn-row' }); + const regBtn = el('button', { type: 'button', className: 'btn btn-primary' }, 'Create Account'); + const loginBtn = el('button', { type: 'button', className: 'btn' }, 'Sign In'); + const analysisBtn = el('button', { type: 'button', className: 'btn' }, 'Open Analysis Board'); + regBtn.addEventListener('click', () => ctx.navigate('/register')); + loginBtn.addEventListener('click', () => ctx.navigate('/login')); + analysisBtn.addEventListener('click', () => ctx.navigate('/analysis')); + actions.appendChild(regBtn); + actions.appendChild(loginBtn); + actions.appendChild(analysisBtn); + body.appendChild(actions); + hero.appendChild(body); + page.appendChild(hero); + } + + const layout = el('div', { className: 'two-col-lobby' }); + + // Left: Open Lobby Seeks + const lobbyCard = el('div', { className: 'card lobby-card' }); + const lobbyHeader = el('div', { className: 'card-header' }); + lobbyHeader.appendChild(el('h2', { className: 'card-title' }, 'Open Lobby')); + lobbyHeader.appendChild(el('span', { className: 'muted small-text' }, `${seeks.length} waiting`)); + lobbyCard.appendChild(lobbyHeader); + + const lobbyBody = el('div', { className: 'card-body no-pad' }); + if (seeks.length === 0) { + lobbyBody.appendChild( + el( + 'div', + { className: 'empty-state' }, + 'No open seeks right now. Create a seek or share an invite link on the right.' + ) + ); + } else { + const table = el('table', { className: 'data-table' }); + const thead = el('thead'); + const hrow = el('tr'); + hrow.appendChild(el('th', null, 'Player')); + hrow.appendChild(el('th', null, 'Time')); + hrow.appendChild(el('th', null, 'Mode')); + hrow.appendChild(el('th', null, 'Color')); + hrow.appendChild(el('th', { className: 'col-right' }, 'Action')); + thead.appendChild(hrow); + table.appendChild(thead); + + const tbody = el('tbody'); + for (const s of seeks) { + const tr = el('tr'); + const isOwn = user !== null && s.userId === user.id; + + const playerTd = el('td'); + const pLink = el('a', { href: `/u/${encodeURIComponent(s.username)}`, className: 'user-link' }, s.username); + pLink.addEventListener('click', (e) => { + e.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(s.username)}`); + }); + playerTd.appendChild(pLink); + playerTd.appendChild( + el('span', { className: 'rating-chip' }, ` (${s.rating}${s.provisional ? '?' : ''})`) + ); + tr.appendChild(playerTd); + + tr.appendChild( + el('td', null, `${formatTimeControl(s.initialMs, s.incrementMs)} · ${categoryLabel(s.category)}`) + ); + tr.appendChild(el('td', null, s.rated ? 'Rated' : 'Casual')); + tr.appendChild( + el('td', null, s.colorPref === 'white' ? 'Black for you' : s.colorPref === 'black' ? 'White for you' : 'Random') + ); + + const actTd = el('td', { className: 'col-right' }); + if (isOwn) { + const cancelBtn = el('button', { type: 'button', className: 'btn btn-xs btn-danger' }, 'Cancel'); + cancelBtn.addEventListener('click', () => { + wsClient.send({ type: 'lobby:cancel_seek', seekId: s.id }); + }); + actTd.appendChild(cancelBtn); + } else { + const joinBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Join'); + joinBtn.addEventListener('click', () => { + if (!ctx.getUser()) { + ctx.navigate('/login'); + return; + } + wsClient.send({ type: 'lobby:accept_seek', seekId: s.id }); + }); + actTd.appendChild(joinBtn); + } + tr.appendChild(actTd); + tbody.appendChild(tr); + } + table.appendChild(tbody); + lobbyBody.appendChild(table); + } + lobbyCard.appendChild(lobbyBody); + layout.appendChild(lobbyCard); + + // Right: Create Game / Invite / Bots + const sideCol = el('div', { className: 'side-col' }); + + const createCard = el('div', { className: 'card' }); + createCard.appendChild(el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, 'Create a Game'))); + const cBody = el('div', { className: 'card-body' }); + + cBody.appendChild(el('div', { className: 'field-label' }, 'Time Control')); + const presetGrid = el('div', { className: 'preset-grid' }); + for (const p of TIME_PRESETS) { + const isActive = !useCustom && selectedInitialMs === p.initialMs && selectedIncrementMs === p.incrementMs; + const btn = el( + 'button', + { + type: 'button', + className: isActive ? 'btn btn-sm btn-primary preset-btn' : 'btn btn-sm preset-btn' + }, + p.label + ); + btn.addEventListener('click', () => { + useCustom = false; + selectedInitialMs = p.initialMs; + selectedIncrementMs = p.incrementMs; + if (p.initialMs === 0 && p.incrementMs === 0) rated = false; + render(); + }); + presetGrid.appendChild(btn); + } + const customBtn = el( + 'button', + { type: 'button', className: useCustom ? 'btn btn-sm btn-primary preset-btn' : 'btn btn-sm preset-btn' }, + 'Custom' + ); + customBtn.addEventListener('click', () => { + useCustom = true; + render(); + }); + presetGrid.appendChild(customBtn); + cBody.appendChild(presetGrid); + + if (useCustom) { + const customRow = el('div', { className: 'inline-inputs' }); + const minIn = el('input', { + type: 'number', + min: '0', + max: '180', + className: 'input input-sm', + value: customMins, + placeholder: 'Min' + }) as HTMLInputElement; + const incIn = el('input', { + type: 'number', + min: '0', + max: '180', + className: 'input input-sm', + value: customInc, + placeholder: 'Inc (s)' + }) as HTMLInputElement; + minIn.addEventListener('input', () => { + customMins = minIn.value; + }); + incIn.addEventListener('input', () => { + customInc = incIn.value; + }); + customRow.appendChild(el('span', { className: 'small-text muted' }, 'Min:')); + customRow.appendChild(minIn); + customRow.appendChild(el('span', { className: 'small-text muted' }, 'Inc (s):')); + customRow.appendChild(incIn); + cBody.appendChild(customRow); + } + + const tcNow = currentTimeValues(); + const isUnlimited = tcNow.initialMs === 0 && tcNow.incrementMs === 0; + + // Rated / Casual + Color + const optRow = el('div', { className: 'options-row' }); + const modeGrp = el('div', { className: 'btn-group' }); + const ratedBtn = el( + 'button', + { + type: 'button', + className: rated && !isUnlimited ? 'btn btn-xs btn-primary' : 'btn btn-xs', + disabled: isUnlimited + }, + 'Rated' + ); + const casualBtn = el( + 'button', + { + type: 'button', + className: !rated || isUnlimited ? 'btn btn-xs btn-primary' : 'btn btn-xs' + }, + 'Casual' + ); + ratedBtn.addEventListener('click', () => { + if (!isUnlimited) { + rated = true; + render(); + } + }); + casualBtn.addEventListener('click', () => { + rated = false; + render(); + }); + modeGrp.appendChild(ratedBtn); + modeGrp.appendChild(casualBtn); + optRow.appendChild(modeGrp); + + const colorGrp = el('div', { className: 'btn-group' }); + for (const cp of [ + { id: 'white' as ColorPreference, label: 'White' }, + { id: 'random' as ColorPreference, label: 'Random' }, + { id: 'black' as ColorPreference, label: 'Black' } + ]) { + const b = el( + 'button', + { type: 'button', className: colorPref === cp.id ? 'btn btn-xs btn-primary' : 'btn btn-xs' }, + cp.label + ); + b.addEventListener('click', () => { + colorPref = cp.id; + render(); + }); + colorGrp.appendChild(b); + } + optRow.appendChild(colorGrp); + cBody.appendChild(optRow); + + const hasOwnSeek = user !== null && seeks.some((s) => s.userId === user.id); + const submitRow = el('div', { className: 'btn-col' }); + const seekBtn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-block' }, + hasOwnSeek ? 'Replace My Open Seek' : 'Post Open Lobby Seek' + ); + seekBtn.addEventListener('click', () => { + if (!ctx.getUser()) { + ctx.navigate('/login'); + return; + } + const tc = currentTimeValues(); + wsClient.send({ + type: 'lobby:seek', + initialMs: tc.initialMs, + incrementMs: tc.incrementMs, + rated: tc.initialMs === 0 && tc.incrementMs === 0 ? false : rated, + colorPref + }); + }); + + const inviteBtn = el('button', { type: 'button', className: 'btn btn-block' }, 'Create Shareable Invite Link'); + inviteBtn.addEventListener('click', async () => { + if (!ctx.getUser()) { + ctx.navigate('/login'); + return; + } + const tc = currentTimeValues(); + try { + const res = await apiRequest<{ invite: InviteInfo }>('/api/invites', { + method: 'POST', + body: JSON.stringify({ + initialMs: tc.initialMs, + incrementMs: tc.incrementMs, + rated: tc.initialMs === 0 && tc.incrementMs === 0 ? false : rated, + colorPref + }) + }); + inviteLink = `${window.location.origin}/invite/${res.invite.token}`; + render(); + const copied = await copyTextToClipboard(inviteLink); + ctx.toast(copied ? 'Invite link copied to clipboard!' : 'Invite link ready below.', 'success'); + } catch (err) { + ctx.toast(err instanceof Error ? err.message : 'Failed to create invite link.', 'error'); + } + }); + + submitRow.appendChild(seekBtn); + submitRow.appendChild(inviteBtn); + cBody.appendChild(submitRow); + + if (inviteLink) { + const invBox = el('div', { className: 'invite-box' }); + const invInput = el('input', { + type: 'text', + className: 'input input-sm', + value: inviteLink, + readonly: true + }) as HTMLInputElement; + const copyBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Copy'); + copyBtn.addEventListener('click', async () => { + if (inviteLink) { + const ok = await copyTextToClipboard(inviteLink); + ctx.toast(ok ? 'Copied invite link!' : 'Select and copy the URL.', ok ? 'success' : 'info'); + } + }); + invBox.appendChild(invInput); + invBox.appendChild(copyBtn); + cBody.appendChild(invBox); + } + + createCard.appendChild(cBody); + sideCol.appendChild(createCard); + + // Quick Bot card + const botCard = el('div', { className: 'card' }); + botCard.appendChild(el('div', { className: 'card-header' }, el('h2', { className: 'card-title' }, 'Play vs Stockfish'))); + const bBody = el('div', { className: 'card-body' }); + bBody.appendChild( + el('p', { className: 'muted small-text' }, 'Practice against 8 Stockfish strength levels (800 to 2800+ Elo) with unlimited takebacks.') + ); + const goBots = el('button', { type: 'button', className: 'btn btn-block' }, 'Choose Stockfish Level'); + goBots.addEventListener('click', () => ctx.navigate('/bots')); + bBody.appendChild(goBots); + botCard.appendChild(bBody); + sideCol.appendChild(botCard); + + layout.appendChild(sideCol); + page.appendChild(layout); + container.appendChild(page); + } + + const unsub = wsClient.onMessage((msg: ServerWsMessage) => { + if (msg.type === 'lobby:state') { + seeks = msg.seeks; + render(); + } + }); + + wsClient.send({ type: 'lobby:subscribe' }); + apiRequest<{ seeks: LobbySeek[] }>('/api/lobby') + .then((data) => { + seeks = data.seeks; + render(); + }) + .catch(() => {}); + + render(); + + return { + destroy() { + destroyed = true; + unsub(); + wsClient.send({ type: 'lobby:unsubscribe' }); + } + }; +} diff --git a/src/client/views/inviteView.ts b/src/client/views/inviteView.ts new file mode 100644 index 0000000..8e4d71c --- /dev/null +++ b/src/client/views/inviteView.ts @@ -0,0 +1,119 @@ +import { categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { InviteInfo } from '../../shared/types'; +import { apiRequest } from '../api'; +import { clearNode, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +export function mountInviteView(container: HTMLElement, ctx: AppContext, token: string): ViewHandle { + let invite: InviteInfo | null = null; + let errorMsg = ''; + let loading = true; + let accepting = false; + let destroyed = false; + + function render(): void { + if (destroyed) return; + clearNode(container); + + const page = el('div', { className: 'page-container narrow-page' }); + const card = el('div', { className: 'card' }); + card.appendChild(el('div', { className: 'card-header' }, el('h1', { className: 'card-title' }, 'Game Challenge Invite'))); + + const body = el('div', { className: 'card-body' }); + + if (loading) { + body.appendChild(el('p', { className: 'muted' }, 'Loading invite...')); + } else if (errorMsg || !invite) { + body.appendChild(el('div', { className: 'alert alert-error' }, errorMsg || 'Invite is invalid or expired.')); + const homeBtn = el('button', { type: 'button', className: 'btn' }, 'Back to Lobby'); + homeBtn.addEventListener('click', () => ctx.navigate('/')); + body.appendChild(homeBtn); + } else { + const inv = invite; + const user = ctx.getUser(); + const summary = el('div', { className: 'invite-details' }); + summary.appendChild( + el( + 'p', + { className: 'invite-headline' }, + `${inv.creatorUsername} (${inv.creatorRating}) invites you to play` + ) + ); + summary.appendChild( + el( + 'p', + { className: 'muted' }, + `${formatTimeControl(inv.initialMs, inv.incrementMs)} · ${categoryLabel(inv.category)} · ${ + inv.rated ? 'Rated' : 'Casual' + } · Challenger wants ${inv.colorPref}` + ) + ); + body.appendChild(summary); + + if (!user) { + const signInBtn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-block' }, + 'Sign In or Create Account to Play' + ); + signInBtn.addEventListener('click', () => { + ctx.navigate(`/login?next=${encodeURIComponent(`/invite/${token}`)}`); + }); + body.appendChild(signInBtn); + } else if (user.id === inv.creatorUserId) { + body.appendChild( + el( + 'p', + { className: 'alert alert-info' }, + 'This is your invite link. Share this page URL with a friend to start the game!' + ) + ); + } else { + const acceptBtn = el( + 'button', + { type: 'button', className: 'btn btn-primary btn-lg btn-block', disabled: accepting }, + accepting ? 'Starting game...' : 'Accept & Play' + ); + acceptBtn.addEventListener('click', async () => { + accepting = true; + render(); + try { + const res = await apiRequest<{ gameId: string }>(`/api/invites/${encodeURIComponent(token)}/accept`, { + method: 'POST' + }); + ctx.setActiveGameId(res.gameId); + ctx.navigate(`/game/${res.gameId}`); + } catch (err) { + accepting = false; + ctx.toast(err instanceof Error ? err.message : 'Failed to accept invite.', 'error'); + render(); + } + }); + body.appendChild(acceptBtn); + } + } + + card.appendChild(body); + page.appendChild(card); + container.appendChild(page); + } + + apiRequest<{ invite: InviteInfo }>(`/api/invites/${encodeURIComponent(token)}`) + .then((data) => { + loading = false; + invite = data.invite; + render(); + }) + .catch((err) => { + loading = false; + errorMsg = err instanceof Error ? err.message : 'Invite not found.'; + render(); + }); + + render(); + return { + destroy() { + destroyed = true; + } + }; +} diff --git a/src/client/views/leaderboardView.ts b/src/client/views/leaderboardView.ts new file mode 100644 index 0000000..f006b52 --- /dev/null +++ b/src/client/views/leaderboardView.ts @@ -0,0 +1,104 @@ +import { RATED_CATEGORIES, categoryLabel } from '../../shared/timeControl'; +import type { LeaderboardEntry, RatedCategory } from '../../shared/types'; +import { apiRequest } from '../api'; +import { clearNode, el } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +export function mountLeaderboardView(container: HTMLElement, ctx: AppContext): ViewHandle { + let category: RatedCategory = 'blitz'; + let entries: LeaderboardEntry[] = []; + let loading = true; + let destroyed = false; + + async function fetchBoard(): Promise { + loading = true; + render(); + try { + const data = await apiRequest<{ category: RatedCategory; entries: LeaderboardEntry[] }>( + `/api/leaderboard?category=${category}&limit=50` + ); + if (destroyed) return; + entries = data.entries; + loading = false; + render(); + } catch { + if (destroyed) return; + loading = false; + render(); + } + } + + function render(): void { + if (destroyed) return; + clearNode(container); + const page = el('div', { className: 'page-container narrow-page' }); + const card = el('div', { className: 'card' }); + + const head = el('div', { className: 'card-header' }); + head.appendChild(el('h1', { className: 'card-title' }, 'Leaderboard')); + const tabs = el('div', { className: 'btn-group' }); + for (const cat of RATED_CATEGORIES) { + const b = el( + 'button', + { type: 'button', className: category === cat ? 'btn btn-xs btn-primary' : 'btn btn-xs' }, + categoryLabel(cat) + ); + b.addEventListener('click', () => { + category = cat; + fetchBoard(); + }); + tabs.appendChild(b); + } + head.appendChild(tabs); + card.appendChild(head); + + const body = el('div', { className: 'card-body no-pad' }); + if (loading) { + body.appendChild(el('div', { className: 'empty-state' }, 'Loading leaderboard...')); + } else if (entries.length === 0) { + body.appendChild( + el('div', { className: 'empty-state' }, `No rated ${categoryLabel(category)} games played yet.`) + ); + } else { + const table = el('table', { className: 'data-table' }); + const thead = el('thead'); + const hr = el('tr'); + hr.appendChild(el('th', null, '#')); + hr.appendChild(el('th', null, 'Player')); + hr.appendChild(el('th', { className: 'col-right' }, 'Rating')); + hr.appendChild(el('th', { className: 'col-right' }, 'Games')); + thead.appendChild(hr); + table.appendChild(thead); + + const tbody = el('tbody'); + for (const e of entries) { + const tr = el('tr'); + tr.appendChild(el('td', null, e.rank)); + const uTd = el('td'); + const link = el('a', { href: `/u/${encodeURIComponent(e.username)}`, className: 'user-link' }, e.username); + link.addEventListener('click', (ev) => { + ev.preventDefault(); + ctx.navigate(`/u/${encodeURIComponent(e.username)}`); + }); + uTd.appendChild(link); + tr.appendChild(uTd); + tr.appendChild(el('td', { className: 'col-right' }, `${e.rating}${e.provisional ? '?' : ''}`)); + tr.appendChild(el('td', { className: 'col-right' }, e.gamesPlayed)); + tbody.appendChild(tr); + } + table.appendChild(tbody); + body.appendChild(table); + } + + card.appendChild(body); + page.appendChild(card); + container.appendChild(page); + } + + fetchBoard(); + return { + destroy() { + destroyed = true; + } + }; +} diff --git a/src/client/views/profileView.ts b/src/client/views/profileView.ts new file mode 100644 index 0000000..3c00eee --- /dev/null +++ b/src/client/views/profileView.ts @@ -0,0 +1,473 @@ +import { RATED_CATEGORIES, categoryLabel, formatTimeControl } from '../../shared/timeControl'; +import type { + GameListItem, + RatedCategory, + RatingHistoryPoint, + UserProfile +} from '../../shared/types'; +import { apiRequest } from '../api'; +import { clearNode, el, formatDateShort, formatRelativeDate } from '../dom'; +import type { AppContext, ViewHandle } from './context'; + +function renderSparklineSvg(points: ReadonlyArray): SVGSVGElement { + const ns = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(ns, 'svg'); + svg.setAttribute('viewBox', '0 0 200 48'); + svg.setAttribute('class', 'sparkline-svg'); + + if (points.length < 2) { + const line = document.createElementNS(ns, 'line'); + line.setAttribute('x1', '0'); + line.setAttribute('y1', '24'); + line.setAttribute('x2', '200'); + line.setAttribute('y2', '24'); + line.setAttribute('class', 'sparkline-flat'); + svg.appendChild(line); + return svg; + } + + let min = points[0]!.rating; + let max = points[0]!.rating; + for (let i = 1; i < points.length; i++) { + const r = points[i]!.rating; + if (r < min) min = r; + if (r > max) max = r; + } + const span = Math.max(20, max - min); + const coords = points.map((p, idx) => { + const x = (idx / (points.length - 1)) * 200; + const y = 42 - ((p.rating - min) / span) * 36; + return `${x.toFixed(1)},${y.toFixed(1)}`; + }); + + const poly = document.createElementNS(ns, 'polyline'); + poly.setAttribute('points', coords.join(' ')); + poly.setAttribute('fill', 'none'); + poly.setAttribute('class', 'sparkline-line'); + svg.appendChild(poly); + return svg; +} + +export function mountProfileView(container: HTMLElement, ctx: AppContext, username: string): ViewHandle { + let profile: UserProfile | null = null; + let loadError = ''; + let games: GameListItem[] = []; + let totalGames = 0; + let page = 1; + const limit = 15; + + let filterCategory = ''; + let filterVsBot = ''; + let filterResult = ''; + let filterOpponent = ''; + + let showPwForm = false; + let pwMsg = ''; + let destroyed = false; + + async function fetchProfile(): Promise { + try { + const data = await apiRequest<{ profile: UserProfile }>(`/api/users/${encodeURIComponent(username)}`); + if (destroyed) return; + profile = data.profile; + render(); + } catch (err) { + if (destroyed) return; + loadError = err instanceof Error ? err.message : 'User not found.'; + render(); + } + } + + async function fetchGames(): Promise { + const params = new URLSearchParams(); + params.set('page', String(page)); + params.set('limit', String(limit)); + if (filterCategory) params.set('category', filterCategory); + if (filterVsBot) params.set('vsBot', filterVsBot); + if (filterResult) params.set('result', filterResult); + if (filterOpponent.trim()) params.set('opponent', filterOpponent.trim()); + + try { + const data = await apiRequest<{ games: GameListItem[]; total: number; page: number; limit: number }>( + `/api/users/${encodeURIComponent(username)}/games?${params.toString()}` + ); + if (destroyed) return; + games = data.games; + totalGames = data.total; + render(); + } catch { + // Ignore transient + } + } + + function render(): void { + if (destroyed) return; + clearNode(container); + + const pageEl = el('div', { className: 'page-container' }); + + if (loadError) { + const card = el('div', { className: 'card' }); + const body = el('div', { className: 'card-body' }); + body.appendChild(el('div', { className: 'alert alert-error' }, loadError)); + card.appendChild(body); + pageEl.appendChild(card); + container.appendChild(pageEl); + return; + } + + if (!profile) { + pageEl.appendChild(el('div', { className: 'muted' }, 'Loading profile...')); + container.appendChild(pageEl); + return; + } + + const p = profile; + const viewer = ctx.getUser(); + const isSelf = viewer !== null && viewer.id === p.user.id; + + // Header card + const headCard = el('div', { className: 'card profile-header-card' }); + const headBody = el('div', { className: 'card-body profile-header-body' }); + + const leftInfo = el('div', { className: 'profile-id' }); + const titleRow = el('div', { className: 'profile-title-row' }); + const dotCls = + p.onlineStatus === 'in_game' + ? 'dot dot-ingame' + : p.onlineStatus === 'online' + ? 'dot dot-online' + : 'dot dot-offline'; + titleRow.appendChild(el('span', { className: dotCls })); + titleRow.appendChild(el('h1', { className: 'profile-username' }, p.user.username)); + if (p.onlineStatus === 'in_game' && p.activeGameId) { + const specBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Spectate Live'); + specBtn.addEventListener('click', () => ctx.navigate(`/game/${p.activeGameId}`)); + titleRow.appendChild(specBtn); + } + leftInfo.appendChild(titleRow); + + leftInfo.appendChild( + el( + 'div', + { className: 'small-text muted' }, + `Member since ${formatDateShort(p.user.createdAt)} · ${p.wdl.totalGames} games (${p.wdl.wins}W / ${p.wdl.draws}D / ${p.wdl.losses}L)` + ) + ); + + if (p.headToHead && p.headToHead.total > 0) { + leftInfo.appendChild( + el( + 'div', + { className: 'small-text h2h-line' }, + `Head-to-head vs you: ${p.headToHead.wins}W - ${p.headToHead.draws}D - ${p.headToHead.losses}L` + ) + ); + } + + headBody.appendChild(leftInfo); + + const rightActs = el('div', { className: 'btn-row' }); + if (isSelf) { + const pwToggle = el('button', { type: 'button', className: 'btn btn-sm' }, showPwForm ? 'Hide Password' : 'Change Password'); + pwToggle.addEventListener('click', () => { + showPwForm = !showPwForm; + pwMsg = ''; + render(); + }); + rightActs.appendChild(pwToggle); + } else if (viewer && p.friendship) { + const fs = p.friendship; + if (fs.status === 'none') { + const addBtn = el('button', { type: 'button', className: 'btn btn-sm btn-primary' }, 'Add Friend'); + addBtn.addEventListener('click', async () => { + await apiRequest('/api/friends/request', { + method: 'POST', + body: JSON.stringify({ userId: p.user.id }) + }); + ctx.toast('Friend request sent.', 'success'); + fetchProfile(); + }); + rightActs.appendChild(addBtn); + } else if (fs.status === 'pending_sent') { + const cancelBtn = el('button', { type: 'button', className: 'btn btn-sm' }, 'Cancel Request'); + cancelBtn.addEventListener('click', async () => { + await apiRequest(`/api/friends/${p.user.id}`, { method: 'DELETE' }); + fetchProfile(); + }); + rightActs.appendChild(cancelBtn); + } else if (fs.status === 'pending_received') { + const accBtn = el('button', { type: 'button', className: 'btn btn-sm btn-primary' }, 'Accept Friend'); + accBtn.addEventListener('click', async () => { + await apiRequest('/api/friends/respond', { + method: 'POST', + body: JSON.stringify({ userId: p.user.id, accept: true }) + }); + fetchProfile(); + }); + rightActs.appendChild(accBtn); + } else if (fs.status === 'accepted') { + const remBtn = el('button', { type: 'button', className: 'btn btn-sm btn-danger' }, 'Remove Friend'); + remBtn.addEventListener('click', async () => { + await apiRequest(`/api/friends/${p.user.id}`, { method: 'DELETE' }); + fetchProfile(); + }); + rightActs.appendChild(remBtn); + } + } + headBody.appendChild(rightActs); + headCard.appendChild(headBody); + + if (isSelf && showPwForm) { + const pwWrap = el('div', { className: 'card-body border-top' }); + if (pwMsg) { + pwWrap.appendChild(el('div', { className: 'alert alert-info' }, pwMsg)); + } + const pwForm = el('form', { className: 'inline-pw-form' }); + const curIn = el('input', { type: 'password', className: 'input input-sm', placeholder: 'Current password', required: true }) as HTMLInputElement; + const newIn = el('input', { type: 'password', className: 'input input-sm', placeholder: 'New password (6+ chars)', required: true }) as HTMLInputElement; + const saveBtn = el('button', { type: 'submit', className: 'btn btn-sm btn-primary' }, 'Update Password'); + pwForm.appendChild(curIn); + pwForm.appendChild(newIn); + pwForm.appendChild(saveBtn); + pwForm.addEventListener('submit', async (e) => { + e.preventDefault(); + try { + await apiRequest('/api/auth/password', { + method: 'POST', + body: JSON.stringify({ currentPassword: curIn.value, newPassword: newIn.value }) + }); + pwMsg = 'Password updated successfully.'; + curIn.value = ''; + newIn.value = ''; + render(); + } catch (err) { + pwMsg = err instanceof Error ? err.message : 'Failed to update password.'; + render(); + } + }); + pwWrap.appendChild(pwForm); + headCard.appendChild(pwWrap); + } + + pageEl.appendChild(headCard); + + // Ratings grid (4 categories with sparklines) + const ratingsGrid = el('div', { className: 'ratings-grid' }); + for (const cat of RATED_CATEGORIES) { + const r = p.user.ratings[cat as RatedCategory]; + const hist = p.ratingHistory[cat as RatedCategory] || []; + const card = el('div', { className: 'card rating-card' }); + const body = el('div', { className: 'card-body compact' }); + const top = el('div', { className: 'rating-card-top' }); + top.appendChild(el('span', { className: 'rating-cat-name' }, categoryLabel(cat))); + top.appendChild( + el('strong', { className: 'rating-big' }, `${r.rating}${r.provisional ? '?' : ''}`) + ); + body.appendChild(top); + body.appendChild(el('div', { className: 'small-text muted' }, `${r.gamesPlayed} rated games · RD ${r.rd}`)); + body.appendChild(renderSparklineSvg(hist)); + card.appendChild(body); + ratingsGrid.appendChild(card); + } + pageEl.appendChild(ratingsGrid); + + // Game history card + const histCard = el('div', { className: 'card' }); + const histHead = el('div', { className: 'card-header' }); + histHead.appendChild(el('h2', { className: 'card-title' }, `Game History (${totalGames})`)); + histCard.appendChild(histHead); + + // Filters bar + const filterBar = el('div', { className: 'filter-bar' }); + const catSelect = el('select', { className: 'select input-sm' }) as HTMLSelectElement; + for (const opt of [ + ['', 'All Time Controls'], + ['bullet', 'Bullet'], + ['blitz', 'Blitz'], + ['rapid', 'Rapid'], + ['classical', 'Classical'], + ['unlimited', 'Unlimited'] + ]) { + const o = el('option', { value: opt[0] }, opt[1]) as HTMLOptionElement; + if (filterCategory === opt[0]) o.selected = true; + catSelect.appendChild(o); + } + catSelect.addEventListener('change', () => { + filterCategory = catSelect.value; + page = 1; + fetchGames(); + }); + + const typeSelect = el('select', { className: 'select input-sm' }) as HTMLSelectElement; + for (const opt of [ + ['', 'Humans & Bots'], + ['exclude', 'Humans Only'], + ['only', 'Stockfish Bots Only'] + ]) { + const o = el('option', { value: opt[0] }, opt[1]) as HTMLOptionElement; + if (filterVsBot === opt[0]) o.selected = true; + typeSelect.appendChild(o); + } + typeSelect.addEventListener('change', () => { + filterVsBot = typeSelect.value; + page = 1; + fetchGames(); + }); + + const resSelect = el('select', { className: 'select input-sm' }) as HTMLSelectElement; + for (const opt of [ + ['', 'All Results'], + ['win', 'Wins'], + ['draw', 'Draws'], + ['loss', 'Losses'] + ]) { + const o = el('option', { value: opt[0] }, opt[1]) as HTMLOptionElement; + if (filterResult === opt[0]) o.selected = true; + resSelect.appendChild(o); + } + resSelect.addEventListener('change', () => { + filterResult = resSelect.value; + page = 1; + fetchGames(); + }); + + const oppInput = el('input', { + type: 'text', + className: 'input input-sm filter-opp', + placeholder: 'Filter opponent...', + value: filterOpponent + }) as HTMLInputElement; + const oppBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Filter'); + oppBtn.addEventListener('click', () => { + filterOpponent = oppInput.value; + page = 1; + fetchGames(); + }); + oppInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + filterOpponent = oppInput.value; + page = 1; + fetchGames(); + } + }); + + filterBar.appendChild(catSelect); + filterBar.appendChild(typeSelect); + filterBar.appendChild(resSelect); + filterBar.appendChild(oppInput); + filterBar.appendChild(oppBtn); + histCard.appendChild(filterBar); + + const histBody = el('div', { className: 'card-body no-pad' }); + if (games.length === 0) { + histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.')); + } else { + const table = el('table', { className: 'data-table' }); + const thead = el('thead'); + const hr = el('tr'); + hr.appendChild(el('th', null, 'Players')); + hr.appendChild(el('th', null, 'Time')); + hr.appendChild(el('th', null, 'Result')); + hr.appendChild(el('th', null, 'Date')); + hr.appendChild(el('th', { className: 'col-right' }, 'Open')); + thead.appendChild(hr); + table.appendChild(thead); + + const tbody = el('tbody'); + for (const g of games) { + const tr = el('tr'); + const isWhite = g.whiteUserId === p.user.id; + const userResult = + g.result === '1/2-1/2' + ? 'draw' + : (isWhite && g.result === '1-0') || (!isWhite && g.result === '0-1') + ? 'win' + : 'loss'; + + const playersTd = el('td'); + playersTd.appendChild( + el( + 'div', + null, + `${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${ + g.blackUsername + }${g.blackRatingBefore ? ` (${g.blackRatingBefore})` : ''}` + ) + ); + tr.appendChild(playersTd); + + tr.appendChild( + el( + 'td', + null, + `${formatTimeControl(g.initialMs, g.incrementMs)} · ${g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'}` + ) + ); + + const resTd = el('td'); + const badgeCls = + userResult === 'win' + ? 'res-badge res-win' + : userResult === 'loss' + ? 'res-badge res-loss' + : 'res-badge res-draw'; + resTd.appendChild(el('span', { className: badgeCls }, userResult.toUpperCase())); + resTd.appendChild(el('span', { className: 'small-text muted' }, ` ${g.termination}`)); + tr.appendChild(resTd); + + tr.appendChild(el('td', { className: 'small-text muted' }, formatRelativeDate(g.endedAt))); + + const actTd = el('td', { className: 'col-right' }); + const viewBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'View'); + const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze'); + viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`)); + analyzeBtn.addEventListener('click', () => ctx.navigate(`/analysis/${g.id}`)); + actTd.appendChild(viewBtn); + actTd.appendChild(analyzeBtn); + tr.appendChild(actTd); + + tbody.appendChild(tr); + } + table.appendChild(tbody); + histBody.appendChild(table); + } + + const totalPages = Math.max(1, Math.ceil(totalGames / limit)); + if (totalPages > 1) { + const pager = el('div', { className: 'pager-bar' }); + const prevBtn = el('button', { type: 'button', className: 'btn btn-xs', disabled: page <= 1 }, 'Prev'); + const nextBtn = el('button', { type: 'button', className: 'btn btn-xs', disabled: page >= totalPages }, 'Next'); + prevBtn.addEventListener('click', () => { + if (page > 1) { + page--; + fetchGames(); + } + }); + nextBtn.addEventListener('click', () => { + if (page < totalPages) { + page++; + fetchGames(); + } + }); + pager.appendChild(prevBtn); + pager.appendChild(el('span', { className: 'small-text muted' }, `Page ${page} of ${totalPages}`)); + pager.appendChild(nextBtn); + histBody.appendChild(pager); + } + + histCard.appendChild(histBody); + pageEl.appendChild(histCard); + container.appendChild(pageEl); + } + + fetchProfile(); + fetchGames(); + render(); + + return { + destroy() { + destroyed = true; + } + }; +} diff --git a/src/server/app.ts b/src/server/app.ts new file mode 100644 index 0000000..6d4f4eb --- /dev/null +++ b/src/server/app.ts @@ -0,0 +1,91 @@ +import http from 'node:http'; +import { type AppConfig, loadConfig } from './config'; +import { ChessDatabase } from './db'; +import { GameManager } from './gameManager'; +import { createHttpHandler } from './httpApi'; +import { LobbyManager } from './lobbyManager'; +import { StockfishPool } from './stockfish'; +import { WsHub } from './wsServer'; + +export interface ChessUpApp { + config: AppConfig; + db: ChessDatabase; + stockfish: StockfishPool; + lobbyManager: LobbyManager; + gameManager: GameManager; + wsHub: WsHub; + server: http.Server; + start(): Promise; + stop(): Promise; +} + +export function createApp(overrides: Partial = {}): ChessUpApp { + const config = loadConfig(overrides); + const db = new ChessDatabase(config.dbPath); + const stockfish = new StockfishPool(config.stockfishWorkers); + const wsHub = new WsHub(config, db, stockfish); + const lobbyManager = new LobbyManager(db, wsHub); + const gameManager = new GameManager(config, db, stockfish, wsHub, lobbyManager); + + lobbyManager.setGameLauncher(gameManager); + wsHub.attachManagers(lobbyManager, gameManager); + + const handler = createHttpHandler({ + config, + db, + lobbyManager, + gameManager, + wsHub + }); + + const server = http.createServer(handler); + server.on('upgrade', (req, socket, head) => { + const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`); + if (url.pathname === '/ws') { + wsHub.handleUpgrade(req, socket, head); + } else { + socket.destroy(); + } + }); + + let actualPort = config.port; + + return { + config, + db, + stockfish, + lobbyManager, + gameManager, + wsHub, + server, + async start(): Promise { + await stockfish.warmup(); + db.pruneExpiredSessions(); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(config.port, config.host, () => { + server.removeListener('error', reject); + const addr = server.address(); + if (addr && typeof addr === 'object') { + actualPort = addr.port; + } + resolve(); + }); + }); + return actualPort; + }, + async stop(): Promise { + lobbyManager.stop(); + gameManager.stop(); + wsHub.close(); + stockfish.shutdown(); + await new Promise((resolve) => { + server.close(() => resolve()); + if (typeof server.closeAllConnections === 'function') { + server.closeAllConnections(); + } + }); + db.close(); + } + }; +} diff --git a/src/server/auth.ts b/src/server/auth.ts new file mode 100644 index 0000000..3430a56 --- /dev/null +++ b/src/server/auth.ts @@ -0,0 +1,150 @@ +import crypto from 'node:crypto'; +import type http from 'node:http'; + +export const SESSION_COOKIE_NAME = 'chessup_sid'; + +const USERNAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{2,19}$/; +const RESERVED_NAMES = new Set([ + 'stockfish', + 'bot', + 'guest', + 'anonymous', + 'admin', + 'administrator', + 'system', + 'chessup', + 'moderator', + 'support' +]); + +export function validateUsername(raw: string): { ok: true; username: string } | { ok: false; error: string } { + const trimmed = raw.trim(); + if (!USERNAME_RE.test(trimmed)) { + return { + ok: false, + error: 'Username must be 3-20 characters (letters, digits, _ or -), starting with a letter or digit.' + }; + } + const lower = trimmed.toLowerCase(); + if (RESERVED_NAMES.has(lower) || lower.startsWith('stockfish_') || lower.startsWith('stockfish-')) { + return { + ok: false, + error: 'That username is reserved.' + }; + } + return { ok: true, username: trimmed }; +} + +export function validatePassword(raw: string): { ok: true } | { ok: false; error: string } { + if (typeof raw !== 'string' || raw.length < 6 || raw.length > 128) { + return { ok: false, error: 'Password must be between 6 and 128 characters.' }; + } + return { ok: true }; +} + +export function hashPassword(password: string): { hashHex: string; saltHex: string } { + const salt = crypto.randomBytes(16); + const hash = crypto.scryptSync(password, salt, 64); + return { + hashHex: hash.toString('hex'), + saltHex: salt.toString('hex') + }; +} + +export function verifyPassword(password: string, hashHex: string, saltHex: string): boolean { + const salt = Buffer.from(saltHex, 'hex'); + const expected = Buffer.from(hashHex, 'hex'); + const derived = crypto.scryptSync(password, salt, 64); + if (derived.length !== expected.length) return false; + return crypto.timingSafeEqual(derived, expected); +} + +export function createSessionToken(): { token: string; tokenHash: string } { + const token = crypto.randomBytes(32).toString('hex'); + const tokenHash = hashSessionToken(token); + return { token, tokenHash }; +} + +export function hashSessionToken(token: string): string { + return crypto.createHash('sha256').update(token).digest('hex'); +} + +export function parseCookies(headerValue: string | undefined): Record { + const out: Record = {}; + if (!headerValue) return out; + const parts = headerValue.split(';'); + for (const part of parts) { + const eq = part.indexOf('='); + if (eq <= 0) continue; + const key = part.slice(0, eq).trim(); + const val = part.slice(eq + 1).trim(); + if (key) { + try { + out[key] = decodeURIComponent(val); + } catch { + out[key] = val; + } + } + } + return out; +} + +export function buildSessionCookie(token: string, maxAgeSec: number, secure: boolean): string { + const parts = [ + `${SESSION_COOKIE_NAME}=${encodeURIComponent(token)}`, + 'HttpOnly', + 'Path=/', + 'SameSite=Lax', + `Max-Age=${Math.max(0, Math.floor(maxAgeSec))}` + ]; + if (secure) parts.push('Secure'); + return parts.join('; '); +} + +export function buildClearSessionCookie(secure: boolean): string { + const parts = [`${SESSION_COOKIE_NAME}=`, 'HttpOnly', 'Path=/', 'SameSite=Lax', 'Max-Age=0']; + if (secure) parts.push('Secure'); + return parts.join('; '); +} + +export function isSameOriginAllowed(req: http.IncomingMessage): boolean { + const origin = req.headers.origin; + if (!origin) return true; // Non-browser clients / same-origin curl / tests without Origin + try { + const parsed = new URL(origin); + const host = req.headers.host; + if (host && parsed.host === host) return true; + const fwdHost = req.headers['x-forwarded-host']; + if (typeof fwdHost === 'string' && fwdHost.trim()) { + const first = fwdHost.split(',')[0]!.trim(); + if (first && parsed.host === first) return true; + } + return false; + } catch { + return false; + } +} + +export class SlidingRateLimiter { + private hits = new Map(); + + constructor( + private readonly maxHits: number, + private readonly windowMs: number, + private readonly disabled: boolean = false + ) {} + + allow(key: string, now: number = Date.now()): boolean { + if (this.disabled) return true; + const list = this.hits.get(key) ?? []; + const cutoff = now - this.windowMs; + const fresh = list.filter((t) => t > cutoff); + if (fresh.length >= this.maxHits) { + this.hits.set(key, fresh); + return false; + } + fresh.push(now); + this.hits.set(key, fresh); + return true; + } +} diff --git a/src/server/config.ts b/src/server/config.ts new file mode 100644 index 0000000..cb1ec38 --- /dev/null +++ b/src/server/config.ts @@ -0,0 +1,49 @@ +import path from 'node:path'; + +export interface AppConfig { + port: number; + host: string; + dbPath: string; + publicDir: string; + stockfishWorkers: number; + analysisDepth: number; + multipvDepth: number; + disconnectForfeitMs: number; + firstMoveAbortMs: number; + sessionTtlMs: number; + cookieSecure: boolean; + disableRateLimit: boolean; +} + +export function loadConfig(overrides: Partial = {}): AppConfig { + const portEnv = Number(process.env.PORT); + const workersEnv = Number(process.env.STOCKFISH_WORKERS); + const analysisDepthEnv = Number(process.env.ANALYSIS_DEPTH); + const multipvDepthEnv = Number(process.env.MULTIPV_DEPTH); + const disconnectEnv = Number(process.env.DISCONNECT_FORFEIT_MS); + const abortEnv = Number(process.env.FIRST_MOVE_ABORT_MS); + const sessionTtlEnv = Number(process.env.SESSION_TTL_MS); + + return { + port: overrides.port ?? (Number.isFinite(portEnv) && portEnv >= 0 ? portEnv : 3000), + host: overrides.host ?? (process.env.HOST || '0.0.0.0'), + dbPath: overrides.dbPath ?? (process.env.DB_PATH || path.join(process.cwd(), 'data', 'chessup.db')), + publicDir: overrides.publicDir ?? (process.env.PUBLIC_DIR || path.join(process.cwd(), 'dist', 'public')), + stockfishWorkers: + overrides.stockfishWorkers ?? (Number.isFinite(workersEnv) && workersEnv > 0 ? workersEnv : 2), + analysisDepth: + overrides.analysisDepth ?? (Number.isFinite(analysisDepthEnv) && analysisDepthEnv > 0 ? analysisDepthEnv : 12), + multipvDepth: + overrides.multipvDepth ?? (Number.isFinite(multipvDepthEnv) && multipvDepthEnv > 0 ? multipvDepthEnv : 14), + disconnectForfeitMs: + overrides.disconnectForfeitMs ?? + (Number.isFinite(disconnectEnv) && disconnectEnv > 0 ? disconnectEnv : 60_000), + firstMoveAbortMs: + overrides.firstMoveAbortMs ?? (Number.isFinite(abortEnv) && abortEnv > 0 ? abortEnv : 45_000), + sessionTtlMs: + overrides.sessionTtlMs ?? + (Number.isFinite(sessionTtlEnv) && sessionTtlEnv > 0 ? sessionTtlEnv : 30 * 24 * 60 * 60 * 1000), + cookieSecure: overrides.cookieSecure ?? process.env.COOKIE_SECURE === '1', + disableRateLimit: overrides.disableRateLimit ?? process.env.DISABLE_RATE_LIMIT === '1' + }; +} diff --git a/src/server/db.ts b/src/server/db.ts new file mode 100644 index 0000000..261ecb9 --- /dev/null +++ b/src/server/db.ts @@ -0,0 +1,964 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { RATED_CATEGORIES } from '../shared/timeControl'; +import type { + FriendEntry, + FriendRequestEntry, + GameAnalysisReport, + GameListItem, + GameResult, + GlickoRating, + HeadToHead, + LeaderboardEntry, + RatedCategory, + RatingHistoryPoint, + StoredGame, + TerminationReason, + TimeCategory, + UserSummary, + UserWdl +} from '../shared/types'; +import { INITIAL_RATING, INITIAL_RD, INITIAL_VOLATILITY, createInitialGlicko, isProvisionalRd } from './glicko2'; +import type { RawGlickoState } from './glicko2'; + +export interface DbUserRow { + id: number; + username: string; + username_lower: string; + password_hash: string; + password_salt: string; + created_at: number; + last_seen_at: number; +} + +export interface SaveFinishedGameInput { + id: string; + whiteUserId: number | null; + blackUserId: number | null; + whiteUsername: string; + blackUsername: string; + botLevel: number | null; + botColor: 'w' | 'b' | null; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + result: GameResult; + termination: TerminationReason; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + initialFen: string; + finalFen: string; + movesUci: string[]; + movesSan: string[]; + moveTimesMs: number[]; + pgn: string; + createdAt: number; + endedAt: number; + ratingUpdates?: { + category: RatedCategory; + whiteUserId: number; + blackUserId: number; + nextWhite: RawGlickoState; + nextBlack: RawGlickoState; + }; +} + +export interface GameHistoryFilters { + category?: TimeCategory; + result?: 'win' | 'loss' | 'draw'; + opponent?: string; + vsBot?: 'only' | 'exclude'; + page?: number; + limit?: number; +} + +export class ChessDatabase { + private readonly db: DatabaseSync; + + constructor(dbPath: string) { + if (dbPath !== ':memory:') { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + } + this.db = new DatabaseSync(dbPath); + this.db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + PRAGMA busy_timeout = 5000; + `); + this.initSchema(); + } + + private initSchema(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + username_lower TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + password_salt TEXT NOT NULL, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS sessions ( + token_hash TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS ratings ( + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + category TEXT NOT NULL, + rating REAL NOT NULL DEFAULT ${INITIAL_RATING}, + rd REAL NOT NULL DEFAULT ${INITIAL_RD}, + volatility REAL NOT NULL DEFAULT ${INITIAL_VOLATILITY}, + games_played INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL, + PRIMARY KEY (user_id, category) + ); + + CREATE TABLE IF NOT EXISTS rating_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + category TEXT NOT NULL, + rating REAL NOT NULL, + game_id TEXT, + created_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS friends ( + user_low_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + user_high_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + requester_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (user_low_id, user_high_id) + ); + + CREATE TABLE IF NOT EXISTS games ( + id TEXT PRIMARY KEY, + white_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + black_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + white_username TEXT NOT NULL, + black_username TEXT NOT NULL, + bot_level INTEGER, + bot_color TEXT, + initial_ms INTEGER NOT NULL, + increment_ms INTEGER NOT NULL, + category TEXT NOT NULL, + rated INTEGER NOT NULL, + result TEXT NOT NULL, + termination TEXT NOT NULL, + white_rating_before INTEGER, + black_rating_before INTEGER, + white_rating_diff INTEGER, + black_rating_diff INTEGER, + initial_fen TEXT NOT NULL, + final_fen TEXT NOT NULL, + moves_uci_json TEXT NOT NULL, + moves_san_json TEXT NOT NULL, + move_times_ms_json TEXT NOT NULL, + pgn TEXT NOT NULL, + plies_count INTEGER NOT NULL, + created_at INTEGER NOT NULL, + ended_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS game_analyses ( + game_id TEXT PRIMARY KEY REFERENCES games(id) ON DELETE CASCADE, + depth INTEGER NOT NULL, + status TEXT NOT NULL, + progress_ply INTEGER NOT NULL, + total_plies INTEGER NOT NULL, + white_accuracy REAL, + black_accuracy REAL, + white_acpl INTEGER, + black_acpl INTEGER, + summary_json TEXT, + plies_json TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id); + CREATE INDEX IF NOT EXISTS idx_games_white ON games(white_user_id, ended_at DESC); + CREATE INDEX IF NOT EXISTS idx_games_black ON games(black_user_id, ended_at DESC); + CREATE INDEX IF NOT EXISTS idx_games_ended ON games(ended_at DESC); + CREATE INDEX IF NOT EXISTS idx_ratings_cat ON ratings(category, rating DESC); + CREATE INDEX IF NOT EXISTS idx_rating_hist_user ON rating_history(user_id, category, created_at ASC); + CREATE INDEX IF NOT EXISTS idx_friends_high ON friends(user_high_id, status); + `); + } + + close(): void { + this.db.close(); + } + + private runTransaction(fn: () => T): T { + this.db.exec('BEGIN IMMEDIATE'); + try { + const result = fn(); + this.db.exec('COMMIT'); + return result; + } catch (err) { + try { + this.db.exec('ROLLBACK'); + } catch { + // Ignore rollback failure + } + throw err; + } + } + + // ---- Users ---- + + createUser(username: string, passwordHash: string, passwordSalt: string, now: number = Date.now()): UserSummary { + const lower = username.toLowerCase(); + const userId = this.runTransaction(() => { + const info = this.db + .prepare( + `INSERT INTO users (username, username_lower, password_hash, password_salt, created_at, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?)` + ) + .run(username, lower, passwordHash, passwordSalt, now, now); + const id = Number(info.lastInsertRowid); + const insertRating = this.db.prepare( + `INSERT INTO ratings (user_id, category, rating, rd, volatility, games_played, updated_at) + VALUES (?, ?, ?, ?, ?, 0, ?)` + ); + for (const cat of RATED_CATEGORIES) { + insertRating.run(id, cat, INITIAL_RATING, INITIAL_RD, INITIAL_VOLATILITY, now); + } + return id; + }); + const summary = this.getUserSummaryById(userId); + if (!summary) throw new Error('Failed to load newly created user'); + return summary; + } + + findUserRowByUsername(username: string): DbUserRow | null { + const row = this.db + .prepare(`SELECT * FROM users WHERE username_lower = ?`) + .get(username.trim().toLowerCase()) as unknown as DbUserRow | undefined; + return row ?? null; + } + + findUserRowById(userId: number): DbUserRow | null { + const row = this.db.prepare(`SELECT * FROM users WHERE id = ?`).get(userId) as unknown as DbUserRow | undefined; + return row ?? null; + } + + updatePassword(userId: number, passwordHash: string, passwordSalt: string): void { + this.db + .prepare(`UPDATE users SET password_hash = ?, password_salt = ? WHERE id = ?`) + .run(passwordHash, passwordSalt, userId); + } + + updateLastSeen(userId: number, now: number = Date.now()): void { + this.db.prepare(`UPDATE users SET last_seen_at = ? WHERE id = ?`).run(now, userId); + } + + getRawRatingsMap(userId: number): Record { + const rows = this.db + .prepare(`SELECT category, rating, rd, volatility, games_played FROM ratings WHERE user_id = ?`) + .all(userId) as unknown as Array<{ + category: string; + rating: number; + rd: number; + volatility: number; + games_played: number; + }>; + + const map: Record = { + bullet: { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 }, + blitz: { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 }, + rapid: { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 }, + classical: { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 } + }; + + for (const r of rows) { + if (r.category === 'bullet' || r.category === 'blitz' || r.category === 'rapid' || r.category === 'classical') { + map[r.category] = { + rating: r.rating, + rd: r.rd, + volatility: r.volatility, + gamesPlayed: r.games_played + }; + } + } + return map; + } + + getUserRatings(userId: number): Record { + const raw = this.getRawRatingsMap(userId); + const out = {} as Record; + for (const cat of RATED_CATEGORIES) { + const r = raw[cat]; + out[cat] = { + category: cat, + rating: Math.round(r.rating), + rd: Math.round(r.rd), + volatility: r.volatility, + gamesPlayed: r.gamesPlayed, + provisional: isProvisionalRd(r.rd) + }; + } + return out; + } + + getUserSummaryById(userId: number): UserSummary | null { + const row = this.findUserRowById(userId); + if (!row) return null; + return { + id: row.id, + username: row.username, + ratings: this.getUserRatings(row.id), + createdAt: row.created_at, + lastSeenAt: row.last_seen_at + }; + } + + getUserSummaryByUsername(username: string): UserSummary | null { + const row = this.findUserRowByUsername(username); + if (!row) return null; + return { + id: row.id, + username: row.username, + ratings: this.getUserRatings(row.id), + createdAt: row.created_at, + lastSeenAt: row.last_seen_at + }; + } + + searchUsers(query: string, excludeUserId?: number, limit: number = 20): UserSummary[] { + const clean = query.trim().toLowerCase(); + if (!clean) return []; + const like = `%${clean}%`; + const rows = ( + excludeUserId !== undefined + ? this.db + .prepare(`SELECT id FROM users WHERE username_lower LIKE ? AND id != ? ORDER BY username_lower ASC LIMIT ?`) + .all(like, excludeUserId, limit) + : this.db + .prepare(`SELECT id FROM users WHERE username_lower LIKE ? ORDER BY username_lower ASC LIMIT ?`) + .all(like, limit) + ) as unknown as Array<{ id: number }>; + + const results: UserSummary[] = []; + for (const r of rows) { + const u = this.getUserSummaryById(r.id); + if (u) results.push(u); + } + return results; + } + + // ---- Sessions ---- + + createSession(tokenHash: string, userId: number, expiresAt: number, now: number = Date.now()): void { + this.db + .prepare(`INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)`) + .run(tokenHash, userId, now, expiresAt); + } + + findUserBySessionTokenHash(tokenHash: string, now: number = Date.now()): UserSummary | null { + const row = this.db + .prepare(`SELECT user_id, expires_at FROM sessions WHERE token_hash = ?`) + .get(tokenHash) as unknown as { user_id: number; expires_at: number } | undefined; + if (!row) return null; + if (row.expires_at <= now) { + this.deleteSession(tokenHash); + return null; + } + return this.getUserSummaryById(row.user_id); + } + + deleteSession(tokenHash: string): void { + this.db.prepare(`DELETE FROM sessions WHERE token_hash = ?`).run(tokenHash); + } + + pruneExpiredSessions(now: number = Date.now()): void { + this.db.prepare(`DELETE FROM sessions WHERE expires_at <= ?`).run(now); + } + + // ---- Ratings & Leaderboard ---- + + getRatingHistory(userId: number, limitPerCategory: number = 100): Record { + const out: Record = { + bullet: [], + blitz: [], + rapid: [], + classical: [] + }; + for (const cat of RATED_CATEGORIES) { + const rows = this.db + .prepare( + `SELECT rating, game_id, created_at FROM rating_history + WHERE user_id = ? AND category = ? + ORDER BY created_at DESC, id DESC LIMIT ?` + ) + .all(userId, cat, limitPerCategory) as unknown as Array<{ + rating: number; + game_id: string | null; + created_at: number; + }>; + rows.reverse(); + out[cat] = rows.map((r) => ({ + category: cat, + rating: Math.round(r.rating), + gameId: r.game_id, + createdAt: r.created_at + })); + } + return out; + } + + getLeaderboard(category: RatedCategory, limit: number = 50): LeaderboardEntry[] { + const rows = this.db + .prepare( + `SELECT r.user_id, u.username, r.rating, r.rd, r.games_played + FROM ratings r + JOIN users u ON u.id = r.user_id + WHERE r.category = ? AND r.games_played > 0 + ORDER BY r.rating DESC, r.games_played DESC + LIMIT ?` + ) + .all(category, limit) as unknown as Array<{ + user_id: number; + username: string; + rating: number; + rd: number; + games_played: number; + }>; + + return rows.map((r, idx) => ({ + rank: idx + 1, + userId: r.user_id, + username: r.username, + rating: Math.round(r.rating), + rd: Math.round(r.rd), + gamesPlayed: r.games_played, + provisional: isProvisionalRd(r.rd) + })); + } + + // ---- Friends ---- + + private pairKeys(a: number, b: number): [number, number] { + return a < b ? [a, b] : [b, a]; + } + + getFriendship( + viewerId: number, + otherId: number + ): { status: 'none' | 'pending_sent' | 'pending_received' | 'accepted'; requesterId: number | null } { + const [low, high] = this.pairKeys(viewerId, otherId); + const row = this.db + .prepare(`SELECT status, requester_id FROM friends WHERE user_low_id = ? AND user_high_id = ?`) + .get(low, high) as unknown as { status: string; requester_id: number } | undefined; + if (!row) return { status: 'none', requesterId: null }; + if (row.status === 'accepted') return { status: 'accepted', requesterId: row.requester_id }; + if (row.requester_id === viewerId) return { status: 'pending_sent', requesterId: row.requester_id }; + return { status: 'pending_received', requesterId: row.requester_id }; + } + + getAcceptedFriendIds(userId: number): number[] { + const rows = this.db + .prepare( + `SELECT user_low_id, user_high_id FROM friends + WHERE (user_low_id = ? OR user_high_id = ?) AND status = 'accepted'` + ) + .all(userId, userId) as unknown as Array<{ user_low_id: number; user_high_id: number }>; + return rows.map((r) => (r.user_low_id === userId ? r.user_high_id : r.user_low_id)); + } + + sendFriendRequest(fromId: number, toId: number, now: number = Date.now()): 'created' | 'accepted' | 'already' { + if (fromId === toId) throw new Error('Cannot friend yourself'); + const [low, high] = this.pairKeys(fromId, toId); + return this.runTransaction(() => { + const existing = this.db + .prepare(`SELECT status, requester_id FROM friends WHERE user_low_id = ? AND user_high_id = ?`) + .get(low, high) as unknown as { status: string; requester_id: number } | undefined; + if (existing) { + if (existing.status === 'accepted') return 'already'; + if (existing.requester_id !== fromId) { + // Mutual request auto-accepts + this.db + .prepare(`UPDATE friends SET status = 'accepted', updated_at = ? WHERE user_low_id = ? AND user_high_id = ?`) + .run(now, low, high); + return 'accepted'; + } + return 'already'; + } + this.db + .prepare( + `INSERT INTO friends (user_low_id, user_high_id, status, requester_id, created_at, updated_at) + VALUES (?, ?, 'pending', ?, ?, ?)` + ) + .run(low, high, fromId, now, now); + return 'created'; + }); + } + + respondFriendRequest(userId: number, otherUserId: number, accept: boolean, now: number = Date.now()): boolean { + const [low, high] = this.pairKeys(userId, otherUserId); + const existing = this.db + .prepare(`SELECT status, requester_id FROM friends WHERE user_low_id = ? AND user_high_id = ?`) + .get(low, high) as unknown as { status: string; requester_id: number } | undefined; + if (!existing || existing.status !== 'pending' || existing.requester_id !== otherUserId) { + return false; + } + if (accept) { + this.db + .prepare(`UPDATE friends SET status = 'accepted', updated_at = ? WHERE user_low_id = ? AND user_high_id = ?`) + .run(now, low, high); + } else { + this.db.prepare(`DELETE FROM friends WHERE user_low_id = ? AND user_high_id = ?`).run(low, high); + } + return true; + } + + removeFriendOrRequest(userId: number, otherUserId: number): boolean { + const [low, high] = this.pairKeys(userId, otherUserId); + const info = this.db + .prepare(`DELETE FROM friends WHERE user_low_id = ? AND user_high_id = ?`) + .run(low, high); + return Number(info.changes) > 0; + } + + listFriendsAndRequests( + userId: number, + getPresence: (uid: number) => { onlineStatus: 'online' | 'in_game' | 'offline'; activeGameId: string | null } + ): { friends: FriendEntry[]; requests: FriendRequestEntry[] } { + const rows = this.db + .prepare( + `SELECT user_low_id, user_high_id, status, requester_id, created_at FROM friends + WHERE user_low_id = ? OR user_high_id = ? + ORDER BY updated_at DESC` + ) + .all(userId, userId) as unknown as Array<{ + user_low_id: number; + user_high_id: number; + status: string; + requester_id: number; + created_at: number; + }>; + + const friends: FriendEntry[] = []; + const requests: FriendRequestEntry[] = []; + + for (const r of rows) { + const otherId = r.user_low_id === userId ? r.user_high_id : r.user_low_id; + const summary = this.getUserSummaryById(otherId); + if (!summary) continue; + + if (r.status === 'accepted') { + const presence = getPresence(otherId); + friends.push({ + userId: otherId, + username: summary.username, + ratings: summary.ratings, + onlineStatus: presence.onlineStatus, + activeGameId: presence.activeGameId, + headToHead: this.getHeadToHead(userId, otherId) + }); + } else if (r.status === 'pending') { + requests.push({ + userId: otherId, + username: summary.username, + ratings: summary.ratings, + direction: r.requester_id === userId ? 'outgoing' : 'incoming', + createdAt: r.created_at + }); + } + } + + return { friends, requests }; + } + + getHeadToHead(viewerId: number, opponentId: number): HeadToHead { + const row = this.db + .prepare( + `SELECT + SUM(CASE + WHEN (white_user_id = ? AND black_user_id = ? AND result = '1-0') + OR (black_user_id = ? AND white_user_id = ? AND result = '0-1') + THEN 1 ELSE 0 END) AS wins, + SUM(CASE + WHEN ((white_user_id = ? AND black_user_id = ?) OR (black_user_id = ? AND white_user_id = ?)) + AND result = '1/2-1/2' + THEN 1 ELSE 0 END) AS draws, + SUM(CASE + WHEN (white_user_id = ? AND black_user_id = ? AND result = '0-1') + OR (black_user_id = ? AND white_user_id = ? AND result = '1-0') + THEN 1 ELSE 0 END) AS losses + FROM games + WHERE (white_user_id = ? AND black_user_id = ?) OR (white_user_id = ? AND black_user_id = ?)` + ) + .get( + viewerId, + opponentId, + viewerId, + opponentId, + viewerId, + opponentId, + viewerId, + opponentId, + viewerId, + opponentId, + viewerId, + opponentId, + viewerId, + opponentId, + opponentId, + viewerId + ) as unknown as { wins: number | null; draws: number | null; losses: number | null }; + + const wins = row.wins ?? 0; + const draws = row.draws ?? 0; + const losses = row.losses ?? 0; + return { wins, draws, losses, total: wins + draws + losses }; + } + + // ---- Games ---- + + saveFinishedGameAndRatings(input: SaveFinishedGameInput): void { + this.runTransaction(() => { + this.db + .prepare( + `INSERT INTO games ( + id, white_user_id, black_user_id, white_username, black_username, + bot_level, bot_color, initial_ms, increment_ms, category, rated, + result, termination, white_rating_before, black_rating_before, + white_rating_diff, black_rating_diff, initial_fen, final_fen, + moves_uci_json, moves_san_json, move_times_ms_json, pgn, + plies_count, created_at, ended_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + input.id, + input.whiteUserId, + input.blackUserId, + input.whiteUsername, + input.blackUsername, + input.botLevel, + input.botColor, + input.initialMs, + input.incrementMs, + input.category, + input.rated ? 1 : 0, + input.result, + input.termination, + input.whiteRatingBefore, + input.blackRatingBefore, + input.whiteRatingDiff, + input.blackRatingDiff, + input.initialFen, + input.finalFen, + JSON.stringify(input.movesUci), + JSON.stringify(input.movesSan), + JSON.stringify(input.moveTimesMs), + input.pgn, + input.movesUci.length, + input.createdAt, + input.endedAt + ); + + if (input.ratingUpdates) { + const ru = input.ratingUpdates; + const upsertStmt = this.db.prepare( + `INSERT INTO ratings (user_id, category, rating, rd, volatility, games_played, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(user_id, category) DO UPDATE SET + rating = excluded.rating, + rd = excluded.rd, + volatility = excluded.volatility, + games_played = excluded.games_played, + updated_at = excluded.updated_at` + ); + upsertStmt.run( + ru.whiteUserId, + ru.category, + ru.nextWhite.rating, + ru.nextWhite.rd, + ru.nextWhite.volatility, + ru.nextWhite.gamesPlayed, + input.endedAt + ); + upsertStmt.run( + ru.blackUserId, + ru.category, + ru.nextBlack.rating, + ru.nextBlack.rd, + ru.nextBlack.volatility, + ru.nextBlack.gamesPlayed, + input.endedAt + ); + + const histStmt = this.db.prepare( + `INSERT INTO rating_history (user_id, category, rating, game_id, created_at) + VALUES (?, ?, ?, ?, ?)` + ); + histStmt.run(ru.whiteUserId, ru.category, ru.nextWhite.rating, input.id, input.endedAt); + histStmt.run(ru.blackUserId, ru.category, ru.nextBlack.rating, input.id, input.endedAt); + } + }); + } + + getGameById(gameId: string): StoredGame | null { + const r = this.db.prepare(`SELECT * FROM games WHERE id = ?`).get(gameId) as unknown as + | Record + | undefined; + if (!r) return null; + + return { + id: String(r['id']), + whiteUserId: (r['white_user_id'] as number | null) ?? null, + blackUserId: (r['black_user_id'] as number | null) ?? null, + whiteUsername: String(r['white_username']), + blackUsername: String(r['black_username']), + botLevel: (r['bot_level'] as number | null) ?? null, + botColor: ((r['bot_color'] as 'w' | 'b' | null) ?? null), + initialMs: Number(r['initial_ms']), + incrementMs: Number(r['increment_ms']), + category: String(r['category']) as TimeCategory, + rated: Number(r['rated']) === 1, + result: String(r['result']) as GameResult, + termination: String(r['termination']) as TerminationReason, + whiteRatingBefore: (r['white_rating_before'] as number | null) ?? null, + blackRatingBefore: (r['black_rating_before'] as number | null) ?? null, + whiteRatingDiff: (r['white_rating_diff'] as number | null) ?? null, + blackRatingDiff: (r['black_rating_diff'] as number | null) ?? null, + initialFen: String(r['initial_fen']), + finalFen: String(r['final_fen']), + movesUci: JSON.parse(String(r['moves_uci_json'])) as string[], + movesSan: JSON.parse(String(r['moves_san_json'])) as string[], + moveTimesMs: JSON.parse(String(r['move_times_ms_json'])) as number[], + pgn: String(r['pgn']), + createdAt: Number(r['created_at']), + endedAt: Number(r['ended_at']) + }; + } + + getUserWdl(userId: number): UserWdl { + const row = this.db + .prepare( + `SELECT + SUM(CASE + WHEN (white_user_id = ? AND result = '1-0') OR (black_user_id = ? AND result = '0-1') + THEN 1 ELSE 0 END) AS wins, + SUM(CASE WHEN result = '1/2-1/2' THEN 1 ELSE 0 END) AS draws, + SUM(CASE + WHEN (white_user_id = ? AND result = '0-1') OR (black_user_id = ? AND result = '1-0') + THEN 1 ELSE 0 END) AS losses + FROM games + WHERE white_user_id = ? OR black_user_id = ?` + ) + .get(userId, userId, userId, userId, userId, userId) as unknown as { + wins: number | null; + draws: number | null; + losses: number | null; + }; + + const wins = row.wins ?? 0; + const draws = row.draws ?? 0; + const losses = row.losses ?? 0; + return { wins, draws, losses, totalGames: wins + draws + losses }; + } + + listUserGames( + userId: number, + filters: GameHistoryFilters = {} + ): { games: GameListItem[]; total: number; page: number; limit: number } { + const limit = Math.min(50, Math.max(1, filters.limit ?? 20)); + const page = Math.max(1, filters.page ?? 1); + const offset = (page - 1) * limit; + + const whereClauses: string[] = ['(white_user_id = ? OR black_user_id = ?)']; + const params: Array = [userId, userId]; + + if (filters.category) { + whereClauses.push('category = ?'); + params.push(filters.category); + } + + if (filters.vsBot === 'only') { + whereClauses.push('bot_level IS NOT NULL'); + } else if (filters.vsBot === 'exclude') { + whereClauses.push('bot_level IS NULL'); + } + + if (filters.result === 'win') { + whereClauses.push(`((white_user_id = ? AND result = '1-0') OR (black_user_id = ? AND result = '0-1'))`); + params.push(userId, userId); + } else if (filters.result === 'loss') { + whereClauses.push(`((white_user_id = ? AND result = '0-1') OR (black_user_id = ? AND result = '1-0'))`); + params.push(userId, userId); + } else if (filters.result === 'draw') { + whereClauses.push(`result = '1/2-1/2'`); + } + + if (filters.opponent && filters.opponent.trim()) { + const oppLike = `%${filters.opponent.trim().toLowerCase()}%`; + whereClauses.push( + `((white_user_id = ? AND LOWER(black_username) LIKE ?) OR (black_user_id = ? AND LOWER(white_username) LIKE ?))` + ); + params.push(userId, oppLike, userId, oppLike); + } + + const whereSql = whereClauses.join(' AND '); + const countRow = this.db + .prepare(`SELECT COUNT(*) AS cnt FROM games WHERE ${whereSql}`) + .get(...params) as unknown as { cnt: number }; + + const rows = this.db + .prepare( + `SELECT id, white_user_id, black_user_id, white_username, black_username, + bot_level, bot_color, initial_ms, increment_ms, category, rated, + result, termination, white_rating_before, black_rating_before, + white_rating_diff, black_rating_diff, plies_count, created_at, ended_at + FROM games + WHERE ${whereSql} + ORDER BY ended_at DESC + LIMIT ? OFFSET ?` + ) + .all(...params, limit, offset) as unknown as Array>; + + const games: GameListItem[] = rows.map((r) => ({ + id: String(r['id']), + whiteUserId: (r['white_user_id'] as number | null) ?? null, + blackUserId: (r['black_user_id'] as number | null) ?? null, + whiteUsername: String(r['white_username']), + blackUsername: String(r['black_username']), + botLevel: (r['bot_level'] as number | null) ?? null, + botColor: ((r['bot_color'] as 'w' | 'b' | null) ?? null), + initialMs: Number(r['initial_ms']), + incrementMs: Number(r['increment_ms']), + category: String(r['category']) as TimeCategory, + rated: Number(r['rated']) === 1, + result: String(r['result']) as GameResult, + termination: String(r['termination']) as TerminationReason, + whiteRatingBefore: (r['white_rating_before'] as number | null) ?? null, + blackRatingBefore: (r['black_rating_before'] as number | null) ?? null, + whiteRatingDiff: (r['white_rating_diff'] as number | null) ?? null, + blackRatingDiff: (r['black_rating_diff'] as number | null) ?? null, + pliesCount: Number(r['plies_count']), + createdAt: Number(r['created_at']), + endedAt: Number(r['ended_at']) + })); + + return { + games, + total: countRow.cnt, + page, + limit + }; + } + + // ---- Analyses ---- + + getAnalysis(gameId: string): GameAnalysisReport | null { + const row = this.db.prepare(`SELECT * FROM game_analyses WHERE game_id = ?`).get(gameId) as unknown as + | Record + | undefined; + if (!row) return null; + + if (row['summary_json'] && row['plies_json']) { + try { + const parsed = JSON.parse(String(row['summary_json'])) as Omit; + const plies = JSON.parse(String(row['plies_json'])) as GameAnalysisReport['plies']; + return { + ...parsed, + plies + }; + } catch { + // Fallback below + } + } + + return { + gameId: String(row['game_id']), + status: String(row['status']) as GameAnalysisReport['status'], + depth: Number(row['depth']), + progressPly: Number(row['progress_ply']), + totalPlies: Number(row['total_plies']), + whiteSummary: null, + blackSummary: null, + initialEvalCp: null, + initialEvalMate: null, + initialWinPercent: 50, + initialBestMoveUci: null, + initialBestMoveSan: null, + initialPvSan: [], + plies: [], + createdAt: Number(row['created_at']), + updatedAt: Number(row['updated_at']) + }; + } + + upsertAnalysisRunning(gameId: string, depth: number, totalPlies: number, now: number = Date.now()): void { + this.db + .prepare( + `INSERT INTO game_analyses ( + game_id, depth, status, progress_ply, total_plies, + white_accuracy, black_accuracy, white_acpl, black_acpl, + summary_json, plies_json, created_at, updated_at + ) VALUES (?, ?, 'running', 0, ?, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?) + ON CONFLICT(game_id) DO UPDATE SET + depth = excluded.depth, + status = 'running', + progress_ply = 0, + total_plies = excluded.total_plies, + updated_at = excluded.updated_at` + ) + .run(gameId, depth, totalPlies, now, now); + } + + updateAnalysisProgress(gameId: string, progressPly: number, now: number = Date.now()): void { + this.db + .prepare(`UPDATE game_analyses SET progress_ply = ?, updated_at = ? WHERE game_id = ?`) + .run(progressPly, now, gameId); + } + + saveAnalysisDone(report: GameAnalysisReport): void { + const { plies, ...summaryMeta } = report; + this.db + .prepare( + `UPDATE game_analyses + SET status = 'done', + progress_ply = ?, + total_plies = ?, + white_accuracy = ?, + black_accuracy = ?, + white_acpl = ?, + black_acpl = ?, + summary_json = ?, + plies_json = ?, + updated_at = ? + WHERE game_id = ?` + ) + .run( + report.totalPlies, + report.totalPlies, + report.whiteSummary?.accuracy ?? null, + report.blackSummary?.accuracy ?? null, + report.whiteSummary?.acpl ?? null, + report.blackSummary?.acpl ?? null, + JSON.stringify(summaryMeta), + JSON.stringify(plies), + report.updatedAt, + report.gameId + ); + } + + saveAnalysisError(gameId: string, now: number = Date.now()): void { + this.db + .prepare(`UPDATE game_analyses SET status = 'error', updated_at = ? WHERE game_id = ?`) + .run(now, gameId); + } +} diff --git a/src/server/gameManager.ts b/src/server/gameManager.ts new file mode 100644 index 0000000..c986567 --- /dev/null +++ b/src/server/gameManager.ts @@ -0,0 +1,1134 @@ +import crypto from 'node:crypto'; +import { Chess, INITIAL_FEN, oppositeColor } from '../shared/chess'; +import { BOT_LEVELS, buildTimeControl } from '../shared/timeControl'; +import type { + ActiveGameState, + ActivePlayerInfo, + ChatMessage, + Color, + ColorPreference, + GameAnalysisReport, + GameResult, + RatedCategory, + TerminationReason, + TimeCategory +} from '../shared/types'; +import type { AppConfig } from './config'; +import type { ChessDatabase } from './db'; +import { updateGlicko2Pair } from './glicko2'; +import type { CreateGameRequest, GameLauncher, LobbyManager, RealtimeTransport } from './lobbyManager'; +import type { StockfishPool } from './stockfish'; + +interface InternalGame { + id: string; + chess: Chess; + white: ActivePlayerInfo; + black: ActivePlayerInfo; + initialFen: string; + movesUci: string[]; + movesSan: string[]; + moveTimesMs: number[]; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + botLevel: number | null; + botColor: Color | null; + whiteTimeMs: number; + blackTimeMs: number; + lastMoveAt: number; + clockRunning: boolean; + abortDeadlineMs: number | null; + drawOfferFrom: Color | null; + takebackOfferFrom: Color | null; + rematchOfferFrom: Color | null; + rematchGameId: string | null; + chat: ChatMessage[]; + finished: boolean; + result: GameResult; + termination: TerminationReason | null; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + saved: boolean; + pgn: string | null; + createdAt: number; + endedAt: number | null; + clockTimer: NodeJS.Timeout | null; + abortTimer: NodeJS.Timeout | null; + whiteDisconnectTimer: NodeJS.Timeout | null; + blackDisconnectTimer: NodeJS.Timeout | null; + botGeneration: number; +} + +const FINISHED_RETENTION_MS = 5 * 60 * 1000; +const MIN_BOT_DELAY_MS = 220; + +export class GameManager implements GameLauncher { + private readonly activeGames = new Map(); + private readonly finishedGames = new Map(); + private readonly cleanupTimers = new Map(); + private readonly chatRateMap = new Map(); + + constructor( + private readonly config: AppConfig, + private readonly db: ChessDatabase, + private readonly stockfish: StockfishPool, + private readonly transport: RealtimeTransport, + private readonly lobby: LobbyManager + ) {} + + stop(): void { + for (const g of this.activeGames.values()) { + this.clearAllTimers(g); + } + for (const t of this.cleanupTimers.values()) { + clearTimeout(t); + } + this.cleanupTimers.clear(); + } + + private getGame(gameId: string): InternalGame | null { + return this.activeGames.get(gameId) ?? this.finishedGames.get(gameId) ?? null; + } + + getUserActiveGameId(userId: number): string | null { + for (const g of this.activeGames.values()) { + if (!g.finished && (g.white.userId === userId || g.black.userId === userId)) { + return g.id; + } + } + return null; + } + + getGameState(gameId: string): ActiveGameState | null { + const g = this.getGame(gameId); + if (!g) return null; + return this.toDto(g); + } + + getGamePlayerIds(gameId: string): { whiteUserId: number | null; blackUserId: number | null } | null { + const g = this.getGame(gameId); + if (!g) return null; + return { whiteUserId: g.white.userId, blackUserId: g.black.userId }; + } + + private toDto(g: InternalGame): ActiveGameState { + const now = Date.now(); + let whiteTimeMs = g.whiteTimeMs; + let blackTimeMs = g.blackTimeMs; + if (!g.finished && g.clockRunning && g.category !== 'unlimited') { + const elapsed = Math.max(0, now - g.lastMoveAt); + if (g.chess.turn() === 'w') { + whiteTimeMs = Math.max(0, g.whiteTimeMs - elapsed); + } else { + blackTimeMs = Math.max(0, g.blackTimeMs - elapsed); + } + } + + return { + id: g.id, + white: { ...g.white }, + black: { ...g.black }, + initialFen: g.initialFen, + fen: g.chess.fen(), + movesUci: g.movesUci.slice(), + movesSan: g.movesSan.slice(), + moveTimesMs: g.moveTimesMs.slice(), + turn: g.chess.turn(), + initialMs: g.initialMs, + incrementMs: g.incrementMs, + category: g.category, + rated: g.rated, + botLevel: g.botLevel, + whiteTimeMs, + blackTimeMs, + serverTimeMs: now, + clockRunning: g.clockRunning, + abortDeadlineMs: g.abortDeadlineMs, + drawOfferFrom: g.drawOfferFrom, + takebackOfferFrom: g.takebackOfferFrom, + rematchOfferFrom: g.rematchOfferFrom, + rematchGameId: g.rematchGameId, + spectatorCount: this.transport.getGameSpectatorCount(g.id), + chat: g.chat.slice(), + finished: g.finished, + result: g.result, + termination: g.termination, + whiteRatingBefore: g.whiteRatingBefore, + blackRatingBefore: g.blackRatingBefore, + whiteRatingDiff: g.whiteRatingDiff, + blackRatingDiff: g.blackRatingDiff, + saved: g.saved, + pgn: g.pgn + }; + } + + private generateGameId(): string { + return crypto.randomBytes(6).toString('base64url'); + } + + createPvpGame(req: CreateGameRequest): string { + const id = this.generateGameId(); + const tc = buildTimeControl(req.initialMs, req.incrementMs); + const startClock = tc.category === 'unlimited' ? 0 : req.initialMs > 0 ? req.initialMs : req.incrementMs; + const now = Date.now(); + const abortDeadlineMs = tc.category === 'unlimited' ? null : now + this.config.firstMoveAbortMs; + + const g: InternalGame = { + id, + chess: new Chess(INITIAL_FEN), + white: { + userId: req.whiteUserId, + username: req.whiteUsername, + rating: req.whiteRating, + provisional: req.whiteProvisional, + isBot: false, + botLevel: null, + connected: this.transport.isUserConnected(req.whiteUserId), + disconnectDeadlineMs: null + }, + black: { + userId: req.blackUserId, + username: req.blackUsername, + rating: req.blackRating, + provisional: req.blackProvisional, + isBot: false, + botLevel: null, + connected: this.transport.isUserConnected(req.blackUserId), + disconnectDeadlineMs: null + }, + initialFen: INITIAL_FEN, + movesUci: [], + movesSan: [], + moveTimesMs: [], + initialMs: req.initialMs, + incrementMs: req.incrementMs, + category: tc.category, + rated: tc.category === 'unlimited' ? false : req.rated, + botLevel: null, + botColor: null, + whiteTimeMs: startClock, + blackTimeMs: startClock, + lastMoveAt: now, + clockRunning: false, + abortDeadlineMs, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: null, + rematchGameId: null, + chat: [], + finished: false, + result: '*', + termination: null, + whiteRatingBefore: req.rated && tc.category !== 'unlimited' ? req.whiteRating : null, + blackRatingBefore: req.rated && tc.category !== 'unlimited' ? req.blackRating : null, + whiteRatingDiff: null, + blackRatingDiff: null, + saved: false, + pgn: null, + createdAt: now, + endedAt: null, + clockTimer: null, + abortTimer: null, + whiteDisconnectTimer: null, + blackDisconnectTimer: null, + botGeneration: 0 + }; + + this.activeGames.set(id, g); + this.scheduleAbortTimer(g); + return id; + } + + createBotGame( + userId: number, + opts: { level: number; colorPref: ColorPreference; initialMs: number; incrementMs: number } + ): { ok: true; gameId: string } | { ok: false; error: string } { + if (this.getUserActiveGameId(userId)) { + return { ok: false, error: 'Finish your active game first.' }; + } + const user = this.db.getUserSummaryById(userId); + if (!user) return { ok: false, error: 'User not found.' }; + + const level = Math.min(8, Math.max(1, Math.round(opts.level))); + const botCfg = BOT_LEVELS.find((b) => b.level === level) ?? BOT_LEVELS[0]!; + if (opts.initialMs < 0 || opts.incrementMs < 0) { + return { ok: false, error: 'Invalid time control.' }; + } + const tc = buildTimeControl(opts.initialMs, opts.incrementMs); + if (tc.category !== 'unlimited' && opts.initialMs < 15_000 && opts.incrementMs < 2_000) { + return { ok: false, error: 'Minimum timed game requires at least 15s initial or 2s increment.' }; + } + + const humanColor: Color = + opts.colorPref === 'white' ? 'w' : opts.colorPref === 'black' ? 'b' : Math.random() < 0.5 ? 'w' : 'b'; + const botColor: Color = oppositeColor(humanColor); + const ratingCat: RatedCategory = tc.category === 'unlimited' ? 'rapid' : tc.category; + const humanRating = user.ratings[ratingCat]; + + const humanInfo: ActivePlayerInfo = { + userId: user.id, + username: user.username, + rating: humanRating.rating, + provisional: humanRating.provisional, + isBot: false, + botLevel: null, + connected: this.transport.isUserConnected(user.id), + disconnectDeadlineMs: null + }; + + const botInfo: ActivePlayerInfo = { + userId: null, + username: `${botCfg.name} (~${botCfg.approxElo})`, + rating: botCfg.approxElo, + provisional: false, + isBot: true, + botLevel: level, + connected: true, + disconnectDeadlineMs: null + }; + + const id = this.generateGameId(); + const startClock = tc.category === 'unlimited' ? 0 : opts.initialMs > 0 ? opts.initialMs : opts.incrementMs; + const now = Date.now(); + + const g: InternalGame = { + id, + chess: new Chess(INITIAL_FEN), + white: humanColor === 'w' ? humanInfo : botInfo, + black: humanColor === 'b' ? humanInfo : botInfo, + initialFen: INITIAL_FEN, + movesUci: [], + movesSan: [], + moveTimesMs: [], + initialMs: opts.initialMs, + incrementMs: opts.incrementMs, + category: tc.category, + rated: false, + botLevel: level, + botColor, + whiteTimeMs: startClock, + blackTimeMs: startClock, + lastMoveAt: now, + clockRunning: false, + abortDeadlineMs: null, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: null, + rematchGameId: null, + chat: [], + finished: false, + result: '*', + termination: null, + whiteRatingBefore: null, + blackRatingBefore: null, + whiteRatingDiff: null, + blackRatingDiff: null, + saved: false, + pgn: null, + createdAt: now, + endedAt: null, + clockTimer: null, + abortTimer: null, + whiteDisconnectTimer: null, + blackDisconnectTimer: null, + botGeneration: 0 + }; + + this.activeGames.set(id, g); + this.transport.sendToUser(userId, { type: 'game:started', gameId: id }); + this.lobby.notifyFriendsPresence(userId); + + if (botColor === 'w') { + this.scheduleBotTurn(g); + } + + return { ok: true, gameId: id }; + } + + private scheduleAbortTimer(g: InternalGame): void { + if (g.abortTimer) clearTimeout(g.abortTimer); + if (g.finished || g.abortDeadlineMs === null || g.movesUci.length >= 2) return; + const delay = Math.max(50, g.abortDeadlineMs - Date.now()); + g.abortTimer = setTimeout(() => { + if (!g.finished && g.movesUci.length < 2) { + this.finishGame(g, '*', 'aborted'); + } + }, delay); + } + + private scheduleClockTimer(g: InternalGame): void { + if (g.clockTimer) { + clearTimeout(g.clockTimer); + g.clockTimer = null; + } + if (g.finished || !g.clockRunning || g.category === 'unlimited') return; + + const turn = g.chess.turn(); + const remaining = turn === 'w' ? g.whiteTimeMs : g.blackTimeMs; + g.clockTimer = setTimeout(() => { + if (g.finished || !g.clockRunning) return; + if (turn === 'w') g.whiteTimeMs = 0; + else g.blackTimeMs = 0; + + const winnerColor = oppositeColor(turn); + const insufficient = g.chess.hasInsufficientMatingMaterial(winnerColor); + const result: GameResult = insufficient ? '1/2-1/2' : winnerColor === 'w' ? '1-0' : '0-1'; + this.finishGame(g, result, 'timeout'); + }, Math.max(10, remaining)); + } + + private clearAllTimers(g: InternalGame): void { + if (g.clockTimer) { + clearTimeout(g.clockTimer); + g.clockTimer = null; + } + if (g.abortTimer) { + clearTimeout(g.abortTimer); + g.abortTimer = null; + } + if (g.whiteDisconnectTimer) { + clearTimeout(g.whiteDisconnectTimer); + g.whiteDisconnectTimer = null; + } + if (g.blackDisconnectTimer) { + clearTimeout(g.blackDisconnectTimer); + g.blackDisconnectTimer = null; + } + } + + private playerColor(g: InternalGame, userId: number | null): Color | null { + if (userId === null) return null; + if (g.white.userId === userId) return 'w'; + if (g.black.userId === userId) return 'b'; + return null; + } + + handleMove(userId: number | null, gameId: string, uci: string): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'You are not a player in this game.' }; + if (g.chess.turn() !== color) return { ok: false, error: 'It is not your turn.' }; + + return this.applyMoveInternal(g, uci, false); + } + + private applyMoveInternal(g: InternalGame, uci: string, isBotMove: boolean): { ok: true } | { ok: false; error: string } { + if (g.finished) return { ok: false, error: 'Game already finished.' }; + + const now = Date.now(); + const mover = g.chess.turn(); + let moveTimeMs = 0; + + if (g.clockRunning && g.category !== 'unlimited') { + const elapsed = Math.max(0, now - g.lastMoveAt); + moveTimeMs = elapsed; + const beforeMs = mover === 'w' ? g.whiteTimeMs : g.blackTimeMs; + if (beforeMs - elapsed <= 0) { + if (mover === 'w') g.whiteTimeMs = 0; + else g.blackTimeMs = 0; + const winnerColor = oppositeColor(mover); + const insufficient = g.chess.hasInsufficientMatingMaterial(winnerColor); + const res: GameResult = insufficient ? '1/2-1/2' : winnerColor === 'w' ? '1-0' : '0-1'; + this.finishGame(g, res, 'timeout'); + return { ok: false, error: 'Flagged on time.' }; + } + const nextRemaining = beforeMs - elapsed + g.incrementMs; + if (mover === 'w') g.whiteTimeMs = nextRemaining; + else g.blackTimeMs = nextRemaining; + } + + const mv = g.chess.moveUci(uci); + if (!mv) { + return { ok: false, error: 'Illegal move.' }; + } + + g.botGeneration++; + g.movesUci.push(mv.uci); + g.movesSan.push(mv.san); + g.moveTimesMs.push(moveTimeMs); + g.lastMoveAt = now; + + // Clear pending draw/takeback offers when a move is played + if (g.drawOfferFrom !== null || g.takebackOfferFrom !== null) { + g.drawOfferFrom = null; + g.takebackOfferFrom = null; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: g.rematchOfferFrom + }); + } + + if (g.movesUci.length === 2 && g.category !== 'unlimited') { + if (g.abortTimer) { + clearTimeout(g.abortTimer); + g.abortTimer = null; + } + g.abortDeadlineMs = null; + g.clockRunning = true; + } + + this.transport.broadcastToGame(g.id, { + type: 'game:move', + gameId: g.id, + uci: mv.uci, + san: mv.san, + fen: g.chess.fen(), + turn: g.chess.turn(), + moveTimeMs, + whiteTimeMs: g.whiteTimeMs, + blackTimeMs: g.blackTimeMs, + serverTimeMs: now, + clockRunning: g.clockRunning, + abortDeadlineMs: g.abortDeadlineMs + }); + + const outcome = g.chess.gameOutcome(); + if (outcome) { + this.finishGame(g, outcome.result, outcome.termination); + return { ok: true }; + } + + if (g.clockRunning) { + this.scheduleClockTimer(g); + } + + if (!isBotMove && g.botColor !== null && g.chess.turn() === g.botColor) { + this.scheduleBotTurn(g); + } + + return { ok: true }; + } + + private scheduleBotTurn(g: InternalGame): void { + if (g.finished || g.botLevel === null || g.botColor === null) return; + if (g.chess.turn() !== g.botColor) return; + + const expectedGen = g.botGeneration; + const fen = g.chess.fen(); + const level = g.botLevel; + const startedAt = Date.now(); + + this.stockfish + .getBotMove(fen, level) + .then(async (botUci) => { + const elapsed = Date.now() - startedAt; + if (elapsed < MIN_BOT_DELAY_MS) { + await new Promise((r) => setTimeout(r, MIN_BOT_DELAY_MS - elapsed)); + } + if (g.finished || g.botGeneration !== expectedGen) return; + this.applyMoveInternal(g, botUci, true); + }) + .catch(() => { + // Ignore errors if pool shut down + }); + } + + handleAbort(userId: number | null, gameId: string): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + if (!this.playerColor(g, userId)) return { ok: false, error: 'Not a player in this game.' }; + if (g.movesUci.length >= 2) { + return { ok: false, error: 'Cannot abort after both sides have moved; resign instead.' }; + } + this.finishGame(g, '*', 'aborted'); + return { ok: true }; + } + + handleResign(userId: number | null, gameId: string): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + + if (g.movesUci.length < 2) { + this.finishGame(g, '*', 'aborted'); + return { ok: true }; + } + const result: GameResult = color === 'w' ? '0-1' : '1-0'; + this.finishGame(g, result, 'resign'); + return { ok: true }; + } + + handleDrawOffer(userId: number | null, gameId: string): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + if (g.botLevel !== null) return { ok: false, error: 'Bots do not accept draw offers.' }; + if (g.movesUci.length < 2) return { ok: false, error: 'Play a move before offering a draw.' }; + + if (g.drawOfferFrom && g.drawOfferFrom !== color) { + this.finishGame(g, '1/2-1/2', 'draw_agreement'); + return { ok: true }; + } + g.drawOfferFrom = color; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: g.drawOfferFrom, + takebackOfferFrom: g.takebackOfferFrom, + rematchOfferFrom: g.rematchOfferFrom + }); + return { ok: true }; + } + + handleDrawRespond(userId: number | null, gameId: string, accept: boolean): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + if (!g.drawOfferFrom || g.drawOfferFrom === color) { + return { ok: false, error: 'No incoming draw offer to respond to.' }; + } + + if (accept) { + this.finishGame(g, '1/2-1/2', 'draw_agreement'); + } else { + g.drawOfferFrom = null; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: null, + takebackOfferFrom: g.takebackOfferFrom, + rematchOfferFrom: g.rematchOfferFrom + }); + } + return { ok: true }; + } + + handleTakebackOffer(userId: number | null, gameId: string): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + if (g.rated) return { ok: false, error: 'Takebacks are disabled in rated games.' }; + if (g.movesUci.length === 0) return { ok: false, error: 'No moves to take back.' }; + + // Bot games: instant unlimited takeback back to human's turn + if (g.botLevel !== null && g.botColor !== null) { + const humanColor = oppositeColor(g.botColor); + if (color !== humanColor) return { ok: false, error: 'Invalid player.' }; + + const pliesToPop = g.chess.turn() === humanColor ? 2 : 1; + if (g.movesUci.length < pliesToPop) { + return { ok: false, error: 'No human move to take back yet.' }; + } + + g.botGeneration++; + for (let i = 0; i < pliesToPop; i++) { + g.chess.undo(); + g.movesUci.pop(); + g.movesSan.pop(); + g.moveTimesMs.pop(); + } + g.lastMoveAt = Date.now(); + if (g.movesUci.length < 2) { + g.clockRunning = false; + if (g.clockTimer) { + clearTimeout(g.clockTimer); + g.clockTimer = null; + } + } else if (g.clockRunning) { + this.scheduleClockTimer(g); + } + + this.transport.broadcastToGame(g.id, { + type: 'game:takeback', + gameId: g.id, + game: this.toDto(g) + }); + return { ok: true }; + } + + // Casual PvP mutual takeback + if (g.takebackOfferFrom && g.takebackOfferFrom !== color) { + return this.executePvpTakeback(g, g.takebackOfferFrom); + } + + g.takebackOfferFrom = color; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: g.drawOfferFrom, + takebackOfferFrom: g.takebackOfferFrom, + rematchOfferFrom: g.rematchOfferFrom + }); + return { ok: true }; + } + + handleTakebackRespond(userId: number | null, gameId: string, accept: boolean): { ok: true } | { ok: false; error: string } { + const g = this.activeGames.get(gameId); + if (!g || g.finished) return { ok: false, error: 'Game is not active.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + if (!g.takebackOfferFrom || g.takebackOfferFrom === color) { + return { ok: false, error: 'No incoming takeback request.' }; + } + + if (!accept) { + g.takebackOfferFrom = null; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: g.drawOfferFrom, + takebackOfferFrom: null, + rematchOfferFrom: g.rematchOfferFrom + }); + return { ok: true }; + } + + return this.executePvpTakeback(g, g.takebackOfferFrom); + } + + private executePvpTakeback(g: InternalGame, requester: Color): { ok: true } | { ok: false; error: string } { + const pliesToPop = g.chess.turn() === requester ? 2 : 1; + if (g.movesUci.length < pliesToPop) { + g.takebackOfferFrom = null; + return { ok: false, error: 'Not enough moves to take back.' }; + } + + for (let i = 0; i < pliesToPop; i++) { + g.chess.undo(); + g.movesUci.pop(); + g.movesSan.pop(); + g.moveTimesMs.pop(); + } + g.takebackOfferFrom = null; + g.lastMoveAt = Date.now(); + if (g.movesUci.length < 2) { + g.clockRunning = false; + if (g.clockTimer) { + clearTimeout(g.clockTimer); + g.clockTimer = null; + } + if (g.category !== 'unlimited') { + g.abortDeadlineMs = Date.now() + this.config.firstMoveAbortMs; + this.scheduleAbortTimer(g); + } + } else if (g.clockRunning) { + this.scheduleClockTimer(g); + } + + this.transport.broadcastToGame(g.id, { + type: 'game:takeback', + gameId: g.id, + game: this.toDto(g) + }); + return { ok: true }; + } + + handleRematchOffer(userId: number | null, gameId: string): { ok: true; newGameId?: string } | { ok: false; error: string } { + const g = this.getGame(gameId); + if (!g || !g.finished) return { ok: false, error: 'Game must be finished to request a rematch.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Only players can request a rematch.' }; + if (g.rematchGameId) { + return { ok: true, newGameId: g.rematchGameId }; + } + + // Bot rematch: start immediately with swapped colors! + if (g.botLevel !== null && g.botColor !== null && userId !== null) { + const nextColor: ColorPreference = g.botColor === 'w' ? 'white' : 'black'; + const created = this.createBotGame(userId, { + level: g.botLevel, + colorPref: nextColor, + initialMs: g.initialMs, + incrementMs: g.incrementMs + }); + if (!created.ok) return created; + g.rematchGameId = created.gameId; + this.transport.broadcastToGame(g.id, { + type: 'game:rematch_started', + oldGameId: g.id, + newGameId: created.gameId + }); + return { ok: true, newGameId: created.gameId }; + } + + if (g.rematchOfferFrom && g.rematchOfferFrom !== color) { + return this.launchPvpRematch(g); + } + + g.rematchOfferFrom = color; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: g.rematchOfferFrom + }); + return { ok: true }; + } + + handleRematchRespond( + userId: number | null, + gameId: string, + accept: boolean + ): { ok: true; newGameId?: string } | { ok: false; error: string } { + const g = this.getGame(gameId); + if (!g || !g.finished) return { ok: false, error: 'Game is not finished.' }; + const color = this.playerColor(g, userId); + if (!color) return { ok: false, error: 'Not a player in this game.' }; + if (!g.rematchOfferFrom || g.rematchOfferFrom === color) { + return { ok: false, error: 'No incoming rematch offer.' }; + } + + if (!accept) { + g.rematchOfferFrom = null; + this.transport.broadcastToGame(g.id, { + type: 'game:offers', + gameId: g.id, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: null + }); + return { ok: true }; + } + + return this.launchPvpRematch(g); + } + + private launchPvpRematch(g: InternalGame): { ok: true; newGameId: string } | { ok: false; error: string } { + if (g.white.userId === null || g.black.userId === null) { + return { ok: false, error: 'Players missing for rematch.' }; + } + if (this.getUserActiveGameId(g.white.userId) || this.getUserActiveGameId(g.black.userId)) { + return { ok: false, error: 'One of the players is already in another active game.' }; + } + + const whiteSummary = this.db.getUserSummaryById(g.black.userId); // swap colors + const blackSummary = this.db.getUserSummaryById(g.white.userId); + if (!whiteSummary || !blackSummary) return { ok: false, error: 'Player account not found.' }; + + const cat: RatedCategory = g.category === 'unlimited' ? 'rapid' : g.category; + const newGameId = this.createPvpGame({ + whiteUserId: whiteSummary.id, + whiteUsername: whiteSummary.username, + whiteRating: whiteSummary.ratings[cat].rating, + whiteProvisional: whiteSummary.ratings[cat].provisional, + blackUserId: blackSummary.id, + blackUsername: blackSummary.username, + blackRating: blackSummary.ratings[cat].rating, + blackProvisional: blackSummary.ratings[cat].provisional, + initialMs: g.initialMs, + incrementMs: g.incrementMs, + rated: g.rated + }); + + g.rematchGameId = newGameId; + g.rematchOfferFrom = null; + this.transport.broadcastToGame(g.id, { + type: 'game:rematch_started', + oldGameId: g.id, + newGameId + }); + this.lobby.notifyFriendsPresence(whiteSummary.id); + this.lobby.notifyFriendsPresence(blackSummary.id); + + return { ok: true, newGameId }; + } + + handleChat(userId: number | null, username: string | null, gameId: string, rawText: string): { ok: true } | { ok: false; error: string } { + const g = this.getGame(gameId); + if (!g) return { ok: false, error: 'Game not found.' }; + if (userId === null || !username) { + return { ok: false, error: 'Sign in to send chat messages.' }; + } + + const text = rawText.trim(); + if (!text || text.length > 300) { + return { ok: false, error: 'Message must be 1-300 characters.' }; + } + + const now = Date.now(); + const hits = (this.chatRateMap.get(userId) ?? []).filter((t) => now - t < 10_000); + if (hits.length >= 6) { + return { ok: false, error: 'Sending chat messages too quickly.' }; + } + hits.push(now); + this.chatRateMap.set(userId, hits); + + const msg: ChatMessage = { + id: crypto.randomBytes(6).toString('hex'), + userId, + username, + text, + createdAt: now + }; + g.chat.push(msg); + if (g.chat.length > 100) g.chat.shift(); + + this.transport.broadcastToGame(g.id, { + type: 'game:chat', + gameId: g.id, + message: msg + }); + return { ok: true }; + } + + handleUserPresenceChange(userId: number, connected: boolean): void { + for (const g of this.activeGames.values()) { + if (g.finished) continue; + const isWhite = g.white.userId === userId; + const isBlack = g.black.userId === userId; + if (!isWhite && !isBlack) continue; + + if (isWhite) { + g.white.connected = connected; + if (connected) { + if (g.whiteDisconnectTimer) { + clearTimeout(g.whiteDisconnectTimer); + g.whiteDisconnectTimer = null; + } + g.white.disconnectDeadlineMs = null; + } else if (!g.whiteDisconnectTimer) { + const deadline = Date.now() + this.config.disconnectForfeitMs; + g.white.disconnectDeadlineMs = deadline; + g.whiteDisconnectTimer = setTimeout(() => { + if (!g.finished && !g.white.connected) { + if (g.movesUci.length < 2) { + this.finishGame(g, '*', 'aborted'); + } else { + const insufficient = g.chess.hasInsufficientMatingMaterial('b'); + const result: GameResult = insufficient ? '1/2-1/2' : '0-1'; + this.finishGame(g, result, 'abandonment'); + } + } + }, this.config.disconnectForfeitMs); + } + } + + if (isBlack) { + g.black.connected = connected; + if (connected) { + if (g.blackDisconnectTimer) { + clearTimeout(g.blackDisconnectTimer); + g.blackDisconnectTimer = null; + } + g.black.disconnectDeadlineMs = null; + } else if (!g.blackDisconnectTimer) { + const deadline = Date.now() + this.config.disconnectForfeitMs; + g.black.disconnectDeadlineMs = deadline; + g.blackDisconnectTimer = setTimeout(() => { + if (!g.finished && !g.black.connected) { + if (g.movesUci.length < 2) { + this.finishGame(g, '*', 'aborted'); + } else { + const insufficient = g.chess.hasInsufficientMatingMaterial('w'); + const result: GameResult = insufficient ? '1/2-1/2' : '1-0'; + this.finishGame(g, result, 'abandonment'); + } + } + }, this.config.disconnectForfeitMs); + } + } + + this.broadcastGamePresence(g.id); + } + } + + broadcastGamePresence(gameId: string): void { + const g = this.getGame(gameId); + if (!g) return; + this.transport.broadcastToGame(g.id, { + type: 'game:presence', + gameId: g.id, + whiteConnected: g.white.connected, + whiteDisconnectDeadlineMs: g.white.disconnectDeadlineMs, + blackConnected: g.black.connected, + blackDisconnectDeadlineMs: g.black.disconnectDeadlineMs, + spectatorCount: this.transport.getGameSpectatorCount(g.id) + }); + } + + private finishGame(g: InternalGame, result: GameResult, termination: TerminationReason): void { + if (g.finished) return; + g.finished = true; + g.botGeneration++; + g.result = result; + g.termination = termination; + g.clockRunning = false; + g.abortDeadlineMs = null; + g.drawOfferFrom = null; + g.takebackOfferFrom = null; + g.endedAt = Date.now(); + this.clearAllTimers(g); + g.white.disconnectDeadlineMs = null; + g.black.disconnectDeadlineMs = null; + + this.activeGames.delete(g.id); + this.finishedGames.set(g.id, g); + const evictTimer = setTimeout(() => { + this.finishedGames.delete(g.id); + this.cleanupTimers.delete(g.id); + }, FINISHED_RETENTION_MS); + evictTimer.unref(); + this.cleanupTimers.set(g.id, evictTimer); + + const shouldSave = g.movesUci.length >= 2 && termination !== 'aborted'; + if (shouldSave) { + const pgn = g.chess.toPgn({ + Event: g.botLevel ? `ChessUp vs Stockfish Lv ${g.botLevel}` : g.rated ? `ChessUp Rated ${g.category}` : `ChessUp Casual ${g.category}`, + Site: 'ChessUp', + White: g.white.username, + Black: g.black.username, + Result: result, + TimeControl: g.category === 'unlimited' ? '-' : `${Math.round(g.initialMs / 1000)}+${Math.round(g.incrementMs / 1000)}`, + Termination: termination + }); + g.pgn = pgn; + + let ratingUpdates: + | { + category: RatedCategory; + whiteUserId: number; + blackUserId: number; + nextWhite: ReturnType['nextWhite']; + nextBlack: ReturnType['nextBlack']; + } + | undefined; + + if ( + g.rated && + g.botLevel === null && + g.category !== 'unlimited' && + g.white.userId !== null && + g.black.userId !== null + ) { + const cat = g.category as RatedCategory; + const wRatings = this.db.getRawRatingsMap(g.white.userId)[cat]; + const bRatings = this.db.getRawRatingsMap(g.black.userId)[cat]; + g.whiteRatingBefore = Math.round(wRatings.rating); + g.blackRatingBefore = Math.round(bRatings.rating); + + const whiteScore = result === '1-0' ? 1 : result === '0-1' ? 0 : 0.5; + const updated = updateGlicko2Pair(wRatings, bRatings, whiteScore); + g.whiteRatingDiff = updated.whiteDiff; + g.blackRatingDiff = updated.blackDiff; + ratingUpdates = { + category: cat, + whiteUserId: g.white.userId, + blackUserId: g.black.userId, + nextWhite: updated.nextWhite, + nextBlack: updated.nextBlack + }; + } + + this.db.saveFinishedGameAndRatings({ + id: g.id, + whiteUserId: g.white.userId, + blackUserId: g.black.userId, + whiteUsername: g.white.username, + blackUsername: g.black.username, + botLevel: g.botLevel, + botColor: g.botColor, + initialMs: g.initialMs, + incrementMs: g.incrementMs, + category: g.category, + rated: g.rated, + result, + termination, + whiteRatingBefore: g.whiteRatingBefore, + blackRatingBefore: g.blackRatingBefore, + whiteRatingDiff: g.whiteRatingDiff, + blackRatingDiff: g.blackRatingDiff, + initialFen: g.initialFen, + finalFen: g.chess.fen(), + movesUci: g.movesUci.slice(), + movesSan: g.movesSan.slice(), + moveTimesMs: g.moveTimesMs.slice(), + pgn, + createdAt: g.createdAt, + endedAt: g.endedAt, + ratingUpdates + }); + g.saved = true; + } + + this.transport.broadcastToGame(g.id, { + type: 'game:over', + gameId: g.id, + result, + termination, + whiteRatingBefore: g.whiteRatingBefore, + blackRatingBefore: g.blackRatingBefore, + whiteRatingDiff: g.whiteRatingDiff, + blackRatingDiff: g.blackRatingDiff, + saved: g.saved, + pgn: g.pgn + }); + + if (g.white.userId !== null) this.lobby.notifyFriendsPresence(g.white.userId); + if (g.black.userId !== null) this.lobby.notifyFriendsPresence(g.black.userId); + } + + // ---- Post-Game Analysis Trigger ---- + + requestGameAnalysis( + gameId: string, + depthOverride?: number, + broadcastProgress?: (msg: { type: 'analysis:progress'; gameId: string; progressPly: number; totalPlies: number } | { type: 'analysis:done'; gameId: string; report: GameAnalysisReport } | { type: 'analysis:error'; gameId: string; message: string }) => void + ): { ok: true; report: GameAnalysisReport } | { ok: false; status: number; error: string } { + const existing = this.db.getAnalysis(gameId); + if (existing && (existing.status === 'done' || existing.status === 'running')) { + return { ok: true, report: existing }; + } + + const stored = this.db.getGameById(gameId); + if (!stored) { + return { ok: false, status: 404, error: 'Saved game not found.' }; + } + + const depth = depthOverride && depthOverride >= 8 && depthOverride <= 18 ? depthOverride : this.config.analysisDepth; + this.db.upsertAnalysisRunning(gameId, depth, stored.movesUci.length); + const runningReport = this.db.getAnalysis(gameId)!; + + let lastDbProgressUpdate = 0; + this.stockfish + .analyzeFullGame(gameId, stored.initialFen, stored.movesUci, stored.movesSan, depth, (done, total) => { + const now = Date.now(); + if (now - lastDbProgressUpdate > 400 || done === total) { + lastDbProgressUpdate = now; + this.db.updateAnalysisProgress(gameId, done, now); + } + if (broadcastProgress) { + broadcastProgress({ + type: 'analysis:progress', + gameId, + progressPly: done, + totalPlies: total + }); + } + }) + .then((report) => { + this.db.saveAnalysisDone(report); + if (broadcastProgress) { + broadcastProgress({ + type: 'analysis:done', + gameId, + report + }); + } + }) + .catch((err) => { + this.db.saveAnalysisError(gameId); + if (broadcastProgress) { + broadcastProgress({ + type: 'analysis:error', + gameId, + message: err instanceof Error ? err.message : 'Analysis failed' + }); + } + }); + + return { ok: true, report: runningReport }; + } +} diff --git a/src/server/glicko2.ts b/src/server/glicko2.ts new file mode 100644 index 0000000..1cfbcc4 --- /dev/null +++ b/src/server/glicko2.ts @@ -0,0 +1,164 @@ +import type { GlickoRating, RatedCategory } from '../shared/types'; + +export const GLICKO_SCALE = 173.7178; +export const INITIAL_RATING = 1500; +export const INITIAL_RD = 350; +export const INITIAL_VOLATILITY = 0.06; +export const GLICKO_TAU = 0.5; +export const MIN_RD = 45; +export const MAX_RD = 350; +export const PROVISIONAL_RD_THRESHOLD = 110; + +export interface RawGlickoState { + rating: number; + rd: number; + volatility: number; + gamesPlayed: number; +} + +export interface GlickoOpponentResult { + rating: number; + rd: number; + score: number; // 1 = win, 0.5 = draw, 0 = loss +} + +export function createInitialGlicko(category: RatedCategory): GlickoRating { + return { + category, + rating: INITIAL_RATING, + rd: INITIAL_RD, + volatility: INITIAL_VOLATILITY, + gamesPlayed: 0, + provisional: true + }; +} + +export function isProvisionalRd(rd: number): boolean { + return rd > PROVISIONAL_RD_THRESHOLD; +} + +function g(phi: number): number { + return 1 / Math.sqrt(1 + (3 * phi * phi) / (Math.PI * Math.PI)); +} + +function expectedScore(mu: number, muOpp: number, phiOpp: number): number { + return 1 / (1 + Math.exp(-g(phiOpp) * (mu - muOpp))); +} + +/** + * Exact Mark Glickman Glicko-2 rating period update. + * Supports 0 opponents (inactivity RD increase) or N opponents. + */ +export function updateGlicko2( + player: RawGlickoState, + opponents: ReadonlyArray, + tau: number = GLICKO_TAU +): RawGlickoState { + const mu = (player.rating - INITIAL_RATING) / GLICKO_SCALE; + const phi = player.rd / GLICKO_SCALE; + const sigma = player.volatility; + + if (opponents.length === 0) { + const phiStar = Math.sqrt(phi * phi + sigma * sigma); + const nextRd = Math.min(MAX_RD, Math.max(MIN_RD, phiStar * GLICKO_SCALE)); + return { + rating: player.rating, + rd: nextRd, + volatility: sigma, + gamesPlayed: player.gamesPlayed + }; + } + + let vInv = 0; + let deltaSum = 0; + + for (const opp of opponents) { + const muJ = (opp.rating - INITIAL_RATING) / GLICKO_SCALE; + const phiJ = opp.rd / GLICKO_SCALE; + const gJ = g(phiJ); + const eJ = expectedScore(mu, muJ, phiJ); + vInv += gJ * gJ * eJ * (1 - eJ); + deltaSum += gJ * (opp.score - eJ); + } + + const v = 1 / vInv; + const delta = v * deltaSum; + + const a = Math.log(sigma * sigma); + const tauSq = tau * tau; + const phiSq = phi * phi; + const deltaSq = delta * delta; + + const f = (x: number): number => { + const ex = Math.exp(x); + const denom = phiSq + v + ex; + return (ex * (deltaSq - phiSq - v - ex)) / (2 * denom * denom) - (x - a) / tauSq; + }; + + let A = a; + let B: number; + if (deltaSq > phiSq + v) { + B = Math.log(deltaSq - phiSq - v); + } else { + let k = 1; + while (f(a - k * tau) < 0 && k < 100) { + k++; + } + B = a - k * tau; + } + + let fA = f(A); + let fB = f(B); + const eps = 1e-6; + let iter = 0; + + while (Math.abs(B - A) > eps && iter < 100) { + iter++; + const C = A + ((A - B) * fA) / (fB - fA); + const fC = f(C); + if (fC * fB <= 0) { + A = B; + fA = fB; + } else { + fA = fA / 2; + } + B = C; + fB = fC; + } + + const nextSigma = Math.exp(A / 2); + const phiStar = Math.sqrt(phiSq + nextSigma * nextSigma); + const nextPhi = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v); + const nextMu = mu + nextPhi * nextPhi * deltaSum; + + const nextRating = GLICKO_SCALE * nextMu + INITIAL_RATING; + const nextRd = Math.min(MAX_RD, Math.max(MIN_RD, GLICKO_SCALE * nextPhi)); + + return { + rating: nextRating, + rd: nextRd, + volatility: nextSigma, + gamesPlayed: player.gamesPlayed + opponents.length + }; +} + +export function updateGlicko2Pair( + white: RawGlickoState, + black: RawGlickoState, + scoreWhite: number +): { + nextWhite: RawGlickoState; + nextBlack: RawGlickoState; + whiteDiff: number; + blackDiff: number; +} { + const nextWhite = updateGlicko2(white, [{ rating: black.rating, rd: black.rd, score: scoreWhite }]); + const nextBlack = updateGlicko2(black, [{ rating: white.rating, rd: white.rd, score: 1 - scoreWhite }]); + + return { + nextWhite, + nextBlack, + whiteDiff: Math.round(nextWhite.rating) - Math.round(white.rating), + blackDiff: Math.round(nextBlack.rating) - Math.round(black.rating) + }; +} diff --git a/src/server/httpApi.ts b/src/server/httpApi.ts new file mode 100644 index 0000000..a7aae50 --- /dev/null +++ b/src/server/httpApi.ts @@ -0,0 +1,608 @@ +import fs from 'node:fs'; +import type http from 'node:http'; +import path from 'node:path'; +import { RATED_CATEGORIES } from '../shared/timeControl'; +import type { ColorPreference, RatedCategory, TimeCategory, UserProfile, UserSummary } from '../shared/types'; +import { + SESSION_COOKIE_NAME, + SlidingRateLimiter, + buildClearSessionCookie, + buildSessionCookie, + createSessionToken, + hashPassword, + hashSessionToken, + isSameOriginAllowed, + parseCookies, + validatePassword, + validateUsername, + verifyPassword +} from './auth'; +import type { AppConfig } from './config'; +import type { ChessDatabase } from './db'; +import type { GameManager } from './gameManager'; +import type { LobbyManager } from './lobbyManager'; +import type { WsHub } from './wsServer'; + +const MIME_TYPES: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'application/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.ico': 'image/x-icon' +}; + +const MAX_BODY_BYTES = 1_048_576; + +function sendJson(res: http.ServerResponse, status: number, body: unknown, extraHeaders?: Record): void { + const payload = JSON.stringify(body); + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + ...(extraHeaders || {}) + }); + res.end(payload); +} + +function readJsonBody(req: http.IncomingMessage): Promise> { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let total = 0; + + req.on('data', (chunk: Buffer) => { + total += chunk.length; + if (total > MAX_BODY_BYTES) { + reject(Object.assign(new Error('Request body too large'), { statusCode: 413 })); + req.destroy(); + return; + } + chunks.push(chunk); + }); + + req.on('end', () => { + if (chunks.length === 0) { + resolve({}); + return; + } + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + resolve(parsed as Record); + } else { + reject(Object.assign(new Error('Expected JSON object'), { statusCode: 400 })); + } + } catch { + reject(Object.assign(new Error('Invalid JSON payload'), { statusCode: 400 })); + } + }); + + req.on('error', (err) => reject(err)); + }); +} + +function getClientIp(req: http.IncomingMessage): string { + const cfIp = req.headers['cf-connecting-ip']; + if (typeof cfIp === 'string' && cfIp.trim()) { + return cfIp.trim(); + } + const fwd = req.headers['x-forwarded-for']; + if (typeof fwd === 'string' && fwd.trim()) { + return fwd.split(',')[0]!.trim(); + } + return req.socket.remoteAddress || 'unknown'; +} + +export function createHttpHandler(deps: { + config: AppConfig; + db: ChessDatabase; + lobbyManager: LobbyManager; + gameManager: GameManager; + wsHub: WsHub; +}): http.RequestListener { + const { config, db, lobbyManager, gameManager, wsHub } = deps; + const authRateLimiter = new SlidingRateLimiter(40, 5 * 60 * 1000, config.disableRateLimit); + const analysisRateLimiter = new SlidingRateLimiter(20, 10 * 60 * 1000, config.disableRateLimit); + const publicDirResolved = path.resolve(config.publicDir); + + function getSessionContext(req: http.IncomingMessage): { user: UserSummary | null; tokenHash: string | null } { + const cookies = parseCookies(req.headers.cookie); + const sid = cookies[SESSION_COOKIE_NAME]; + if (!sid) return { user: null, tokenHash: null }; + const tokenHash = hashSessionToken(sid); + const user = db.findUserBySessionTokenHash(tokenHash); + if (!user) return { user: null, tokenHash: null }; + return { user, tokenHash }; + } + + function serveStatic(res: http.ServerResponse, urlPath: string, method: string): void { + let relPath = urlPath; + if (relPath === '/' || !path.extname(relPath)) { + relPath = '/index.html'; + } + + const safeRel = relPath.replace(/^\/+/, ''); + const resolved = path.resolve(publicDirResolved, safeRel); + if (resolved !== publicDirResolved && !resolved.startsWith(publicDirResolved + path.sep)) { + res.writeHead(403); + res.end('Forbidden'); + return; + } + + let targetFile = resolved; + if (!fs.existsSync(targetFile) || fs.statSync(targetFile).isDirectory()) { + targetFile = path.join(publicDirResolved, 'index.html'); + } + + if (!fs.existsSync(targetFile)) { + res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(method === 'HEAD' ? undefined : 'Not built yet. Run npm run build.'); + return; + } + + const ext = path.extname(targetFile); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + const isHtml = ext === '.html'; + const cacheControl = isHtml ? 'no-cache' : 'public, max-age=300'; + const content = fs.readFileSync(targetFile); + res.writeHead(200, { + 'Content-Type': contentType, + 'Cache-Control': cacheControl, + 'Content-Length': content.length + }); + res.end(method === 'HEAD' ? undefined : content); + } + + return async (req, res) => { + try { + const method = (req.method || 'GET').toUpperCase(); + const parsedUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`); + let pathname: string; + try { + pathname = decodeURIComponent(parsedUrl.pathname); + } catch { + sendJson(res, 400, { error: 'Malformed URL path.' }); + return; + } + + if (!pathname.startsWith('/api/')) { + if (method !== 'GET' && method !== 'HEAD') { + sendJson(res, 405, { error: 'Method not allowed' }); + return; + } + serveStatic(res, pathname, method); + return; + } + + // CSRF protection on mutating API calls + if (method !== 'GET' && method !== 'HEAD' && !isSameOriginAllowed(req)) { + sendJson(res, 403, { error: 'Origin mismatch' }); + return; + } + + const { user, tokenHash } = getSessionContext(req); + const segments = pathname.slice(5).split('/').filter(Boolean); // after /api/ + + if (segments[0] === 'health' && !segments[1] && method === 'GET') { + sendJson(res, 200, { ok: true }); + return; + } + + // ---- AUTH ---- + if (segments[0] === 'auth') { + if (segments[1] === 'register' && method === 'POST') { + if (!authRateLimiter.allow(getClientIp(req))) { + sendJson(res, 429, { error: 'Too many authentication attempts. Try again shortly.' }); + return; + } + const body = await readJsonBody(req); + const uCheck = validateUsername(String(body['username'] || '')); + if (!uCheck.ok) { + sendJson(res, 400, { error: uCheck.error }); + return; + } + const pCheck = validatePassword(String(body['password'] || '')); + if (!pCheck.ok) { + sendJson(res, 400, { error: pCheck.error }); + return; + } + if (db.findUserRowByUsername(uCheck.username)) { + sendJson(res, 409, { error: 'Username is already taken.' }); + return; + } + + const { hashHex, saltHex } = hashPassword(String(body['password'])); + const created = db.createUser(uCheck.username, hashHex, saltHex); + const { token, tokenHash: newHash } = createSessionToken(); + db.createSession(newHash, created.id, Date.now() + config.sessionTtlMs); + + sendJson( + res, + 201, + { user: created }, + { 'Set-Cookie': buildSessionCookie(token, config.sessionTtlMs / 1000, config.cookieSecure) } + ); + return; + } + + if (segments[1] === 'login' && method === 'POST') { + if (!authRateLimiter.allow(getClientIp(req))) { + sendJson(res, 429, { error: 'Too many login attempts. Try again shortly.' }); + return; + } + const body = await readJsonBody(req); + const username = String(body['username'] || '').trim(); + const password = String(body['password'] || ''); + const row = db.findUserRowByUsername(username); + if (!row || !verifyPassword(password, row.password_hash, row.password_salt)) { + sendJson(res, 401, { error: 'Invalid username or password.' }); + return; + } + + db.updateLastSeen(row.id); + const { token, tokenHash: newHash } = createSessionToken(); + db.createSession(newHash, row.id, Date.now() + config.sessionTtlMs); + const summary = db.getUserSummaryById(row.id)!; + + sendJson( + res, + 200, + { user: summary }, + { 'Set-Cookie': buildSessionCookie(token, config.sessionTtlMs / 1000, config.cookieSecure) } + ); + return; + } + + if (segments[1] === 'logout' && method === 'POST') { + if (tokenHash) { + db.deleteSession(tokenHash); + } + sendJson( + res, + 200, + { ok: true }, + { 'Set-Cookie': buildClearSessionCookie(config.cookieSecure) } + ); + return; + } + + if (segments[1] === 'me' && method === 'GET') { + const activeGameId = user ? gameManager.getUserActiveGameId(user.id) : null; + sendJson(res, 200, { user, activeGameId }); + return; + } + + if (segments[1] === 'password' && method === 'POST') { + if (!user) { + sendJson(res, 401, { error: 'Authentication required.' }); + return; + } + const body = await readJsonBody(req); + const currentPw = String(body['currentPassword'] || ''); + const newPw = String(body['newPassword'] || ''); + const row = db.findUserRowById(user.id); + if (!row || !verifyPassword(currentPw, row.password_hash, row.password_salt)) { + sendJson(res, 400, { error: 'Current password is incorrect.' }); + return; + } + const pCheck = validatePassword(newPw); + if (!pCheck.ok) { + sendJson(res, 400, { error: pCheck.error }); + return; + } + const { hashHex, saltHex } = hashPassword(newPw); + db.updatePassword(user.id, hashHex, saltHex); + sendJson(res, 200, { ok: true }); + return; + } + } + + // ---- USERS ---- + if (segments[0] === 'users') { + if (segments[1] === 'search' && method === 'GET') { + const q = parsedUrl.searchParams.get('q') || ''; + const users = db.searchUsers(q, user?.id, 20); + sendJson(res, 200, { users }); + return; + } + + if (segments[1] && segments[2] === 'games' && method === 'GET') { + const target = db.getUserSummaryByUsername(segments[1]); + if (!target) { + sendJson(res, 404, { error: 'User not found.' }); + return; + } + const catParam = parsedUrl.searchParams.get('category') || ''; + const resParam = parsedUrl.searchParams.get('result') || ''; + const oppParam = parsedUrl.searchParams.get('opponent') || ''; + const vsBotParam = parsedUrl.searchParams.get('vsBot') || ''; + const page = Number(parsedUrl.searchParams.get('page')) || 1; + const limit = Number(parsedUrl.searchParams.get('limit')) || 20; + + const validCat: TimeCategory | undefined = + catParam === 'bullet' || + catParam === 'blitz' || + catParam === 'rapid' || + catParam === 'classical' || + catParam === 'unlimited' + ? catParam + : undefined; + const validRes = resParam === 'win' || resParam === 'loss' || resParam === 'draw' ? resParam : undefined; + const validVsBot = vsBotParam === 'only' || vsBotParam === 'exclude' ? vsBotParam : undefined; + + const history = db.listUserGames(target.id, { + category: validCat, + result: validRes, + opponent: oppParam || undefined, + vsBot: validVsBot, + page, + limit + }); + sendJson(res, 200, history); + return; + } + + if (segments[1] && !segments[2] && method === 'GET') { + const target = db.getUserSummaryByUsername(segments[1]); + if (!target) { + sendJson(res, 404, { error: 'User not found.' }); + return; + } + const presence = lobbyManager.getPresence(target.id); + const profile: UserProfile = { + user: target, + onlineStatus: presence.onlineStatus, + activeGameId: presence.activeGameId, + wdl: db.getUserWdl(target.id), + ratingHistory: db.getRatingHistory(target.id, 100) + }; + if (user && user.id !== target.id) { + profile.friendship = db.getFriendship(user.id, target.id); + profile.headToHead = db.getHeadToHead(user.id, target.id); + } + sendJson(res, 200, { profile }); + return; + } + } + + // ---- LEADERBOARD ---- + if (segments[0] === 'leaderboard' && method === 'GET') { + const catParam = parsedUrl.searchParams.get('category') || 'blitz'; + const cat: RatedCategory = (RATED_CATEGORIES as ReadonlyArray).includes(catParam) + ? (catParam as RatedCategory) + : 'blitz'; + const limit = Math.min(100, Math.max(1, Number(parsedUrl.searchParams.get('limit')) || 50)); + sendJson(res, 200, { category: cat, entries: db.getLeaderboard(cat, limit) }); + return; + } + + // ---- FRIENDS ---- + if (segments[0] === 'friends') { + if (!user) { + sendJson(res, 401, { error: 'Authentication required.' }); + return; + } + + if (!segments[1] && method === 'GET') { + const list = db.listFriendsAndRequests(user.id, (uid) => lobbyManager.getPresence(uid)); + const challenges = lobbyManager.getUserChallenges(user.id); + sendJson(res, 200, { ...list, challenges }); + return; + } + + if (segments[1] === 'request' && method === 'POST') { + const body = await readJsonBody(req); + let targetUser: UserSummary | null = null; + if (typeof body['userId'] === 'number') { + targetUser = db.getUserSummaryById(body['userId']); + } else if (typeof body['username'] === 'string') { + targetUser = db.getUserSummaryByUsername(body['username']); + } + if (!targetUser) { + sendJson(res, 404, { error: 'Player not found.' }); + return; + } + if (targetUser.id === user.id) { + sendJson(res, 400, { error: 'You cannot add yourself as a friend.' }); + return; + } + const outcome = db.sendFriendRequest(user.id, targetUser.id); + wsHub.sendToUser(targetUser.id, { type: 'friend:update' }); + wsHub.sendToUser(user.id, { type: 'friend:update' }); + sendJson(res, 200, { outcome }); + return; + } + + if (segments[1] === 'respond' && method === 'POST') { + const body = await readJsonBody(req); + const otherId = Number(body['userId']); + const accept = Boolean(body['accept']); + if (!Number.isInteger(otherId)) { + sendJson(res, 400, { error: 'Invalid userId.' }); + return; + } + const ok = db.respondFriendRequest(user.id, otherId, accept); + if (!ok) { + sendJson(res, 404, { error: 'Pending friend request not found.' }); + return; + } + wsHub.sendToUser(otherId, { type: 'friend:update' }); + wsHub.sendToUser(user.id, { type: 'friend:update' }); + sendJson(res, 200, { ok: true }); + return; + } + + if (segments[1] && method === 'DELETE') { + const otherId = Number(segments[1]); + if (!Number.isInteger(otherId)) { + sendJson(res, 400, { error: 'Invalid userId.' }); + return; + } + db.removeFriendOrRequest(user.id, otherId); + wsHub.sendToUser(otherId, { type: 'friend:update' }); + wsHub.sendToUser(user.id, { type: 'friend:update' }); + sendJson(res, 200, { ok: true }); + return; + } + } + + // ---- LOBBY & INVITES ---- + if (segments[0] === 'lobby' && !segments[1] && method === 'GET') { + sendJson(res, 200, { seeks: lobbyManager.listSeeks() }); + return; + } + + if (segments[0] === 'invites') { + if (!segments[1] && method === 'POST') { + if (!user) { + sendJson(res, 401, { error: 'Sign in to create an invite link.' }); + return; + } + const body = await readJsonBody(req); + const resInvite = lobbyManager.createInvite(user.id, { + initialMs: Number(body['initialMs']) || 0, + incrementMs: Number(body['incrementMs']) || 0, + rated: Boolean(body['rated']), + colorPref: (body['colorPref'] as ColorPreference) || 'random' + }); + if (!resInvite.ok) { + sendJson(res, 400, { error: resInvite.error }); + return; + } + sendJson(res, 201, { invite: resInvite.invite }); + return; + } + + if (segments[1] && !segments[2] && method === 'GET') { + const invite = lobbyManager.getInvite(segments[1]); + if (!invite) { + sendJson(res, 404, { error: 'Invite link is invalid or expired.' }); + return; + } + sendJson(res, 200, { invite }); + return; + } + + if (segments[1] && segments[2] === 'accept' && method === 'POST') { + if (!user) { + sendJson(res, 401, { error: 'Sign in to accept this challenge.' }); + return; + } + const resAccept = lobbyManager.acceptInvite(user.id, segments[1]); + if (!resAccept.ok) { + sendJson(res, 400, { error: resAccept.error }); + return; + } + sendJson(res, 200, { gameId: resAccept.gameId }); + return; + } + } + + // ---- GAMES & BOT GAMES & ANALYTICS ---- + if (segments[0] === 'games') { + if (segments[1] === 'bot' && method === 'POST') { + if (!user) { + sendJson(res, 401, { error: 'Sign in to play against Stockfish.' }); + return; + } + const body = await readJsonBody(req); + const created = gameManager.createBotGame(user.id, { + level: Number(body['level']) || 1, + colorPref: (body['colorPref'] as ColorPreference) || 'random', + initialMs: Number(body['initialMs']) || 0, + incrementMs: Number(body['incrementMs']) || 0 + }); + if (!created.ok) { + sendJson(res, 400, { error: created.error }); + return; + } + sendJson(res, 201, { gameId: created.gameId }); + return; + } + + const gameId = segments[1]; + if (gameId && segments[2] === 'pgn' && method === 'GET') { + const active = gameManager.getGameState(gameId); + let pgn: string | null = active?.pgn ?? null; + if (!pgn) { + pgn = db.getGameById(gameId)?.pgn ?? null; + } + if (!pgn) { + sendJson(res, 404, { error: 'PGN not found for this game.' }); + return; + } + const safeId = gameId.replace(/[^A-Za-z0-9_-]/g, ''); + res.writeHead(200, { + 'Content-Type': 'application/x-chess-pgn; charset=utf-8', + 'Content-Disposition': `attachment; filename="chessup-${safeId || 'game'}.pgn"` + }); + res.end(pgn); + return; + } + + if (gameId && segments[2] === 'analysis') { + if (method === 'GET') { + const report = db.getAnalysis(gameId); + if (!report) { + const stored = db.getGameById(gameId); + if (!stored) { + sendJson(res, 404, { error: 'Saved game not found.' }); + return; + } + sendJson(res, 200, { report: null }); + return; + } + sendJson(res, 200, { report }); + return; + } + + if (method === 'POST') { + if (!analysisRateLimiter.allow(getClientIp(req))) { + sendJson(res, 429, { error: 'Too many analysis requests. Try again shortly.' }); + return; + } + const body = await readJsonBody(req); + const depthOpt = typeof body['depth'] === 'number' ? body['depth'] : undefined; + const triggered = gameManager.requestGameAnalysis(gameId, depthOpt, (msg) => { + wsHub.broadcastToAnalysis(gameId, msg); + }); + if (!triggered.ok) { + sendJson(res, triggered.status, { error: triggered.error }); + return; + } + const code = triggered.report.status === 'done' ? 200 : 202; + sendJson(res, code, { report: triggered.report }); + return; + } + } + + if (gameId && !segments[2] && method === 'GET') { + const active = gameManager.getGameState(gameId); + if (active) { + sendJson(res, 200, { kind: 'active', game: active }); + return; + } + const stored = db.getGameById(gameId); + if (!stored) { + sendJson(res, 404, { error: 'Game not found.' }); + return; + } + const analysis = db.getAnalysis(gameId); + sendJson(res, 200, { kind: 'stored', game: stored, analysis }); + return; + } + } + + sendJson(res, 404, { error: 'API route not found.' }); + } catch (err) { + const status = (err as { statusCode?: number }).statusCode || 500; + const message = err instanceof Error ? err.message : 'Internal server error'; + if (status >= 500) { + console.error('[HTTP Error]', err); + } + if (!res.headersSent) { + sendJson(res, status, { error: message }); + } + } + }; +} diff --git a/src/server/index.ts b/src/server/index.ts new file mode 100644 index 0000000..c5e2441 --- /dev/null +++ b/src/server/index.ts @@ -0,0 +1,28 @@ +import { createApp } from './app'; + +const app = createApp(); +let stopping = false; + +const shutdown = async () => { + if (stopping) return; + stopping = true; + console.log('\n[ChessUp] Shutting down...'); + try { + await app.stop(); + } finally { + process.exit(0); + } +}; + +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); + +app + .start() + .then((port) => { + console.log(`[ChessUp] Listening on http://${app.config.host}:${port}`); + }) + .catch((err) => { + console.error('[ChessUp] Failed to start:', err); + process.exit(1); + }); diff --git a/src/server/lobbyManager.ts b/src/server/lobbyManager.ts new file mode 100644 index 0000000..8c52f22 --- /dev/null +++ b/src/server/lobbyManager.ts @@ -0,0 +1,551 @@ +import crypto from 'node:crypto'; +import { buildTimeControl } from '../shared/timeControl'; +import type { + Color, + ColorPreference, + DirectChallenge, + InviteInfo, + LobbySeek, + PresenceStatus, + RatedCategory, + ServerWsMessage +} from '../shared/types'; +import type { ChessDatabase } from './db'; + +export interface RealtimeTransport { + sendToUser(userId: number, msg: ServerWsMessage): void; + broadcastToLobby(msg: ServerWsMessage): void; + broadcastToGame(gameId: string, msg: ServerWsMessage): void; + isUserConnected(userId: number): boolean; + getGameSpectatorCount(gameId: string): number; +} + +export interface CreateGameRequest { + whiteUserId: number; + whiteUsername: string; + whiteRating: number; + whiteProvisional: boolean; + blackUserId: number; + blackUsername: string; + blackRating: number; + blackProvisional: boolean; + initialMs: number; + incrementMs: number; + rated: boolean; +} + +export interface GameLauncher { + createPvpGame(req: CreateGameRequest): string; + getUserActiveGameId(userId: number): string | null; +} + +interface StoredInvite extends InviteInfo {} + +const CHALLENGE_TTL_MS = 5 * 60 * 1000; +const INVITE_TTL_MS = 30 * 60 * 1000; + +export class LobbyManager { + private readonly seeks = new Map(); + private readonly challenges = new Map(); + private readonly invites = new Map(); + private gameLauncher: GameLauncher | null = null; + private pruneTimer: NodeJS.Timeout | null = null; + + constructor( + private readonly db: ChessDatabase, + private readonly transport: RealtimeTransport + ) { + this.pruneTimer = setInterval(() => this.pruneExpired(), 30_000); + this.pruneTimer.unref(); + } + + setGameLauncher(launcher: GameLauncher): void { + this.gameLauncher = launcher; + } + + stop(): void { + if (this.pruneTimer) { + clearInterval(this.pruneTimer); + this.pruneTimer = null; + } + } + + getPresence(userId: number): { onlineStatus: PresenceStatus; activeGameId: string | null } { + const activeGameId = this.gameLauncher?.getUserActiveGameId(userId) ?? null; + if (activeGameId) { + return { onlineStatus: 'in_game', activeGameId }; + } + if (this.transport.isUserConnected(userId)) { + return { onlineStatus: 'online', activeGameId: null }; + } + return { onlineStatus: 'offline', activeGameId: null }; + } + + notifyFriendsPresence(userId: number): void { + const presence = this.getPresence(userId); + const friendIds = this.db.getAcceptedFriendIds(userId); + for (const fid of friendIds) { + this.transport.sendToUser(fid, { + type: 'friend:presence', + userId, + onlineStatus: presence.onlineStatus, + activeGameId: presence.activeGameId + }); + } + } + + handleUserDisconnect(userId: number): void { + // Remove any open lobby seek owned by this user if they now have 0 connections + if (!this.transport.isUserConnected(userId)) { + let removed = false; + for (const [id, seek] of this.seeks) { + if (seek.userId === userId) { + this.seeks.delete(id); + removed = true; + } + } + if (removed) { + this.broadcastSeeks(); + } + } + this.notifyFriendsPresence(userId); + } + + listSeeks(): LobbySeek[] { + return Array.from(this.seeks.values()).sort((a, b) => b.createdAt - a.createdAt); + } + + private broadcastSeeks(): void { + this.transport.broadcastToLobby({ + type: 'lobby:state', + seeks: this.listSeeks() + }); + } + + private resolveCategoryAndRating( + userId: number, + initialMs: number, + incrementMs: number, + rated: boolean + ): { ok: true; rating: number; provisional: boolean; rated: boolean; category: ReturnType['category'] } | { ok: false; error: string } { + if (initialMs < 0 || incrementMs < 0) { + return { ok: false, error: 'Time control values cannot be negative.' }; + } + if (initialMs > 180 * 60 * 1000 || incrementMs > 180 * 1000) { + return { ok: false, error: 'Time control exceeds maximum allowed limit.' }; + } + const tc = buildTimeControl(initialMs, incrementMs); + if (tc.category !== 'unlimited' && initialMs < 15_000 && incrementMs < 2_000) { + return { ok: false, error: 'Minimum timed game requires at least 15s initial or 2s increment.' }; + } + + const effectiveRated = tc.category === 'unlimited' ? false : rated; + const summary = this.db.getUserSummaryById(userId); + if (!summary) return { ok: false, error: 'User not found.' }; + + const ratingCat: RatedCategory = tc.category === 'unlimited' ? 'rapid' : tc.category; + const r = summary.ratings[ratingCat]; + return { + ok: true, + rating: r.rating, + provisional: r.provisional, + rated: effectiveRated, + category: tc.category + }; + } + + createSeek( + userId: number, + opts: { + initialMs: number; + incrementMs: number; + rated: boolean; + colorPref: ColorPreference; + minRating?: number; + maxRating?: number; + } + ): { ok: true; seek: LobbySeek } | { ok: false; error: string } { + if (this.gameLauncher?.getUserActiveGameId(userId)) { + return { ok: false, error: 'Finish your active game before creating a seek.' }; + } + const user = this.db.getUserSummaryById(userId); + if (!user) return { ok: false, error: 'User not found.' }; + + const tcCheck = this.resolveCategoryAndRating(userId, opts.initialMs, opts.incrementMs, opts.rated); + if (!tcCheck.ok) return tcCheck; + + // One seek per user: replace any existing seek by this user + for (const [id, s] of this.seeks) { + if (s.userId === userId) { + this.seeks.delete(id); + } + } + + const seek: LobbySeek = { + id: crypto.randomBytes(6).toString('hex'), + userId: user.id, + username: user.username, + rating: tcCheck.rating, + provisional: tcCheck.provisional, + initialMs: opts.initialMs, + incrementMs: opts.incrementMs, + category: tcCheck.category, + rated: tcCheck.rated, + colorPref: opts.colorPref, + minRating: opts.minRating, + maxRating: opts.maxRating, + createdAt: Date.now() + }; + + this.seeks.set(seek.id, seek); + this.broadcastSeeks(); + return { ok: true, seek }; + } + + cancelSeek(userId: number, seekId?: string): boolean { + let removed = false; + for (const [id, s] of this.seeks) { + if (s.userId === userId && (!seekId || id === seekId)) { + this.seeks.delete(id); + removed = true; + } + } + if (removed) { + this.broadcastSeeks(); + } + return removed; + } + + private clearUserSeeks(userId: number): boolean { + let removed = false; + for (const [id, s] of this.seeks) { + if (s.userId === userId) { + this.seeks.delete(id); + removed = true; + } + } + return removed; + } + + private assignColors( + creatorPref: ColorPreference + ): { creatorColor: Color; joinerColor: Color } { + if (creatorPref === 'white') return { creatorColor: 'w', joinerColor: 'b' }; + if (creatorPref === 'black') return { creatorColor: 'b', joinerColor: 'w' }; + return Math.random() < 0.5 + ? { creatorColor: 'w', joinerColor: 'b' } + : { creatorColor: 'b', joinerColor: 'w' }; + } + + private launchMatchedGame( + creatorId: number, + joinerId: number, + initialMs: number, + incrementMs: number, + rated: boolean, + colorPref: ColorPreference + ): { ok: true; gameId: string } | { ok: false; error: string } { + if (!this.gameLauncher) return { ok: false, error: 'Game launcher unavailable.' }; + if (creatorId === joinerId) return { ok: false, error: 'Cannot play against yourself.' }; + if (this.gameLauncher.getUserActiveGameId(creatorId)) { + return { ok: false, error: 'Opponent is already in an active game.' }; + } + if (this.gameLauncher.getUserActiveGameId(joinerId)) { + return { ok: false, error: 'You already have an active game.' }; + } + + const creator = this.db.getUserSummaryById(creatorId); + const joiner = this.db.getUserSummaryById(joinerId); + if (!creator || !joiner) return { ok: false, error: 'Player account not found.' }; + + const tc = buildTimeControl(initialMs, incrementMs); + const ratingCat: RatedCategory = tc.category === 'unlimited' ? 'rapid' : tc.category; + const effectiveRated = tc.category === 'unlimited' ? false : rated; + + const { creatorColor } = this.assignColors(colorPref); + const whiteUser = creatorColor === 'w' ? creator : joiner; + const blackUser = creatorColor === 'w' ? joiner : creator; + + const gameId = this.gameLauncher.createPvpGame({ + whiteUserId: whiteUser.id, + whiteUsername: whiteUser.username, + whiteRating: whiteUser.ratings[ratingCat].rating, + whiteProvisional: whiteUser.ratings[ratingCat].provisional, + blackUserId: blackUser.id, + blackUsername: blackUser.username, + blackRating: blackUser.ratings[ratingCat].rating, + blackProvisional: blackUser.ratings[ratingCat].provisional, + initialMs, + incrementMs, + rated: effectiveRated + }); + + const clearedA = this.clearUserSeeks(creatorId); + const clearedB = this.clearUserSeeks(joinerId); + if (clearedA || clearedB) { + this.broadcastSeeks(); + } + + this.transport.sendToUser(creatorId, { type: 'game:started', gameId }); + this.transport.sendToUser(joinerId, { type: 'game:started', gameId }); + this.notifyFriendsPresence(creatorId); + this.notifyFriendsPresence(joinerId); + + return { ok: true, gameId }; + } + + acceptSeek(joinerId: number, seekId: string): { ok: true; gameId: string } | { ok: false; error: string } { + const seek = this.seeks.get(seekId); + if (!seek) return { ok: false, error: 'That lobby seek is no longer available.' }; + if (seek.userId === joinerId) return { ok: false, error: 'Cannot accept your own seek.' }; + if (this.gameLauncher?.getUserActiveGameId(joinerId)) { + return { ok: false, error: 'Finish your active game first.' }; + } + + const joiner = this.db.getUserSummaryById(joinerId); + if (!joiner) return { ok: false, error: 'User not found.' }; + const ratingCat: RatedCategory = seek.category === 'unlimited' ? 'rapid' : seek.category; + const joinerRating = joiner.ratings[ratingCat].rating; + if (seek.minRating !== undefined && joinerRating < seek.minRating) { + return { ok: false, error: `Minimum rating required: ${seek.minRating}.` }; + } + if (seek.maxRating !== undefined && joinerRating > seek.maxRating) { + return { ok: false, error: `Maximum rating allowed: ${seek.maxRating}.` }; + } + + this.seeks.delete(seekId); + this.broadcastSeeks(); + + return this.launchMatchedGame( + seek.userId, + joinerId, + seek.initialMs, + seek.incrementMs, + seek.rated, + seek.colorPref + ); + } + + // ---- Direct Friend Challenges ---- + + getUserChallenges(userId: number): DirectChallenge[] { + const now = Date.now(); + const out: DirectChallenge[] = []; + for (const [id, ch] of this.challenges) { + if (ch.expiresAt <= now) { + this.challenges.delete(id); + continue; + } + if (ch.fromUserId === userId || ch.toUserId === userId) { + out.push(ch); + } + } + return out; + } + + sendDirectChallenge( + fromUserId: number, + toUserId: number, + opts: { initialMs: number; incrementMs: number; rated: boolean; colorPref: ColorPreference } + ): { ok: true; challenge: DirectChallenge } | { ok: false; error: string } { + if (fromUserId === toUserId) { + return { ok: false, error: 'Cannot challenge yourself.' }; + } + const friendship = this.db.getFriendship(fromUserId, toUserId); + if (friendship.status !== 'accepted') { + return { ok: false, error: 'You can only send direct challenges to accepted friends.' }; + } + if (this.gameLauncher?.getUserActiveGameId(fromUserId)) { + return { ok: false, error: 'Finish your active game before sending a challenge.' }; + } + + const tcCheck = this.resolveCategoryAndRating(fromUserId, opts.initialMs, opts.incrementMs, opts.rated); + if (!tcCheck.ok) return tcCheck; + + const fromUser = this.db.getUserSummaryById(fromUserId); + const toUser = this.db.getUserSummaryById(toUserId); + if (!fromUser || !toUser) return { ok: false, error: 'User not found.' }; + + // Replace existing pending challenge between this same pair + for (const [id, existing] of this.challenges) { + if (existing.fromUserId === fromUserId && existing.toUserId === toUserId) { + this.challenges.delete(id); + this.transport.sendToUser(toUserId, { type: 'challenge:removed', challengeId: id, reason: 'replaced' }); + } + } + + const now = Date.now(); + const challenge: DirectChallenge = { + id: crypto.randomBytes(8).toString('hex'), + fromUserId, + fromUsername: fromUser.username, + fromRating: tcCheck.rating, + toUserId, + toUsername: toUser.username, + initialMs: opts.initialMs, + incrementMs: opts.incrementMs, + category: tcCheck.category, + rated: tcCheck.rated, + colorPref: opts.colorPref, + createdAt: now, + expiresAt: now + CHALLENGE_TTL_MS + }; + + this.challenges.set(challenge.id, challenge); + this.transport.sendToUser(toUserId, { type: 'challenge:received', challenge }); + this.transport.sendToUser(fromUserId, { type: 'challenge:list', challenges: this.getUserChallenges(fromUserId) }); + return { ok: true, challenge }; + } + + respondChallenge( + userId: number, + challengeId: string, + accept: boolean + ): { ok: true; gameId?: string } | { ok: false; error: string } { + const ch = this.challenges.get(challengeId); + if (!ch || ch.expiresAt <= Date.now()) { + this.challenges.delete(challengeId); + return { ok: false, error: 'Challenge expired or not found.' }; + } + if (ch.toUserId !== userId) { + return { ok: false, error: 'Only the challenged player can respond.' }; + } + + if (!accept) { + this.challenges.delete(challengeId); + this.transport.sendToUser(ch.fromUserId, { + type: 'challenge:removed', + challengeId, + reason: 'declined' + }); + this.transport.sendToUser(ch.toUserId, { + type: 'challenge:removed', + challengeId, + reason: 'declined' + }); + return { ok: true }; + } + + const res = this.launchMatchedGame( + ch.fromUserId, + ch.toUserId, + ch.initialMs, + ch.incrementMs, + ch.rated, + ch.colorPref + ); + if (!res.ok) return res; + + this.challenges.delete(challengeId); + this.transport.sendToUser(ch.fromUserId, { + type: 'challenge:removed', + challengeId, + reason: 'accepted' + }); + this.transport.sendToUser(ch.toUserId, { + type: 'challenge:removed', + challengeId, + reason: 'accepted' + }); + return { ok: true, gameId: res.gameId }; + } + + cancelChallenge(userId: number, challengeId: string): boolean { + const ch = this.challenges.get(challengeId); + if (!ch || ch.fromUserId !== userId) return false; + this.challenges.delete(challengeId); + this.transport.sendToUser(ch.toUserId, { + type: 'challenge:removed', + challengeId, + reason: 'cancelled' + }); + this.transport.sendToUser(ch.fromUserId, { + type: 'challenge:removed', + challengeId, + reason: 'cancelled' + }); + return true; + } + + // ---- Shareable Invite Links ---- + + createInvite( + creatorUserId: number, + opts: { initialMs: number; incrementMs: number; rated: boolean; colorPref: ColorPreference } + ): { ok: true; invite: InviteInfo } | { ok: false; error: string } { + if (this.gameLauncher?.getUserActiveGameId(creatorUserId)) { + return { ok: false, error: 'Finish your active game before creating an invite link.' }; + } + const tcCheck = this.resolveCategoryAndRating(creatorUserId, opts.initialMs, opts.incrementMs, opts.rated); + if (!tcCheck.ok) return tcCheck; + + const creator = this.db.getUserSummaryById(creatorUserId); + if (!creator) return { ok: false, error: 'User not found.' }; + + const now = Date.now(); + const token = crypto.randomBytes(6).toString('base64url'); + const invite: StoredInvite = { + token, + creatorUserId, + creatorUsername: creator.username, + creatorRating: tcCheck.rating, + initialMs: opts.initialMs, + incrementMs: opts.incrementMs, + category: tcCheck.category, + rated: tcCheck.rated, + colorPref: opts.colorPref, + createdAt: now, + expiresAt: now + INVITE_TTL_MS + }; + + this.invites.set(token, invite); + return { ok: true, invite }; + } + + getInvite(token: string): InviteInfo | null { + const inv = this.invites.get(token); + if (!inv) return null; + if (inv.expiresAt <= Date.now()) { + this.invites.delete(token); + return null; + } + return inv; + } + + acceptInvite(joinerUserId: number, token: string): { ok: true; gameId: string } | { ok: false; error: string } { + const inv = this.getInvite(token); + if (!inv) return { ok: false, error: 'Invite link is invalid or expired.' }; + if (inv.creatorUserId === joinerUserId) { + return { ok: false, error: 'You cannot accept your own invite link.' }; + } + + const res = this.launchMatchedGame( + inv.creatorUserId, + joinerUserId, + inv.initialMs, + inv.incrementMs, + inv.rated, + inv.colorPref + ); + if (!res.ok) return res; + + this.invites.delete(token); + return { ok: true, gameId: res.gameId }; + } + + private pruneExpired(): void { + const now = Date.now(); + for (const [id, ch] of this.challenges) { + if (ch.expiresAt <= now) { + this.challenges.delete(id); + this.transport.sendToUser(ch.fromUserId, { type: 'challenge:removed', challengeId: id, reason: 'expired' }); + this.transport.sendToUser(ch.toUserId, { type: 'challenge:removed', challengeId: id, reason: 'expired' }); + } + } + for (const [tok, inv] of this.invites) { + if (inv.expiresAt <= now) { + this.invites.delete(tok); + } + } + } +} diff --git a/src/server/stockfish.ts b/src/server/stockfish.ts new file mode 100644 index 0000000..2427806 --- /dev/null +++ b/src/server/stockfish.ts @@ -0,0 +1,783 @@ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; +import { createRequire } from 'node:module'; +import fs from 'node:fs'; +import path from 'node:path'; +import readline from 'node:readline'; +import { Chess } from '../shared/chess'; +import type { Color, GameAnalysisReport, MultiPvLine, PlyAnalysis } from '../shared/types'; +import { + classifyMove, + computeMoveAccuracy, + computePlayerSummary, + cpToWinPercent, + winPercentForSide +} from '../shared/winProb'; + +interface BotTuning { + skillLevel: number; + depth: number; + movetime: number; + multiPv: number; + weights?: number[]; +} + +const BOT_TUNING: Record = { + 1: { skillLevel: 0, depth: 1, movetime: 60, multiPv: 4, weights: [0.15, 0.25, 0.3, 0.3] }, + 2: { skillLevel: 2, depth: 2, movetime: 90, multiPv: 3, weights: [0.35, 0.4, 0.25] }, + 3: { skillLevel: 5, depth: 3, movetime: 120, multiPv: 1 }, + 4: { skillLevel: 8, depth: 5, movetime: 200, multiPv: 1 }, + 5: { skillLevel: 11, depth: 7, movetime: 300, multiPv: 1 }, + 6: { skillLevel: 14, depth: 10, movetime: 450, multiPv: 1 }, + 7: { skillLevel: 17, depth: 13, movetime: 700, multiPv: 1 }, + 8: { skillLevel: 20, depth: 16, movetime: 1100, multiPv: 1 } +}; + +export function resolveStockfishScriptPath(): string { + const req = createRequire(__filename); + const pkgJsonPath = req.resolve('stockfish/package.json'); + const pkgDir = path.dirname(pkgJsonPath); + const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')) as { buildVersion?: string }; + const binDir = path.join(pkgDir, 'bin'); + + if (pkg.buildVersion) { + const preferred = [ + `stockfish-${pkg.buildVersion}-lite-single.js`, + `stockfish-${pkg.buildVersion}-single.js`, + `stockfish-${pkg.buildVersion}-lite.js`, + `stockfish-${pkg.buildVersion}.js` + ]; + for (const file of preferred) { + const full = path.join(binDir, file); + if (fs.existsSync(full)) return full; + } + } + + if (fs.existsSync(binDir)) { + const entries = fs.readdirSync(binDir); + const liteSingle = entries.find((e) => e.endsWith('-lite-single.js')); + if (liteSingle) return path.join(binDir, liteSingle); + const single = entries.find((e) => e.endsWith('-single.js')); + if (single) return path.join(binDir, single); + const anyJs = entries.find((e) => e.endsWith('.js')); + if (anyJs) return path.join(binDir, anyJs); + } + + throw new Error('Could not locate a runnable Stockfish engine JS file inside node_modules/stockfish/bin'); +} + +interface ParsedInfoLine { + depth: number; + multipv: number; + scoreCp: number | null; + scoreMate: number | null; + isBound: boolean; + pvUci: string[]; +} + +function parseUciInfoLine(line: string): ParsedInfoLine | null { + if (!line.startsWith('info ')) return null; + const tokens = line.trim().split(/\s+/); + let depth = 0; + let multipv = 1; + let scoreCp: number | null = null; + let scoreMate: number | null = null; + let isBound = false; + let pvUci: string[] = []; + + for (let i = 1; i < tokens.length; i++) { + const tok = tokens[i]!; + if (tok === 'depth' && i + 1 < tokens.length) { + depth = parseInt(tokens[++i]!, 10) || 0; + } else if (tok === 'multipv' && i + 1 < tokens.length) { + multipv = parseInt(tokens[++i]!, 10) || 1; + } else if (tok === 'score' && i + 2 < tokens.length) { + const kind = tokens[++i]!; + const val = parseInt(tokens[++i]!, 10); + if (!Number.isNaN(val)) { + if (kind === 'cp') { + scoreCp = val; + scoreMate = null; + } else if (kind === 'mate') { + scoreMate = val; + scoreCp = null; + } + } + if (tokens[i + 1] === 'lowerbound' || tokens[i + 1] === 'upperbound') { + isBound = true; + } + } else if (tok === 'pv') { + pvUci = tokens.slice(i + 1); + break; + } + } + + if (depth <= 0 && pvUci.length === 0) return null; + if (scoreCp === null && scoreMate === null) return null; + + return { depth, multipv, scoreCp, scoreMate, isBound, pvUci }; +} + +function pvUciToSan(fen: string, pvUci: ReadonlyArray, maxPlies: number = 10): string[] { + try { + const chess = new Chess(fen); + const out: string[] = []; + const limit = Math.min(pvUci.length, maxPlies); + for (let i = 0; i < limit; i++) { + const mv = chess.moveUci(pvUci[i]!); + if (!mv) break; + out.push(mv.san); + } + return out; + } catch { + return []; + } +} + +interface SearchRequest { + fen: string; + depth?: number; + movetime?: number; + skillLevel: number; + multiPv: number; + newGame?: boolean; + cancelSignal?: AbortSignal; + onUpdate?: (lines: MultiPvLine[], depth: number) => void; +} + +interface SearchResult { + bestMove: string | null; + lines: MultiPvLine[]; +} + +class StockfishWorker { + private proc: ChildProcessWithoutNullStreams | null = null; + private rl: readline.Interface | null = null; + private readyPromise: Promise | null = null; + private currentSkillLevel = 20; + private currentMultiPv = 1; + private closed = false; + private exited = false; + private busy = false; + private lineHandler: ((line: string) => void) | null = null; + private exitHandler: ((err: Error) => void) | null = null; + + constructor(private readonly scriptPath: string) {} + + async init(): Promise { + if (this.readyPromise) return this.readyPromise; + this.readyPromise = new Promise((resolve, reject) => { + const child = spawn(process.execPath, [this.scriptPath], { + stdio: ['pipe', 'pipe', 'pipe'] + }); + this.proc = child; + this.rl = readline.createInterface({ input: child.stdout }); + + let initialized = false; + let sawUciOk = false; + + const onLine = (rawLine: string) => { + const line = rawLine.trim(); + if (!line) return; + + if (!initialized) { + if (line === 'uciok' && !sawUciOk) { + sawUciOk = true; + this.send('setoption name Hash value 32'); + this.send('setoption name Skill Level value 20'); + this.send('setoption name MultiPV value 1'); + this.send('isready'); + } else if (line === 'readyok' && sawUciOk) { + initialized = true; + resolve(); + } + return; + } + + if (this.lineHandler) { + this.lineHandler(line); + } + }; + + this.rl.on('line', onLine); + child.stderr.on('data', () => { + // Ignore non-fatal WASM info/warnings + }); + + child.on('error', (err) => { + if (!initialized) { + reject(err); + } else if (this.exitHandler) { + this.exitHandler(err); + } + }); + + child.on('exit', (code, signal) => { + this.exited = true; + const err = new Error(`Stockfish worker exited (code=${code}, signal=${signal})`); + if (!initialized) { + reject(err); + } else if (!this.closed && this.exitHandler) { + this.exitHandler(err); + } + this.cleanupHandles(); + }); + + this.send('uci'); + }); + return this.readyPromise; + } + + isBusy(): boolean { + return this.busy; + } + + isAlive(): boolean { + if (this.closed || this.exited) return false; + if (this.proc && this.proc.exitCode !== null) return false; + return true; + } + + private send(cmd: string): void { + if (this.proc && this.proc.stdin.writable) { + this.proc.stdin.write(cmd + '\n'); + } + } + + private cleanupHandles(): void { + try { + this.rl?.close(); + } catch { + // Ignore + } + this.rl = null; + this.proc = null; + this.readyPromise = null; + } + + async search(req: SearchRequest): Promise { + if (this.closed) { + throw new Error('Stockfish worker is closed'); + } + if (this.busy) { + throw new Error('Stockfish worker is already busy'); + } + + this.busy = true; + try { + await this.init(); + } catch (err) { + this.busy = false; + throw err; + } + + if (this.closed || !this.proc) { + this.busy = false; + throw new Error('Stockfish worker is closed'); + } + + const chessTurn: Color = req.fen.trim().split(/\s+/)[1] === 'b' ? 'b' : 'w'; + const sign = chessTurn === 'w' ? 1 : -1; + + return new Promise((resolve, reject) => { + const pvMap = new Map(); + let highestDepth = 0; + let stopped = false; + let waitingReady = true; + + const finish = (bestMove: string | null) => { + this.lineHandler = null; + this.exitHandler = null; + this.busy = false; + if (req.cancelSignal) { + req.cancelSignal.removeEventListener('abort', onAbort); + } + const sorted = Array.from(pvMap.values()).sort((a, b) => a.multipv - b.multipv); + resolve({ bestMove, lines: sorted }); + }; + + const fail = (err: Error) => { + this.lineHandler = null; + this.exitHandler = null; + this.busy = false; + if (req.cancelSignal) { + req.cancelSignal.removeEventListener('abort', onAbort); + } + reject(err); + }; + + const onAbort = () => { + if (!stopped && !waitingReady) { + stopped = true; + this.send('stop'); + } + }; + + if (req.cancelSignal) { + if (req.cancelSignal.aborted) { + this.busy = false; + resolve({ bestMove: null, lines: [] }); + return; + } + req.cancelSignal.addEventListener('abort', onAbort, { once: true }); + } + + this.exitHandler = (err) => fail(err); + + this.lineHandler = (line: string) => { + if (waitingReady) { + if (line === 'readyok') { + waitingReady = false; + if (req.cancelSignal?.aborted) { + finish(null); + return; + } + this.send(`position fen ${req.fen}`); + const goParts = ['go']; + if (req.depth !== undefined) goParts.push(`depth ${req.depth}`); + if (req.movetime !== undefined) goParts.push(`movetime ${req.movetime}`); + if (req.depth === undefined && req.movetime === undefined) goParts.push('depth 12'); + this.send(goParts.join(' ')); + } + return; + } + + if (line.startsWith('info ')) { + const parsed = parseUciInfoLine(line); + if (!parsed) return; + if (parsed.multipv > req.multiPv) return; + + const existing = pvMap.get(parsed.multipv); + // Avoid overwriting an exact score at the same depth with a bound + if (existing && existing.depth === parsed.depth && parsed.isBound) { + return; + } + + const scoreCp = parsed.scoreCp !== null ? parsed.scoreCp * sign : null; + const scoreMate = parsed.scoreMate !== null ? parsed.scoreMate * sign : null; + + const pvLine: MultiPvLine = { + multipv: parsed.multipv, + depth: parsed.depth, + scoreCp, + scoreMate, + pvUci: parsed.pvUci, + pvSan: pvUciToSan(req.fen, parsed.pvUci, 10) + }; + pvMap.set(parsed.multipv, pvLine); + if (parsed.depth > highestDepth) highestDepth = parsed.depth; + + if (req.onUpdate && !req.cancelSignal?.aborted) { + const snapshot = Array.from(pvMap.values()).sort((a, b) => a.multipv - b.multipv); + req.onUpdate(snapshot, highestDepth); + } + return; + } + + if (line.startsWith('bestmove ')) { + const parts = line.split(/\s+/); + const rawMove = parts[1] || null; + const bestMove = rawMove && rawMove !== '(none)' ? rawMove : null; + finish(bestMove); + } + }; + + // Configure options cleanly before starting search + if (req.newGame) { + this.send('ucinewgame'); + } + if (this.currentSkillLevel !== req.skillLevel) { + this.currentSkillLevel = req.skillLevel; + this.send(`setoption name Skill Level value ${req.skillLevel}`); + } + if (this.currentMultiPv !== req.multiPv) { + this.currentMultiPv = req.multiPv; + this.send(`setoption name MultiPV value ${req.multiPv}`); + } + this.send('isready'); + }); + } + + close(): void { + this.closed = true; + if (this.exitHandler) { + this.exitHandler(new Error('Stockfish worker closed')); + } + if (this.proc) { + try { + this.proc.stdin.write('quit\n'); + } catch { + // Ignore + } + const p = this.proc; + setTimeout(() => { + try { + if (p.exitCode === null) p.kill('SIGKILL'); + } catch { + // Ignore + } + }, 200).unref(); + } + this.cleanupHandles(); + } +} + +interface QueuedJob { + priority: number; // 1 = bot, 2 = live multipv, 3 = full game analysis + seq: number; + req: SearchRequest; + resolve: (res: SearchResult) => void; + reject: (err: unknown) => void; +} + +interface PositionEval { + cp: number | null; + mate: number | null; + bestMoveUci: string | null; + bestMoveSan: string | null; + pvUci: string[]; + pvSan: string[]; +} + +export class StockfishPool { + private readonly scriptPath: string; + private readonly workers: StockfishWorker[] = []; + private readonly queue: QueuedJob[] = []; + private seqCounter = 0; + private shuttingDown = false; + private readonly activeGameAnalyses = new Map< + string, + { promise: Promise; listeners: Set<(done: number, total: number) => void> } + >(); + + constructor(private readonly workerCount: number = 2) { + this.scriptPath = resolveStockfishScriptPath(); + const count = Math.max(1, workerCount); + for (let i = 0; i < count; i++) { + this.workers.push(new StockfishWorker(this.scriptPath)); + } + } + + async warmup(): Promise { + await Promise.all(this.workers.map((w) => w.init())); + } + + private enqueue(priority: number, req: SearchRequest): Promise { + if (this.shuttingDown) { + return Promise.reject(new Error('Stockfish pool is shutting down')); + } + if (req.cancelSignal?.aborted) { + return Promise.resolve({ bestMove: null, lines: [] }); + } + + return new Promise((resolve, reject) => { + const job: QueuedJob = { + priority, + seq: ++this.seqCounter, + req, + resolve, + reject + }; + + if (req.cancelSignal) { + const onAbort = () => { + const idx = this.queue.indexOf(job); + if (idx >= 0) { + this.queue.splice(idx, 1); + resolve({ bestMove: null, lines: [] }); + } + }; + req.cancelSignal.addEventListener('abort', onAbort, { once: true }); + } + + this.queue.push(job); + this.queue.sort((a, b) => (a.priority !== b.priority ? a.priority - b.priority : a.seq - b.seq)); + this.pump(); + }); + } + + private pump(): void { + if (this.shuttingDown) return; + + for (let i = 0; i < this.workers.length; i++) { + if (this.queue.length === 0) break; + let worker = this.workers[i]!; + if (!worker.isAlive()) { + worker = new StockfishWorker(this.scriptPath); + this.workers[i] = worker; + } + if (worker.isBusy()) continue; + + const job = this.queue.shift(); + if (!job) break; + + if (job.req.cancelSignal?.aborted) { + job.resolve({ bestMove: null, lines: [] }); + continue; + } + + worker + .search(job.req) + .then((res) => job.resolve(res)) + .catch((err) => job.reject(err)) + .finally(() => { + this.pump(); + }); + } + } + + async getBotMove(fen: string, level: number): Promise { + const safeLevel = Math.min(8, Math.max(1, Math.round(level))); + const tuning = BOT_TUNING[safeLevel] ?? BOT_TUNING[4]!; + const chess = new Chess(fen); + const legal = chess.legalMoves(); + if (legal.length === 0) { + throw new Error('No legal moves in position'); + } + if (legal.length === 1) { + return legal[0]!.uci; + } + + const res = await this.enqueue(1, { + fen, + depth: tuning.depth, + movetime: tuning.movetime, + skillLevel: tuning.skillLevel, + multiPv: tuning.multiPv + }); + + if (tuning.weights && res.lines.length > 1) { + const candidateLines = res.lines.filter((l) => l.pvUci.length > 0); + if (candidateLines.length > 0) { + // Avoid picking catastrophic blunders too wildly on Lv 2, but give Lv 1/2 realistic variety + const count = Math.min(candidateLines.length, tuning.weights.length); + const weights = tuning.weights.slice(0, count); + const total = weights.reduce((a, b) => a + b, 0); + let r = Math.random() * total; + for (let i = 0; i < count; i++) { + r -= weights[i]!; + if (r <= 0) { + const pickedUci = candidateLines[i]!.pvUci[0]!; + if (legal.some((m) => m.uci === pickedUci)) { + return pickedUci; + } + break; + } + } + } + } + + if (res.bestMove && legal.some((m) => m.uci === res.bestMove)) { + return res.bestMove; + } + return legal[0]!.uci; + } + + async analyzePositionMultiPv( + fen: string, + depth: number, + multiPv: number, + cancelSignal?: AbortSignal, + onUpdate?: (lines: MultiPvLine[], depth: number) => void + ): Promise { + const chess = new Chess(fen); + if (chess.isGameOver()) { + return []; + } + + const res = await this.enqueue(2, { + fen, + depth: Math.min(20, Math.max(4, depth)), + multiPv: Math.min(5, Math.max(1, multiPv)), + skillLevel: 20, + cancelSignal, + onUpdate + }); + return res.lines; + } + + private async evaluatePositionExact(fen: string, depth: number): Promise { + const chess = new Chess(fen); + if (!chess.legalMoves().length) { + if (chess.inCheck()) { + // Side to move is checkmated -> enemy delivered mate + const mateWinner = chess.turn() === 'w' ? -1 : 1; + return { + cp: null, + mate: mateWinner, + bestMoveUci: null, + bestMoveSan: null, + pvUci: [], + pvSan: [] + }; + } + // Stalemate + return { + cp: 0, + mate: null, + bestMoveUci: null, + bestMoveSan: null, + pvUci: [], + pvSan: [] + }; + } + + if (chess.isInsufficientMaterial()) { + return { + cp: 0, + mate: null, + bestMoveUci: chess.legalMoves()[0]?.uci ?? null, + bestMoveSan: chess.legalMoves()[0]?.san ?? null, + pvUci: [], + pvSan: [] + }; + } + + const res = await this.enqueue(3, { + fen, + depth, + skillLevel: 20, + multiPv: 1 + }); + + const top = res.lines[0]; + const bestMoveUci = top?.pvUci[0] ?? res.bestMove ?? null; + let bestMoveSan: string | null = null; + if (bestMoveUci) { + const clone = new Chess(fen); + bestMoveSan = clone.moveUci(bestMoveUci)?.san ?? null; + } + + return { + cp: top ? top.scoreCp : 0, + mate: top ? top.scoreMate : null, + bestMoveUci, + bestMoveSan, + pvUci: top?.pvUci ?? (bestMoveUci ? [bestMoveUci] : []), + pvSan: top?.pvSan ?? (bestMoveSan ? [bestMoveSan] : []) + }; + } + + analyzeFullGame( + gameId: string, + initialFen: string, + movesUci: ReadonlyArray, + movesSan: ReadonlyArray, + depth: number, + onProgress?: (done: number, total: number) => void + ): Promise { + const existing = this.activeGameAnalyses.get(gameId); + if (existing) { + if (onProgress) existing.listeners.add(onProgress); + return existing.promise; + } + + const listeners = new Set<(done: number, total: number) => void>(); + if (onProgress) listeners.add(onProgress); + + const run = async (): Promise => { + const startedAt = Date.now(); + const chess = new Chess(initialFen); + const positions: Array<{ fen: string; turn: Color }> = [{ fen: chess.fen(), turn: chess.turn() }]; + + for (let i = 0; i < movesUci.length; i++) { + const mv = chess.moveUci(movesUci[i]!); + if (!mv) { + throw new Error(`Invalid move ${movesUci[i]} at ply ${i + 1} during analysis`); + } + positions.push({ fen: chess.fen(), turn: chess.turn() }); + } + + const totalPositions = positions.length; + const evals: Array = new Array(totalPositions); + let completed = 0; + + // Evaluate all positions through the priority-3 pool (runs concurrently across workers) + await Promise.all( + positions.map(async (pos, idx) => { + const ev = await this.evaluatePositionExact(pos.fen, depth); + evals[idx] = ev; + completed++; + for (const cb of listeners) { + cb(Math.min(movesUci.length, completed), movesUci.length); + } + }) + ); + + const initialEval = evals[0]!; + const initialWinPercent = cpToWinPercent(initialEval.cp, initialEval.mate); + + const plies: PlyAnalysis[] = []; + for (let i = 0; i < movesUci.length; i++) { + const before = evals[i]!; + const after = evals[i + 1]!; + const moverColor = positions[i]!.turn; + + const whiteWinBefore = cpToWinPercent(before.cp, before.mate); + const whiteWinAfter = cpToWinPercent(after.cp, after.mate); + const moverWinBefore = winPercentForSide(whiteWinBefore, moverColor); + const moverWinAfter = winPercentForSide(whiteWinAfter, moverColor); + const winDrop = Math.max(0, moverWinBefore - moverWinAfter); + const isBest = before.bestMoveUci !== null && before.bestMoveUci === movesUci[i]; + const classification = classifyMove(moverWinBefore, moverWinAfter, isBest); + const accuracy = computeMoveAccuracy(winDrop); + + plies.push({ + ply: i + 1, + moveUci: movesUci[i]!, + moveSan: movesSan[i] || movesUci[i]!, + color: moverColor, + evalCpBefore: before.cp, + evalMateBefore: before.mate, + evalCpAfter: after.cp, + evalMateAfter: after.mate, + winPercentBefore: Math.round(whiteWinBefore * 10) / 10, + winPercentAfter: Math.round(whiteWinAfter * 10) / 10, + winDrop: Math.round(winDrop * 10) / 10, + accuracy: Math.round(accuracy * 10) / 10, + bestMoveUci: before.bestMoveUci, + bestMoveSan: before.bestMoveSan, + pvUci: before.pvUci, + pvSan: before.pvSan, + classification + }); + } + + const now = Date.now(); + return { + gameId, + status: 'done', + depth, + progressPly: movesUci.length, + totalPlies: movesUci.length, + whiteSummary: computePlayerSummary(plies, 'w'), + blackSummary: computePlayerSummary(plies, 'b'), + initialEvalCp: initialEval.cp, + initialEvalMate: initialEval.mate, + initialWinPercent: Math.round(initialWinPercent * 10) / 10, + initialBestMoveUci: initialEval.bestMoveUci, + initialBestMoveSan: initialEval.bestMoveSan, + initialPvSan: initialEval.pvSan, + plies, + createdAt: startedAt, + updatedAt: now + }; + }; + + const promise = run().finally(() => { + this.activeGameAnalyses.delete(gameId); + }); + this.activeGameAnalyses.set(gameId, { promise, listeners }); + return promise; + } + + shutdown(): void { + this.shuttingDown = true; + while (this.queue.length > 0) { + const job = this.queue.shift()!; + job.reject(new Error('Stockfish pool shutdown')); + } + for (const w of this.workers) { + w.close(); + } + } +} diff --git a/src/server/wsServer.ts b/src/server/wsServer.ts new file mode 100644 index 0000000..501ea98 --- /dev/null +++ b/src/server/wsServer.ts @@ -0,0 +1,628 @@ +import type http from 'node:http'; +import type { Duplex } from 'node:stream'; +import { WebSocket, WebSocketServer } from 'ws'; +import { SESSION_COOKIE_NAME, hashSessionToken, isSameOriginAllowed, parseCookies } from './auth'; +import type { AppConfig } from './config'; +import type { ChessDatabase } from './db'; +import type { GameManager } from './gameManager'; +import type { LobbyManager, RealtimeTransport } from './lobbyManager'; +import type { StockfishPool } from './stockfish'; +import type { ClientWsMessage, ServerWsMessage } from '../shared/types'; + +interface ClientConn { + ws: WebSocket; + userId: number | null; + username: string | null; + alive: boolean; + subscribedGames: Set; + subscribedAnalyses: Set; + inLobby: boolean; + multipvAbort: AbortController | null; + activeMultipvId: string | null; +} + +export class WsHub implements RealtimeTransport { + private readonly wss: WebSocketServer; + private readonly clients = new Set(); + private readonly userSockets = new Map>(); + private readonly lobbySubs = new Set(); + private readonly gameSubs = new Map>(); + private readonly analysisSubs = new Map>(); + private lobbyManager: LobbyManager | null = null; + private gameManager: GameManager | null = null; + private heartbeatTimer: NodeJS.Timeout | null = null; + + constructor( + private readonly config: AppConfig, + private readonly db: ChessDatabase, + private readonly stockfish: StockfishPool + ) { + this.wss = new WebSocketServer({ noServer: true }); + this.heartbeatTimer = setInterval(() => this.pingClients(), 25_000); + this.heartbeatTimer.unref(); + } + + attachManagers(lobby: LobbyManager, game: GameManager): void { + this.lobbyManager = lobby; + this.gameManager = game; + } + + handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): void { + if (!isSameOriginAllowed(req)) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + + const cookies = parseCookies(req.headers.cookie); + const sid = cookies[SESSION_COOKIE_NAME]; + let userId: number | null = null; + let username: string | null = null; + + if (sid) { + const user = this.db.findUserBySessionTokenHash(hashSessionToken(sid)); + if (user) { + userId = user.id; + username = user.username; + this.db.updateLastSeen(user.id); + } + } + + this.wss.handleUpgrade(req, socket, head, (ws) => { + this.onConnection(ws, userId, username); + }); + } + + private onConnection(ws: WebSocket, userId: number | null, username: string | null): void { + const conn: ClientConn = { + ws, + userId, + username, + alive: true, + subscribedGames: new Set(), + subscribedAnalyses: new Set(), + inLobby: false, + multipvAbort: null, + activeMultipvId: null + }; + this.clients.add(conn); + + if (userId !== null) { + let set = this.userSockets.get(userId); + const wasOffline = !set || set.size === 0; + if (!set) { + set = new Set(); + this.userSockets.set(userId, set); + } + set.add(conn); + + if (wasOffline) { + this.gameManager?.handleUserPresenceChange(userId, true); + this.lobbyManager?.notifyFriendsPresence(userId); + } + } + + const userSummary = userId !== null ? this.db.getUserSummaryById(userId) : null; + const activeGameId = userId !== null ? (this.gameManager?.getUserActiveGameId(userId) ?? null) : null; + const challenges = userId !== null ? (this.lobbyManager?.getUserChallenges(userId) ?? []) : []; + + this.send(conn, { + type: 'session:init', + user: userSummary, + activeGameId, + challenges + }); + + ws.on('pong', () => { + conn.alive = true; + }); + + ws.on('message', (data) => { + this.handleMessage(conn, data.toString()); + }); + + ws.on('close', () => { + this.cleanupConn(conn); + }); + + ws.on('error', () => { + this.cleanupConn(conn); + }); + } + + private cleanupConn(conn: ClientConn): void { + if (!this.clients.has(conn)) return; + this.clients.delete(conn); + + if (conn.multipvAbort) { + conn.multipvAbort.abort(); + conn.multipvAbort = null; + } + + if (conn.inLobby) { + this.lobbySubs.delete(conn); + conn.inLobby = false; + } + + for (const gameId of conn.subscribedGames) { + const set = this.gameSubs.get(gameId); + if (set) { + set.delete(conn); + if (set.size === 0) this.gameSubs.delete(gameId); + } + this.gameManager?.broadcastGamePresence(gameId); + } + conn.subscribedGames.clear(); + + for (const gameId of conn.subscribedAnalyses) { + const set = this.analysisSubs.get(gameId); + if (set) { + set.delete(conn); + if (set.size === 0) this.analysisSubs.delete(gameId); + } + } + conn.subscribedAnalyses.clear(); + + if (conn.userId !== null) { + const set = this.userSockets.get(conn.userId); + if (set) { + set.delete(conn); + if (set.size === 0) { + this.userSockets.delete(conn.userId); + this.gameManager?.handleUserPresenceChange(conn.userId, false); + this.lobbyManager?.handleUserDisconnect(conn.userId); + } + } + } + } + + private pingClients(): void { + for (const conn of this.clients) { + if (!conn.alive) { + conn.ws.terminate(); + this.cleanupConn(conn); + continue; + } + conn.alive = false; + try { + conn.ws.ping(); + } catch { + conn.ws.terminate(); + this.cleanupConn(conn); + } + } + } + + private send(conn: ClientConn, msg: ServerWsMessage): void { + if (conn.ws.readyState === WebSocket.OPEN) { + conn.ws.send(JSON.stringify(msg)); + } + } + + private sendError(conn: ClientConn, code: string, message: string): void { + this.send(conn, { type: 'error', code, message }); + } + + sendToUser(userId: number, msg: ServerWsMessage): void { + const set = this.userSockets.get(userId); + if (!set) return; + const payload = JSON.stringify(msg); + for (const conn of set) { + if (conn.ws.readyState === WebSocket.OPEN) { + conn.ws.send(payload); + } + } + } + + broadcastToLobby(msg: ServerWsMessage): void { + const payload = JSON.stringify(msg); + for (const conn of this.lobbySubs) { + if (conn.ws.readyState === WebSocket.OPEN) { + conn.ws.send(payload); + } + } + } + + broadcastToGame(gameId: string, msg: ServerWsMessage): void { + const set = this.gameSubs.get(gameId); + if (!set) return; + const payload = JSON.stringify(msg); + for (const conn of set) { + if (conn.ws.readyState === WebSocket.OPEN) { + conn.ws.send(payload); + } + } + } + + broadcastToAnalysis(gameId: string, msg: ServerWsMessage): void { + const set = this.analysisSubs.get(gameId); + if (!set) return; + const payload = JSON.stringify(msg); + for (const conn of set) { + if (conn.ws.readyState === WebSocket.OPEN) { + conn.ws.send(payload); + } + } + } + + isUserConnected(userId: number): boolean { + const set = this.userSockets.get(userId); + return !!set && set.size > 0; + } + + getGameSpectatorCount(gameId: string): number { + const set = this.gameSubs.get(gameId); + if (!set) return 0; + const players = this.gameManager?.getGamePlayerIds(gameId); + let count = 0; + for (const conn of set) { + if (players && (conn.userId === players.whiteUserId || conn.userId === players.blackUserId)) { + continue; + } + count++; + } + return count; + } + + private handleMessage(conn: ClientConn, raw: string): void { + let msg: ClientWsMessage; + try { + msg = JSON.parse(raw) as ClientWsMessage; + } catch { + this.sendError(conn, 'BAD_JSON', 'Invalid JSON message.'); + return; + } + if (!msg || typeof msg.type !== 'string') return; + + const lobby = this.lobbyManager; + const games = this.gameManager; + if (!lobby || !games) return; + + switch (msg.type) { + case 'ping': { + this.send(conn, { type: 'pong', serverTimeMs: Date.now() }); + break; + } + + case 'lobby:subscribe': { + conn.inLobby = true; + this.lobbySubs.add(conn); + this.send(conn, { type: 'lobby:state', seeks: lobby.listSeeks() }); + break; + } + + case 'lobby:unsubscribe': { + conn.inLobby = false; + this.lobbySubs.delete(conn); + break; + } + + case 'lobby:seek': { + if (conn.userId === null) { + this.sendError(conn, 'UNAUTHORIZED', 'Sign in to create a seek.'); + return; + } + const res = lobby.createSeek(conn.userId, { + initialMs: Number(msg.initialMs) || 0, + incrementMs: Number(msg.incrementMs) || 0, + rated: Boolean(msg.rated), + colorPref: msg.colorPref || 'random', + minRating: msg.minRating, + maxRating: msg.maxRating + }); + if (!res.ok) this.sendError(conn, 'SEEK_ERROR', res.error); + break; + } + + case 'lobby:cancel_seek': { + if (conn.userId === null) return; + lobby.cancelSeek(conn.userId, msg.seekId); + break; + } + + case 'lobby:accept_seek': { + if (conn.userId === null) { + this.sendError(conn, 'UNAUTHORIZED', 'Sign in to join a game.'); + return; + } + const res = lobby.acceptSeek(conn.userId, msg.seekId); + if (!res.ok) this.sendError(conn, 'JOIN_ERROR', res.error); + break; + } + + case 'challenge:send': { + if (conn.userId === null) { + this.sendError(conn, 'UNAUTHORIZED', 'Sign in to challenge a friend.'); + return; + } + const res = lobby.sendDirectChallenge(conn.userId, Number(msg.toUserId), { + initialMs: Number(msg.initialMs) || 0, + incrementMs: Number(msg.incrementMs) || 0, + rated: Boolean(msg.rated), + colorPref: msg.colorPref || 'random' + }); + if (!res.ok) this.sendError(conn, 'CHALLENGE_ERROR', res.error); + break; + } + + case 'challenge:respond': { + if (conn.userId === null) return; + const res = lobby.respondChallenge(conn.userId, msg.challengeId, Boolean(msg.accept)); + if (!res.ok) this.sendError(conn, 'CHALLENGE_ERROR', res.error); + break; + } + + case 'challenge:cancel': { + if (conn.userId === null) return; + lobby.cancelChallenge(conn.userId, msg.challengeId); + break; + } + + case 'game:subscribe': { + const gameId = msg.gameId; + if (!gameId) return; + conn.subscribedGames.add(gameId); + let set = this.gameSubs.get(gameId); + if (!set) { + set = new Set(); + this.gameSubs.set(gameId, set); + } + set.add(conn); + + const state = games.getGameState(gameId); + if (state) { + this.send(conn, { type: 'game:state', game: state }); + games.broadcastGamePresence(gameId); + } else { + // Check stored game fallback + const stored = this.db.getGameById(gameId); + if (!stored) { + this.sendError(conn, 'NOT_FOUND', 'Game not found.'); + } else { + this.send(conn, { + type: 'game:state', + game: { + id: stored.id, + white: { + userId: stored.whiteUserId, + username: stored.whiteUsername, + rating: stored.whiteRatingBefore, + provisional: false, + isBot: stored.botColor === 'w', + botLevel: stored.botColor === 'w' ? stored.botLevel : null, + connected: false, + disconnectDeadlineMs: null + }, + black: { + userId: stored.blackUserId, + username: stored.blackUsername, + rating: stored.blackRatingBefore, + provisional: false, + isBot: stored.botColor === 'b', + botLevel: stored.botColor === 'b' ? stored.botLevel : null, + connected: false, + disconnectDeadlineMs: null + }, + initialFen: stored.initialFen, + fen: stored.finalFen, + movesUci: stored.movesUci, + movesSan: stored.movesSan, + moveTimesMs: stored.moveTimesMs, + turn: stored.movesUci.length % 2 === 0 ? 'w' : 'b', + initialMs: stored.initialMs, + incrementMs: stored.incrementMs, + category: stored.category, + rated: stored.rated, + botLevel: stored.botLevel, + whiteTimeMs: 0, + blackTimeMs: 0, + serverTimeMs: Date.now(), + clockRunning: false, + abortDeadlineMs: null, + drawOfferFrom: null, + takebackOfferFrom: null, + rematchOfferFrom: null, + rematchGameId: null, + spectatorCount: 0, + chat: [], + finished: true, + result: stored.result, + termination: stored.termination, + whiteRatingBefore: stored.whiteRatingBefore, + blackRatingBefore: stored.blackRatingBefore, + whiteRatingDiff: stored.whiteRatingDiff, + blackRatingDiff: stored.blackRatingDiff, + saved: true, + pgn: stored.pgn + } + }); + } + } + break; + } + + case 'game:unsubscribe': { + const gameId = msg.gameId; + conn.subscribedGames.delete(gameId); + const set = this.gameSubs.get(gameId); + if (set) { + set.delete(conn); + if (set.size === 0) this.gameSubs.delete(gameId); + } + games.broadcastGamePresence(gameId); + break; + } + + case 'game:move': { + const res = games.handleMove(conn.userId, msg.gameId, msg.uci); + if (!res.ok) this.sendError(conn, 'MOVE_ERROR', res.error); + break; + } + + case 'game:abort': { + const res = games.handleAbort(conn.userId, msg.gameId); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:resign': { + const res = games.handleResign(conn.userId, msg.gameId); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:draw_offer': { + const res = games.handleDrawOffer(conn.userId, msg.gameId); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:draw_respond': { + const res = games.handleDrawRespond(conn.userId, msg.gameId, Boolean(msg.accept)); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:takeback_offer': { + const res = games.handleTakebackOffer(conn.userId, msg.gameId); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:takeback_respond': { + const res = games.handleTakebackRespond(conn.userId, msg.gameId, Boolean(msg.accept)); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:rematch_offer': { + const res = games.handleRematchOffer(conn.userId, msg.gameId); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:rematch_respond': { + const res = games.handleRematchRespond(conn.userId, msg.gameId, Boolean(msg.accept)); + if (!res.ok) this.sendError(conn, 'GAME_ERROR', res.error); + break; + } + + case 'game:chat': { + const res = games.handleChat(conn.userId, conn.username, msg.gameId, msg.text); + if (!res.ok) this.sendError(conn, 'CHAT_ERROR', res.error); + break; + } + + case 'analysis:subscribe': { + const gameId = msg.gameId; + if (!gameId) return; + conn.subscribedAnalyses.add(gameId); + let set = this.analysisSubs.get(gameId); + if (!set) { + set = new Set(); + this.analysisSubs.set(gameId, set); + } + set.add(conn); + + const report = this.db.getAnalysis(gameId); + if (report?.status === 'done') { + this.send(conn, { type: 'analysis:done', gameId, report }); + } else if (report?.status === 'running') { + this.send(conn, { + type: 'analysis:progress', + gameId, + progressPly: report.progressPly, + totalPlies: report.totalPlies + }); + } + break; + } + + case 'analysis:unsubscribe': { + const gameId = msg.gameId; + conn.subscribedAnalyses.delete(gameId); + const set = this.analysisSubs.get(gameId); + if (set) { + set.delete(conn); + if (set.size === 0) this.analysisSubs.delete(gameId); + } + break; + } + + case 'analysis:multipv': { + if (conn.multipvAbort) { + conn.multipvAbort.abort(); + } + const abort = new AbortController(); + conn.multipvAbort = abort; + conn.activeMultipvId = msg.requestId; + + const targetDepth = Math.min(18, Math.max(6, msg.depth ?? this.config.multipvDepth)); + const multiPv = Math.min(4, Math.max(1, msg.multiPv ?? 3)); + const reqFen = msg.fen; + const reqId = msg.requestId; + + let lastSentAt = 0; + this.stockfish + .analyzePositionMultiPv(reqFen, targetDepth, multiPv, abort.signal, (lines, curDepth) => { + if (abort.signal.aborted || conn.activeMultipvId !== reqId) return; + const now = Date.now(); + if (now - lastSentAt < 120) return; + lastSentAt = now; + this.send(conn, { + type: 'analysis:multipv_result', + requestId: reqId, + fen: reqFen, + depth: curDepth, + lines, + done: false + }); + }) + .then((finalLines) => { + if (abort.signal.aborted || conn.activeMultipvId !== reqId) return; + const maxDepth = finalLines.reduce((m, l) => Math.max(m, l.depth), targetDepth); + this.send(conn, { + type: 'analysis:multipv_result', + requestId: reqId, + fen: reqFen, + depth: maxDepth, + lines: finalLines, + done: true + }); + }) + .catch((err) => { + if (!abort.signal.aborted) { + this.sendError(conn, 'MULTIPV_ERROR', err instanceof Error ? err.message : 'Analysis error'); + } + }); + break; + } + + case 'analysis:multipv_stop': { + if (!msg.requestId || msg.requestId === conn.activeMultipvId) { + if (conn.multipvAbort) { + conn.multipvAbort.abort(); + conn.multipvAbort = null; + } + conn.activeMultipvId = null; + } + break; + } + } + } + + close(): void { + if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = null; + } + for (const conn of this.clients) { + try { + conn.ws.close(); + } catch { + // Ignore + } + } + this.wss.close(); + } +} diff --git a/src/shared/chess.ts b/src/shared/chess.ts new file mode 100644 index 0000000..c5d0bee --- /dev/null +++ b/src/shared/chess.ts @@ -0,0 +1,1370 @@ +import type { ChessMove, Color, GameResult, Piece, PieceType, PromotionPiece, TerminationReason } from './types'; + +export const INITIAL_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; + +export const FLAG_NORMAL = 0; +export const FLAG_CAPTURE = 1; +export const FLAG_EP = 2; +export const FLAG_PAWN_DOUBLE = 4; +export const FLAG_PROMO = 8; +export const FLAG_KCASTLE = 16; +export const FLAG_QCASTLE = 32; + +const FILES = 'abcdefgh'; +const RANKS = '87654321'; + +const KNIGHT_DELTAS: ReadonlyArray = [ + [-2, -1], + [-2, 1], + [-1, -2], + [-1, 2], + [1, -2], + [1, 2], + [2, -1], + [2, 1] +]; + +const KING_DELTAS: ReadonlyArray = [ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 1], + [1, -1], + [1, 0], + [1, 1] +]; + +const BISHOP_DIRS: ReadonlyArray = [ + [-1, -1], + [-1, 1], + [1, -1], + [1, 1] +]; + +const ROOK_DIRS: ReadonlyArray = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1] +]; + +const PROMO_PIECES: ReadonlyArray = ['q', 'r', 'b', 'n']; + +// Castling rights bits: wK=1, wQ=2, bK=4, bQ=8 +const CASTLING_MASK = new Uint8Array(64); +CASTLING_MASK.fill(15); +CASTLING_MASK[0] = 15 & ~8; // a8 +CASTLING_MASK[4] = 15 & ~12; // e8 +CASTLING_MASK[7] = 15 & ~4; // h8 +CASTLING_MASK[56] = 15 & ~2; // a1 +CASTLING_MASK[60] = 15 & ~3; // e1 +CASTLING_MASK[63] = 15 & ~1; // h1 + +export function sqToAlg(sq: number): string { + return FILES.charAt(sq & 7) + RANKS.charAt(sq >> 3); +} + +export function algToSq(alg: string): number { + if (alg.length !== 2) return -1; + const f = FILES.indexOf(alg.charAt(0)); + const r = RANKS.indexOf(alg.charAt(1)); + if (f < 0 || r < 0) return -1; + return (r << 3) | f; +} + +export function oppositeColor(c: Color): Color { + return c === 'w' ? 'b' : 'w'; +} + +interface RawMove { + from: number; + to: number; + piece: PieceType; + color: Color; + captured?: PieceType; + promotion?: PromotionPiece; + flags: number; +} + +interface UndoEntry { + move: ChessMove; + capturedPiece: Piece | null; + castling: number; + epSquare: number; + halfmoveClock: number; + fullmoveNumber: number; + kingSqW: number; + kingSqB: number; + repKey: string; +} + +export interface PgnParseResult { + headers: Record; + initialFen: string; + moves: ChessMove[]; + result: GameResult; + chess: Chess; +} + +export class Chess { + private squares: Array = new Array(64).fill(null); + private turnColor: Color = 'w'; + private castling = 15; + private epSquare = -1; + private halfmoveClock = 0; + private fullmoveNumber = 1; + private kingSqW = 60; + private kingSqB = 4; + private initialFenStr = INITIAL_FEN; + private undoStack: UndoEntry[] = []; + private repCounts = new Map(); + + constructor(fen?: string) { + this.loadFen(fen || INITIAL_FEN); + } + + clone(): Chess { + const copy = new Chess(this.initialFenStr); + for (let i = 0; i < this.undoStack.length; i++) { + const entry = this.undoStack[i]!; + copy.applyRawMoveAndRecord(entry.move); + } + return copy; + } + + loadFen(fen: string): void { + const parts = fen.trim().split(/\s+/); + if (parts.length < 4 || parts.length > 6) { + throw new Error('Invalid FEN: expected 4 to 6 space-separated fields'); + } + + const placement = parts[0]!; + const active = parts[1]!; + const castlingStr = parts[2]!; + const epStr = parts[3]!; + const halfStr = parts[4] !== undefined ? parts[4] : '0'; + const fullStr = parts[5] !== undefined ? parts[5] : '1'; + + const rows = placement.split('/'); + if (rows.length !== 8) { + throw new Error('Invalid FEN: board must have 8 ranks'); + } + + const nextSquares: Array = new Array(64).fill(null); + let wKings = 0; + let bKings = 0; + let wKingSq = -1; + let bKingSq = -1; + + for (let r = 0; r < 8; r++) { + const rowStr = rows[r]!; + let c = 0; + for (let i = 0; i < rowStr.length; i++) { + const ch = rowStr.charAt(i); + if (ch >= '1' && ch <= '8') { + c += parseInt(ch, 10); + } else { + const lower = ch.toLowerCase(); + if ( + lower !== 'p' && + lower !== 'n' && + lower !== 'b' && + lower !== 'r' && + lower !== 'q' && + lower !== 'k' + ) { + throw new Error(`Invalid FEN: unexpected piece character "${ch}"`); + } + if (c >= 8) { + throw new Error('Invalid FEN: rank has too many squares'); + } + const color: Color = ch === lower ? 'b' : 'w'; + const type = lower as PieceType; + if (type === 'p' && (r === 0 || r === 7)) { + throw new Error('Invalid FEN: pawn cannot be on rank 1 or 8'); + } + const sq = (r << 3) | c; + nextSquares[sq] = { color, type }; + if (type === 'k') { + if (color === 'w') { + wKings++; + wKingSq = sq; + } else { + bKings++; + bKingSq = sq; + } + } + c++; + } + } + if (c !== 8) { + throw new Error('Invalid FEN: rank does not sum to 8 squares'); + } + } + + if (wKings !== 1 || bKings !== 1) { + throw new Error('Invalid FEN: each side must have exactly one king'); + } + + if (active !== 'w' && active !== 'b') { + throw new Error('Invalid FEN: active color must be "w" or "b"'); + } + + let nextCastling = 0; + if (castlingStr !== '-') { + for (let i = 0; i < castlingStr.length; i++) { + const ch = castlingStr.charAt(i); + if (ch === 'K') nextCastling |= 1; + else if (ch === 'Q') nextCastling |= 2; + else if (ch === 'k') nextCastling |= 4; + else if (ch === 'q') nextCastling |= 8; + else throw new Error(`Invalid FEN: bad castling character "${ch}"`); + } + } + + let nextEp = -1; + if (epStr !== '-') { + nextEp = algToSq(epStr); + if (nextEp < 0) { + throw new Error(`Invalid FEN: bad en-passant square "${epStr}"`); + } + const epRow = nextEp >> 3; + if ((active === 'w' && epRow !== 2) || (active === 'b' && epRow !== 5)) { + throw new Error('Invalid FEN: en-passant square on invalid rank for side to move'); + } + } + + const halfmove = Number(halfStr); + const fullmove = Number(fullStr); + if (!Number.isInteger(halfmove) || halfmove < 0) { + throw new Error('Invalid FEN: halfmove clock must be a non-negative integer'); + } + if (!Number.isInteger(fullmove) || fullmove < 1) { + throw new Error('Invalid FEN: fullmove number must be >= 1'); + } + + // Validate castling rights against piece locations + if ((nextCastling & 1) && (wKingSq !== 60 || nextSquares[63]?.color !== 'w' || nextSquares[63]?.type !== 'r')) { + nextCastling &= ~1; + } + if ((nextCastling & 2) && (wKingSq !== 60 || nextSquares[56]?.color !== 'w' || nextSquares[56]?.type !== 'r')) { + nextCastling &= ~2; + } + if ((nextCastling & 4) && (bKingSq !== 4 || nextSquares[7]?.color !== 'b' || nextSquares[7]?.type !== 'r')) { + nextCastling &= ~4; + } + if ((nextCastling & 8) && (bKingSq !== 4 || nextSquares[0]?.color !== 'b' || nextSquares[0]?.type !== 'r')) { + nextCastling &= ~8; + } + + this.squares = nextSquares; + this.turnColor = active; + this.castling = nextCastling; + this.epSquare = nextEp; + this.halfmoveClock = halfmove; + this.fullmoveNumber = fullmove; + this.kingSqW = wKingSq; + this.kingSqB = bKingSq; + this.undoStack = []; + this.repCounts = new Map(); + + // Side NOT to move cannot already be in check + const passiveColor = oppositeColor(this.turnColor); + const passiveKingSq = passiveColor === 'w' ? this.kingSqW : this.kingSqB; + if (this.isSquareAttacked(passiveKingSq, this.turnColor)) { + throw new Error('Invalid FEN: non-active king is in check'); + } + + this.initialFenStr = this.fen(); + const key = this.positionKey(); + this.repCounts.set(key, 1); + } + + fen(): string { + const rows: string[] = []; + for (let r = 0; r < 8; r++) { + let rowStr = ''; + let empty = 0; + for (let c = 0; c < 8; c++) { + const p = this.squares[(r << 3) | c]; + if (!p) { + empty++; + } else { + if (empty > 0) { + rowStr += String(empty); + empty = 0; + } + rowStr += p.color === 'w' ? p.type.toUpperCase() : p.type; + } + } + if (empty > 0) rowStr += String(empty); + rows.push(rowStr); + } + + let castle = ''; + if (this.castling & 1) castle += 'K'; + if (this.castling & 2) castle += 'Q'; + if (this.castling & 4) castle += 'k'; + if (this.castling & 8) castle += 'q'; + if (castle === '') castle = '-'; + + const ep = this.epSquare >= 0 ? sqToAlg(this.epSquare) : '-'; + return `${rows.join('/')} ${this.turnColor} ${castle} ${ep} ${this.halfmoveClock} ${this.fullmoveNumber}`; + } + + initialFen(): string { + return this.initialFenStr; + } + + turn(): Color { + return this.turnColor; + } + + get(sq: number): Piece | null { + if (sq < 0 || sq >= 64) return null; + return this.squares[sq] ?? null; + } + + board(): Array { + return this.squares.slice(); + } + + kingSquare(color: Color): number { + return color === 'w' ? this.kingSqW : this.kingSqB; + } + + halfmove(): number { + return this.halfmoveClock; + } + + fullmove(): number { + return this.fullmoveNumber; + } + + history(): ChessMove[] { + return this.undoStack.map((u) => u.move); + } + + ply(): number { + return this.undoStack.length; + } + + isSquareAttacked(sq: number, byColor: Color): boolean { + const r = sq >> 3; + const c = sq & 7; + + // Pawns + if (byColor === 'w') { + if (r + 1 < 8) { + if (c - 1 >= 0) { + const p = this.squares[((r + 1) << 3) | (c - 1)]; + if (p && p.color === 'w' && p.type === 'p') return true; + } + if (c + 1 < 8) { + const p = this.squares[((r + 1) << 3) | (c + 1)]; + if (p && p.color === 'w' && p.type === 'p') return true; + } + } + } else { + if (r - 1 >= 0) { + if (c - 1 >= 0) { + const p = this.squares[((r - 1) << 3) | (c - 1)]; + if (p && p.color === 'b' && p.type === 'p') return true; + } + if (c + 1 < 8) { + const p = this.squares[((r - 1) << 3) | (c + 1)]; + if (p && p.color === 'b' && p.type === 'p') return true; + } + } + } + + // Knights + for (let i = 0; i < KNIGHT_DELTAS.length; i++) { + const d = KNIGHT_DELTAS[i]!; + const nr = r + d[0]; + const nc = c + d[1]; + if (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) { + const p = this.squares[(nr << 3) | nc]; + if (p && p.color === byColor && p.type === 'n') return true; + } + } + + // King + for (let i = 0; i < KING_DELTAS.length; i++) { + const d = KING_DELTAS[i]!; + const nr = r + d[0]; + const nc = c + d[1]; + if (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) { + const p = this.squares[(nr << 3) | nc]; + if (p && p.color === byColor && p.type === 'k') return true; + } + } + + // Diagonals (Bishop / Queen) + for (let i = 0; i < BISHOP_DIRS.length; i++) { + const d = BISHOP_DIRS[i]!; + let nr = r + d[0]; + let nc = c + d[1]; + while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) { + const p = this.squares[(nr << 3) | nc]; + if (p) { + if (p.color === byColor && (p.type === 'b' || p.type === 'q')) return true; + break; + } + nr += d[0]; + nc += d[1]; + } + } + + // Orthogonals (Rook / Queen) + for (let i = 0; i < ROOK_DIRS.length; i++) { + const d = ROOK_DIRS[i]!; + let nr = r + d[0]; + let nc = c + d[1]; + while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) { + const p = this.squares[(nr << 3) | nc]; + if (p) { + if (p.color === byColor && (p.type === 'r' || p.type === 'q')) return true; + break; + } + nr += d[0]; + nc += d[1]; + } + } + + return false; + } + + inCheck(): boolean { + const kSq = this.turnColor === 'w' ? this.kingSqW : this.kingSqB; + return this.isSquareAttacked(kSq, oppositeColor(this.turnColor)); + } + + private generatePseudoMoves(fromFilter?: number): RawMove[] { + const moves: RawMove[] = []; + const us = this.turnColor; + const them = oppositeColor(us); + + const startSq = fromFilter !== undefined ? fromFilter : 0; + const endSq = fromFilter !== undefined ? fromFilter : 63; + + for (let sq = startSq; sq <= endSq; sq++) { + const p = this.squares[sq]; + if (!p || p.color !== us) continue; + + const r = sq >> 3; + const c = sq & 7; + + if (p.type === 'p') { + const dir = us === 'w' ? -1 : 1; + const startRank = us === 'w' ? 6 : 1; + const promoRank = us === 'w' ? 0 : 7; + const nextR = r + dir; + + if (nextR >= 0 && nextR < 8) { + const oneSq = (nextR << 3) | c; + if (!this.squares[oneSq]) { + if (nextR === promoRank) { + for (let pi = 0; pi < PROMO_PIECES.length; pi++) { + moves.push({ + from: sq, + to: oneSq, + piece: 'p', + color: us, + promotion: PROMO_PIECES[pi], + flags: FLAG_PROMO + }); + } + } else { + moves.push({ from: sq, to: oneSq, piece: 'p', color: us, flags: FLAG_NORMAL }); + if (r === startRank) { + const twoSq = ((r + dir * 2) << 3) | c; + if (!this.squares[twoSq]) { + moves.push({ from: sq, to: twoSq, piece: 'p', color: us, flags: FLAG_PAWN_DOUBLE }); + } + } + } + } + + // Pawn captures + for (let dc = -1; dc <= 1; dc += 2) { + const nc = c + dc; + if (nc < 0 || nc >= 8) continue; + const capSq = (nextR << 3) | nc; + const target = this.squares[capSq]; + if (target && target.color === them) { + if (nextR === promoRank) { + for (let pi = 0; pi < PROMO_PIECES.length; pi++) { + moves.push({ + from: sq, + to: capSq, + piece: 'p', + color: us, + captured: target.type, + promotion: PROMO_PIECES[pi], + flags: FLAG_CAPTURE | FLAG_PROMO + }); + } + } else { + moves.push({ + from: sq, + to: capSq, + piece: 'p', + color: us, + captured: target.type, + flags: FLAG_CAPTURE + }); + } + } else if (capSq === this.epSquare) { + moves.push({ + from: sq, + to: capSq, + piece: 'p', + color: us, + captured: 'p', + flags: FLAG_CAPTURE | FLAG_EP + }); + } + } + } + } else if (p.type === 'n') { + for (let i = 0; i < KNIGHT_DELTAS.length; i++) { + const d = KNIGHT_DELTAS[i]!; + const nr = r + d[0]; + const nc = c + d[1]; + if (nr < 0 || nr >= 8 || nc < 0 || nc >= 8) continue; + const to = (nr << 3) | nc; + const target = this.squares[to]; + if (!target) { + moves.push({ from: sq, to, piece: 'n', color: us, flags: FLAG_NORMAL }); + } else if (target.color === them) { + moves.push({ from: sq, to, piece: 'n', color: us, captured: target.type, flags: FLAG_CAPTURE }); + } + } + } else if (p.type === 'k') { + for (let i = 0; i < KING_DELTAS.length; i++) { + const d = KING_DELTAS[i]!; + const nr = r + d[0]; + const nc = c + d[1]; + if (nr < 0 || nr >= 8 || nc < 0 || nc >= 8) continue; + const to = (nr << 3) | nc; + const target = this.squares[to]; + if (!target) { + moves.push({ from: sq, to, piece: 'k', color: us, flags: FLAG_NORMAL }); + } else if (target.color === them) { + moves.push({ from: sq, to, piece: 'k', color: us, captured: target.type, flags: FLAG_CAPTURE }); + } + } + + // Castling + if (us === 'w' && sq === 60) { + if ( + (this.castling & 1) && + !this.squares[61] && + !this.squares[62] && + this.squares[63]?.color === 'w' && + this.squares[63]?.type === 'r' && + !this.isSquareAttacked(60, 'b') && + !this.isSquareAttacked(61, 'b') && + !this.isSquareAttacked(62, 'b') + ) { + moves.push({ from: 60, to: 62, piece: 'k', color: 'w', flags: FLAG_KCASTLE }); + } + if ( + (this.castling & 2) && + !this.squares[59] && + !this.squares[58] && + !this.squares[57] && + this.squares[56]?.color === 'w' && + this.squares[56]?.type === 'r' && + !this.isSquareAttacked(60, 'b') && + !this.isSquareAttacked(59, 'b') && + !this.isSquareAttacked(58, 'b') + ) { + moves.push({ from: 60, to: 58, piece: 'k', color: 'w', flags: FLAG_QCASTLE }); + } + } else if (us === 'b' && sq === 4) { + if ( + (this.castling & 4) && + !this.squares[5] && + !this.squares[6] && + this.squares[7]?.color === 'b' && + this.squares[7]?.type === 'r' && + !this.isSquareAttacked(4, 'w') && + !this.isSquareAttacked(5, 'w') && + !this.isSquareAttacked(6, 'w') + ) { + moves.push({ from: 4, to: 6, piece: 'k', color: 'b', flags: FLAG_KCASTLE }); + } + if ( + (this.castling & 8) && + !this.squares[3] && + !this.squares[2] && + !this.squares[1] && + this.squares[0]?.color === 'b' && + this.squares[0]?.type === 'r' && + !this.isSquareAttacked(4, 'w') && + !this.isSquareAttacked(3, 'w') && + !this.isSquareAttacked(2, 'w') + ) { + moves.push({ from: 4, to: 2, piece: 'k', color: 'b', flags: FLAG_QCASTLE }); + } + } + } else { + const dirs = + p.type === 'b' + ? BISHOP_DIRS + : p.type === 'r' + ? ROOK_DIRS + : BISHOP_DIRS.concat(ROOK_DIRS); + for (let di = 0; di < dirs.length; di++) { + const d = dirs[di]!; + let nr = r + d[0]; + let nc = c + d[1]; + while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) { + const to = (nr << 3) | nc; + const target = this.squares[to]; + if (!target) { + moves.push({ from: sq, to, piece: p.type, color: us, flags: FLAG_NORMAL }); + } else { + if (target.color === them) { + moves.push({ + from: sq, + to, + piece: p.type, + color: us, + captured: target.type, + flags: FLAG_CAPTURE + }); + } + break; + } + nr += d[0]; + nc += d[1]; + } + } + } + } + + return moves; + } + + private isMoveLegal(m: RawMove): boolean { + const us = m.color; + const them = oppositeColor(us); + + const origFrom = this.squares[m.from]!; + const origTo = this.squares[m.to]!; + let epCapSq = -1; + let origEpCap: Piece | null = null; + + this.squares[m.from] = null; + this.squares[m.to] = m.promotion ? { color: us, type: m.promotion } : origFrom; + + if (m.flags & FLAG_EP) { + epCapSq = us === 'w' ? m.to + 8 : m.to - 8; + origEpCap = this.squares[epCapSq]!; + this.squares[epCapSq] = null; + } + + let kingSq = us === 'w' ? this.kingSqW : this.kingSqB; + if (m.piece === 'k') { + kingSq = m.to; + } + + const safe = !this.isSquareAttacked(kingSq, them); + + // Unmake + this.squares[m.from] = origFrom; + this.squares[m.to] = origTo; + if (epCapSq >= 0) { + this.squares[epCapSq] = origEpCap; + } + + return safe; + } + + private rawLegalMoves(fromFilter?: number): RawMove[] { + const pseudo = this.generatePseudoMoves(fromFilter); + const legal: RawMove[] = []; + for (let i = 0; i < pseudo.length; i++) { + const m = pseudo[i]!; + if (this.isMoveLegal(m)) { + legal.push(m); + } + } + return legal; + } + + private hasAnyLegalMove(): boolean { + const pseudo = this.generatePseudoMoves(); + for (let i = 0; i < pseudo.length; i++) { + if (this.isMoveLegal(pseudo[i]!)) return true; + } + return false; + } + + private hasLegalEpCapture(): boolean { + if (this.epSquare < 0) return false; + const us = this.turnColor; + const r = this.epSquare >> 3; + const c = this.epSquare & 7; + const pawnRow = us === 'w' ? r + 1 : r - 1; + if (pawnRow < 0 || pawnRow >= 8) return false; + + for (let dc = -1; dc <= 1; dc += 2) { + const nc = c + dc; + if (nc < 0 || nc >= 8) continue; + const fromSq = (pawnRow << 3) | nc; + const p = this.squares[fromSq]; + if (p && p.color === us && p.type === 'p') { + if ( + this.isMoveLegal({ + from: fromSq, + to: this.epSquare, + piece: 'p', + color: us, + captured: 'p', + flags: FLAG_CAPTURE | FLAG_EP + }) + ) { + return true; + } + } + } + return false; + } + + private positionKey(): string { + let boardStr = ''; + for (let i = 0; i < 64; i++) { + const p = this.squares[i]; + if (!p) { + boardStr += '.'; + } else { + boardStr += p.color === 'w' ? p.type.toUpperCase() : p.type; + } + } + const effEp = this.hasLegalEpCapture() ? this.epSquare : -1; + return `${boardStr}|${this.turnColor}|${this.castling}|${effEp}`; + } + + private formatUci(m: RawMove): string { + return sqToAlg(m.from) + sqToAlg(m.to) + (m.promotion ? m.promotion : ''); + } + + private formatSan(m: RawMove, allLegal: ReadonlyArray): string { + let base = ''; + if (m.flags & FLAG_KCASTLE) { + base = 'O-O'; + } else if (m.flags & FLAG_QCASTLE) { + base = 'O-O-O'; + } else if (m.piece === 'p') { + if (m.flags & FLAG_CAPTURE) { + base = `${FILES.charAt(m.from & 7)}x${sqToAlg(m.to)}`; + } else { + base = sqToAlg(m.to); + } + if (m.promotion) { + base += `=${m.promotion.toUpperCase()}`; + } + } else { + const pieceLetter = m.piece.toUpperCase(); + let sameFile = false; + let sameRank = false; + let conflict = false; + const fromCol = m.from & 7; + const fromRow = m.from >> 3; + + for (let i = 0; i < allLegal.length; i++) { + const other = allLegal[i]!; + if (other.from !== m.from && other.to === m.to && other.piece === m.piece) { + conflict = true; + if ((other.from & 7) === fromCol) sameFile = true; + if ((other.from >> 3) === fromRow) sameRank = true; + } + } + + let disambig = ''; + if (conflict) { + if (!sameFile) { + disambig = FILES.charAt(fromCol); + } else if (!sameRank) { + disambig = RANKS.charAt(fromRow); + } else { + disambig = sqToAlg(m.from); + } + } + + const cap = m.flags & FLAG_CAPTURE ? 'x' : ''; + base = `${pieceLetter}${disambig}${cap}${sqToAlg(m.to)}`; + } + + // Temporarily execute move to detect check / checkmate + const snap = this.pushTempRaw(m); + const enemyInCheck = this.inCheck(); + let suffix = ''; + if (enemyInCheck) { + suffix = this.hasAnyLegalMove() ? '+' : '#'; + } + this.popTempRaw(snap); + + return base + suffix; + } + + private pushTempRaw(m: RawMove) { + const prevTurn = this.turnColor; + const prevCastling = this.castling; + const prevEp = this.epSquare; + const prevKW = this.kingSqW; + const prevKB = this.kingSqB; + const fromPiece = this.squares[m.from]!; + const toPiece = this.squares[m.to]!; + let epCapSq = -1; + let epCapPiece: Piece | null = null; + let rookFrom = -1; + let rookTo = -1; + + this.squares[m.from] = null; + this.squares[m.to] = m.promotion ? { color: m.color, type: m.promotion } : fromPiece; + + if (m.flags & FLAG_EP) { + epCapSq = m.color === 'w' ? m.to + 8 : m.to - 8; + epCapPiece = this.squares[epCapSq]!; + this.squares[epCapSq] = null; + } else if (m.flags & FLAG_KCASTLE) { + rookFrom = m.color === 'w' ? 63 : 7; + rookTo = m.color === 'w' ? 61 : 5; + this.squares[rookTo] = this.squares[rookFrom]!; + this.squares[rookFrom] = null; + } else if (m.flags & FLAG_QCASTLE) { + rookFrom = m.color === 'w' ? 56 : 0; + rookTo = m.color === 'w' ? 59 : 3; + this.squares[rookTo] = this.squares[rookFrom]!; + this.squares[rookFrom] = null; + } + + if (m.piece === 'k') { + if (m.color === 'w') this.kingSqW = m.to; + else this.kingSqB = m.to; + } + + this.castling &= CASTLING_MASK[m.from]! & CASTLING_MASK[m.to]!; + this.epSquare = m.flags & FLAG_PAWN_DOUBLE ? (m.from + m.to) >> 1 : -1; + this.turnColor = oppositeColor(m.color); + + return { + m, + fromPiece, + toPiece, + epCapSq, + epCapPiece, + rookFrom, + rookTo, + prevTurn, + prevCastling, + prevEp, + prevKW, + prevKB + }; + } + + private popTempRaw(s: ReturnType): void { + this.turnColor = s.prevTurn; + this.castling = s.prevCastling; + this.epSquare = s.prevEp; + this.kingSqW = s.prevKW; + this.kingSqB = s.prevKB; + + this.squares[s.m.from] = s.fromPiece; + this.squares[s.m.to] = s.toPiece; + + if (s.epCapSq >= 0) { + this.squares[s.epCapSq] = s.epCapPiece; + } + if (s.rookFrom >= 0) { + this.squares[s.rookFrom] = this.squares[s.rookTo]!; + this.squares[s.rookTo] = null; + } + } + + legalMoves(fromSq?: number): ChessMove[] { + const allLegal = this.rawLegalMoves(); + const filtered = fromSq !== undefined ? allLegal.filter((m) => m.from === fromSq) : allLegal; + return filtered.map((m) => ({ + from: m.from, + to: m.to, + piece: m.piece, + color: m.color, + captured: m.captured, + promotion: m.promotion, + flags: m.flags, + san: this.formatSan(m, allLegal), + uci: this.formatUci(m) + })); + } + + private applyRawMoveAndRecord(m: RawMove, precomputedSan?: string): ChessMove { + const allLegal = precomputedSan ? [] : this.rawLegalMoves(); + const san = precomputedSan || this.formatSan(m, allLegal); + const uci = this.formatUci(m); + + const moveObj: ChessMove = { + from: m.from, + to: m.to, + piece: m.piece, + color: m.color, + captured: m.captured, + promotion: m.promotion, + flags: m.flags, + san, + uci + }; + + const prevCastling = this.castling; + const prevEp = this.epSquare; + const prevHalf = this.halfmoveClock; + const prevFull = this.fullmoveNumber; + const prevKW = this.kingSqW; + const prevKB = this.kingSqB; + + const fromPiece = this.squares[m.from]!; + let capturedPiece: Piece | null = this.squares[m.to]!; + + this.squares[m.from] = null; + this.squares[m.to] = m.promotion ? { color: m.color, type: m.promotion } : fromPiece; + + if (m.flags & FLAG_EP) { + const capSq = m.color === 'w' ? m.to + 8 : m.to - 8; + capturedPiece = this.squares[capSq]!; + this.squares[capSq] = null; + } else if (m.flags & FLAG_KCASTLE) { + const rookFrom = m.color === 'w' ? 63 : 7; + const rookTo = m.color === 'w' ? 61 : 5; + this.squares[rookTo] = this.squares[rookFrom]!; + this.squares[rookFrom] = null; + } else if (m.flags & FLAG_QCASTLE) { + const rookFrom = m.color === 'w' ? 56 : 0; + const rookTo = m.color === 'w' ? 59 : 3; + this.squares[rookTo] = this.squares[rookFrom]!; + this.squares[rookFrom] = null; + } + + if (m.piece === 'k') { + if (m.color === 'w') this.kingSqW = m.to; + else this.kingSqB = m.to; + } + + this.castling &= CASTLING_MASK[m.from]! & CASTLING_MASK[m.to]!; + this.epSquare = m.flags & FLAG_PAWN_DOUBLE ? (m.from + m.to) >> 1 : -1; + + if (m.piece === 'p' || (m.flags & FLAG_CAPTURE)) { + this.halfmoveClock = 0; + } else { + this.halfmoveClock++; + } + + if (m.color === 'b') { + this.fullmoveNumber++; + } + + this.turnColor = oppositeColor(m.color); + + const repKey = this.positionKey(); + this.repCounts.set(repKey, (this.repCounts.get(repKey) ?? 0) + 1); + + this.undoStack.push({ + move: moveObj, + capturedPiece, + castling: prevCastling, + epSquare: prevEp, + halfmoveClock: prevHalf, + fullmoveNumber: prevFull, + kingSqW: prevKW, + kingSqB: prevKB, + repKey + }); + + return moveObj; + } + + moveUci(uci: string): ChessMove | null { + const clean = uci.trim().toLowerCase(); + if (clean.length < 4 || clean.length > 5) return null; + const from = algToSq(clean.slice(0, 2)); + const to = algToSq(clean.slice(2, 4)); + if (from < 0 || to < 0) return null; + const promo = clean.length === 5 ? (clean.charAt(4) as PromotionPiece) : undefined; + + const candidates = this.rawLegalMoves(from); + for (let i = 0; i < candidates.length; i++) { + const m = candidates[i]!; + if (m.to === to && m.promotion === promo) { + return this.applyRawMoveAndRecord(m); + } + } + return null; + } + + moveSan(sanInput: string): ChessMove | null { + const clean = sanInput + .trim() + .replace(/[+#?!]+$/g, '') + .replace(/^0-0-0$/, 'O-O-O') + .replace(/^0-0$/, 'O-O'); + + const legal = this.legalMoves(); + for (let i = 0; i < legal.length; i++) { + const m = legal[i]!; + const mClean = m.san.replace(/[+#?!]+$/g, ''); + if (mClean === clean) { + return this.applyRawMoveAndRecord(m, m.san); + } + } + + // Fallback: relax 'x' or '=' formatting in sloppy SAN + const normalizedInput = clean.replace(/x/g, '').replace(/=/g, ''); + for (let i = 0; i < legal.length; i++) { + const m = legal[i]!; + const mNorm = m.san.replace(/[+#?!x=]+/g, ''); + if (mNorm === normalizedInput) { + return this.applyRawMoveAndRecord(m, m.san); + } + } + + return null; + } + + makeMove(move: Pick): ChessMove | null { + const candidates = this.rawLegalMoves(move.from); + for (let i = 0; i < candidates.length; i++) { + const m = candidates[i]!; + if (m.to === move.to && m.promotion === move.promotion) { + return this.applyRawMoveAndRecord(m); + } + } + return null; + } + + undo(): ChessMove | null { + const entry = this.undoStack.pop(); + if (!entry) return null; + + const count = this.repCounts.get(entry.repKey) ?? 1; + if (count <= 1) { + this.repCounts.delete(entry.repKey); + } else { + this.repCounts.set(entry.repKey, count - 1); + } + + const m = entry.move; + this.turnColor = m.color; + this.castling = entry.castling; + this.epSquare = entry.epSquare; + this.halfmoveClock = entry.halfmoveClock; + this.fullmoveNumber = entry.fullmoveNumber; + this.kingSqW = entry.kingSqW; + this.kingSqB = entry.kingSqB; + + this.squares[m.from] = { color: m.color, type: m.piece }; + + if (m.flags & FLAG_EP) { + this.squares[m.to] = null; + const capSq = m.color === 'w' ? m.to + 8 : m.to - 8; + this.squares[capSq] = entry.capturedPiece; + } else { + this.squares[m.to] = entry.capturedPiece; + if (m.flags & FLAG_KCASTLE) { + const rookFrom = m.color === 'w' ? 63 : 7; + const rookTo = m.color === 'w' ? 61 : 5; + this.squares[rookFrom] = this.squares[rookTo]!; + this.squares[rookTo] = null; + } else if (m.flags & FLAG_QCASTLE) { + const rookFrom = m.color === 'w' ? 56 : 0; + const rookTo = m.color === 'w' ? 59 : 3; + this.squares[rookFrom] = this.squares[rookTo]!; + this.squares[rookTo] = null; + } + } + + return m; + } + + isCheckmate(): boolean { + return this.inCheck() && !this.hasAnyLegalMove(); + } + + isStalemate(): boolean { + return !this.inCheck() && !this.hasAnyLegalMove(); + } + + isInsufficientMaterial(): boolean { + let wMinors = 0; + let bMinors = 0; + let wBishopColor = -1; + let bBishopColor = -1; + let wBishops = 0; + let bBishops = 0; + + for (let sq = 0; sq < 64; sq++) { + const p = this.squares[sq]; + if (!p || p.type === 'k') continue; + if (p.type === 'p' || p.type === 'r' || p.type === 'q') { + return false; + } + if (p.color === 'w') { + wMinors++; + if (p.type === 'b') { + wBishops++; + wBishopColor = ((sq >> 3) + (sq & 7)) & 1; + } + } else { + bMinors++; + if (p.type === 'b') { + bBishops++; + bBishopColor = ((sq >> 3) + (sq & 7)) & 1; + } + } + } + + if (wMinors === 0 && bMinors === 0) return true; + if ((wMinors === 1 && bMinors === 0) || (bMinors === 1 && wMinors === 0)) return true; + if (wMinors === 1 && bMinors === 1 && wBishops === 1 && bBishops === 1 && wBishopColor === bBishopColor) { + return true; + } + return false; + } + + hasInsufficientMatingMaterial(color: Color): boolean { + let minors = 0; + let knights = 0; + let bishops = 0; + for (let sq = 0; sq < 64; sq++) { + const p = this.squares[sq]; + if (!p || p.color !== color || p.type === 'k') continue; + if (p.type === 'p' || p.type === 'r' || p.type === 'q') return false; + minors++; + if (p.type === 'n') knights++; + if (p.type === 'b') bishops++; + } + // Single knight or single bishop alone cannot force checkmate (conservatively K+N or K+B vs arbitrary) + // Wait: technically K+B vs K+N can mate in a corner! Only bare K cannot win under FIDE rules, + // OR K+N / K+B when opponent also has no pawns/pieces. Keep standard simple check: bare king or K+single minor vs bare king. + if (minors === 0) return true; + if (minors === 1 && (knights === 1 || bishops === 1)) { + // Check if opponent has anything besides king + const opp = oppositeColor(color); + for (let sq = 0; sq < 64; sq++) { + const p = this.squares[sq]; + if (p && p.color === opp && p.type !== 'k') return false; + } + return true; + } + return false; + } + + isFiftyMoveDraw(): boolean { + return this.halfmoveClock >= 100; + } + + isThreefoldRepetition(): boolean { + const key = this.positionKey(); + return (this.repCounts.get(key) ?? 0) >= 3; + } + + gameOutcome(): { result: GameResult; termination: TerminationReason } | null { + if (!this.hasAnyLegalMove()) { + if (this.inCheck()) { + return { + result: this.turnColor === 'w' ? '0-1' : '1-0', + termination: 'checkmate' + }; + } + return { + result: '1/2-1/2', + termination: 'stalemate' + }; + } + if (this.isInsufficientMaterial()) { + return { result: '1/2-1/2', termination: 'insufficient_material' }; + } + if (this.isFiftyMoveDraw()) { + return { result: '1/2-1/2', termination: 'fifty_move' }; + } + if (this.isThreefoldRepetition()) { + return { result: '1/2-1/2', termination: 'repetition' }; + } + return null; + } + + isGameOver(): boolean { + return this.gameOutcome() !== null; + } + + perft(depth: number): number { + if (depth <= 0) return 1; + const moves = this.rawLegalMoves(); + if (depth === 1) return moves.length; + let nodes = 0; + for (let i = 0; i < moves.length; i++) { + const snap = this.pushTempRaw(moves[i]!); + nodes += this.perft(depth - 1); + this.popTempRaw(snap); + } + return nodes; + } + + toPgn(headers: Record = {}): string { + const defaultHeaders: Record = { + Event: headers['Event'] || 'ChessUp Game', + Site: headers['Site'] || 'ChessUp', + Date: headers['Date'] || new Date().toISOString().slice(0, 10).replace(/-/g, '.'), + Round: headers['Round'] || '-', + White: headers['White'] || 'White', + Black: headers['Black'] || 'Black', + Result: headers['Result'] || '*' + }; + + const merged: Record = { ...defaultHeaders, ...headers }; + if (this.initialFenStr !== INITIAL_FEN && !merged['FEN']) { + merged['SetUp'] = '1'; + merged['FEN'] = this.initialFenStr; + } + + const orderedKeys = ['Event', 'Site', 'Date', 'Round', 'White', 'Black', 'Result']; + const headerLines: string[] = []; + for (const k of orderedKeys) { + headerLines.push(`[${k} "${(merged[k] || '').replace(/"/g, '\\"')}"]`); + } + for (const k of Object.keys(merged)) { + if (orderedKeys.indexOf(k) === -1 && merged[k] !== undefined) { + headerLines.push(`[${k} "${merged[k]!.replace(/"/g, '\\"')}"]`); + } + } + + // Reconstruct move numbers from initial FEN + const temp = new Chess(this.initialFenStr); + let moveNum = temp.fullmoveNumber; + let startsBlack = temp.turnColor === 'b'; + const tokens: string[] = []; + + for (let i = 0; i < this.undoStack.length; i++) { + const move = this.undoStack[i]!.move; + if (i === 0 && startsBlack) { + tokens.push(`${moveNum}...`); + tokens.push(move.san); + moveNum++; + } else if (move.color === 'w') { + tokens.push(`${moveNum}.`); + tokens.push(move.san); + } else { + tokens.push(move.san); + moveNum++; + } + } + + const resultToken = merged['Result'] || '*'; + tokens.push(resultToken); + + return `${headerLines.join('\n')}\n\n${tokens.join(' ')}`; + } + + static fromPgn(pgnText: string): PgnParseResult { + const headers: Record = {}; + let i = 0; + const len = pgnText.length; + + // Strip BOM if present + if (len > 0 && pgnText.charCodeAt(0) === 0xfeff) i = 1; + + // Parse headers & movetext cleanly + const headerRegex = /\[([A-Za-z0-9_]+)\s+"((?:\\.|[^"\\])*)"\]/g; + let lastHeaderEnd = 0; + let match: RegExpExecArray | null; + while ((match = headerRegex.exec(pgnText)) !== null) { + headers[match[1]!] = match[2]!.replace(/\\"/g, '"').replace(/\\\\/g, '\\'); + lastHeaderEnd = headerRegex.lastIndex; + } + + const moveText = pgnText.slice(lastHeaderEnd); + + // Strip comments {}, ;..., variations (...), and NAGs $N + let cleaned = ''; + let parenDepth = 0; + let inBrace = false; + let inLineComment = false; + + for (i = 0; i < moveText.length; i++) { + const ch = moveText.charAt(i); + if (inLineComment) { + if (ch === '\n' || ch === '\r') inLineComment = false; + continue; + } + if (inBrace) { + if (ch === '}') inBrace = false; + continue; + } + if (ch === '{') { + inBrace = true; + cleaned += ' '; + continue; + } + if (ch === ';') { + inLineComment = true; + cleaned += ' '; + continue; + } + if (ch === '(') { + parenDepth++; + cleaned += ' '; + continue; + } + if (ch === ')') { + if (parenDepth > 0) parenDepth--; + cleaned += ' '; + continue; + } + if (parenDepth === 0) { + cleaned += ch; + } + } + + const initialFen = headers['FEN'] || INITIAL_FEN; + const chess = new Chess(initialFen); + const moves: ChessMove[] = []; + let result: GameResult = (headers['Result'] as GameResult) || '*'; + + const rawTokens = cleaned.trim().split(/\s+/).filter(Boolean); + for (let t = 0; t < rawTokens.length; t++) { + let tok = rawTokens[t]!; + if (tok.startsWith('$')) continue; + if (tok === '1-0' || tok === '0-1' || tok === '1/2-1/2' || tok === '*') { + result = tok; + break; + } + // Strip leading move numbers like "1." or "12..." + tok = tok.replace(/^\d+\.{1,3}/, ''); + if (!tok || /^\d+$/.test(tok) || /^\.+$/.test(tok)) continue; + + const mv = chess.moveSan(tok); + if (!mv) { + throw new Error(`Invalid PGN move "${tok}" at ply ${moves.length + 1}`); + } + moves.push(mv); + } + + if (result === '*') { + const outcome = chess.gameOutcome(); + if (outcome) result = outcome.result; + } + + return { + headers, + initialFen, + moves, + result, + chess + }; + } +} diff --git a/src/shared/timeControl.ts b/src/shared/timeControl.ts new file mode 100644 index 0000000..9b40b8b --- /dev/null +++ b/src/shared/timeControl.ts @@ -0,0 +1,96 @@ +import type { BotLevelConfig, RatedCategory, TimeCategory, TimeControl } from './types'; + +export const TIME_PRESETS: ReadonlyArray<{ label: string; initialMs: number; incrementMs: number }> = [ + { label: '1+0', initialMs: 60_000, incrementMs: 0 }, + { label: '2+1', initialMs: 120_000, incrementMs: 1_000 }, + { label: '3+0', initialMs: 180_000, incrementMs: 0 }, + { label: '3+2', initialMs: 180_000, incrementMs: 2_000 }, + { label: '5+0', initialMs: 300_000, incrementMs: 0 }, + { label: '5+3', initialMs: 300_000, incrementMs: 3_000 }, + { label: '10+0', initialMs: 600_000, incrementMs: 0 }, + { label: '10+5', initialMs: 600_000, incrementMs: 5_000 }, + { label: '15+10', initialMs: 900_000, incrementMs: 10_000 }, + { label: '30+0', initialMs: 1_800_000, incrementMs: 0 }, + { label: 'Unlimited', initialMs: 0, incrementMs: 0 } +]; + +export const RATED_CATEGORIES: ReadonlyArray = ['bullet', 'blitz', 'rapid', 'classical']; + +export const BOT_LEVELS: ReadonlyArray = [ + { level: 1, name: 'Stockfish Lv 1', approxElo: 800, description: 'Beginner — misses tactics and drops material' }, + { level: 2, name: 'Stockfish Lv 2', approxElo: 1100, description: 'Casual — spots simple captures, plays loosely' }, + { level: 3, name: 'Stockfish Lv 3', approxElo: 1350, description: 'Club novice — basic tactics and development' }, + { level: 4, name: 'Stockfish Lv 4', approxElo: 1600, description: 'Intermediate — solid positional and tactical play' }, + { level: 5, name: 'Stockfish Lv 5', approxElo: 1850, description: 'Strong club — punishes inaccuracies consistently' }, + { level: 6, name: 'Stockfish Lv 6', approxElo: 2100, description: 'Expert — deep tactical awareness and clean endgames' }, + { level: 7, name: 'Stockfish Lv 7', approxElo: 2400, description: 'Master — relentless pressure and calculation' }, + { level: 8, name: 'Stockfish Lv 8', approxElo: 2800, description: 'Grandmaster — full-strength Stockfish engine' } +]; + +export function classifyTimeControl(initialMs: number, incrementMs: number): TimeCategory { + if (initialMs <= 0 && incrementMs <= 0) { + return 'unlimited'; + } + const estimatedSec = Math.max(0, initialMs) / 1000 + 40 * (Math.max(0, incrementMs) / 1000); + if (estimatedSec < 180) return 'bullet'; + if (estimatedSec < 480) return 'blitz'; + if (estimatedSec < 1500) return 'rapid'; + return 'classical'; +} + +export function buildTimeControl(initialMs: number, incrementMs: number): TimeControl { + const safeInitial = Math.max(0, Math.floor(initialMs)); + const safeIncrement = Math.max(0, Math.floor(incrementMs)); + return { + initialMs: safeInitial, + incrementMs: safeIncrement, + category: classifyTimeControl(safeInitial, safeIncrement) + }; +} + +export function formatTimeControl(initialMs: number, incrementMs: number): string { + if (initialMs <= 0 && incrementMs <= 0) { + return 'Unlimited'; + } + const initSec = Math.round(initialMs / 1000); + const incSec = Math.round(incrementMs / 1000); + if (initSec < 60 && initSec % 60 !== 0) { + return `${initSec}s+${incSec}`; + } + const mins = initSec / 60; + const minLabel = Number.isInteger(mins) ? String(mins) : mins.toFixed(1); + return `${minLabel}+${incSec}`; +} + +export function formatClock(ms: number): string { + const clamped = Math.max(0, ms); + if (clamped < 10_000) { + const totalTenths = Math.ceil(clamped / 100); + const secs = Math.floor(totalTenths / 10); + const tenths = totalTenths % 10; + return `0:${secs < 10 ? '0' : ''}${secs}.${tenths}`; + } + const totalSecs = Math.ceil(clamped / 1000); + const hours = Math.floor(totalSecs / 3600); + const mins = Math.floor((totalSecs % 3600) / 60); + const secs = totalSecs % 60; + if (hours > 0) { + return `${hours}:${mins < 10 ? '0' : ''}${mins}:${secs < 10 ? '0' : ''}${secs}`; + } + return `${mins < 10 ? '0' : ''}${mins}:${secs < 10 ? '0' : ''}${secs}`; +} + +export function categoryLabel(category: TimeCategory): string { + switch (category) { + case 'bullet': + return 'Bullet'; + case 'blitz': + return 'Blitz'; + case 'rapid': + return 'Rapid'; + case 'classical': + return 'Classical'; + case 'unlimited': + return 'Unlimited'; + } +} diff --git a/src/shared/types.ts b/src/shared/types.ts new file mode 100644 index 0000000..b38e456 --- /dev/null +++ b/src/shared/types.ts @@ -0,0 +1,465 @@ +export type Color = 'w' | 'b'; +export type PieceType = 'p' | 'n' | 'b' | 'r' | 'q' | 'k'; +export type PromotionPiece = 'q' | 'r' | 'b' | 'n'; + +export interface Piece { + color: Color; + type: PieceType; +} + +export interface ChessMove { + from: number; + to: number; + piece: PieceType; + color: Color; + captured?: PieceType; + promotion?: PromotionPiece; + flags: number; + san: string; + uci: string; +} + +export type GameResult = '1-0' | '0-1' | '1/2-1/2' | '*'; + +export type TerminationReason = + | 'checkmate' + | 'resign' + | 'timeout' + | 'abandonment' + | 'stalemate' + | 'draw_agreement' + | 'repetition' + | 'fifty_move' + | 'insufficient_material' + | 'aborted'; + +export type TimeCategory = 'bullet' | 'blitz' | 'rapid' | 'classical' | 'unlimited'; +export type RatedCategory = 'bullet' | 'blitz' | 'rapid' | 'classical'; +export type ColorPreference = 'white' | 'black' | 'random'; + +export interface TimeControl { + initialMs: number; + incrementMs: number; + category: TimeCategory; +} + +export interface GlickoRating { + category: RatedCategory; + rating: number; + rd: number; + volatility: number; + gamesPlayed: number; + provisional: boolean; +} + +export interface UserSummary { + id: number; + username: string; + ratings: Record; + createdAt: number; + lastSeenAt: number; +} + +export interface RatingHistoryPoint { + category: RatedCategory; + rating: number; + gameId: string | null; + createdAt: number; +} + +export interface UserWdl { + wins: number; + draws: number; + losses: number; + totalGames: number; +} + +export interface HeadToHead { + wins: number; + draws: number; + losses: number; + total: number; +} + +export type PresenceStatus = 'online' | 'in_game' | 'offline'; + +export interface UserProfile { + user: UserSummary; + onlineStatus: PresenceStatus; + activeGameId: string | null; + wdl: UserWdl; + ratingHistory: Record; + friendship?: { + status: 'none' | 'pending_sent' | 'pending_received' | 'accepted'; + requesterId: number | null; + }; + headToHead?: HeadToHead; +} + +export interface FriendEntry { + userId: number; + username: string; + ratings: Record; + onlineStatus: PresenceStatus; + activeGameId: string | null; + headToHead: HeadToHead; +} + +export interface FriendRequestEntry { + userId: number; + username: string; + ratings: Record; + direction: 'incoming' | 'outgoing'; + createdAt: number; +} + +export interface LobbySeek { + id: string; + userId: number; + username: string; + rating: number; + provisional: boolean; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + colorPref: ColorPreference; + minRating?: number; + maxRating?: number; + createdAt: number; +} + +export interface DirectChallenge { + id: string; + fromUserId: number; + fromUsername: string; + fromRating: number; + toUserId: number; + toUsername: string; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + colorPref: ColorPreference; + createdAt: number; + expiresAt: number; +} + +export interface InviteInfo { + token: string; + creatorUserId: number; + creatorUsername: string; + creatorRating: number; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + colorPref: ColorPreference; + createdAt: number; + expiresAt: number; +} + +export interface BotLevelConfig { + level: number; + name: string; + approxElo: number; + description: string; +} + +export interface ChatMessage { + id: string; + userId: number | null; + username: string; + text: string; + createdAt: number; + isSystem?: boolean; +} + +export interface ActivePlayerInfo { + userId: number | null; + username: string; + rating: number | null; + provisional: boolean; + isBot: boolean; + botLevel: number | null; + connected: boolean; + disconnectDeadlineMs: number | null; +} + +export interface ActiveGameState { + id: string; + white: ActivePlayerInfo; + black: ActivePlayerInfo; + initialFen: string; + fen: string; + movesUci: string[]; + movesSan: string[]; + moveTimesMs: number[]; + turn: Color; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + botLevel: number | null; + whiteTimeMs: number; + blackTimeMs: number; + serverTimeMs: number; + clockRunning: boolean; + abortDeadlineMs: number | null; + drawOfferFrom: Color | null; + takebackOfferFrom: Color | null; + rematchOfferFrom: Color | null; + rematchGameId: string | null; + spectatorCount: number; + chat: ChatMessage[]; + finished: boolean; + result: GameResult; + termination: TerminationReason | null; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + saved: boolean; + pgn: string | null; +} + +export interface StoredGame { + id: string; + whiteUserId: number | null; + blackUserId: number | null; + whiteUsername: string; + blackUsername: string; + botLevel: number | null; + botColor: Color | null; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + result: GameResult; + termination: TerminationReason; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + initialFen: string; + finalFen: string; + movesUci: string[]; + movesSan: string[]; + moveTimesMs: number[]; + pgn: string; + createdAt: number; + endedAt: number; +} + +export interface GameListItem { + id: string; + whiteUserId: number | null; + blackUserId: number | null; + whiteUsername: string; + blackUsername: string; + botLevel: number | null; + botColor: Color | null; + initialMs: number; + incrementMs: number; + category: TimeCategory; + rated: boolean; + result: GameResult; + termination: TerminationReason; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + pliesCount: number; + createdAt: number; + endedAt: number; +} + +export type MoveClassification = 'best' | 'good' | 'inaccuracy' | 'mistake' | 'blunder'; + +export interface PlyAnalysis { + ply: number; + moveUci: string; + moveSan: string; + color: Color; + evalCpBefore: number | null; + evalMateBefore: number | null; + evalCpAfter: number | null; + evalMateAfter: number | null; + winPercentBefore: number; + winPercentAfter: number; + winDrop: number; + accuracy: number; + bestMoveUci: string | null; + bestMoveSan: string | null; + pvUci: string[]; + pvSan: string[]; + classification: MoveClassification; +} + +export interface PlayerAnalysisSummary { + accuracy: number; + acpl: number; + best: number; + good: number; + inaccuracies: number; + mistakes: number; + blunders: number; +} + +export interface GameAnalysisReport { + gameId: string; + status: 'pending' | 'running' | 'done' | 'error'; + depth: number; + progressPly: number; + totalPlies: number; + whiteSummary: PlayerAnalysisSummary | null; + blackSummary: PlayerAnalysisSummary | null; + initialEvalCp: number | null; + initialEvalMate: number | null; + initialWinPercent: number; + initialBestMoveUci: string | null; + initialBestMoveSan: string | null; + initialPvSan: string[]; + plies: PlyAnalysis[]; + createdAt: number; + updatedAt: number; +} + +export interface MultiPvLine { + multipv: number; + depth: number; + scoreCp: number | null; + scoreMate: number | null; + pvUci: string[]; + pvSan: string[]; +} + +export interface LeaderboardEntry { + rank: number; + userId: number; + username: string; + rating: number; + rd: number; + gamesPlayed: number; + provisional: boolean; +} + +export type ClientWsMessage = + | { type: 'ping' } + | { type: 'lobby:subscribe' } + | { type: 'lobby:unsubscribe' } + | { + type: 'lobby:seek'; + initialMs: number; + incrementMs: number; + rated: boolean; + colorPref: ColorPreference; + minRating?: number; + maxRating?: number; + } + | { type: 'lobby:cancel_seek'; seekId?: string } + | { type: 'lobby:accept_seek'; seekId: string } + | { + type: 'challenge:send'; + toUserId: number; + initialMs: number; + incrementMs: number; + rated: boolean; + colorPref: ColorPreference; + } + | { type: 'challenge:respond'; challengeId: string; accept: boolean } + | { type: 'challenge:cancel'; challengeId: string } + | { type: 'game:subscribe'; gameId: string } + | { type: 'game:unsubscribe'; gameId: string } + | { type: 'game:move'; gameId: string; uci: string } + | { type: 'game:abort'; gameId: string } + | { type: 'game:resign'; gameId: string } + | { type: 'game:draw_offer'; gameId: string } + | { type: 'game:draw_respond'; gameId: string; accept: boolean } + | { type: 'game:takeback_offer'; gameId: string } + | { type: 'game:takeback_respond'; gameId: string; accept: boolean } + | { type: 'game:rematch_offer'; gameId: string } + | { type: 'game:rematch_respond'; gameId: string; accept: boolean } + | { type: 'game:chat'; gameId: string; text: string } + | { type: 'analysis:subscribe'; gameId: string } + | { type: 'analysis:unsubscribe'; gameId: string } + | { type: 'analysis:multipv'; requestId: string; fen: string; depth?: number; multiPv?: number } + | { type: 'analysis:multipv_stop'; requestId?: string }; + +export type ServerWsMessage = + | { type: 'pong'; serverTimeMs: number } + | { type: 'error'; code: string; message: string } + | { + type: 'session:init'; + user: UserSummary | null; + activeGameId: string | null; + challenges: DirectChallenge[]; + } + | { type: 'lobby:state'; seeks: LobbySeek[] } + | { type: 'challenge:list'; challenges: DirectChallenge[] } + | { type: 'challenge:received'; challenge: DirectChallenge } + | { type: 'challenge:removed'; challengeId: string; reason: string } + | { type: 'friend:presence'; userId: number; onlineStatus: PresenceStatus; activeGameId: string | null } + | { type: 'friend:update' } + | { type: 'game:started'; gameId: string } + | { type: 'game:state'; game: ActiveGameState } + | { + type: 'game:move'; + gameId: string; + uci: string; + san: string; + fen: string; + turn: Color; + moveTimeMs: number; + whiteTimeMs: number; + blackTimeMs: number; + serverTimeMs: number; + clockRunning: boolean; + abortDeadlineMs: number | null; + } + | { + type: 'game:takeback'; + gameId: string; + game: ActiveGameState; + } + | { + type: 'game:offers'; + gameId: string; + drawOfferFrom: Color | null; + takebackOfferFrom: Color | null; + rematchOfferFrom: Color | null; + } + | { + type: 'game:presence'; + gameId: string; + whiteConnected: boolean; + whiteDisconnectDeadlineMs: number | null; + blackConnected: boolean; + blackDisconnectDeadlineMs: number | null; + spectatorCount: number; + } + | { type: 'game:chat'; gameId: string; message: ChatMessage } + | { + type: 'game:over'; + gameId: string; + result: GameResult; + termination: TerminationReason; + whiteRatingBefore: number | null; + blackRatingBefore: number | null; + whiteRatingDiff: number | null; + blackRatingDiff: number | null; + saved: boolean; + pgn: string | null; + } + | { type: 'game:rematch_started'; oldGameId: string; newGameId: string } + | { type: 'analysis:progress'; gameId: string; progressPly: number; totalPlies: number } + | { type: 'analysis:done'; gameId: string; report: GameAnalysisReport } + | { type: 'analysis:error'; gameId: string; message: string } + | { + type: 'analysis:multipv_result'; + requestId: string; + fen: string; + depth: number; + lines: MultiPvLine[]; + done: boolean; + }; diff --git a/src/shared/winProb.ts b/src/shared/winProb.ts new file mode 100644 index 0000000..31f2a4e --- /dev/null +++ b/src/shared/winProb.ts @@ -0,0 +1,142 @@ +import type { Color, MoveClassification, PlayerAnalysisSummary, PlyAnalysis } from './types'; + +const CP_CLAMP = 2000; +const ACPL_CLAMP = 1000; + +export function clamp(val: number, min: number, max: number): number { + return val < min ? min : val > max ? max : val; +} + +/** + * Converts White-perspective evaluation (centipawns or mate in N) to White's winning probability [0, 100]. + * Uses Lichess's empirical win-percentage curve. + */ +export function cpToWinPercent(cp: number | null, mate: number | null): number { + if (mate !== null) { + if (mate > 0) return 100; + if (mate < 0) return 0; + return 50; + } + if (cp === null) return 50; + const bounded = clamp(cp, -CP_CLAMP, CP_CLAMP); + const raw = 50 + 50 * (2 / (1 + Math.exp(-0.00368208 * bounded)) - 1); + return clamp(raw, 0, 100); +} + +/** + * Returns White-perspective win% flipped for the given side. + */ +export function winPercentForSide(whiteWinPercent: number, side: Color): number { + return side === 'w' ? whiteWinPercent : 100 - whiteWinPercent; +} + +export function classifyMove( + moverWinBefore: number, + moverWinAfter: number, + isBestMove: boolean +): MoveClassification { + const drop = Math.max(0, moverWinBefore - moverWinAfter); + if (drop >= 30) return 'blunder'; + if (drop >= 20) return 'mistake'; + if (drop >= 10) return 'inaccuracy'; + if (isBestMove || drop < 2) return 'best'; + return 'good'; +} + +export function computeMoveAccuracy(winDrop: number): number { + const safeDrop = Math.max(0, winDrop); + if (safeDrop === 0) return 100; + const acc = 103.1668 * Math.exp(-0.04354 * safeDrop) - 3.1669; + return clamp(acc, 0, 100); +} + +export function evalToClampedCp(cp: number | null, mate: number | null): number { + if (mate !== null) { + return mate > 0 ? ACPL_CLAMP : -ACPL_CLAMP; + } + if (cp === null) return 0; + return clamp(cp, -ACPL_CLAMP, ACPL_CLAMP); +} + +export function computePlayerSummary(plies: ReadonlyArray, color: Color): PlayerAnalysisSummary { + const ownPlies = plies.filter((p) => p.color === color); + if (ownPlies.length === 0) { + return { + accuracy: 100, + acpl: 0, + best: 0, + good: 0, + inaccuracies: 0, + mistakes: 0, + blunders: 0 + }; + } + + let accSum = 0; + let cplSum = 0; + let best = 0; + let good = 0; + let inaccuracies = 0; + let mistakes = 0; + let blunders = 0; + + for (const ply of ownPlies) { + accSum += ply.accuracy; + const beforeCp = evalToClampedCp(ply.evalCpBefore, ply.evalMateBefore); + const afterCp = evalToClampedCp(ply.evalCpAfter, ply.evalMateAfter); + const loss = color === 'w' ? Math.max(0, beforeCp - afterCp) : Math.max(0, afterCp - beforeCp); + cplSum += loss; + + switch (ply.classification) { + case 'best': + best++; + break; + case 'good': + good++; + break; + case 'inaccuracy': + inaccuracies++; + break; + case 'mistake': + mistakes++; + break; + case 'blunder': + blunders++; + break; + } + } + + return { + accuracy: Math.round((accSum / ownPlies.length) * 10) / 10, + acpl: Math.round(cplSum / ownPlies.length), + best, + good, + inaccuracies, + mistakes, + blunders + }; +} + +export function formatEvalShort(cp: number | null, mate: number | null): string { + if (mate !== null) { + return mate > 0 ? `M${mate}` : `-M${Math.abs(mate)}`; + } + if (cp === null) return '0.0'; + const tenths = Math.round(Math.abs(cp) / 10); + if (tenths === 0) return '0.0'; + const sign = cp > 0 ? '+' : '-'; + return `${sign}${(tenths / 10).toFixed(1)}`; +} + +export function classificationNag(c: MoveClassification): string { + switch (c) { + case 'inaccuracy': + return '?!'; + case 'mistake': + return '?'; + case 'blunder': + return '??'; + default: + return ''; + } +} diff --git a/tests/chess.test.ts b/tests/chess.test.ts new file mode 100644 index 0000000..0a5d788 --- /dev/null +++ b/tests/chess.test.ts @@ -0,0 +1,135 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Chess, INITIAL_FEN } from '../src/shared/chess'; + +test('Perft startpos depths 1-4', () => { + const c = new Chess(INITIAL_FEN); + assert.equal(c.perft(1), 20); + assert.equal(c.perft(2), 400); + assert.equal(c.perft(3), 8902); + assert.equal(c.perft(4), 197281); +}); + +test('Perft Kiwipete depths 1-3', () => { + const c = new Chess('r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1'); + assert.equal(c.perft(1), 48); + assert.equal(c.perft(2), 2039); + assert.equal(c.perft(3), 97862); +}); + +test('Perft Position 3 (EP discovered check pin) depths 1-4', () => { + const c = new Chess('8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1'); + assert.equal(c.perft(1), 14); + assert.equal(c.perft(2), 191); + assert.equal(c.perft(3), 2812); + assert.equal(c.perft(4), 43238); +}); + +test('Perft Position 4 (promotions & castling) depths 1-3', () => { + const c = new Chess('r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1'); + assert.equal(c.perft(1), 6); + assert.equal(c.perft(2), 264); + assert.equal(c.perft(3), 9467); +}); + +test('Perft Position 5 depths 1-3', () => { + const c = new Chess('rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8'); + assert.equal(c.perft(1), 44); + assert.equal(c.perft(2), 1486); + assert.equal(c.perft(3), 62379); +}); + +test('Rook capture clears opponent castling right', () => { + const c = new Chess('r3k2r/8/8/8/8/8/7B/R3K2R w KQkq - 0 1'); + const mv = c.moveSan('Bxh8'); + //Wait h2 to h8 is blocked? Wait a1->h8 diagonal is b2..g7, h2->b8; let's use Bishop on g7 or a1 + assert.equal(mv, null); + const c2 = new Chess('r3k2r/8/8/8/8/8/1B6/R3K2R w KQkq - 0 1'); + const cap = c2.moveSan('Bxh8'); + assert.ok(cap); + assert.equal(c2.fen().split(' ')[2], 'KQq'); +}); + +test('SAN disambiguation, promotion, check, and checkmate symbols', () => { + // Two rooks on same file + two knights on same rank targeting f4 + const c = new Chess('4k3/8/8/8/R7/8/4N1N1/R3K3 w - - 0 1'); + const rMove = c.moveSan('R1a3'); + assert.ok(rMove); + assert.equal(rMove.san, 'R1a3'); + c.undo(); + + const nMove = c.moveSan('Nef4'); + assert.ok(nMove); + assert.equal(nMove.san, 'Nef4'); + + // Promotion with checkmate + const promo = new Chess('6k1/4P3/6K1/8/8/8/8/8 w - - 0 1'); + const mateMv = promo.moveUci('e7e8q'); + assert.ok(mateMv); + assert.equal(mateMv.san, 'e8=Q#'); +}); + +test('PGN export and import with comments and variations', () => { + const pgn = `[Event "Test Game"] +[White "Alice"] +[Black "Bob"] +[Result "1-0"] + +1. e4 {King's pawn} e5 (1... c5 2. Nf3) 2. Qh5 Nc6 3. Bc4 Nf6 $4 4. Qxf7# 1-0`; + + const parsed = Chess.fromPgn(pgn); + assert.equal(parsed.headers['White'], 'Alice'); + assert.equal(parsed.moves.length, 7); + assert.equal(parsed.result, '1-0'); + assert.equal(parsed.chess.isCheckmate(), true); + + const exported = parsed.chess.toPgn({ White: 'Alice', Black: 'Bob', Result: '1-0' }); + const reparsed = Chess.fromPgn(exported); + assert.deepEqual( + reparsed.moves.map((m) => m.uci), + parsed.moves.map((m) => m.uci) + ); +}); + +test('Draw conditions: stalemate, insufficient material, threefold repetition with EP rule, 50-move', () => { + // Stalemate + const stale = new Chess('7k/5Q2/6K1/8/8/8/8/8 b - - 0 1'); + assert.equal(stale.isStalemate(), true); + assert.deepEqual(stale.gameOutcome(), { result: '1/2-1/2', termination: 'stalemate' }); + + // Insufficient material: same-color bishops (c3 dark & g1 dark) vs opposite-color bishops (c3 dark & h1 light) + const sameColor = new Chess('4k3/8/8/8/8/2B5/8/4K1b1 w - - 0 1'); + assert.equal(sameColor.isInsufficientMaterial(), true); + + const diffColor = new Chess('4k3/8/8/8/8/2B5/8/4K2b w - - 0 1'); + assert.equal(diffColor.isInsufficientMaterial(), false); + + // 50-move rule + const fifty = new Chess('4k3/8/8/8/8/8/R7/4K3 w - - 100 60'); + assert.equal(fifty.isFiftyMoveDraw(), true); + + // Threefold repetition ignoring non-capturable EP square vs respecting capturable EP square + const rep = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'); + // Shuffle knights back and forth + const seq = ['Nf6', 'Nf3', 'Ng8', 'Ng1', 'Nf6', 'Nf3', 'Ng8', 'Ng1']; + for (let i = 0; i < seq.length - 1; i++) { + assert.ok(rep.moveSan(seq[i]!)); + assert.equal(rep.isThreefoldRepetition(), false); + } + assert.ok(rep.moveSan(seq[seq.length - 1]!)); + assert.equal(rep.isThreefoldRepetition(), true); +}); + +test('Undo restores exact FEN and repetition count', () => { + const c = new Chess(INITIAL_FEN); + const fens: string[] = [c.fen()]; + const moves = ['e2e4', 'e7e5', 'g1f3', 'b8c6', 'f1b5', 'a7a6', 'b5a4', 'g8f6', 'e1g1']; + for (const uci of moves) { + assert.ok(c.moveUci(uci)); + fens.push(c.fen()); + } + for (let i = moves.length - 1; i >= 0; i--) { + c.undo(); + assert.equal(c.fen(), fens[i]); + } +}); diff --git a/tests/glicko2.test.ts b/tests/glicko2.test.ts new file mode 100644 index 0000000..d187ae1 --- /dev/null +++ b/tests/glicko2.test.ts @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + INITIAL_RATING, + INITIAL_RD, + INITIAL_VOLATILITY, + PROVISIONAL_RD_THRESHOLD, + isProvisionalRd, + updateGlicko2, + updateGlicko2Pair +} from '../src/server/glicko2'; + +test('Glicko-2 matches Mark Glickman official paper worked example', () => { + // Paper example: player rating 1500, RD 200, vol 0.06 + // Opponents: (1400, 30, win=1), (1550, 100, loss=0), (1700, 300, loss=0) + const res = updateGlicko2( + { rating: 1500, rd: 200, volatility: 0.06, gamesPlayed: 5 }, + [ + { rating: 1400, rd: 30, score: 1 }, + { rating: 1550, rd: 100, score: 0 }, + { rating: 1700, rd: 300, score: 0 } + ] + ); + + assert.ok(Math.abs(res.rating - 1464.06) < 0.05, `Expected ~1464.06, got ${res.rating}`); + assert.ok(Math.abs(res.rd - 151.52) < 0.05, `Expected ~151.52, got ${res.rd}`); + assert.ok(Math.abs(res.volatility - 0.05999) < 0.0005, `Expected ~0.05999, got ${res.volatility}`); + assert.equal(res.gamesPlayed, 8); +}); + +test('Glicko-2 pair update symmetry and RD decay', () => { + const p1 = { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 }; + const p2 = { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 }; + + const out = updateGlicko2Pair(p1, p2, 1); + assert.ok(out.whiteDiff > 0); + assert.equal(out.whiteDiff, -out.blackDiff); + assert.ok(out.nextWhite.rd < INITIAL_RD); + assert.ok(out.nextBlack.rd < INITIAL_RD); + + // Draw between equal players yields 0 rating change + const drawOut = updateGlicko2Pair(p1, p2, 0.5); + assert.equal(drawOut.whiteDiff, 0); + assert.equal(drawOut.blackDiff, 0); + + // Provisional threshold + assert.equal(isProvisionalRd(PROVISIONAL_RD_THRESHOLD + 1), true); + assert.equal(isProvisionalRd(PROVISIONAL_RD_THRESHOLD), false); +}); diff --git a/tests/server.test.ts b/tests/server.test.ts new file mode 100644 index 0000000..a41449f --- /dev/null +++ b/tests/server.test.ts @@ -0,0 +1,420 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import WebSocket from 'ws'; +import { createApp, type ChessUpApp } from '../src/server/app'; +import type { ActiveGameState, GameAnalysisReport, ServerWsMessage } from '../src/shared/types'; + +class TestClient { + public cookie = ''; + public ws: WebSocket | null = null; + private msgQueue: ServerWsMessage[] = []; + private waiters: Array<{ + pred: (m: ServerWsMessage) => boolean; + resolve: (m: ServerWsMessage) => void; + reject: (err: Error) => void; + timer: NodeJS.Timeout; + }> = []; + + constructor(private readonly baseUrl: string) {} + + async req(urlPath: string, init: RequestInit = {}): Promise<{ status: number; data: T; rawText: string }> { + const headers: Record = {}; + if (init.body) headers['Content-Type'] = 'application/json'; + if (this.cookie) headers['Cookie'] = this.cookie; + + const resp = await fetch(this.baseUrl + urlPath, { + ...init, + headers: { + ...headers, + ...(init.headers as Record | undefined) + } + }); + + const setCookie = resp.headers.get('set-cookie'); + if (setCookie) { + const part = setCookie.split(';')[0]!; + if (part.endsWith('=')) { + this.cookie = ''; + } else { + this.cookie = part; + } + } + + const rawText = await resp.text(); + let data: unknown = {}; + try { + data = rawText ? JSON.parse(rawText) : {}; + } catch { + data = rawText; + } + return { status: resp.status, data: data as T, rawText }; + } + + connectWs(): Promise { + return new Promise((resolve, reject) => { + const wsUrl = this.baseUrl.replace(/^http/, 'ws') + '/ws'; + const headers: Record = {}; + if (this.cookie) headers['Cookie'] = this.cookie; + const ws = new WebSocket(wsUrl, { headers }); + this.ws = ws; + + ws.once('open', () => resolve()); + ws.once('error', reject); + ws.on('message', (buf) => { + const msg = JSON.parse(buf.toString()) as ServerWsMessage; + for (let i = 0; i < this.waiters.length; i++) { + const w = this.waiters[i]!; + if (w.pred(msg)) { + this.waiters.splice(i, 1); + clearTimeout(w.timer); + w.resolve(msg); + return; + } + } + this.msgQueue.push(msg); + }); + }); + } + + sendWs(msg: unknown): void { + assert.ok(this.ws && this.ws.readyState === WebSocket.OPEN, 'WS is not open'); + this.ws.send(JSON.stringify(msg)); + } + + waitFor(pred: (m: ServerWsMessage) => boolean, timeoutMs: number = 8000): Promise { + for (let i = 0; i < this.msgQueue.length; i++) { + const m = this.msgQueue[i]!; + if (pred(m)) { + this.msgQueue.splice(i, 1); + return Promise.resolve(m); + } + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + const idx = this.waiters.findIndex((w) => w.timer === timer); + if (idx >= 0) this.waiters.splice(idx, 1); + reject(new Error('Timed out waiting for WS message')); + }, timeoutMs); + this.waiters.push({ pred, resolve, reject, timer }); + }); + } + + closeWs(): Promise { + return new Promise((resolve) => { + if (!this.ws || this.ws.readyState === WebSocket.CLOSED) { + this.ws = null; + resolve(); + return; + } + this.ws.once('close', () => { + this.ws = null; + resolve(); + }); + this.ws.close(); + }); + } +} + +test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, bots, friends, invites, spectating, disconnect forfeit', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chessup-test-')); + const dbPath = path.join(tmpDir, 'test.db'); + + const app: ChessUpApp = createApp({ + port: 0, + host: '127.0.0.1', + dbPath, + stockfishWorkers: 2, + analysisDepth: 8, + disconnectForfeitMs: 450, + disableRateLimit: true + }); + + const port = await app.start(); + const baseUrl = `http://127.0.0.1:${port}`; + + const alice = new TestClient(baseUrl); + const bob = new TestClient(baseUrl); + const spectator = new TestClient(baseUrl); + + try { + // 1. Auth: register, duplicate check, login, password update + const regA = await alice.req<{ user: { id: number; username: string } }>('/api/auth/register', { + method: 'POST', + body: JSON.stringify({ username: 'Alice_01', password: 'password123' }) + }); + assert.equal(regA.status, 201); + assert.equal(regA.data.user.username, 'Alice_01'); + + const dupA = await alice.req('/api/auth/register', { + method: 'POST', + body: JSON.stringify({ username: 'alice_01', password: 'password123' }) + }); + assert.equal(dupA.status, 409); + + const regB = await bob.req<{ user: { id: number; username: string } }>('/api/auth/register', { + method: 'POST', + body: JSON.stringify({ username: 'Bob_02', password: 'password456' }) + }); + assert.equal(regB.status, 201); + + const badLogin = await new TestClient(baseUrl).req('/api/auth/login', { + method: 'POST', + body: JSON.stringify({ username: 'Bob_02', password: 'wrong' }) + }); + assert.equal(badLogin.status, 401); + + const meA = await alice.req<{ user: { username: string } | null }>('/api/auth/me'); + assert.equal(meA.status, 200); + assert.equal(meA.data.user?.username, 'Alice_01'); + + // Connect WS clients + await alice.connectWs(); + await bob.connectWs(); + await spectator.connectWs(); + + await alice.waitFor((m) => m.type === 'session:init'); + await bob.waitFor((m) => m.type === 'session:init'); + await spectator.waitFor((m) => m.type === 'session:init'); + + // 2. Open lobby seek -> accept -> Scholar's Mate -> DB persistence + Glicko-2 update + alice.sendWs({ type: 'lobby:subscribe' }); + bob.sendWs({ type: 'lobby:subscribe' }); + await alice.waitFor((m) => m.type === 'lobby:state'); + await bob.waitFor((m) => m.type === 'lobby:state'); + + alice.sendWs({ + type: 'lobby:seek', + initialMs: 180_000, + incrementMs: 0, + rated: true, + colorPref: 'white' + }); + + const seekMsg = (await bob.waitFor( + (m) => m.type === 'lobby:state' && m.seeks.length === 1 + )) as Extract; + const seekId = seekMsg.seeks[0]!.id; + + bob.sendWs({ type: 'lobby:accept_seek', seekId }); + const startA = (await alice.waitFor((m) => m.type === 'game:started')) as Extract< + ServerWsMessage, + { type: 'game:started' } + >; + const startB = (await bob.waitFor((m) => m.type === 'game:started')) as Extract< + ServerWsMessage, + { type: 'game:started' } + >; + assert.equal(startA.gameId, startB.gameId); + const pvpGameId = startA.gameId; + + alice.sendWs({ type: 'game:subscribe', gameId: pvpGameId }); + bob.sendWs({ type: 'game:subscribe', gameId: pvpGameId }); + spectator.sendWs({ type: 'game:subscribe', gameId: pvpGameId }); + + const stateA = (await alice.waitFor((m) => m.type === 'game:state')) as Extract< + ServerWsMessage, + { type: 'game:state' } + >; + assert.equal(stateA.game.white.username, 'Alice_01'); + assert.equal(stateA.game.black.username, 'Bob_02'); + + // Unauthenticated spectator watches + authenticated player chats + await spectator.waitFor((m) => m.type === 'game:state'); + alice.sendWs({ type: 'game:chat', gameId: pvpGameId, text: 'Good luck!' }); + const chatSpec = (await spectator.waitFor((m) => m.type === 'game:chat')) as Extract< + ServerWsMessage, + { type: 'game:chat' } + >; + assert.equal(chatSpec.message.text, 'Good luck!'); + + // Play Scholar's Mate + const scholarMoves: Array<[TestClient, string]> = [ + [alice, 'e2e4'], + [bob, 'e7e5'], + [alice, 'd1h5'], + [bob, 'b8c6'], + [alice, 'f1c4'], + [bob, 'g8f6'], + [alice, 'h5f7'] + ]; + for (const [player, uci] of scholarMoves) { + player.sendWs({ type: 'game:move', gameId: pvpGameId, uci }); + await alice.waitFor((m) => m.type === 'game:move' && m.uci === uci); + await bob.waitFor((m) => m.type === 'game:move' && m.uci === uci); + } + + const overA = (await alice.waitFor((m) => m.type === 'game:over')) as Extract< + ServerWsMessage, + { type: 'game:over' } + >; + assert.equal(overA.result, '1-0'); + assert.equal(overA.termination, 'checkmate'); + assert.equal(overA.saved, true); + assert.ok(overA.whiteRatingDiff !== null && overA.whiteRatingDiff > 0); + assert.ok(overA.blackRatingDiff !== null && overA.blackRatingDiff < 0); + + // Check REST history, PGN, leaderboard + const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`); + assert.equal(storedRes.status, 200); + assert.equal(storedRes.data.game.result, '1-0'); + + const pgnRes = await alice.req(`/api/games/${pvpGameId}/pgn`); + assert.equal(pgnRes.status, 200); + assert.ok(pgnRes.rawText.includes('Qxf7#')); + + const lbRes = await alice.req<{ entries: Array<{ username: string }> }>('/api/leaderboard?category=blitz'); + assert.equal(lbRes.status, 200); + assert.equal(lbRes.data.entries[0]!.username, 'Alice_01'); + + // 3. Stockfish Post-Game Analysis + Cache verification + alice.sendWs({ type: 'analysis:subscribe', gameId: pvpGameId }); + const triggerRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, { + method: 'POST', + body: JSON.stringify({}) + }); + assert.ok(triggerRes.status === 202 || triggerRes.status === 200); + + const analysisDone = (await alice.waitFor( + (m) => m.type === 'analysis:done' && m.gameId === pvpGameId, + 15_000 + )) as Extract; + assert.equal(analysisDone.report.status, 'done'); + assert.equal(analysisDone.report.plies.length, 7); + assert.equal(analysisDone.report.plies[5]!.classification, 'blunder'); + + // Second POST returns cached 200 immediately + const cachedRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, { + method: 'POST', + body: JSON.stringify({}) + }); + assert.equal(cachedRes.status, 200); + assert.equal(cachedRes.data.report.status, 'done'); + + // 4. Play vs Stockfish Level 1 + takeback + const botRes = await alice.req<{ gameId: string }>('/api/games/bot', { + method: 'POST', + body: JSON.stringify({ level: 1, colorPref: 'white', initialMs: 0, incrementMs: 0 }) + }); + assert.equal(botRes.status, 201); + const botGameId = botRes.data.gameId; + alice.sendWs({ type: 'game:subscribe', gameId: botGameId }); + await alice.waitFor((m) => m.type === 'game:state' && m.game.id === botGameId); + + alice.sendWs({ type: 'game:move', gameId: botGameId, uci: 'e2e4' }); + await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.uci === 'e2e4'); + // Wait for Stockfish Level 1 response + await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.turn === 'w'); + + // Takeback restores back to 0 plies + alice.sendWs({ type: 'game:takeback_offer', gameId: botGameId }); + const tbMsg = (await alice.waitFor( + (m) => m.type === 'game:takeback' && m.gameId === botGameId + )) as Extract; + assert.equal(tbMsg.game.movesUci.length, 0); + + alice.sendWs({ type: 'game:abort', gameId: botGameId }); + await alice.waitFor((m) => m.type === 'game:over' && m.gameId === botGameId && m.termination === 'aborted'); + + // 5. Mutual friends + Direct challenge + const frReq = await alice.req('/api/friends/request', { + method: 'POST', + body: JSON.stringify({ username: 'Bob_02' }) + }); + assert.equal(frReq.status, 200); + + const frAcc = await bob.req('/api/friends/respond', { + method: 'POST', + body: JSON.stringify({ userId: regA.data.user.id, accept: true }) + }); + assert.equal(frAcc.status, 200); + + alice.sendWs({ + type: 'challenge:send', + toUserId: regB.data.user.id, + initialMs: 300_000, + incrementMs: 0, + rated: false, + colorPref: 'white' + }); + + const chalRecv = (await bob.waitFor((m) => m.type === 'challenge:received')) as Extract< + ServerWsMessage, + { type: 'challenge:received' } + >; + bob.sendWs({ type: 'challenge:respond', challengeId: chalRecv.challenge.id, accept: true }); + + const chalStart = (await bob.waitFor( + (m) => m.type === 'game:started' && m.gameId !== pvpGameId + )) as Extract; + const chalGameId = chalStart.gameId; + + alice.sendWs({ type: 'game:subscribe', gameId: chalGameId }); + bob.sendWs({ type: 'game:subscribe', gameId: chalGameId }); + await alice.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId); + await bob.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId); + + // Play 2 plies so game counts and test disconnect forfeit + alice.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd2d4' }); + await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd2d4'); + bob.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd7d5' }); + await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd7d5'); + + // Alice disconnects -> after disconnectForfeitMs (450ms), Bob wins by abandonment! + await alice.closeWs(); + const abandonOver = (await bob.waitFor( + (m) => m.type === 'game:over' && m.gameId === chalGameId + )) as Extract; + assert.equal(abandonOver.result, '0-1'); + assert.equal(abandonOver.termination, 'abandonment'); + + // 6. Shareable invite link flow + await alice.connectWs(); + await alice.waitFor((m) => m.type === 'session:init'); + const invCreate = await alice.req<{ invite: { token: string } }>('/api/invites', { + method: 'POST', + body: JSON.stringify({ initialMs: 600_000, incrementMs: 5_000, rated: false, colorPref: 'black' }) + }); + assert.equal(invCreate.status, 201); + const invToken = invCreate.data.invite.token; + + const invGet = await bob.req<{ invite: { creatorUsername: string } }>(`/api/invites/${invToken}`); + assert.equal(invGet.status, 200); + assert.equal(invGet.data.invite.creatorUsername, 'Alice_01'); + + const invAcc = await bob.req<{ gameId: string }>(`/api/invites/${invToken}/accept`, { method: 'POST' }); + assert.equal(invAcc.status, 200); + const invGame = await bob.req<{ kind: string; game: ActiveGameState }>(`/api/games/${invAcc.data.gameId}`); + assert.equal(invGame.status, 200); + assert.equal(invGame.data.game.white.username, 'Bob_02'); + assert.equal(invGame.data.game.black.username, 'Alice_01'); + + // 7. Health endpoint, malformed URL handling, and X-Forwarded-Host origin support + const healthRes = await alice.req<{ ok: boolean }>('/api/health'); + assert.equal(healthRes.status, 200); + assert.equal(healthRes.data.ok, true); + + const badPathRes = await alice.req<{ error: string }>('/api/%E0%A4%A'); + assert.equal(badPathRes.status, 400); + + const fwdOriginRes = await new TestClient(baseUrl).req('/api/auth/logout', { + method: 'POST', + headers: { Origin: 'https://chess.example.com', 'X-Forwarded-Host': 'chess.example.com' } + }); + assert.equal(fwdOriginRes.status, 200); + + const badOriginPost = await alice.req('/api/auth/logout', { + method: 'POST', + headers: { Origin: 'https://evil.example.com', 'X-Forwarded-Host': 'chess.example.com' } + }); + assert.equal(badOriginPost.status, 403); + } finally { + await alice.closeWs(); + await bob.closeWs(); + await spectator.closeWs(); + await app.stop(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); diff --git a/tests/stockfish.test.ts b/tests/stockfish.test.ts new file mode 100644 index 0000000..e5f2b79 --- /dev/null +++ b/tests/stockfish.test.ts @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Chess, INITIAL_FEN } from '../src/shared/chess'; +import { StockfishPool } from '../src/server/stockfish'; + +test('StockfishPool bot moves, MultiPV perspective normalization, cancellation, and full-game analysis', async () => { + const pool = new StockfishPool(2); + try { + await pool.warmup(); + + // 1. Bot Level 1 and Level 8 return legal UCI moves + const c = new Chess(INITIAL_FEN); + const lv1Move = await pool.getBotMove(c.fen(), 1); + assert.ok(c.legalMoves().some((m) => m.uci === lv1Move), `Illegal lv1 move: ${lv1Move}`); + + const lv8Move = await pool.getBotMove(c.fen(), 8); + assert.ok(c.legalMoves().some((m) => m.uci === lv8Move), `Illegal lv8 move: ${lv8Move}`); + + // 2. MultiPV on Black-to-move position where White is up a Queen -> scoreCp MUST be positive (White's perspective)! + const whiteUpQueenBlackToMove = 'rnb1kbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1'; + const lines = await pool.analyzePositionMultiPv(whiteUpQueenBlackToMove, 8, 2); + assert.ok(lines.length >= 1); + assert.ok( + lines[0]!.scoreCp !== null && lines[0]!.scoreCp > 400, + `Expected White-perspective positive cp > 400, got ${lines[0]!.scoreCp}` + ); + + // 3. Cancellation works cleanly + const ac = new AbortController(); + const cancelPromise = pool.analyzePositionMultiPv(INITIAL_FEN, 18, 3, ac.signal); + setTimeout(() => ac.abort(), 30); + const cancelledLines = await cancelPromise; + assert.ok(Array.isArray(cancelledLines)); + + // 4. Full-game analysis on Scholar's Mate + const gameChess = new Chess(INITIAL_FEN); + const uciList = ['e2e4', 'e7e5', 'd1h5', 'b8c6', 'f1c4', 'g8f6', 'h5f7']; + const sanList: string[] = []; + for (const u of uciList) { + const mv = gameChess.moveUci(u); + assert.ok(mv); + sanList.push(mv.san); + } + + let sawProgress = false; + const report = await pool.analyzeFullGame('test-scholar', INITIAL_FEN, uciList, sanList, 10, (done, total) => { + assert.ok(done <= total); + sawProgress = true; + }); + + assert.equal(sawProgress, true); + assert.equal(report.status, 'done'); + assert.equal(report.plies.length, 7); + assert.ok(report.whiteSummary && report.blackSummary); + // 3... Nf6?? allows 4. Qxf7# -> blunder! + const nf6Ply = report.plies[5]!; + assert.equal(nf6Ply.moveSan, 'Nf6'); + assert.equal(nf6Ply.classification, 'blunder'); + // 4. Qxf7# delivers mate -> 100% win percent after + const matePly = report.plies[6]!; + assert.equal(matePly.winPercentAfter, 100); + } finally { + pool.shutdown(); + } +}); diff --git a/tests/winProb.test.ts b/tests/winProb.test.ts new file mode 100644 index 0000000..95c14c7 --- /dev/null +++ b/tests/winProb.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + classifyMove, + computeMoveAccuracy, + computePlayerSummary, + cpToWinPercent, + formatEvalShort +} from '../src/shared/winProb'; +import type { PlyAnalysis } from '../src/shared/types'; + +test('cpToWinPercent symmetry and mate bounds', () => { + assert.equal(cpToWinPercent(0, null), 50); + assert.equal(cpToWinPercent(null, 3), 100); + assert.equal(cpToWinPercent(null, -2), 0); + + const pos = cpToWinPercent(250, null); + const neg = cpToWinPercent(-250, null); + assert.ok(pos > 65 && pos < 80); + assert.ok(Math.abs(pos + neg - 100) < 1e-6); +}); + +test('classifyMove thresholds and accuracy', () => { + assert.equal(classifyMove(60, 60, true), 'best'); + assert.equal(classifyMove(60, 59, false), 'best'); + assert.equal(classifyMove(60, 55, false), 'good'); + assert.equal(classifyMove(60, 49, false), 'inaccuracy'); + assert.equal(classifyMove(60, 39, false), 'mistake'); + assert.equal(classifyMove(60, 29, false), 'blunder'); + + assert.equal(computeMoveAccuracy(0), 100); + assert.ok(computeMoveAccuracy(35) < 25); +}); + +test('computePlayerSummary calculates ACPL and counts accurately', () => { + const plies: PlyAnalysis[] = [ + { + ply: 1, + moveUci: 'e2e4', + moveSan: 'e4', + color: 'w', + evalCpBefore: 20, + evalMateBefore: null, + evalCpAfter: 20, + evalMateAfter: null, + winPercentBefore: 51, + winPercentAfter: 51, + winDrop: 0, + accuracy: 100, + bestMoveUci: 'e2e4', + bestMoveSan: 'e4', + pvUci: ['e2e4'], + pvSan: ['e4'], + classification: 'best' + }, + { + ply: 2, + moveUci: 'g7g5', + moveSan: 'g5', + color: 'b', + evalCpBefore: 20, + evalMateBefore: null, + evalCpAfter: 320, + evalMateAfter: null, + winPercentBefore: 51, + winPercentAfter: 76, + winDrop: 25, + accuracy: 31.6, + bestMoveUci: 'e7e5', + bestMoveSan: 'e5', + pvUci: ['e7e5'], + pvSan: ['e5'], + classification: 'mistake' + } + ]; + + const wSum = computePlayerSummary(plies, 'w'); + assert.equal(wSum.accuracy, 100); + assert.equal(wSum.acpl, 0); + assert.equal(wSum.best, 1); + + const bSum = computePlayerSummary(plies, 'b'); + assert.equal(bSum.acpl, 300); + assert.equal(bSum.mistakes, 1); + assert.equal(formatEvalShort(145, null), '+1.5'); + assert.equal(formatEvalShort(null, -4), '-M4'); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..5d8e380 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "noUncheckedIndexedAccess": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "noEmit": true, + "skipLibCheck": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "tests/**/*.ts"] +}