File size: 1,284 Bytes
95e3d2a
91806f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// @ts-nocheck
// Tiny static file server with SPA fallback.
// Serves `dist/` (built by `vite build` via @sveltejs/adapter-static)
// on $PORT (defaults to 7860 — Hugging Face Spaces' default app_port).

import { join, normalize } from 'node:path';

const distDir = join(import.meta.dir, 'dist');
const indexPath = join(distDir, 'index.html');
const port = Number(process.env.PORT) || 7860;
const host = process.env.HOST || '0.0.0.0';

const server = Bun.serve({
	port,
	hostname: host,
	async fetch(req) {
		const url = new URL(req.url);
		const reqPath = url.pathname === '/' ? '/index.html' : url.pathname;

		// Resolve and pin inside distDir to defeat path traversal.
		const filePath = normalize(join(distDir, reqPath));
		if (!filePath.startsWith(distDir)) {
			return new Response('Not found', { status: 404 });
		}

		const file = Bun.file(filePath);
		if (await file.exists()) return new Response(file);

		// Anything without an extension is a client-side route — hand back
		// index.html so SvelteKit's runtime can take over.
		if (!reqPath.split('/').pop()!.includes('.')) {
			return new Response(Bun.file(indexPath));
		}

		return new Response('Not found', { status: 404 });
	}
});

console.log(`Serving ${distDir} at http://${server.hostname}:${server.port}`);