import { AsyncLocalStorage } from 'node:async_hooks' export interface TestReqInfo { url: string proxyPort: number testData: string } export interface TestRequestReader { url(req: R): string header(req: R, name: string): string | null } const testStorage = new AsyncLocalStorage() function extractTestInfoFromRequest( req: R, reader: TestRequestReader ): TestReqInfo | undefined { const proxyPortHeader = reader.header(req, 'next-test-proxy-port') if (!proxyPortHeader) { return undefined } const url = reader.url(req) const proxyPort = Number(proxyPortHeader) const testData = reader.header(req, 'next-test-data') || '' return { url, proxyPort, testData } } export function withRequest( req: R, reader: TestRequestReader, fn: () => T ): T { const testReqInfo = extractTestInfoFromRequest(req, reader) if (!testReqInfo) { return fn() } return testStorage.run(testReqInfo, fn) } export function getTestReqInfo( req?: R, reader?: TestRequestReader ): TestReqInfo | undefined { const testReqInfo = testStorage.getStore() if (testReqInfo) { return testReqInfo } if (req && reader) { return extractTestInfoFromRequest(req, reader) } return undefined }