diff --git a/pkgs/server/api-ctx.ts b/pkgs/server/api-ctx.ts index 3c61507..1356202 100644 --- a/pkgs/server/api-ctx.ts +++ b/pkgs/server/api-ctx.ts @@ -57,6 +57,10 @@ export const createResponse = ( headers?: any; res?: any; high_compression?: boolean; + rewrite?: (arg: { + body: Bun.BodyInit; + headers: Headers | any; + }) => Bun.BodyInit; } ) => { const status = @@ -66,11 +70,18 @@ export const createResponse = ( const is_binary = binaryExtensions.includes( mime.getExtension(content_type) || "" ); - let content: any = - typeof body === "string" || is_binary ? body : JSON.stringify(body); - const headers = { ...(opt?.headers || {}) } as Record; + let pre_content = body; + if (opt?.rewrite) { + pre_content = opt.rewrite({ body: pre_content, headers }); + } + + let content: any = + typeof pre_content === "string" || is_binary + ? pre_content + : JSON.stringify(pre_content); + if (opt?.cache_accept) { let cached = false; @@ -116,12 +127,6 @@ export const createResponse = ( : undefined ); - if (opt?.headers?.["content-type"]?.includes("woff")) { - new Response(body, { - headers: { "content-type": headers["content-type"] }, - }); - } - for (const [k, v] of Object.entries(headers)) { res.headers.append(k, v); } diff --git a/pkgs/server/create.ts b/pkgs/server/create.ts index 5d81d23..c70ae75 100644 --- a/pkgs/server/create.ts +++ b/pkgs/server/create.ts @@ -79,11 +79,18 @@ export const createServer = async () => { const url = new URL(req.url) as URL; url.pathname = url.pathname.replace(/\/+/g, "/"); - const prasi = {}; const index = prodIndex(g.deploy.config.site_id, prasi); - const handle = async (req: Request) => { + const handle = async ( + req: Request, + opt?: { + rewrite?: (arg: { + body: Bun.BodyInit; + headers: Headers | any; + }) => Bun.BodyInit; + } + ) => { const api = await serveAPI(url, req); if (api) { @@ -97,6 +104,7 @@ export const createServer = async () => { content: index.render(), pathname: "index.html", cache_accept: req.headers.get("accept-encoding") || "", + opt, }); } @@ -117,6 +125,7 @@ export const createServer = async () => { content: index.render(), pathname: "index.html", cache_accept: req.headers.get("accept-encoding") || "", + opt, }); } @@ -131,6 +140,7 @@ export const createServer = async () => { content, pathname, cache_accept: req.headers.get("accept-encoding") || "", + opt, }); } } diff --git a/pkgs/server/serve-web.ts b/pkgs/server/serve-web.ts index 0fcb420..d30780e 100644 --- a/pkgs/server/serve-web.ts +++ b/pkgs/server/serve-web.ts @@ -5,6 +5,12 @@ export const serveWeb = async (arg: { pathname: string; content: string; cache_accept: string; + opt?: { + rewrite?: (arg: { + body: Bun.BodyInit; + headers: Headers | any; + }) => Bun.BodyInit; + }; }) => { const type = mime.getType(arg.pathname);