import { packageContext } from 'kody:runtime' import { ASSETS } from './assets.ts' import { renderPage, type PageCtx } from './page.ts' const HOST = /^[a-z0-9.-]+(:\d{1,5})?$/i const FALLBACK_ORIGIN = 'https://kentcdodds.kody.run' /** Public origin for absolute og:image URLs. The runtime may rewrite request.url, so prefer the forwarded/Host header. */ function publicOrigin(request: Request, url: URL) { const raw = (request.headers.get('x-forwarded-host') || request.headers.get('host') || url.host).split(',')[0]!.trim() if (!HOST.test(raw)) return FALLBACK_ORIGIN const local = /^(localhost|127\.|\[::1\])/.test(raw) return `${local ? 'http' : 'https'}://${raw.toLowerCase()}` } function asset(path: string) { const a = ASSETS[path] if (!a) return null const bytes = Uint8Array.from(atob(a.b64), (c) => c.charCodeAt(0)) return new Response(bytes, { headers: { 'content-type': a.type, 'cache-control': 'public, max-age=3600' } }) } export default { async fetch(request: Request) { const url = new URL(request.url) const appBase = String(packageContext?.appBasePath ?? '').replace(/\/+$/, '') let path = url.pathname if (appBase && path.startsWith(appBase)) path = path.slice(appBase.length) path = path.replace(/\/+$/, '') || '/' if (path.endsWith('/health')) { return Response.json({ ok: true, service: 'roadster' }) } const img = asset(path) if (img) return img const clientModuleUrl = packageContext?.clientModuleUrl ?? null if (!clientModuleUrl) { return new Response('Game client is not available yet. Try again after publish.', { status: 503, headers: { 'content-type': 'text/plain; charset=utf-8' }, }) } const ctx: PageCtx = { origin: publicOrigin(request, url), appBase } return new Response(renderPage(clientModuleUrl, ctx), { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', }, }) }, }