| 1 | import { createServer } from 'node:http'; |
| 2 | import { createReadStream } from 'node:fs'; |
| 3 | import { stat } from 'node:fs/promises'; |
| 4 | import { extname, join, resolve } from 'node:path'; |
| 5 | import { fileURLToPath } from 'node:url'; |
| 6 | import { attachRooms } from './rooms.ts'; |
| 7 | |
| 8 | /** |
| 9 | * The whole production stack in one process: the built game out of dist/, and |
| 10 | * the room relay on /ws of the same origin. `npm run build && npm run serve`. |
| 11 | * In development this file is not involved — vite serves the game and |
| 12 | * vite.config.ts attaches the same relay to vite's own server. |
| 13 | */ |
| 14 | |
| 15 | const DIST = resolve(fileURLToPath(import.meta.url), '../../dist'); |
| 16 | const PORT = process.env.PORT ? Number(process.env.PORT) : 8080; |
| 17 | const HOST = process.env.HOST || '0.0.0.0'; |
| 18 | |
| 19 | const MIME: Record<string, string> = { |
| 20 | '.html': 'text/html; charset=utf-8', |
| 21 | '.js': 'text/javascript', |
| 22 | '.css': 'text/css', |
| 23 | '.svg': 'image/svg+xml', |
| 24 | '.png': 'image/png', |
| 25 | '.mp3': 'audio/mpeg', |
| 26 | '.json': 'application/json', |
| 27 | '.webmanifest': 'application/manifest+json', |
| 28 | '.ico': 'image/x-icon', |
| 29 | '.txt': 'text/plain; charset=utf-8', |
| 30 | '.map': 'application/json', |
| 31 | '.woff2': 'font/woff2', |
| 32 | }; |
| 33 | |
| 34 | /** |
| 35 | * A room link is a path — `/UV9WTU`, `/UV9WTU-1` — because a QR that has to be |
| 36 | * read off a tile lying on the felt cannot afford `?room=`. See `roomLink` in |
| 37 | * src/net/protocol.ts for why. Nothing is on disk under those names, so any |
| 38 | * request for a page rather than a file is answered with the game, which reads |
| 39 | * the room out of its own address. |
| 40 | */ |
| 41 | const wantsPage = (req: { headers: { accept?: string } }, pathname: string): boolean => |
| 42 | !extname(pathname) && (req.headers.accept ?? '').includes('text/html'); |
| 43 | |
| 44 | const server = createServer(async (req, res) => { |
| 45 | const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname); |
| 46 | const file = resolve(join(DIST, pathname === '/' ? 'index.html' : pathname)); |
| 47 | if (!file.startsWith(DIST)) { |
| 48 | res.writeHead(403).end(); |
| 49 | return; |
| 50 | } |
| 51 | try { |
| 52 | // The file if there is one; the game itself if what was asked for is a page |
| 53 | // and there is not. Only then — an extensionless file that does exist is |
| 54 | // still served as itself. |
| 55 | const found = await stat(file).catch(() => null); |
| 56 | const served = found?.isFile() |
| 57 | ? file |
| 58 | : wantsPage(req, pathname) |
| 59 | ? join(DIST, 'index.html') |
| 60 | : file; |
| 61 | const s = found?.isFile() ? found : await stat(served); |
| 62 | if (!s.isFile()) throw new Error('not a file'); |
| 63 | const ext = extname(served); |
| 64 | res.writeHead(200, { |
| 65 | 'content-type': MIME[ext] ?? 'application/octet-stream', |
| 66 | 'content-length': s.size, |
| 67 | // Hashed assets may be kept forever; everything else asks again. |
| 68 | 'cache-control': pathname.startsWith('/assets/') |
| 69 | ? 'public, max-age=31536000, immutable' |
| 70 | : 'no-cache', |
| 71 | }); |
| 72 | createReadStream(served).pipe(res); |
| 73 | } catch { |
| 74 | res.writeHead(404, { 'content-type': 'text/plain' }).end('not found\n'); |
| 75 | } |
| 76 | }); |
| 77 | |
| 78 | attachRooms(server); |
| 79 | // Upgrades to anything but /ws have no other takers here — hang up. |
| 80 | server.on('upgrade', (req, socket) => { |
| 81 | if (new URL(req.url ?? '/', 'http://localhost').pathname !== '/ws') socket.destroy(); |
| 82 | }); |
| 83 | |
| 84 | server.listen(PORT, HOST, async () => { |
| 85 | const built = await stat(join(DIST, 'index.html')).catch(() => null); |
| 86 | console.log(`mahjong on http://${HOST}:${PORT} — rooms on /ws`); |
| 87 | if (!built) console.log('dist/ is empty — run `npm run build` first'); |
| 88 | }); |