File size: 1,554 Bytes
b91e262 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import { middlewareResponse } from './middleware-response'
import type { ServerResponse, IncomingMessage } from 'http'
import * as inspector from 'inspector'
export function getAttachNodejsDebuggerMiddleware() {
return async function (
req: IncomingMessage,
res: ServerResponse,
next: () => void
): Promise<void> {
const { pathname } = new URL(`http://n${req.url}`)
if (pathname !== '/__nextjs_attach-nodejs-inspector') {
return next()
}
try {
const isInspecting = inspector.url() !== undefined
const debugPort = process.debugPort
if (!isInspecting) {
// Node.js will already log that the inspector is listening.
inspector.open(debugPort)
}
const inspectorURLRaw = inspector.url()
if (inspectorURLRaw === undefined) {
// could not open, possibly because already in use.
return middlewareResponse.badRequest(
res,
`Failed to open port "${debugPort}". Address may be already in use.`
)
}
const inspectorURL = new URL(inspectorURLRaw)
const debugInfoListResponse = await fetch(
`http://${inspectorURL.host}/json/list`
)
const debugInfoList = await debugInfoListResponse.json()
if (!Array.isArray(debugInfoList) || debugInfoList.length === 0) {
throw new Error('No debug targets found')
}
return middlewareResponse.json(res, debugInfoList[0].devtoolsFrontendUrl)
} catch (error) {
return middlewareResponse.internalServerError(res)
}
}
}
|