Unverified Commit ab86fcf5 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

NODE_OPTIONS updates (#65006)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

### What?

Previously, parsing and managing the `NODE_OPTIONS` was performed using
a series of regular expressions. These were prone to bugs, and have
already caused a few issues. This moves us over to the standard
`parseArgs`
([docs](https://nodejs.org/docs/latest/api/util.html#utilparseargsconfig)):

```js
import { parseArgs } from "node:utils"
```

### Why?

This simplifies the argument parser dramatically, removing the need for
any special patterns or accommodations. No need to maintain all these
patterns when there's a lightweight built-in parser already available.

Fixes https://github.com/vercel/next.js/issues/53127
Fixes https://github.com/vercel/next.js/issues/53757
Fixes https://github.com/vercel/next.js/issues/47083
Fixes https://github.com/vercel/next.js/issues/50489
Closes https://github.com/vercel/next.js/pull/60919 
Closes https://github.com/vercel/next.js/pull/59410
Closes NEXT-3219
parent a6dfe823
...@@ -4,11 +4,13 @@ import '../server/lib/cpu-profile' ...@@ -4,11 +4,13 @@ import '../server/lib/cpu-profile'
import type { StartServerOptions } from '../server/lib/start-server' import type { StartServerOptions } from '../server/lib/start-server'
import { import {
RESTART_EXIT_CODE, RESTART_EXIT_CODE,
checkNodeDebugType, getNodeDebugType,
getDebugPort, getParsedDebugAddress,
getMaxOldSpaceSize, getMaxOldSpaceSize,
getNodeOptionsWithoutInspect, getParsedNodeOptionsWithoutInspect,
printAndExit, printAndExit,
formatNodeOptions,
formatDebugAddress,
} 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'
...@@ -225,23 +227,25 @@ const nextDev = async ( ...@@ -225,23 +227,25 @@ 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
let NODE_OPTIONS = getNodeOptionsWithoutInspect() const nodeOptions = getParsedNodeOptionsWithoutInspect()
let nodeDebugType = checkNodeDebugType() const nodeDebugType = getNodeDebugType()
const maxOldSpaceSize = getMaxOldSpaceSize()
let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()
if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) { if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {
const totalMem = os.totalmem() const totalMem = os.totalmem()
const totalMemInMB = Math.floor(totalMem / 1024 / 1024) const totalMemInMB = Math.floor(totalMem / 1024 / 1024)
NODE_OPTIONS = `${NODE_OPTIONS} --max-old-space-size=${Math.floor( maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString()
totalMemInMB * 0.5
)}` nodeOptions['max-old-space-size'] = maxOldSpaceSize
// Ensure the max_old_space_size is not also set.
delete nodeOptions['max_old_space_size']
} }
if (nodeDebugType) { if (nodeDebugType) {
NODE_OPTIONS = `${NODE_OPTIONS} --${nodeDebugType}=${ const address = getParsedDebugAddress()
getDebugPort() + 1 address.port = address.port + 1
}` nodeOptions[nodeDebugType] = formatDebugAddress(address)
} }
child = fork(startServerPath, { child = fork(startServerPath, {
...@@ -253,7 +257,7 @@ const nextDev = async ( ...@@ -253,7 +257,7 @@ const nextDev = async (
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
? startServerOptions.selfSignedCertificate.rootCA ? startServerOptions.selfSignedCertificate.rootCA
: defaultEnv.NODE_EXTRA_CA_CERTS, : defaultEnv.NODE_EXTRA_CA_CERTS,
NODE_OPTIONS, NODE_OPTIONS: formatNodeOptions(nodeOptions),
}, },
}) })
......
import { execSync } from 'child_process' import { execSync } from 'child_process'
import { getPkgManager } from './get-pkg-manager' import { getPkgManager } from './get-pkg-manager'
import { getNodeOptionsWithoutInspect } from '../../server/lib/utils' import { getFormattedNodeOptionsWithoutInspect } from '../../server/lib/utils'
/** /**
* Returns the package registry using the user's package manager. * Returns the package registry using the user's package manager.
...@@ -14,7 +14,7 @@ export function getRegistry(baseDir: string = process.cwd()) { ...@@ -14,7 +14,7 @@ export function getRegistry(baseDir: string = process.cwd()) {
const output = execSync(`${pkgManager} config get registry`, { const output = execSync(`${pkgManager} config get registry`, {
env: { env: {
...process.env, ...process.env,
NODE_OPTIONS: getNodeOptionsWithoutInspect(), NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),
}, },
}) })
.toString() .toString()
......
import type { ChildProcess } from 'child_process' import type { ChildProcess } from 'child_process'
import { Worker as JestWorker } from 'next/dist/compiled/jest-worker' import { Worker as JestWorker } from 'next/dist/compiled/jest-worker'
import { getNodeOptionsWithoutInspect } from '../server/lib/utils' import {
getParsedNodeOptionsWithoutInspect,
formatNodeOptions,
} from '../server/lib/utils'
type FarmOptions = ConstructorParameters<typeof JestWorker>[1] type FarmOptions = ConstructorParameters<typeof JestWorker>[1]
const RESTARTED = Symbol('restarted') const RESTARTED = Symbol('restarted')
...@@ -35,6 +38,12 @@ export class Worker { ...@@ -35,6 +38,12 @@ export class Worker {
this._worker = undefined this._worker = undefined
const createWorker = () => { const createWorker = () => {
// Get the node options without inspect and also remove the
// --max-old-space-size flag as it can cause memory issues.
const nodeOptions = getParsedNodeOptionsWithoutInspect()
delete nodeOptions['max-old-space-size']
delete nodeOptions['max_old_space_size']
this._worker = new JestWorker(workerPath, { this._worker = new JestWorker(workerPath, {
...farmOptions, ...farmOptions,
forkOptions: { forkOptions: {
...@@ -42,11 +51,7 @@ export class Worker { ...@@ -42,11 +51,7 @@ export class Worker {
env: { env: {
...((farmOptions.forkOptions?.env || {}) as any), ...((farmOptions.forkOptions?.env || {}) as any),
...process.env, ...process.env,
// we don't pass down NODE_OPTIONS as it can NODE_OPTIONS: formatNodeOptions(nodeOptions),
// extra memory usage
NODE_OPTIONS: getNodeOptionsWithoutInspect()
.replace(/--max-old-space-size=[\d]{1,}/, '')
.trim(),
} as any, } as any,
}, },
}) as JestWorker }) as JestWorker
......
...@@ -42,7 +42,7 @@ import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-pref ...@@ -42,7 +42,7 @@ import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-pref
import { Telemetry } from '../../telemetry/storage' import { Telemetry } from '../../telemetry/storage'
import { type Span, setGlobal, trace } from '../../trace' import { type Span, setGlobal, trace } from '../../trace'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
import { getNodeOptionsWithoutInspect } from '../lib/utils' import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'
import { withCoalescedInvoke } from '../../lib/coalesced-function' import { withCoalescedInvoke } from '../../lib/coalesced-function'
import { loadDefaultErrorComponents } from '../load-default-error-components' import { loadDefaultErrorComponents } from '../load-default-error-components'
import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils' import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'
...@@ -133,7 +133,7 @@ export default class DevServer extends Server { ...@@ -133,7 +133,7 @@ export default class DevServer extends Server {
// would be started if user launch Next.js in debugging mode. The number of debuggers is linked to // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
// the number of workers Next.js tries to launch. The only worker users are interested in debugging // the number of workers Next.js tries to launch. The only worker users are interested in debugging
// is the main Next.js one // is the main Next.js one
NODE_OPTIONS: getNodeOptionsWithoutInspect(), NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),
}, },
}, },
}) as Worker & { }) as Worker & {
......
...@@ -17,7 +17,11 @@ import os from 'os' ...@@ -17,7 +17,11 @@ import os from 'os'
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 { RESTART_EXIT_CODE, checkNodeDebugType, getDebugPort } from './utils' import {
RESTART_EXIT_CODE,
getFormattedDebugAddress,
getNodeDebugType,
} 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'
...@@ -211,10 +215,10 @@ export async function startServer( ...@@ -211,10 +215,10 @@ export async function startServer(
} }
}) })
const nodeDebugType = checkNodeDebugType()
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'
...@@ -236,9 +240,9 @@ export async function startServer( ...@@ -236,9 +240,9 @@ export async function startServer(
}://${formattedHostname}:${port}` }://${formattedHostname}:${port}`
if (nodeDebugType) { if (nodeDebugType) {
const debugPort = getDebugPort() const formattedDebugAddress = getFormattedDebugAddress()
Log.info( Log.info(
`the --${nodeDebugType} option was detected, the Next.js router server should be inspected at port ${debugPort}.` `the --${nodeDebugType} option was detected, the Next.js router server should be inspected at ${formattedDebugAddress}.`
) )
} }
......
/* eslint-env jest */ import {
import { getNodeOptionsWithoutInspect } from 'next/dist/server/lib/utils' getFormattedNodeOptionsWithoutInspect,
getParsedDebugAddress,
} from './utils'
const originalNodeOptions = process.env.NODE_OPTIONS const originalNodeOptions = process.env.NODE_OPTIONS
...@@ -7,38 +9,52 @@ afterAll(() => { ...@@ -7,38 +9,52 @@ afterAll(() => {
process.env.NODE_OPTIONS = originalNodeOptions process.env.NODE_OPTIONS = originalNodeOptions
}) })
describe('getNodeOptionsWithoutInspect', () => { describe('getParsedDebugAddress', () => {
it('supports the flag with an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect=1234'
const result = getParsedDebugAddress()
expect(result).toEqual({ host: undefined, port: 1234 })
})
it('supports the flag without an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect 1234'
const result = getParsedDebugAddress()
expect(result).toEqual({ host: undefined, port: 1234 })
})
})
describe('getFormattedNodeOptionsWithoutInspect', () => {
it('removes --inspect option', () => { it('removes --inspect option', () => {
process.env.NODE_OPTIONS = '--other --inspect --additional' process.env.NODE_OPTIONS = '--other --inspect --additional'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other --additional') expect(result).toBe('--other --additional')
}) })
it('removes --inspect option at end of line', () => { it('removes --inspect option at end of line', () => {
process.env.NODE_OPTIONS = '--other --inspect' process.env.NODE_OPTIONS = '--other --inspect'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other ') expect(result).toBe('--other')
}) })
it('removes --inspect option with parameters', () => { it('removes --inspect option with parameters', () => {
process.env.NODE_OPTIONS = '--other --inspect=0.0.0.0:1234 --additional' process.env.NODE_OPTIONS = '--other --inspect=0.0.0.0:1234 --additional'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other --additional') expect(result).toBe('--other --additional')
}) })
it('removes --inspect-brk option', () => { it('removes --inspect-brk option', () => {
process.env.NODE_OPTIONS = '--other --inspect-brk --additional' process.env.NODE_OPTIONS = '--other --inspect-brk --additional'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other --additional') expect(result).toBe('--other --additional')
}) })
it('removes --inspect-brk option with parameters', () => { it('removes --inspect-brk option with parameters', () => {
process.env.NODE_OPTIONS = '--other --inspect-brk=0.0.0.0:1234 --additional' process.env.NODE_OPTIONS = '--other --inspect-brk=0.0.0.0:1234 --additional'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other --additional') expect(result).toBe('--other --additional')
}) })
...@@ -46,7 +62,7 @@ describe('getNodeOptionsWithoutInspect', () => { ...@@ -46,7 +62,7 @@ describe('getNodeOptionsWithoutInspect', () => {
it('ignores unrelated options starting with --inspect-', () => { it('ignores unrelated options starting with --inspect-', () => {
process.env.NODE_OPTIONS = process.env.NODE_OPTIONS =
'--other --inspect-port=0.0.0.0:1234 --additional' '--other --inspect-port=0.0.0.0:1234 --additional'
const result = getNodeOptionsWithoutInspect() const result = getFormattedNodeOptionsWithoutInspect()
expect(result).toBe('--other --inspect-port=0.0.0.0:1234 --additional') expect(result).toBe('--other --inspect-port=0.0.0.0:1234 --additional')
}) })
......
import { parseArgs } from 'node:util'
import { InvalidArgumentError } from 'next/dist/compiled/commander' import { InvalidArgumentError } from 'next/dist/compiled/commander'
export function printAndExit(message: string, code = 1) { export function printAndExit(message: string, code = 1) {
...@@ -10,22 +11,164 @@ export function printAndExit(message: string, code = 1) { ...@@ -10,22 +11,164 @@ export function printAndExit(message: string, code = 1) {
return process.exit(code) return process.exit(code)
} }
export const getDebugPort = () => { const parseNodeArgs = (args: string[]) => {
const debugPortStr = const { values, tokens } = parseArgs({ args, strict: false, tokens: true })
process.execArgv
.find( // For the `NODE_OPTIONS`, we support arguments with values without the `=`
(localArg) => // sign. We need to parse them manually.
localArg.startsWith('--inspect') || let found = null
localArg.startsWith('--inspect-brk') for (let i = 0; i < tokens.length; i++) {
) const token = tokens[i]
?.split('=', 2)[1] ??
process.env.NODE_OPTIONS?.match?.(/--inspect(-brk)?(=(\S+))?( |$)/)?.[3] if (token.kind === 'option-terminator') {
return debugPortStr ? parseInt(debugPortStr, 10) : 9229 break
}
// If we haven't found a possibly orphaned option, we need to look for one.
if (!found) {
if (token.kind === 'option' && typeof token.value === 'undefined') {
found = token
}
continue
}
// If the next token isn't a positional value, then it's truly orphaned.
if (token.kind !== 'positional' || !token.value) {
found = null
continue
}
// We found an orphaned option. Let's add it to the values.
values[found.name] = token.value
found = null
}
return values
}
/**
* Get the node options from the environment variable `NODE_OPTIONS` and returns
* them as an array of strings.
*
* @returns An array of strings with the node options.
*/
const getNodeOptionsArgs = () =>
process.env.NODE_OPTIONS?.split(' ').map((arg) => arg.trim()) ?? []
/**
* The debug address is in the form of `[host:]port`. The host is optional.
*/
type DebugAddress = {
host: string | undefined
port: number
}
/**
* Formats the debug address into a string.
*/
export const formatDebugAddress = ({ host, port }: DebugAddress): string => {
if (host) return `${host}:${port}`
return `${port}`
}
/**
* Get's the debug address from the `NODE_OPTIONS` environment variable. If the
* address is not found, it returns the default host (`undefined`) and port
* (`9229`).
*
* @returns An object with the host and port of the debug address.
*/
export const getParsedDebugAddress = (): DebugAddress => {
const args = getNodeOptionsArgs()
if (args.length === 0) return { host: undefined, port: 9229 }
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') {
return { host: undefined, port: 9229 }
}
// The address is in the form of `[host:]port`. Let's parse the address.
if (address.includes(':')) {
const [host, port] = address.split(':')
return { host, port: parseInt(port, 10) }
}
return { host: undefined, port: parseInt(address, 10) }
}
/**
* 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
* argument that has a value of `undefined`.
*
* @param args The arguments to be stringified.
* @returns A string with the arguments.
*/
export function formatNodeOptions(
args: Record<string, string | boolean | undefined>
): string {
return Object.entries(args)
.map(([key, value]) => {
if (value === true) {
return `--${key}`
}
if (value) {
return `--${key}=${value}`
}
return null
})
.filter((arg) => arg !== null)
.join(' ')
} }
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/ /**
export function getNodeOptionsWithoutInspect() { * Get the node options from the `NODE_OPTIONS` environment variable and parse
return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '') * them into an object without the inspect options.
*
* @returns An object with the parsed node options.
*/
export function getParsedNodeOptionsWithoutInspect() {
const args = getNodeOptionsArgs()
if (args.length === 0) return {}
const parsed = parseNodeArgs(args)
// Remove inspect options.
delete parsed.inspect
delete parsed['inspect-brk']
delete parsed['inspect_brk']
return parsed
}
/**
* Get the node options from the `NODE_OPTIONS` environment variable and format
* them into a string without the inspect options.
*
* @returns A string with the formatted node options.
*/
export function getFormattedNodeOptionsWithoutInspect() {
const args = getParsedNodeOptionsWithoutInspect()
if (Object.keys(args).length === 0) return ''
return formatNodeOptions(args)
} }
export function myParseInt(value: string) { export function myParseInt(value: string) {
...@@ -40,30 +183,33 @@ export function myParseInt(value: string) { ...@@ -40,30 +183,33 @@ export function myParseInt(value: string) {
export const RESTART_EXIT_CODE = 77 export const RESTART_EXIT_CODE = 77
export function checkNodeDebugType() { /**
let nodeDebugType = undefined * Get the debug type from the `NODE_OPTIONS` environment variable.
*/
export function getNodeDebugType() {
const args = [...process.execArgv, ...getNodeOptionsArgs()]
if (args.length === 0) return
if ( const parsed = parseNodeArgs(args)
process.execArgv.some((localArg) => localArg.startsWith('--inspect')) ||
process.env.NODE_OPTIONS?.match?.(/--inspect(=\S+)?( |$)/)
) {
nodeDebugType = 'inspect'
}
if (
process.execArgv.some((localArg) => localArg.startsWith('--inspect-brk')) ||
process.env.NODE_OPTIONS?.match?.(/--inspect-brk(=\S+)?( |$)/)
) {
nodeDebugType = 'inspect-brk'
}
return nodeDebugType if (parsed.inspect) return 'inspect'
if (parsed['inspect-brk'] || parsed['inspect_brk']) return 'inspect-brk'
} }
/**
* Get the `max-old-space-size` value from the `NODE_OPTIONS` environment
* variable.
*
* @returns The value of the `max-old-space-size` option as a number.
*/
export function getMaxOldSpaceSize() { export function getMaxOldSpaceSize() {
const maxOldSpaceSize = process.env.NODE_OPTIONS?.match( const args = getNodeOptionsArgs()
/--max[-_]old[-_]space[-_]size=(\d+)/ if (args.length === 0) return
)?.[1]
const parsed = parseNodeArgs(args)
const size = parsed['max-old-space-size'] || parsed['max_old_space_size']
if (!size || typeof size !== 'string') return
return maxOldSpaceSize ? parseInt(maxOldSpaceSize, 10) : undefined return parseInt(size, 10)
} }
...@@ -25,7 +25,7 @@ import { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants' ...@@ -25,7 +25,7 @@ import { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants'
import { getTracer } from './lib/trace/tracer' import { getTracer } from './lib/trace/tracer'
import { NextServerSpan } from './lib/trace/constants' import { NextServerSpan } from './lib/trace/constants'
import { formatUrl } from '../shared/lib/router/utils/format-url' import { formatUrl } from '../shared/lib/router/utils/format-url'
import { checkNodeDebugType } from './lib/utils' import { getNodeDebugType } from './lib/utils'
let ServerImpl: typeof Server let ServerImpl: typeof Server
...@@ -277,7 +277,7 @@ class NextCustomServer extends NextServer { ...@@ -277,7 +277,7 @@ class NextCustomServer extends NextServer {
const { getRequestHandlers } = const { getRequestHandlers } =
require('./lib/start-server') as typeof import('./lib/start-server') require('./lib/start-server') as typeof import('./lib/start-server')
const isNodeDebugging = !!checkNodeDebugType() const isNodeDebugging = typeof getNodeDebugType() === 'string'
const initResult = await getRequestHandlers({ const initResult = await getRequestHandlers({
dir: this.options.dir!, dir: this.options.dir!,
...@@ -285,7 +285,7 @@ class NextCustomServer extends NextServer { ...@@ -285,7 +285,7 @@ class NextCustomServer extends NextServer {
isDev: !!this.options.dev, isDev: !!this.options.dev,
hostname: this.options.hostname || 'localhost', hostname: this.options.hostname || 'localhost',
minimalMode: this.options.minimalMode, minimalMode: this.options.minimalMode,
isNodeDebugging: !!isNodeDebugging, isNodeDebugging,
quiet: this.options.quiet, quiet: this.options.quiet,
}) })
this.requestHandler = initResult[0] this.requestHandler = initResult[0]
......
...@@ -552,7 +552,37 @@ describe('CLI Usage', () => { ...@@ -552,7 +552,37 @@ describe('CLI Usage', () => {
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( expect(output).toContain(
'the --inspect option was detected, the Next.js router server should be inspected at port' 'the --inspect option was detected, the Next.js router server should be inspected at'
)
} finally {
await killApp(app)
}
})
test("NODE_OPTIONS='--inspect=host:port'", async () => {
const port = await findPort()
const inspectPort = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
env: { NODE_OPTIONS: `--inspect=0.0.0.0:${inspectPort}` },
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => errOutput, /Debugger listening on/)
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)
......
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