Unverified Commit 1e53071f authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Allow inspecting dev server on default port with `next dev --inspect` (#85037)

Co-authored-by: 's avatargraphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
parent eee419ea
...@@ -22,7 +22,7 @@ Create a file named `.vscode/launch.json` at the root of your project with the f ...@@ -22,7 +22,7 @@ Create a file named `.vscode/launch.json` at the root of your project with the f
"name": "Next.js: debug server-side", "name": "Next.js: debug server-side",
"type": "node-terminal", "type": "node-terminal",
"request": "launch", "request": "launch",
"command": "npm run dev" "command": "npm run dev -- --inspect"
}, },
{ {
"name": "Next.js: debug client-side", "name": "Next.js: debug client-side",
...@@ -111,23 +111,15 @@ For React-specific debugging, install the [React Developer Tools](https://react. ...@@ -111,23 +111,15 @@ For React-specific debugging, install the [React Developer Tools](https://react.
### Server-side code ### Server-side code
To debug server-side Next.js code with browser DevTools, you need to pass the [`--inspect`](https://nodejs.org/api/cli.html#cli_inspect_host_port) flag to the underlying Node.js process: To debug server-side Next.js code with browser DevTools, you need to pass the `--inspect` flag:
```bash filename="Terminal" ```bash filename="Terminal"
NODE_OPTIONS='--inspect' next dev next dev --inspect
``` ```
> **Good to know**: Use `NODE_OPTIONS='--inspect=0.0.0.0'` to allow remote debugging access outside localhost, such as when running the app in a Docker container. The value of `--inspect` is passed to the underlying Node.js process. Check out the [`--inspect` docs for advanced use cases](https://nodejs.org/api/cli.html#--inspecthostport).
If you're using `npm run dev` or `yarn dev` then you should update the `dev` script on your `package.json`: > **Good to know**: Use `--inspect=0.0.0.0` to allow remote debugging access outside localhost, such as when running the app in a Docker container.
```json filename="package.json"
{
"scripts": {
"dev": "NODE_OPTIONS='--inspect' next dev"
}
}
```
Launching the Next.js dev server with the `--inspect` flag will look something like this: Launching the Next.js dev server with the `--inspect` flag will look something like this:
...@@ -140,22 +132,22 @@ ready - started server on 0.0.0.0:3000, url: http://localhost:3000 ...@@ -140,22 +132,22 @@ ready - started server on 0.0.0.0:3000, url: http://localhost:3000
For Chrome: For Chrome:
1. Open a new tab and visit `chrome://inspect` 1. Open a new tab and visit `chrome://inspect`
2. Click **Configure...** to ensure both debugging ports are listed 1. Look for your Next.js application in the **Remote Target** section
3. Add both `localhost:9229` and `localhost:9230` if they're not already present 1. Click **inspect** to open a separate DevTools window
4. Look for your Next.js application in the **Remote Target** section 1. Go to the **Sources** tab
5. Click **inspect** to open a separate DevTools window
6. Go to the **Sources** tab
For Firefox: For Firefox:
1. Open a new tab and visit `about:debugging` 1. Open a new tab and visit `about:debugging`
2. Click **This Firefox** in the left sidebar 1. Click **This Firefox** in the left sidebar
3. Under **Remote Targets**, find your Next.js application 1. Under **Remote Targets**, find your Next.js application
4. Click **Inspect** to open the debugger 1. Click **Inspect** to open the debugger
5. Go to the **Debugger** tab 1. Go to the **Debugger** tab
Debugging server-side code works similarly to client-side debugging. When searching for files (`Ctrl+P`/`⌘+P`), your source files will have paths starting with `webpack://{application-name}/./` (where `{application-name}` will be replaced with the name of your application according to your `package.json` file). Debugging server-side code works similarly to client-side debugging. When searching for files (`Ctrl+P`/`⌘+P`), your source files will have paths starting with `webpack://{application-name}/./` (where `{application-name}` will be replaced with the name of your application according to your `package.json` file).
To use `--inspect-brk` or `--inspect-wait`, you have to specify `NODE_OPTIONS` instead. e.g. `NODE_OPTIONS=--inspect-brk next dev`.
### Inspect Server Errors with Browser DevTools ### Inspect Server Errors with Browser DevTools
When you encounter an error, inspecting the source code can help trace the root cause of errors. When you encounter an error, inspecting the source code can help trace the root cause of errors.
...@@ -164,19 +156,7 @@ Next.js will display a Node.js icon underneath the Next.js version indicator on ...@@ -164,19 +156,7 @@ Next.js will display a Node.js icon underneath the Next.js version indicator on
### Debugging on Windows ### Debugging on Windows
Windows users may run into an issue when using `NODE_OPTIONS='--inspect'` as that syntax is not supported on Windows platforms. To get around this, install the [`cross-env`](https://www.npmjs.com/package/cross-env) package as a development dependency (`-D` with `npm` and `yarn`) and replace the `dev` script with the following. Ensure Windows Defender is disabled on your machine. This external service will check _every file read_, which has been reported to greatly increase Fast Refresh time with `next dev`. This is a known issue, not related to Next.js, but it does affect Next.js development.
```json filename="package.json"
{
"scripts": {
"dev": "cross-env NODE_OPTIONS='--inspect' next dev"
}
}
```
`cross-env` will set the `NODE_OPTIONS` environment variable regardless of which platform you are on (including Mac, Linux, and Windows) and allow you to debug consistently across devices and operating systems.
> **Good to know**: Ensure Windows Defender is disabled on your machine. This external service will check _every file read_, which has been reported to greatly increase Fast Refresh time with `next dev`. This is a known issue, not related to Next.js, but it does affect Next.js development.
## More information ## More information
......
...@@ -2,14 +2,23 @@ ...@@ -2,14 +2,23 @@
import '../server/require-hook' import '../server/require-hook'
import { Argument, Command, Option } from 'next/dist/compiled/commander' import {
Argument,
Command,
InvalidArgumentError,
Option,
} from 'next/dist/compiled/commander'
import { warn } from '../build/output/log' import { warn } from '../build/output/log'
import semver from 'next/dist/compiled/semver' import semver from 'next/dist/compiled/semver'
import { bold, cyan, italic } from '../lib/picocolors' import { bold, cyan, italic } from '../lib/picocolors'
import { formatCliHelpOutput } from '../lib/format-cli-help-output' import { formatCliHelpOutput } from '../lib/format-cli-help-output'
import { NON_STANDARD_NODE_ENV } from '../lib/constants' import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import { parseValidPositiveInteger } from '../server/lib/utils' import {
getParsedDebugAddress,
parseValidPositiveInteger,
type DebugAddress,
} from '../server/lib/utils'
import { import {
SUPPORTED_TEST_RUNNERS_LIST, SUPPORTED_TEST_RUNNERS_LIST,
type NextTestOptions, type NextTestOptions,
...@@ -57,8 +66,6 @@ class NextRootCommand extends Command { ...@@ -57,8 +66,6 @@ class NextRootCommand extends Command {
createCommand(name: string) { createCommand(name: string) {
const command = new Command(name) const command = new Command(name)
command.addOption(new Option('--inspect').hideHelp())
command.hook('preAction', (event) => { command.hook('preAction', (event) => {
const commandName = event.name() const commandName = event.name()
const defaultEnv = commandName === 'dev' ? 'development' : 'production' const defaultEnv = commandName === 'dev' ? 'development' : 'production'
...@@ -81,7 +88,7 @@ class NextRootCommand extends Command { ...@@ -81,7 +88,7 @@ class NextRootCommand extends Command {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv ;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs' ;(process.env as any).NEXT_RUNTIME = 'nodejs'
if (event.getOptionValue('inspect') === true) { if (commandName !== 'dev' && event.getOptionValue('inspect') === true) {
console.error( console.error(
`\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}` `\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}`
) )
...@@ -93,6 +100,22 @@ class NextRootCommand extends Command { ...@@ -93,6 +100,22 @@ class NextRootCommand extends Command {
} }
} }
function parseValidInspectAddress(value: string): DebugAddress {
const address = getParsedDebugAddress(value)
if (Number.isNaN(address.port)) {
throw new InvalidArgumentError(
'The given value is not a valid inspect address. ' +
'Did you mean to pass an app path?\n' +
`Try switching the order of the arguments or set the default address explicitly e.g.\n` +
`next dev ${value} --inspect\n` +
`next dev --inspect= ${value}`
)
}
return address
}
const program = new NextRootCommand() const program = new NextRootCommand()
program program
...@@ -162,6 +185,7 @@ program ...@@ -162,6 +185,7 @@ program
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
// ensure process exits after build completes so open handles/connections // ensure process exits after build completes so open handles/connections
// don't cause process to hang // don't cause process to hang
return import('../cli/next-build.js').then((mod) => return import('../cli/next-build.js').then((mod) =>
...@@ -181,6 +205,12 @@ program ...@@ -181,6 +205,12 @@ program
'If no directory is provided, the current directory will be used.' 'If no directory is provided, the current directory will be used.'
)}` )}`
) )
.addOption(
new Option(
'--inspect [[host:]port]',
'Allows inspecting server-side code. See https://nextjs.org/docs/app/guides/debugging#server-side-code'
).argParser(parseValidInspectAddress)
)
.option('--turbo', 'Starts development mode using Turbopack.') .option('--turbo', 'Starts development mode using Turbopack.')
.option('--turbopack', 'Starts development mode using Turbopack.') .option('--turbopack', 'Starts development mode using Turbopack.')
.option('--webpack', 'Starts development mode using webpack.') .option('--webpack', 'Starts development mode using webpack.')
......
...@@ -7,10 +7,11 @@ import { ...@@ -7,10 +7,11 @@ import {
getNodeDebugType, getNodeDebugType,
getParsedDebugAddress, getParsedDebugAddress,
getMaxOldSpaceSize, getMaxOldSpaceSize,
getParsedNodeOptionsWithoutInspect,
printAndExit, printAndExit,
formatNodeOptions, formatNodeOptions,
formatDebugAddress, formatDebugAddress,
getParsedNodeOptions,
type DebugAddress,
} from '../server/lib/utils' } from '../server/lib/utils'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
...@@ -46,6 +47,8 @@ import { ...@@ -46,6 +47,8 @@ import {
export type NextDevOptions = { export type NextDevOptions = {
disableSourceMaps: boolean disableSourceMaps: boolean
// Commander is not putting `--inspect` through the arg parser
inspect?: DebugAddress | true
turbo?: boolean turbo?: boolean
turbopack?: boolean turbopack?: boolean
webpack?: boolean webpack?: boolean
...@@ -259,8 +262,7 @@ const nextDev = async ( ...@@ -259,8 +262,7 @@ const nextDev = async (
let resolved = false let resolved = false
const defaultEnv = (initialEnv || process.env) as typeof process.env const defaultEnv = (initialEnv || process.env) as typeof process.env
const nodeOptions = getParsedNodeOptionsWithoutInspect() const nodeOptions = getParsedNodeOptions()
const nodeDebugType = getNodeDebugType()
let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize() let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()
if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) { if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {
...@@ -280,10 +282,22 @@ const nextDev = async ( ...@@ -280,10 +282,22 @@ const nextDev = async (
nodeOptions['enable-source-maps'] = true nodeOptions['enable-source-maps'] = true
} }
if (nodeDebugType) { const nodeDebugType = getNodeDebugType(nodeOptions)
const address = getParsedDebugAddress() const originalAddress =
nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType]
delete nodeOptions.inspect
delete nodeOptions['inspect-brk']
delete nodeOptions['inspect_brk']
if (nodeDebugType !== undefined) {
const address = getParsedDebugAddress(originalAddress)
address.port = address.port === 0 ? 0 : address.port + 1 address.port = address.port === 0 ? 0 : address.port + 1
nodeOptions[nodeDebugType] = formatDebugAddress(address) nodeOptions[nodeDebugType] = formatDebugAddress(address)
} else if (options.inspect) {
const address: DebugAddress =
options.inspect === true
? getParsedDebugAddress(true)
: options.inspect
nodeOptions.inspect = formatDebugAddress(address)
} }
child = fork(startServerPath, { child = fork(startServerPath, {
......
...@@ -6,7 +6,8 @@ import { ...@@ -6,7 +6,8 @@ import {
formatNodeOptions, formatNodeOptions,
getNodeDebugType, getNodeDebugType,
getParsedDebugAddress, getParsedDebugAddress,
getParsedNodeOptionsWithoutInspect, getParsedNodeOptions,
type DebugAddress,
} from '../server/lib/utils' } from '../server/lib/utils'
type FarmOptions = NonNullable<ConstructorParameters<typeof JestWorker>[1]> type FarmOptions = NonNullable<ConstructorParameters<typeof JestWorker>[1]>
...@@ -78,19 +79,25 @@ export class Worker { ...@@ -78,19 +79,25 @@ export class Worker {
this.close() this.close()
}) })
const nodeOptions = getParsedNodeOptionsWithoutInspect() const nodeOptions = getParsedNodeOptions()
const originalOptions = { ...nodeOptions }
delete nodeOptions.inspect
delete nodeOptions['inspect-brk']
delete nodeOptions['inspect_brk']
if (debuggerPortOffset !== -1) { if (debuggerPortOffset !== -1) {
const nodeDebugType = getNodeDebugType() const nodeDebugType = getNodeDebugType(originalOptions)
if (nodeDebugType) { if (nodeDebugType) {
const address = getParsedDebugAddress() const debuggerAddress = getParsedDebugAddress(
address.port = originalOptions[nodeDebugType]
address.port === 0 )
? 0 const address: DebugAddress = {
: address.port + host: debuggerAddress.host,
// current process runs on `address.port` // current process runs on `address.port`
1 + port:
debuggerPortOffset debuggerAddress.port === 0
? 0
: debuggerAddress.port + 1 + debuggerPortOffset,
}
nodeOptions[nodeDebugType] = formatDebugAddress(address) nodeOptions[nodeDebugType] = formatDebugAddress(address)
} }
} }
......
...@@ -78,7 +78,7 @@ import { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-serv ...@@ -78,7 +78,7 @@ import { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-serv
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition' import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { ModernSourceMapPayload } from '../lib/source-maps' import type { ModernSourceMapPayload } from '../lib/source-maps'
import { getNodeDebugType } from '../lib/utils' import { getNodeDebugType, getParsedNodeOptions } from '../lib/utils'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route' import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect' import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware' import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
...@@ -810,7 +810,8 @@ export async function createHotReloaderTurbopack( ...@@ -810,7 +810,8 @@ export async function createHotReloaderTurbopack(
} }
let devtoolsFrontendUrl: string | undefined let devtoolsFrontendUrl: string | undefined
const nodeDebugType = getNodeDebugType() const nodeOptions = getParsedNodeOptions()
const nodeDebugType = getNodeDebugType(nodeOptions)
if (nodeDebugType) { if (nodeDebugType) {
const debugPort = process.debugPort const debugPort = process.debugPort
let debugInfo let debugInfo
......
...@@ -81,7 +81,7 @@ import type { HmrMessageSentToBrowser } from './hot-reloader-types' ...@@ -81,7 +81,7 @@ import type { HmrMessageSentToBrowser } from './hot-reloader-types'
import type { WebpackError } from 'webpack' import type { WebpackError } from 'webpack'
import { PAGE_TYPES } from '../../lib/page-types' import { PAGE_TYPES } from '../../lib/page-types'
import { FAST_REFRESH_RUNTIME_RELOAD } from './messages' import { FAST_REFRESH_RUNTIME_RELOAD } from './messages'
import { getNodeDebugType } from '../lib/utils' import { getNodeDebugType, getParsedNodeOptions } from '../lib/utils'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware' import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware' import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'
import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware' import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'
...@@ -860,7 +860,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -860,7 +860,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
this.versionInfo = await this.tracedGetVersionInfo(startSpan) this.versionInfo = await this.tracedGetVersionInfo(startSpan)
const nodeDebugType = getNodeDebugType() const nodeOptions = getParsedNodeOptions()
const nodeDebugType = getNodeDebugType(nodeOptions)
if (nodeDebugType && !this.devtoolsFrontendUrl) { if (nodeDebugType && !this.devtoolsFrontendUrl) {
const debugPort = process.debugPort const debugPort = process.debugPort
let debugInfo let debugInfo
......
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import * as inspector from 'inspector'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { bold, purple, strikethrough } from '../../lib/picocolors' import { bold, purple, strikethrough } from '../../lib/picocolors'
import { import {
...@@ -50,10 +51,19 @@ export function logStartInfo({ ...@@ -50,10 +51,19 @@ export function logStartInfo({
)}${versionSuffix}` )}${versionSuffix}`
) )
if (appUrl) { if (appUrl) {
Log.bootstrap(`- Local: ${appUrl}`) Log.bootstrap(`- Local: ${appUrl}`)
} }
if (networkUrl) { if (networkUrl) {
Log.bootstrap(`- Network: ${networkUrl}`) Log.bootstrap(`- Network: ${networkUrl}`)
}
const inspectorUrl = inspector.url()
if (inspectorUrl) {
// Could also parse this port from the inspector URL.
// process.debugPort will always be defined even if the process is not being inspected.
// The full URL seems noisy as far as I can tell.
// Node.js will print the full URL anyway.
const debugPort = process.debugPort
Log.bootstrap(`- Debugger port: ${debugPort}`)
} }
if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`) if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`)
......
...@@ -22,12 +22,7 @@ import { exec } from 'child_process' ...@@ -22,12 +22,7 @@ import { exec } from 'child_process'
import Watchpack from 'next/dist/compiled/watchpack' import Watchpack from 'next/dist/compiled/watchpack'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import setupDebug from 'next/dist/compiled/debug' import setupDebug from 'next/dist/compiled/debug'
import { import { RESTART_EXIT_CODE } from './utils'
RESTART_EXIT_CODE,
getFormattedDebugAddress,
getNodeDebugType,
isDebugAddressEphemeral,
} from './utils'
import { formatHostname } from './format-hostname' import { formatHostname } from './format-hostname'
import { initialize } from './router-server' import { initialize } from './router-server'
import { CONFIG_FILES } from '../../shared/lib/constants' import { CONFIG_FILES } from '../../shared/lib/constants'
...@@ -305,8 +300,6 @@ export async function startServer( ...@@ -305,8 +300,6 @@ export async function startServer(
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
server.on('listening', async () => { server.on('listening', async () => {
const nodeDebugType = getNodeDebugType()
const addr = server.address() const addr = server.address()
const actualHostname = formatHostname( const actualHostname = formatHostname(
typeof addr === 'object' typeof addr === 'object'
...@@ -346,17 +339,6 @@ export async function startServer( ...@@ -346,17 +339,6 @@ export async function startServer(
const appUrl = `${protocol}://${formattedHostname}:${port}` const appUrl = `${protocol}://${formattedHostname}:${port}`
if (nodeDebugType) {
const formattedDebugAddress = getFormattedDebugAddress()
const isEphemeral = isDebugAddressEphemeral()
Log.info(
`the --${nodeDebugType} option was detected` +
(isEphemeral
? ''
: `, the Next.js router server should be inspected at ${formattedDebugAddress}.`)
)
}
// Store the selected port to: // Store the selected port to:
// - expose it to render workers // - expose it to render workers
// - re-use it for automatic dev server restarts with a randomly selected port // - re-use it for automatic dev server restarts with a randomly selected port
......
...@@ -3,6 +3,7 @@ import { ...@@ -3,6 +3,7 @@ import {
getParsedDebugAddress, getParsedDebugAddress,
formatNodeOptions, formatNodeOptions,
tokenizeArgs, tokenizeArgs,
getParsedNodeOptions,
} from './utils' } from './utils'
const originalNodeOptions = process.env.NODE_OPTIONS const originalNodeOptions = process.env.NODE_OPTIONS
...@@ -56,13 +57,15 @@ describe('formatNodeOptions', () => { ...@@ -56,13 +57,15 @@ describe('formatNodeOptions', () => {
describe('getParsedDebugAddress', () => { describe('getParsedDebugAddress', () => {
it('supports the flag with an equal sign', () => { it('supports the flag with an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect=1234' process.env.NODE_OPTIONS = '--inspect=1234'
const result = getParsedDebugAddress() const nodeOptions = getParsedNodeOptions()
const result = getParsedDebugAddress(nodeOptions.inspect)
expect(result).toEqual({ host: undefined, port: 1234 }) expect(result).toEqual({ host: undefined, port: 1234 })
}) })
it('supports the flag without an equal sign', () => { it('supports the flag without an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect 1234' process.env.NODE_OPTIONS = '--inspect 1234'
const result = getParsedDebugAddress() const nodeOptions = getParsedNodeOptions()
const result = getParsedDebugAddress(nodeOptions.inspect)
expect(result).toEqual({ host: undefined, port: 1234 }) expect(result).toEqual({ host: undefined, port: 1234 })
}) })
}) })
......
...@@ -11,7 +11,9 @@ export function printAndExit(message: string, code = 1) { ...@@ -11,7 +11,9 @@ export function printAndExit(message: string, code = 1) {
return process.exit(code) return process.exit(code)
} }
const parseNodeArgs = (args: string[]) => { export type NodeOptions = Record<string, string | boolean | undefined>
const parseNodeArgs = (args: string[]): NodeOptions => {
const { values, tokens } = parseArgs({ args, strict: false, tokens: true }) const { values, tokens } = parseArgs({ args, strict: false, tokens: true })
// For the `NODE_OPTIONS`, we support arguments with values without the `=` // For the `NODE_OPTIONS`, we support arguments with values without the `=`
...@@ -127,7 +129,7 @@ export const getNodeOptionsArgs = () => { ...@@ -127,7 +129,7 @@ export const getNodeOptionsArgs = () => {
/** /**
* The debug address is in the form of `[host:]port`. The host is optional. * The debug address is in the form of `[host:]port`. The host is optional.
*/ */
type DebugAddress = { export interface DebugAddress {
host: string | undefined host: string | undefined
port: number port: number
} }
...@@ -147,17 +149,9 @@ export const formatDebugAddress = ({ host, port }: DebugAddress): string => { ...@@ -147,17 +149,9 @@ export const formatDebugAddress = ({ host, port }: DebugAddress): string => {
* *
* @returns An object with the host and port of the debug address. * @returns An object with the host and port of the debug address.
*/ */
export const getParsedDebugAddress = (): DebugAddress => { export const getParsedDebugAddress = (
const args = getNodeOptionsArgs() address: string | boolean | undefined
if (args.length === 0) return { host: undefined, port: 9229 } ): DebugAddress => {
const parsed = parseNodeArgs(args)
// We expect to find the debug port in one of these options. The first one
// found will be used.
const address =
parsed.inspect ?? parsed['inspect-brk'] ?? parsed['inspect_brk']
if (!address || typeof address !== 'string') { if (!address || typeof address !== 'string') {
return { host: undefined, port: 9229 } return { host: undefined, port: 9229 }
} }
...@@ -171,22 +165,6 @@ export const getParsedDebugAddress = (): DebugAddress => { ...@@ -171,22 +165,6 @@ export const getParsedDebugAddress = (): DebugAddress => {
return { host: undefined, port: parseInt(address, 10) } return { host: undefined, port: parseInt(address, 10) }
} }
/**
* Checks if the debug address from `NODE_OPTIONS` specifies to use a random port (e.g., the port set to 0).
*
* @returns A boolean indicating whether or not the debug address is assigned to a random port.
*/
export const isDebugAddressEphemeral = () => getParsedDebugAddress()?.port === 0
/**
* Get the debug address from the `NODE_OPTIONS` environment variable and format
* it into a string.
*
* @returns A string with the formatted debug address.
*/
export const getFormattedDebugAddress = () =>
formatDebugAddress(getParsedDebugAddress())
/** /**
* Stringify the arguments to be used in a command line. It will ignore any * Stringify the arguments to be used in a command line. It will ignore any
* argument that has a value of `undefined`. * argument that has a value of `undefined`.
...@@ -219,6 +197,16 @@ export function formatNodeOptions( ...@@ -219,6 +197,16 @@ export function formatNodeOptions(
.join(' ') .join(' ')
} }
export function getParsedNodeOptions(): Record<
string,
string | boolean | undefined
> {
const args = [...process.execArgv, ...getNodeOptionsArgs()]
if (args.length === 0) return {}
return parseNodeArgs(args)
}
/** /**
* Get the node options from the `NODE_OPTIONS` environment variable and parse * Get the node options from the `NODE_OPTIONS` environment variable and parse
* them into an object without the inspect options. * them into an object without the inspect options.
...@@ -273,14 +261,13 @@ export type NodeInspectType = 'inspect' | 'inspect-brk' | undefined ...@@ -273,14 +261,13 @@ export type NodeInspectType = 'inspect' | 'inspect-brk' | undefined
/** /**
* Get the debug type from the `NODE_OPTIONS` environment variable. * Get the debug type from the `NODE_OPTIONS` environment variable.
*/ */
export function getNodeDebugType(): NodeInspectType { export function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {
const args = [...process.execArgv, ...getNodeOptionsArgs()] if (nodeOptions.inspect) {
if (args.length === 0) return return 'inspect'
}
const parsed = parseNodeArgs(args) if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) {
return 'inspect-brk'
if (parsed.inspect) return 'inspect' }
if (parsed['inspect-brk'] || parsed['inspect_brk']) return 'inspect-brk'
} }
/** /**
......
...@@ -561,11 +561,87 @@ describe('CLI Usage', () => { ...@@ -561,11 +561,87 @@ describe('CLI Usage', () => {
) )
try { try {
await check(() => output, new RegExp(`http://localhost:${port}`)) await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+9229/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect 0', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect', '0'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect [port]', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect', '9230'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+9230/)
await check(() => errOutput, /Debugger listening on/) await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use') expect(errOutput).not.toContain('address already in use')
expect(output).toContain(
'the --inspect option was detected, the Next.js router server should be inspected at'
)
} finally { } finally {
await killApp(app) await killApp(app)
} }
...@@ -590,11 +666,11 @@ describe('CLI Usage', () => { ...@@ -590,11 +666,11 @@ describe('CLI Usage', () => {
) )
try { try {
await check(() => output, new RegExp(`http://localhost:${port}`)) await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/) await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use') expect(errOutput).not.toContain('address already in use')
expect(errOutput).toContain('Debugger listening on') expect(errOutput).toContain('Debugger listening on')
console.log(output) console.log(output)
expect(output).toContain('the --inspect option was detected')
} finally { } finally {
await killApp(app) await killApp(app)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment