/** * The API process's half: global middleware around every route. * * It opens a collection, runs the rest of the pipeline inside it so the * collectors' hooks know which request they are hearing, and stamps the * record's id on the response. The views server proxies that header through, * which is how the bar finds the record of a `fetch` the page made. */ import type { BootOptions, DebugbarRuntime } from './runtime' import process from 'node:process' import { recordException } from './collectors/exceptions' import { runWithCollection } from './context' import { isLocalRequest } from './guard' import { DEBUGBAR_ID_HEADER, withRecordId } from './inject' import { beginCollection, bootDebugbar, finishCollection, shouldCollect } from './runtime' // eslint-disable-next-line pickier/no-unused-vars export type DebugbarMiddleware = (request: Request, next: () => Response | Promise) => Promise /** Let a page on another origin read the id, where CORS already lets it read the response. */ function exposeIdHeader(response: Response): void { if (!response.headers.has('access-control-allow-origin')) return const exposed = response.headers.get('access-control-expose-headers') if (exposed && exposed.toLowerCase().split(',').map(name => name.trim()).includes(DEBUGBAR_ID_HEADER.toLowerCase())) return try { response.headers.set('Access-Control-Expose-Headers', exposed ? `${exposed}, ${DEBUGBAR_ID_HEADER}` : DEBUGBAR_ID_HEADER) } catch { /* immutable headers: the id stays readable same-origin */ } } export function createApiDebugbarMiddleware(runtime: DebugbarRuntime): DebugbarMiddleware { const local = { allowRemote: runtime.config.allowRemote, appUrl: runtime.appUrl } return async (request, next) => { let path: string try { path = new URL(request.url).pathname } catch { return next() } if (request.method === 'OPTIONS' || !shouldCollect(runtime, path) || !isLocalRequest(request, local)) return next() const collection = beginCollection(runtime, request) // The router times each middleware only for a request that carries a // start stamp. The dev server sets one; set it where nothing has. const stamped = request as Request & { _startNs?: bigint } if (stamped._startNs == null) stamped._startNs = process.hrtime.bigint() let response: Response try { response = await runWithCollection(collection, next) } catch (error) { recordException(collection, error) void finishCollection(runtime, collection, { status: 500, headers: new Headers() }) throw error } if (!(response instanceof Response)) return response const answered = withRecordId(response, collection.id) exposeIdHeader(answered) void finishCollection(runtime, collection, answered) return answered } } /** * Register the debugbar on an API router. Returns false, having registered * nothing, when the debugbar is not enabled in this process. * * @example * ```ts * installApiDebugbar(route) * ``` */ export function installApiDebugbar(router: { use: (handler: any) => unknown }, options: BootOptions = {}): boolean { const runtime = bootDebugbar('api', options) if (!runtime) return false router.use(createApiDebugbarMiddleware(runtime)) return true }