/** * The client bundle: the script `/__debugbar/assets/debugbar.js` serves. * * A published package ships it prebuilt beside this module. A checkout runs * from source, where there is no build output, so it is bundled once in * memory on first request. */ import { existsSync } from 'node:fs' import { join } from 'node:path' export interface ClientBundle { body: string /** A short content hash, used as the cache-busting `v` and the ETag. */ version: string } let bundle: Promise | undefined let knownVersion = '0' async function load(): Promise { const built = join(import.meta.dir, 'client', 'debugbar.js') let body: string if (existsSync(built)) { body = await Bun.file(built).text() } else { const result = await Bun.build({ entrypoints: [join(import.meta.dir, 'client', 'index.ts')], target: 'browser', format: 'iife', minify: true, }) const output = result.outputs[0] if (!result.success || !output) throw new Error('The debugbar client could not be bundled.') body = await output.text() } knownVersion = Bun.hash(body).toString(36).slice(0, 10) return { body, version: knownVersion } } /** The loaded bundle's version, or '0' until it has loaded. Never waits. */ export function clientVersion(): string { return knownVersion } export function clientBundle(): Promise { return bundle ??= load().catch((error) => { bundle = undefined throw error }) } /** Forget the bundle, so the next request rebuilds it. For tests and client development. */ export function resetClientBundle(): void { bundle = undefined }