Split The code is public; the app answers only to the crew.
Clean: a rendered `.checkdata/game.html` is committed; `serve()` is a top-level side effect #48
Check · Review · Land · Live done — Landed and live in production.
scout/cs:scout/41-clean-a-rendered-checkdata-game-html-is → main 1 commit fork
6 files
changed +125
−261
.checkdata/game.html deleted −178
| @@ -1,178 +0,0 @@ | ||
| 1 | ||
| 2 | <html lang="en"> | |
| 3 | <meta charset="utf-8"> | |
| 4 | <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> | |
| 5 | <title>cs — a browser defusal shooter</title> | |
| 6 | <meta name="description" content="A Counter-Strike-shaped defusal shooter that runs in the browser: WebGL2, bots, bomb rounds and an economy."> | |
| 7 | <style> | |
| 8 | :root { color-scheme: dark; :#0b0d11; :#141821; :#232a36; :#e7eaf0; :#9aa4b4; :#e2b04a; :#6fa8e8; } | |
| 9 | * { box-sizing: border-box; } | |
| 10 | body { margin:0; background:var(); color:var(); font:16px/1.55 system-ui,-apple-system,Segoe UI,sans-serif; } | |
| 11 | header, main { max-width: 64rem; margin: 0 auto; padding: 0 1rem; } | |
| 12 | header { display:flex; align-items:baseline; gap:.75rem; padding-top:1rem; flex-wrap:wrap; } | |
| 13 | h1 { font-size:1.4rem; margin:0; letter-spacing:.02em; } | |
| 14 | .env { font-size:.72rem; padding:.15rem .5rem; border-radius:999px; background:#1d4ed8; color:#fff; } | |
| 15 | .env.production { background:#15803d; } | |
| 16 | small.commit { color:var(); font-size:.75rem; } | |
| 17 | #stage { position:relative; width:100%; aspect-ratio:16/9; max-height:78vh; margin:1rem auto; background:#000; | |
| 18 | border:1px solid var(); border-radius:.6rem; overflow:hidden; touch-action:none; } | |
| 19 | #scene, #hud { position:absolute; inset:0; width:100%; height:100%; display:block; } | |
| 20 | #hud { pointer-events:none; } | |
| 21 | .overlay { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; | |
| 22 | gap:.75rem; background:rgba(8,10,14,.82); text-align:center; padding:1rem; overflow:auto; | |
| 23 | /* #stage is touch-action:none for the look drag; an overlay taller | |
| 24 | than the stage still has to scroll under a thumb. */ | |
| 25 | touch-action:pan-y; overscroll-behavior:contain; } | |
| 26 | .overlay[hidden] { display:none; } | |
| 27 | .overlay h2 { margin:0; font-size:1.3rem; } | |
| 28 | .overlay p { margin:.2rem 0; color:var(); max-width:34rem; } | |
| 29 | .row { display:flex; gap:.5rem; flex-wrap:wrap; justify-content:center; align-items:center; } | |
| 30 | label { display:flex; flex-direction:column; gap:.25rem; font-size:.8rem; color:var(); text-align:left; } | |
| 31 | input, select { min-height:44px; padding:.5rem .7rem; font:inherit; color:var(); | |
| 32 | background:#0f131a; border:1px solid var(); border-radius:.45rem; } | |
| 33 | button { min-height:44px; min-width:44px; padding:.6rem 1.1rem; font:inherit; border:1px solid var(); | |
| 34 | border-radius:.45rem; background:#1b2230; color:var(); cursor:pointer; } | |
| 35 | button:hover:not(:disabled) { background:#27303f; } | |
| 36 | button:disabled { opacity:.42; cursor:not-allowed; } | |
| 37 | button.primary { background:#2563eb; border-color:#2563eb; font-weight:600; } | |
| 38 | #buy .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(11rem,1fr)); gap:.5rem; width:min(40rem,100%); } | |
| 39 | #buy .hint, .overlay .hint { font-size:.78rem; } | |
| 40 | #summary .score { font-size:2.2rem; line-height:1.1; color:var(); font-variant-numeric:tabular-nums; margin:.1rem 0; } | |
| 41 | #summary h2 { font-size:1.8rem; } | |
| 42 | #summary #summary-line { color:var(); font-size:.95rem; } | |
| 43 | #fps { position:absolute; right:.5rem; bottom:.4rem; font-size:.7rem; color:#8ea; opacity:.7; pointer-events:none; } | |
| 44 | /* The pad is under the view, not over it: the stage is 4:3 on a phone and the | |
| 45 | HUD already owns all four of its corners, so a button on the glass would sit | |
| 46 | on the radar, the health or the ammo. Aim, move and fire stay on the canvas | |
| 47 | — the pad is only the discrete actions. */ | |
| 48 | #touch { max-width:34rem; margin:0 auto 1.5rem; display:flex; flex-direction:column; gap:.4rem; | |
| 49 | touch-action:manipulation; -webkit-user-select:none; user-select:none; -webkit-touch-callout:none; } | |
| 50 | #touch[hidden] { display:none; } | |
| 51 | #touch.blocked { visibility:hidden; } | |
| 52 | #touch .pad { display:grid; grid-template-columns:repeat(auto-fit,minmax(3.4rem,1fr)); gap:.4rem; } | |
| 53 | #touch .pad.wide { grid-template-columns:1fr; } | |
| 54 | #touch button { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:.05rem; | |
| 55 | min-height:48px; min-width:44px; padding:.4rem .25rem; font-size:.82rem; line-height:1.15; } | |
| 56 | #touch button b { color:var(); font-size:.68rem; font-weight:600; } | |
| 57 | #touch button.fire { background:#7f1d1d; border-color:#8f2222; font-weight:600; } | |
| 58 | /* A thumb has no hover, so held has to look held — and the "on" class is put | |
| 59 | there by the same handler that presses the control, since preventDefault | |
| 60 | costs a touched button its :active. */ | |
| 61 | #touch button.on { background:#33405a; border-color:#4a5c7d; } | |
| 62 | #touch button.fire.on { background:#b02626; border-color:#c33; } | |
| 63 | #touch .hint { margin:0; text-align:center; color:var(); font-size:.74rem; } | |
| 64 | main section { margin:1.5rem 0; } | |
| 65 | table { width:100%; border-collapse:collapse; font-size:.9rem; } | |
| 66 | th, td { text-align:left; padding:.35rem .5rem; border-bottom:1px solid var(); } | |
| 67 | th { color:var(); font-weight:500; } | |
| 68 | ul.recent { list-style:none; padding:0; margin:0; font-size:.86rem; } | |
| 69 | ul.recent li { padding:.35rem 0; border-bottom:1px solid var(); display:flex; gap:.5rem; flex-wrap:wrap; } | |
| 70 | ul.recent span, ul.recent time, .empty { color:var(); } | |
| 71 | kbd { background:#1b2230; border:1px solid var(); border-radius:.25rem; padding:0 .3rem; font-size:.82rem; } | |
| 72 | footer { color:var(); font-size:.8rem; padding:1rem; text-align:center; } | |
| 73 | code { background:#141821; padding:.1rem .35rem; border-radius:.25rem; } | |
| 74 | @media (max-width: 640px) { #stage { aspect-ratio:4/3; } h1 { font-size:1.2rem; } } | |
| 75 | </style> | |
| 76 | <header> | |
| 77 | <h1>cs</h1> | |
| 78 | <span class="env ">local</span> | |
| 79 | ||
| 80 | </header> | |
| 81 | <main> | |
| 82 | <div id="stage"> | |
| 83 | <canvas id="scene"></canvas> | |
| 84 | <canvas id="hud"></canvas> | |
| 85 | <div id="fps"></div> | |
| 86 | <div class="overlay" id="menu"> | |
| 87 | <h2>Defuse or detonate</h2> | |
| 88 | <p>Five against five on <b>de_forge</b>. Bomb rounds, CS movement and economy, bots that push the sites.</p> | |
| 89 | <div class="row"> | |
| 90 | <label>Name<input id="name" maxlength="24" placeholder="you" autocomplete="nickname"></label> | |
| 91 | <label>Match<select id="length"><option value="short">Short — first to 5</option><option value="long">Competitive — first to 13</option></select></label> | |
| 92 | <label>Side<select id="side"><option value="ct">Counter-Terrorists</option><option value="t">Terrorists</option></select></label> | |
| 93 | <label>Sensitivity<input id="sens" type="number" min="0.2" max="12" step="0.1" value="2.2"></label> | |
| 94 | </div> | |
| 95 | <div class="row"><button type="button" class="primary" id="play">Play</button></div> | |
| 96 | <p class="hint"><kbd>WASD</kbd> move · <kbd>Space</kbd> jump · <kbd>Ctrl</kbd> crouch · <kbd>Shift</kbd> walk · | |
| 97 | mouse to aim and fire · <kbd>R</kbd> reload · <kbd>E</kbd> plant, defuse or take a gun · <kbd>B</kbd> buy · | |
| 98 | right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · <kbd>Tab</kbd> scores · | |
| 99 | <kbd>Esc</kbd> pause, where sound and sensitivity live too</p> | |
| 100 | <p class="hint">On a phone: the left of the view is a thumb stick, the right aims, a second | |
| 101 | finger on the right fires, and the pad under the view does the rest — guns, scores, buy | |
| 102 | and a menu you can leave the match from.</p> | |
| 103 | </div> | |
| 104 | <div class="overlay" id="pause" hidden> | |
| 105 | <h2>Paused</h2> | |
| 106 | <div class="row"> | |
| 107 | <label>Sensitivity<input id="pause-sens" type="number" min="0.2" max="12" step="0.1"></label> | |
| 108 | <label>Volume<input id="volume" type="range" min="0" max="100" step="1"></label> | |
| 109 | <button type="button" id="mute" aria-pressed="false">Mute</button> | |
| 110 | </div> | |
| 111 | <div class="row"><button type="button" class="primary" id="resume">Resume</button><button type="button" id="quit">Leave match</button></div> | |
| 112 | </div> | |
| 113 | <div class="overlay" id="summary" hidden> | |
| 114 | <h2 id="summary-title">Match over</h2> | |
| 115 | <p id="summary-detail"></p> | |
| 116 | <p class="score" id="summary-score"></p> | |
| 117 | <p id="summary-line"></p> | |
| 118 | <div class="row"> | |
| 119 | <button type="button" class="primary" id="again">Play again</button> | |
| 120 | <button type="button" id="summary-menu">Back to menu</button> | |
| 121 | </div> | |
| 122 | </div> | |
| 123 | <div class="overlay" id="buy" hidden></div> | |
| 124 | </div> | |
| 125 | ||
| 126 | <div id="touch" hidden> | |
| 127 | <div class="pad"> | |
| 128 | <button type="button" data-action="slot1"><b>1</b>rifle</button> | |
| 129 | <button type="button" data-action="slot2"><b>2</b>pistol</button> | |
| 130 | <button type="button" data-action="slot3"><b>3</b>knife</button> | |
| 131 | <button type="button" data-action="scoreboard">scores</button> | |
| 132 | <button type="button" data-action="menu">menu</button> | |
| 133 | </div> | |
| 134 | <div class="pad"> | |
| 135 | <button type="button" data-action="duck">crouch</button> | |
| 136 | <button type="button" data-action="jump">jump</button> | |
| 137 | <button type="button" data-action="use">use</button> | |
| 138 | <button type="button" data-action="reload">reload</button> | |
| 139 | <button type="button" data-action="buy">buy</button> | |
| 140 | <button type="button" data-action="scope">scope</button> | |
| 141 | </div> | |
| 142 | <div class="pad wide"> | |
| 143 | <button type="button" class="fire" data-action="fire">fire</button> | |
| 144 | </div> | |
| 145 | <p class="hint">Left of the view is the stick, the right aims — and a second | |
| 146 | finger anywhere on the right fires without moving your aim.</p> | |
| 147 | </div> | |
| 148 | ||
| 149 | <section id="stats"><h2>Leaderboard</h2> | |
| 150 | <p class="empty">No matches yet. Play one and it lands here.</p> | |
| 151 | <h3>Recent matches</h3> | |
| 152 | <ul class="recent"><li class="empty">nothing yet</li></ul></section> | |
| 153 | ||
| 154 | <section> | |
| 155 | <h2>What this is</h2> | |
| 156 | <p>A defusal shooter written for the browser: WebGL2 drawn by hand, Source-style movement | |
| 157 | (friction, air acceleration, 18-unit steps, strafe jumping), CS damage with armour and | |
| 158 | hitgroups, fixed spray patterns you can learn, a round clock, a bomb and the buy economy. | |
| 159 | Everything you see is generated — the map, the textures, the models and the sounds — so the | |
| 160 | whole game is one small download and no asset files.</p> | |
| 161 | <p>The bots path to a site and plant or defuse on their own, but they do not aim by rule: | |
| 162 | the fight is run by a small neural network trained with PPO against | |
| 163 | 12,288,000 ticks of this same simulation, in | |
| 164 | 12.2 minutes on 2 cores. | |
| 165 | In 240 fixed duels it wins | |
| 166 | 72% against the scripted bots this game used to have, which win | |
| 167 | 42% of the same duels. Its weights are about eight kilobytes | |
| 168 | of int8 inside the bundle — there is no inference server and nothing is sent anywhere. Each | |
| 169 | bot's own skill still decides how fast it can turn, how steady its hands are and how long it | |
| 170 | takes to react, so there is still a ladder from fodder to uncomfortable.</p> | |
| 171 | <p>The match runs entirely in your browser; the leaderboard here is what your browser | |
| 172 | reported about it.</p> | |
| 173 | <p>The app's terminal is off.</p> | |
| 174 | </section> | |
| 175 | </main> | |
| 176 | <footer>cs · local · state lives in this environment's own database</footer> | |
| 177 | <script type="module" src="/static/app.7899a5ee1a.js"></script> | |
| 178 | </html> |
.gitignore +1
| @@ -3,3 +3,4 @@ node_modules/ | ||
| 3 | 3 | *.db-wal |
| 4 | 4 | *.db-shm |
| 5 | 5 | static/app.*.js |
| 6 | .checkdata/ |
README.md +2 −1
| @@ -58,7 +58,8 @@ wants one, but the running server never reads it. | ||
| 58 | 58 | the left channel, to your right the right — and a running player who is not |
| 59 | 59 | walking, ducking or airborne leaves footsteps this way too, so someone |
| 60 | 60 | closing in from behind is something you hear before you see. The |
| 61 | leaderboard is a real SQLite table under `FORGE_APP_DATA`. | |
| 61 | leaderboard is a real SQLite table under `FORGE_APP_DATA`, also served as | |
| 62 | plain JSON from `GET /api/leaderboard` for the terminal or any other client. | |
| 62 | 63 | - **Generated, not licensed.** The map (`de_forge`), the textures, the player and |
| 63 | 64 | weapon models and every sound are produced in code at start-up. There are no |
| 64 | 65 | asset files and nothing from the real game is used — the numbers follow CS's |
src/pages/game.ts +14 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | import { headshotShare, ratio, recentMatches, standings } from "../db.ts"; | |
| 8 | import { headshotShare, ratio, recentMatches, standings, type MatchRow, type Standing } from "../db.ts"; | |
| 9 | 9 | import { CARD } from "../client/weights.ts"; |
| 10 | 10 | |
| 11 | 11 | export const escape = (s: string): string => |
| @@ -36,6 +36,19 @@ ${table.length === 0 | ||
| 36 | 36 | <ul class="recent">${feed || `<li class="empty">nothing yet</li>`}</ul>`; |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | export type LeaderboardJson = { | |
| 40 | standings: Standing[]; | |
| 41 | recent: Omit<MatchRow, "session">[]; | |
| 42 | }; | |
| 43 | ||
| 44 | /** The same leaderboard as statsHtml, as data: what GET /api/leaderboard answers. */ | |
| 45 | export function leaderboardJson(db: Database): LeaderboardJson { | |
| 46 | return { | |
| 47 | standings: standings(db, 10), | |
| 48 | recent: recentMatches(db, 8).map(({ session: _session, ...match }) => match), | |
| 49 | }; | |
| 50 | } | |
| 51 | ||
| 39 | 52 | const STYLE = ` |
| 40 | 53 | :root { color-scheme: dark; --bg:b0d11; --panel:41821; --line:32a36; --text:; --dim:aa4b4; --t:; --ct:fa8e8; } |
| 41 | 54 | * { box-sizing: border-box; } |
src/server.test.ts +14 −1
| @@ -7,7 +7,8 @@ import { parseResult } from "./result.ts"; | ||
| 7 | 7 | |
| 8 | 8 | process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-")); |
| 9 | 9 | process.env.PORT = "0"; |
| 10 | const { server } = await import("./server.ts"); | |
| 10 | const { serve } = await import("./server.ts"); | |
| 11 | const server = await serve(); | |
| 11 | 12 | const base = `http://${server.hostname}:${server.port}`; |
| 12 | 13 | |
| 13 | 14 | const result = (over: Record<string, unknown> = {}): Record<string, unknown> => ({ |
| @@ -151,6 +152,18 @@ test("the script is served immutable, as javascript, under the security floor", | ||
| 151 | 152 | expect(response.headers.get("x-content-type-options")).toBe("nosniff"); |
| 152 | 153 | }); |
| 153 | 154 | |
| 155 | test("the leaderboard is also plain JSON, for a terminal or another client", async () => { | |
| 156 | await post(result({ name: "Jsonface" })); | |
| 157 | const response = await fetch(base + "/api/leaderboard"); | |
| 158 | expect(response.status).toBe(200); | |
| 159 | expect(response.headers.get("content-type")).toBe("application/json; charset=utf-8"); | |
| 160 | expect(response.headers.get("content-security-policy")).toContain("default-src 'self'"); | |
| 161 | const body = (await response.json()) as { standings: unknown[]; recent: Record<string, unknown>[] }; | |
| 162 | expect(body.standings.some((s) => (s as { name: string }).name === "Jsonface")).toBe(true); | |
| 163 | expect(body.recent.some((m) => m.name === "Jsonface")).toBe(true); | |
| 164 | expect(body.recent.every((m) => !("session" in m))).toBe(true); | |
| 165 | }); | |
| 166 | ||
| 154 | 167 | test("a result parses to exactly what was sent, and nothing else", () => { |
| 155 | 168 | const parsed = parseResult({ ...result({ name: " spaced " }), extra: "ignored" }); |
| 156 | 169 | expect(parsed?.name).toBe("spaced"); |
src/server.ts +94 −80
| @@ -9,11 +9,9 @@ | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { bundle } from "./bundle.ts"; |
| 11 | 11 | import { openDatabase, saveMatch } from "./db.ts"; |
| 12 | import { escape, gamePage, statsHtml } from "./pages/game.ts"; | |
| 12 | import { escape, gamePage, leaderboardJson, statsHtml } from "./pages/game.ts"; | |
| 13 | 13 | import { parseResult } from "./result.ts"; |
| 14 | 14 | |
| 15 | const db = openDatabase(); | |
| 16 | ||
| 17 | 15 | const env = process.env.FORGE_APP_ENV ?? "local"; |
| 18 | 16 | const pull = process.env.FORGE_APP_PULL; |
| 19 | 17 | const commit = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7); |
| @@ -109,88 +107,104 @@ const newSession = (): string => | ||
| 109 | 107 | const sessionCookie = (session: string): string => |
| 110 | 108 | `${SESSION_COOKIE}=${session}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000${secure ? "; Secure" : ""}`; |
| 111 | 109 | |
| 112 | // Built once at start-up, kept in memory: a browser can never be served a | |
| 113 | // bundle that predates the sources it names. A build that fails is loud — | |
| 114 | // it never gets to open the port on a page with no game. | |
| 115 | const buildStart = performance.now(); | |
| 116 | let scriptName: string; | |
| 117 | let scriptCode: string; | |
| 118 | try { | |
| 119 | ({ name: scriptName, code: scriptCode } = await bundle()); | |
| 120 | } catch (error) { | |
| 121 | console.error("failed to build the client bundle:", error); | |
| 122 | process.exit(1); | |
| 123 | } | |
| 124 | const buildMs = Math.round(performance.now() - buildStart); | |
| 125 | const script = `/static/${scriptName}`; | |
| 110 | export async function serve(): Promise<ReturnType<typeof Bun.serve>> { | |
| 111 | const db = openDatabase(); | |
| 126 | 112 | |
| 127 | export const server = Bun.serve({ | |
| 128 | port: Number(process.env.PORT ?? 8080), | |
| 129 | hostname: process.env.HOST ?? "127.0.0.1", | |
| 130 | async fetch(request) { | |
| 131 | const url = new URL(request.url); | |
| 132 | if (request.method === "POST" && !sameOrigin(request)) | |
| 133 | return new Response("forbidden", { status: 403, headers: SECURITY }); | |
| 113 | // Built once at start-up, kept in memory: a browser can never be served a | |
| 114 | // bundle that predates the sources it names. A build that fails is loud — | |
| 115 | // it never gets to open the port on a page with no game. | |
| 116 | const buildStart = performance.now(); | |
| 117 | let scriptName: string; | |
| 118 | let scriptCode: string; | |
| 119 | try { | |
| 120 | ({ name: scriptName, code: scriptCode } = await bundle()); | |
| 121 | } catch (error) { | |
| 122 | console.error("failed to build the client bundle:", error); | |
| 123 | process.exit(1); | |
| 124 | } | |
| 125 | const buildMs = Math.round(performance.now() - buildStart); | |
| 126 | const script = `/static/${scriptName}`; | |
| 134 | 127 | |
| 135 | if (request.method === "POST" && url.pathname === "/api/match") { | |
| 136 | const body = await readBody(request); | |
| 137 | if (body === undefined) return new Response("too large", { status: 413, headers: SECURITY }); | |
| 138 | let parsed: unknown; | |
| 139 | try { | |
| 140 | parsed = JSON.parse(new TextDecoder().decode(body)); | |
| 141 | } catch { | |
| 142 | return new Response("bad json", { status: 400, headers: SECURITY }); | |
| 128 | const server = Bun.serve({ | |
| 129 | port: Number(process.env.PORT ?? 8080), | |
| 130 | hostname: process.env.HOST ?? "127.0.0.1", | |
| 131 | async fetch(request) { | |
| 132 | const url = new URL(request.url); | |
| 133 | if (request.method === "POST" && !sameOrigin(request)) | |
| 134 | return new Response("forbidden", { status: 403, headers: SECURITY }); | |
| 135 | ||
| 136 | if (request.method === "POST" && url.pathname === "/api/match") { | |
| 137 | const body = await readBody(request); | |
| 138 | if (body === undefined) return new Response("too large", { status: 413, headers: SECURITY }); | |
| 139 | let parsed: unknown; | |
| 140 | try { | |
| 141 | parsed = JSON.parse(new TextDecoder().decode(body)); | |
| 142 | } catch { | |
| 143 | return new Response("bad json", { status: 400, headers: SECURITY }); | |
| 144 | } | |
| 145 | const result = parseResult(parsed); | |
| 146 | if (result === null) return new Response("bad result", { status: 422, headers: SECURITY }); | |
| 147 | const session = readSession(request) ?? newSession(); | |
| 148 | const stored = saveMatch(db, session, result); | |
| 149 | if (!stored) return new Response("not yours", { status: 409, headers: SECURITY }); | |
| 150 | return html(statsHtml(db), 200, { "set-cookie": sessionCookie(session) }); | |
| 143 | 151 | } |
| 144 | const result = parseResult(parsed); | |
| 145 | if (result === null) return new Response("bad result", { status: 422, headers: SECURITY }); | |
| 146 | const session = readSession(request) ?? newSession(); | |
| 147 | const stored = saveMatch(db, session, result); | |
| 148 | if (!stored) return new Response("not yours", { status: 409, headers: SECURITY }); | |
| 149 | return html(statsHtml(db), 200, { "set-cookie": sessionCookie(session) }); | |
| 150 | } | |
| 151 | 152 | |
| 152 | // HEAD is GET without the body: a health check sees the app up. | |
| 153 | if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) { | |
| 154 | const session = readSession(request); | |
| 155 | const page = gamePage(db, { env, pull, commit, script, ssh }); | |
| 156 | const response = html(page, 200, session === null ? { "set-cookie": sessionCookie(newSession()) } : {}); | |
| 157 | return request.method === "HEAD" | |
| 158 | ? new Response(null, { status: response.status, headers: response.headers }) | |
| 159 | : response; | |
| 160 | } | |
| 153 | // The same leaderboard as the page's first paint, as data: what a | |
| 154 | // terminal or another client reads instead of scraping the HTML. | |
| 155 | if ((request.method === "GET" || request.method === "HEAD") && url.pathname === "/api/leaderboard") { | |
| 156 | const headers = { "content-type": "application/json; charset=utf-8", ...SECURITY }; | |
| 157 | return request.method === "HEAD" | |
| 158 | ? new Response(null, { headers }) | |
| 159 | : new Response(JSON.stringify(leaderboardJson(db)), { headers }); | |
| 160 | } | |
| 161 | 161 | |
| 162 | // The bundle lives in memory, not on disk: it is what start-up just | |
| 163 | // built, so this is the one URL the page's <script src> can ever mean. | |
| 164 | if ((request.method === "GET" || request.method === "HEAD") && url.pathname === script) { | |
| 165 | const headers = { | |
| 166 | "content-type": "text/javascript; charset=utf-8", | |
| 167 | "cache-control": "public, max-age=31536000, immutable", | |
| 168 | ...SECURITY, | |
| 169 | }; | |
| 170 | return request.method === "HEAD" ? new Response(null, { headers }) : new Response(scriptCode, { headers }); | |
| 171 | } | |
| 162 | // HEAD is GET without the body: a health check sees the app up. | |
| 163 | if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) { | |
| 164 | const session = readSession(request); | |
| 165 | const page = gamePage(db, { env, pull, commit, script, ssh }); | |
| 166 | const response = html(page, 200, session === null ? { "set-cookie": sessionCookie(newSession()) } : {}); | |
| 167 | return request.method === "HEAD" | |
| 168 | ? new Response(null, { status: response.status, headers: response.headers }) | |
| 169 | : response; | |
| 170 | } | |
| 172 | 171 | |
| 173 | // Other files under ./static are served as they are, cached for a year. | |
| 174 | // The path is confined to the directory. | |
| 175 | if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { | |
| 176 | const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); | |
| 177 | if (await file.exists()) | |
| 178 | return new Response(file, { | |
| 179 | headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, | |
| 180 | }); | |
| 181 | } | |
| 172 | // The bundle lives in memory, not on disk: it is what start-up just | |
| 173 | // built, so this is the one URL the page's <script src> can ever mean. | |
| 174 | if ((request.method === "GET" || request.method === "HEAD") && url.pathname === script) { | |
| 175 | const headers = { | |
| 176 | "content-type": "text/javascript; charset=utf-8", | |
| 177 | "cache-control": "public, max-age=31536000, immutable", | |
| 178 | ...SECURITY, | |
| 179 | }; | |
| 180 | return request.method === "HEAD" ? new Response(null, { headers }) : new Response(scriptCode, { headers }); | |
| 181 | } | |
| 182 | 182 | |
| 183 | return html(`<h1>Not found</h1><p><a href="/">Back to ${escape("cs")}</a></p>`, 404); | |
| 184 | }, | |
| 185 | // A bug answers with the floor and nothing else: never the runtime's own | |
| 186 | // error page, which carries source and paths, and never without the | |
| 187 | // headers. The detail goes to the log, where it belongs. | |
| 188 | error(error) { | |
| 189 | console.error(error); | |
| 190 | return html("<h1>Something went wrong</h1>", 500); | |
| 191 | }, | |
| 192 | }); | |
| 183 | // Other files under ./static are served as they are, cached for a year. | |
| 184 | // The path is confined to the directory. | |
| 185 | if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { | |
| 186 | const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); | |
| 187 | if (await file.exists()) | |
| 188 | return new Response(file, { | |
| 189 | headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, | |
| 190 | }); | |
| 191 | } | |
| 193 | 192 | |
| 194 | console.log( | |
| 195 | `cs listening on http://${server.hostname}:${server.port} (${env}) serving ${script} (built in ${buildMs}ms)`, | |
| 196 | ); | |
| 193 | return html(`<h1>Not found</h1><p><a href="/">Back to ${escape("cs")}</a></p>`, 404); | |
| 194 | }, | |
| 195 | // A bug answers with the floor and nothing else: never the runtime's own | |
| 196 | // error page, which carries source and paths, and never without the | |
| 197 | // headers. The detail goes to the log, where it belongs. | |
| 198 | error(error) { | |
| 199 | console.error(error); | |
| 200 | return html("<h1>Something went wrong</h1>", 500); | |
| 201 | }, | |
| 202 | }); | |
| 203 | ||
| 204 | console.log( | |
| 205 | `cs listening on http://${server.hostname}:${server.port} (${env}) serving ${script} (built in ${buildMs}ms)`, | |
| 206 | ); | |
| 207 | return server; | |
| 208 | } | |
| 209 | ||
| 210 | if (import.meta.main) await serve(); |
new above
offline