| import { join } from "path"; | |
| const publicDir = join(process.cwd(), "dist", "public"); | |
| export async function router(req: Request): Promise<Response> { | |
| const url = new URL(req.url); | |
| const pathname = url.pathname; | |
| if (pathname === "/health") { | |
| return new Response(JSON.stringify({ status: "ok" }), { | |
| headers: { "Content-Type": "application/json" }, | |
| }); | |
| } | |
| if (pathname.startsWith("/api/")) { | |
| return handleApiRequest(pathname); | |
| } | |
| return serveStatic(pathname); | |
| } | |
| async function handleApiRequest(pathname: string): Promise<Response> { | |
| if (pathname.startsWith("/api/session/")) { | |
| const sessionId = pathname.split("/").pop(); | |
| return new Response(JSON.stringify({ sessionId, valid: true }), { | |
| headers: { "Content-Type": "application/json" }, | |
| }); | |
| } | |
| return new Response(JSON.stringify({ error: "Not found" }), { | |
| status: 404, | |
| headers: { "Content-Type": "application/json" }, | |
| }); | |
| } | |
| async function serveStatic(pathname: string): Promise<Response> { | |
| if (pathname === "/") { | |
| const indexPath = join(publicDir, "index.html"); | |
| const file = Bun.file(indexPath); | |
| return new Response(file, { | |
| headers: { "Content-Type": "text/html" }, | |
| }); | |
| } | |
| const fullPath = join(publicDir, pathname); | |
| const file = Bun.file(fullPath); | |
| const exists = await file.exists(); | |
| if (exists) { | |
| return new Response(file, { | |
| headers: { | |
| "Content-Type": getContentType(pathname), | |
| }, | |
| }); | |
| } | |
| const indexPath = join(publicDir, "index.html"); | |
| const indexFile = Bun.file(indexPath); | |
| return new Response(indexFile, { | |
| headers: { | |
| "Content-Type": "text/html", | |
| }, | |
| }); | |
| } | |
| function getContentType(pathname: string): string { | |
| const ext = pathname.split(".").pop()?.toLowerCase(); | |
| const contentTypes: Record<string, string> = { | |
| html: "text/html", | |
| css: "text/css", | |
| js: "application/javascript", | |
| json: "application/json", | |
| png: "image/png", | |
| jpg: "image/jpeg", | |
| jpeg: "image/jpeg", | |
| gif: "image/gif", | |
| svg: "image/svg+xml", | |
| ico: "image/x-icon", | |
| }; | |
| return contentTypes[ext || ""] || "application/octet-stream"; | |
| } |