From 9b8653ed97b988ea68bd8a7dfab02bc42b5f9b60 Mon Sep 17 00:00:00 2001 From: Chris Wanstrath Date: Fri, 12 Dec 2025 12:06:41 -0800 Subject: [PATCH] threadsafe frontend() --- src/frontend.ts | 14 +++++++------- src/index.tsx | 23 ++++++++++++----------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/frontend.ts b/src/frontend.ts index 324c578..0b9b497 100644 --- a/src/frontend.ts +++ b/src/frontend.ts @@ -1,14 +1,14 @@ -let funcs: string[] = [] +import { AsyncLocalStorage } from 'async_hooks' + +export const fnStorage = new AsyncLocalStorage<{ fns: string[] }>() // Designate a function in a .tsx file as frontend export function frontend(code: Function) { - funcs.push(code.toString()) + const store = fnStorage.getStore() + store?.fns.push(code.toString()) } export function feFunctions(): string[] { - return funcs + const store = fnStorage.getStore() + return store?.fns ?? [] } - -export function clearFeFunctions() { - funcs.length = 0 -} \ No newline at end of file diff --git a/src/index.tsx b/src/index.tsx index 5d72626..b00511a 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -6,7 +6,7 @@ import color from 'kleur' import { transpile } from './utils' import defaultLayout from './layout' -import { feFunctions, clearFeFunctions } from './frontend' +import { feFunctions, fnStorage } from './frontend' const SHOW_HTTP_LOG = true const CSS_RESET = await Bun.file(join(import.meta.dir, '/reset.css')).text() @@ -90,20 +90,21 @@ export class Hype< // serve frontend js this.use('*', async (c, next) => { - await next() + await fnStorage.run({ fns: [] }, async () => { + await next() - const contentType = c.res.headers.get('content-type') - if (!contentType?.includes('text/html')) return + const contentType = c.res.headers.get('content-type') + if (!contentType?.includes('text/html')) return - const fns = feFunctions() - if (!fns.length) return + const fns = feFunctions() + if (!fns.length) return - const res = c.res.clone() - const html = await res.text() - const newHtml = html.replace('', ``) - clearFeFunctions() + const res = c.res.clone() + const html = await res.text() + const newHtml = html.replace('', ``) - c.res = new Response(newHtml, c.res) + c.res = new Response(newHtml, c.res) + }) }) // css reset