import type { NestContext } from '#adapter/core/context'; import { attachTo, bytesOf, writeBody } from './response-body.ts'; import { headerValue, setHeaderValue } from './surface-extras.ts'; import { isCallable, proxyHandler } from './proxy-handler.ts'; import { writer } from './surface.ts'; interface MiddlewareResponse { readonly commit: () => void; readonly proxy: NestContext; } // Shortcut: `write` buffers until `end`, so a piped stream is held in memory. const headerReaders = ( context: NestContext, locals: Record, writeHead: (status?: number) => NestContext, ): Record => { const chunks: Uint8Array[] = []; let ended = false; return { addListener: attachTo(context, 'addListener'), appendHeader: (name: string, value: string): void => { context.header(name, value, { append: true }); }, end: (body?: unknown): void => { if (ended) return; ended = true; writeBody(context, body === undefined ? chunks : [...chunks, bytesOf(body)]); }, get finished(): boolean { return ended || context.finalized; }, getHeader: (name: string): string | readonly string[] | undefined => headerValue(context, name), hasHeader: (name: string): boolean => context.res.headers.has(name), get headersSent(): boolean { return context.finalized; }, locals, off: attachTo(context, 'off'), on: attachTo(context, 'on'), once: attachTo(context, 'once'), removeHeader: (name: string): void => { context.res.headers.delete(name); }, removeListener: attachTo(context, 'removeListener'), setHeader: (name: string, value: number | string | readonly string[]): void => { setHeaderValue(context, name, value); }, get statusCode(): number { return writer.statusOf(context) ?? context.res.status; }, write: (chunk: unknown): boolean => { if (ended) return false; chunks.push(bytesOf(chunk)); return true; }, writeHead, }; }; // `cookies` reads a present `res.set` as a real `ServerResponse`, so the proxy hides it. const middlewareResponse = (context: NestContext): MiddlewareResponse => { const overrides = new Map(); const state: { proxy: NestContext } = { proxy: context }; const writeHead = (status?: number): NestContext => { if (typeof status === 'number') { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Hono types `status` with its StatusCode union; the fitted Express surface takes any number. (context.status as unknown as (code: number) => void)(status); } return state.proxy; }; // Built on first read: a middleware that only touches the request (method spoofing) never pays // for the sixteen response members, and one that reads a fitted member skips them too. A stream // piping into the surface calls `emit`; the transport owns the real listeners. let readers: Record | undefined = undefined; const readersOf = (): Record => (readers ??= Object.assign(headerReaders(context, {}, writeHead), { emit: (event: string, ...args: unknown[]): boolean => { const { outgoing } = context.env; return outgoing === undefined ? false : outgoing.emit(event, ...args); }, })); const handler = proxyHandler(context, overrides, readersOf); // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the proxy layers Express response semantics onto the Hono context. const target = context as unknown as Record; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the handler keeps the context's shape, so the proxy answers as a NestContext. state.proxy = new Proxy(target, handler) as unknown as NestContext; const commit = (): void => { const patched = overrides.get('writeHead'); if (isCallable(patched)) patched.call(state.proxy, context.res.status); }; return { commit, proxy: state.proxy }; }; export { middlewareResponse }; export type { MiddlewareResponse };