diff --git a/src/index.tsx b/src/index.tsx index 06645a4..9140304 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,4 +1,4 @@ -import { join } from 'path' +import { join, resolve } from 'path' import { render as formatHTML } from './lib/html-formatter' import { type Context, Hono, type Schema, type Env } from 'hono' import { serveStatic } from 'hono/bun' @@ -174,23 +174,25 @@ export class Hype< // serve transpiled js this.on('GET', ['/client/:path{.+}', '/shared/:path{.+}'], async c => { - let path = './src/' + c.req.path.replace('..', '.') + const reqPath = resolve('./src/', c.req.path.slice(1)) + if (!reqPath.startsWith(resolve('./src/'))) return render404(c) - // path must end in .js or .ts - if (!path.endsWith('.js') && !path.endsWith('.ts')) path += '.ts' + // strip known extension to get base path + const base = reqPath.replace(/\.(js|jsx|ts|tsx)$/, '') - const ts = path.replace('.js', '.ts') - if (await Bun.file(ts).exists()) - return new Response(await transpile(ts), { headers: { 'Content-Type': 'text/javascript' } }) + // try TS extensions first (needs transpilation) + for (const ext of ['.ts', '.tsx', '.jsx']) { + const file = base + ext + if (await Bun.file(file).exists()) + return new Response(await transpile(file), { headers: { 'Content-Type': 'text/javascript' } }) + } - else if (await Bun.file(ts + 'x').exists()) - return new Response(await transpile(ts + 'x'), { headers: { 'Content-Type': 'text/javascript' } }) + // try plain .js (serve raw) + const jsFile = base + '.js' + if (await Bun.file(jsFile).exists()) + return new Response(Bun.file(jsFile), { headers: { 'Content-Type': 'text/javascript' } }) - else if (await Bun.file(path).exists()) - return new Response(Bun.file(path), { headers: { 'Content-Type': 'text/javascript' } }) - - else - return render404(c) + return render404(c) }) // file based routing