Unverified Commit 47f73cd8 authored by Sam Ko's avatar Sam Ko Committed by GitHub

refactor(cli): refactor cli to commander (#61877)

## Description
Refactor the [Next.js
CLI](https://nextjs.org/docs/app/api-reference/next-cli) to use
[commander](https://github.com/tj/commander.js) instead of
[arg](https://github.com/vercel/arg).

## Why?
- Auto-generated, properly formatted help command + output. With `arg`,
much of the help commands were manually added via a single
`console.log`, causing deviations over time.
- Ergonomic, ease of adding new subcommands and rules

## Breaking Changes
- Update the experimental `next experimental-compile` and `next
experimental-generate` build commands in favor of `next build
--experimental-build-mode=compile/generate`

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 2f7721a6
......@@ -209,6 +209,7 @@
"ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"cli-select": "1.1.2",
"client-only": "0.0.1",
"commander": "12.0.0",
"comment-json": "3.0.3",
"compression": "1.7.4",
"conf": "5.0.0",
......
This diff is collapsed.
......@@ -674,14 +674,14 @@ export default async function build(
noMangling = false,
appDirOnly = false,
turboNextBuild = false,
buildMode: 'default' | 'experimental-compile' | 'experimental-generate'
experimentalBuildMode: 'default' | 'compile' | 'generate'
): Promise<void> {
const isCompileMode = buildMode === 'experimental-compile'
const isGenerateMode = buildMode === 'experimental-generate'
const isCompileMode = experimentalBuildMode === 'compile'
const isGenerateMode = experimentalBuildMode === 'generate'
try {
const nextBuildSpan = trace('next-build', undefined, {
buildMode: buildMode,
buildMode: experimentalBuildMode,
isTurboBuild: String(turboNextBuild),
version: process.env.__NEXT_VERSION as string,
})
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--profile': Boolean,
'--debug': Boolean,
'--no-lint': Boolean,
'--no-mangling': Boolean,
'--experimental-app-only': Boolean,
'--experimental-turbo': Boolean,
'--experimental-turbo-root': String,
'--build-mode': String,
// Aliases
'-h': '--help',
'-d': '--debug',
}
......@@ -2,68 +2,73 @@
import '../server/lib/cpu-profile'
import { existsSync } from 'fs'
import * as Log from '../build/output/log'
import type { CliCommand } from '../lib/commands'
import { italic } from '../lib/picocolors'
import build from '../build'
import { warn } from '../build/output/log'
import { printAndExit } from '../server/lib/utils'
import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir'
const nextBuild: CliCommand = (args) => {
if (args['--help']) {
printAndExit(
`
Description
Compiles the application for production deployment
type NextBuildOptions = {
debug?: boolean
profile?: boolean
lint: boolean
mangling: boolean
experimentalAppOnly?: boolean
experimentalTurbo?: boolean
experimentalBuildMode: 'default' | 'compile' | 'generate'
}
Usage
$ next build <dir>
const nextBuild = (options: NextBuildOptions, directory?: string) => {
process.on('SIGTERM', () => process.exit(0))
process.on('SIGINT', () => process.exit(0))
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
const {
debug,
profile,
lint,
mangling,
experimentalAppOnly,
experimentalTurbo,
experimentalBuildMode,
} = options
Options
--profile Can be used to enable React Production Profiling
--no-lint Disable linting
--no-mangling Disable mangling
--experimental-app-only Only build 'app' routes
--experimental-turbo Enable experimental turbo mode
--help, -h Displays this message
`,
0
)
if (!lint) {
warn('Linting is disabled.')
}
if (args['--profile']) {
Log.warn('Profiling is enabled. Note: This may affect performance')
}
if (args['--no-lint']) {
Log.warn('Linting is disabled')
if (!mangling) {
warn(
'Mangling is disabled. Note: This may affect performance and should only be used for debugging purposes.'
)
}
if (args['--no-mangling']) {
Log.warn(
'Mangling is disabled. Note: This may affect performance and should only be used for debugging purposes'
if (profile) {
warn(
`Profiling is enabled. ${italic('Note: This may affect performance.')}`
)
}
const dir = getProjectDir(args._[0])
const dir = getProjectDir(directory)
// Check if the provided directory exists
if (!existsSync(dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
if (args['--experimental-turbo']) {
if (experimentalTurbo) {
process.env.TURBOPACK = '1'
}
return build(
dir,
args['--profile'],
args['--debug'] || process.env.NEXT_DEBUG_BUILD,
!args['--no-lint'],
args['--no-mangling'],
args['--experimental-app-only'],
profile,
debug || Boolean(process.env.NEXT_DEBUG_BUILD),
lint,
!mangling,
experimentalAppOnly,
!!process.env.TURBOPACK,
args['--build-mode'] || 'default'
experimentalBuildMode
).catch((err) => {
console.error('')
if (
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--port': Number,
'--hostname': String,
'--turbo': Boolean,
'--experimental-https': Boolean,
'--experimental-https-key': String,
'--experimental-https-cert': String,
'--experimental-https-ca': String,
'--experimental-test-proxy': Boolean,
'--experimental-upload-trace': String,
// To align current messages with native binary.
// Will need to adjust subcommand later.
'--show-all': Boolean,
'--root': String,
// Aliases
'-h': '--help',
'-p': '--port',
'-H': '--hostname',
}
......@@ -8,11 +8,9 @@ import {
getDebugPort,
getMaxOldSpaceSize,
getNodeOptionsWithoutInspect,
getPort,
printAndExit,
} from '../server/lib/utils'
import * as Log from '../build/output/log'
import type { CliCommand } from '../lib/commands'
import { getProjectDir } from '../lib/get-project-dir'
import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import path from 'path'
......@@ -36,6 +34,18 @@ import {
import os from 'os'
import { once } from 'node:events'
type NextDevOptions = {
turbo?: boolean
port: number
hostname?: string
experimentalHttps?: boolean
experimentalHttpsKey?: string
experimentalHttpsCert?: string
experimentalHttpsCa?: string
experimentalUploadTrace?: string
experimentalTestProxy?: boolean
}
let dir: string
let child: undefined | ChildProcess
let config: NextConfigComplete
......@@ -117,32 +127,8 @@ process.on('SIGTERM', () => handleSessionStop('SIGKILL'))
// exit event must be synchronous
process.on('exit', () => child?.kill('SIGKILL'))
const nextDev: CliCommand = async (args) => {
if (args['--help']) {
console.log(`
Description
Starts the application in development mode (hot-code reloading, error
reporting, etc.)
Usage
$ next dev <dir> -p <port number>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--port, -p A port number to start the application on
--hostname, -H Hostname start the application on (default: 0.0.0.0)
--experimental-https Start the server with HTTPS and generate a self-signed certificate
--experimental-https-key <path> Path to a HTTPS key file
--experimental-https-cert <path> Path to a HTTPS certificate file
--experimental-https-ca <path> Path to a HTTPS certificate authority file
--experimental-upload-trace=<trace-url> Report a subset of the debugging trace to a remote http url. Includes sensitive data. Disabled by default and url must be provided.
--help, -h Displays this message
`)
process.exit(0)
}
dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || args._[0])
const nextDev = async (options: NextDevOptions, directory?: string) => {
dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || directory)
// Check if pages dir exists and warn if not
if (!(await fileExists(dir, FileType.Directory))) {
......@@ -187,7 +173,7 @@ const nextDev: CliCommand = async (args) => {
}
}
const port = getPort(args)
const port = options.port
if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1)
......@@ -195,21 +181,21 @@ const nextDev: CliCommand = async (args) => {
// If neither --port nor PORT were specified, it's okay to retry new ports.
const allowRetry =
args['--port'] === undefined && process.env.PORT === undefined
options.port === undefined && process.env.PORT === undefined
// We do not set a default host value here to prevent breaking
// some set-ups that rely on listening on other interfaces
const host = args['--hostname']
const host = options.hostname
config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir)
const isExperimentalTestProxy = args['--experimental-test-proxy']
const isExperimentalTestProxy = options.experimentalTestProxy
if (
args['--experimental-upload-trace'] &&
options.experimentalUploadTrace &&
!process.env.NEXT_TRACE_UPLOAD_DISABLED
) {
traceUploadUrl = args['--experimental-upload-trace']
traceUploadUrl = options.experimentalUploadTrace
}
// TODO: remove in the next major version
......@@ -228,7 +214,7 @@ const nextDev: CliCommand = async (args) => {
isExperimentalTestProxy,
}
if (args['--turbo']) {
if (options.turbo) {
process.env.TURBOPACK = '1'
}
......@@ -239,7 +225,8 @@ const nextDev: CliCommand = async (args) => {
setGlobal('distDir', distDir)
const startServerPath = require.resolve('../server/lib/start-server')
async function startServer(options: StartServerOptions) {
async function startServer(startServerOptions: StartServerOptions) {
return new Promise<void>((resolve) => {
let resolved = false
const defaultEnv = (initialEnv || process.env) as typeof process.env
......@@ -269,8 +256,8 @@ const nextDev: CliCommand = async (args) => {
...defaultEnv,
TURBOPACK: process.env.TURBOPACK,
NEXT_PRIVATE_WORKER: '1',
NODE_EXTRA_CA_CERTS: options.selfSignedCertificate
? options.selfSignedCertificate.rootCA
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
? startServerOptions.selfSignedCertificate.rootCA
: defaultEnv.NODE_EXTRA_CA_CERTS,
NODE_OPTIONS,
},
......@@ -279,7 +266,7 @@ const nextDev: CliCommand = async (args) => {
child.on('message', (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) {
child?.send({ nextWorkerOptions: options })
child?.send({ nextWorkerOptions: startServerOptions })
} else if (msg.nextServerReady && !resolved) {
resolved = true
resolve()
......@@ -304,7 +291,7 @@ const nextDev: CliCommand = async (args) => {
sync: true,
})
}
return startServer(options)
return startServer(startServerOptions)
}
await handleSessionStop(signal)
})
......@@ -313,16 +300,16 @@ const nextDev: CliCommand = async (args) => {
const runDevServer = async (reboot: boolean) => {
try {
if (!!args['--experimental-https']) {
if (!!options.experimentalHttps) {
Log.warn(
'Self-signed certificates are currently an experimental feature, use with caution.'
)
let certificate: SelfSignedCertificate | undefined
const key = args['--experimental-https-key']
const cert = args['--experimental-https-cert']
const rootCA = args['--experimental-https-ca']
const key = options.experimentalHttpsKey
const cert = options.experimentalHttpsCert
const rootCA = options.experimentalHttpsCa
if (key && cert) {
certificate = {
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--silent': Boolean,
'--outdir': String,
'--threads': Number,
// Aliases
'-h': '--help',
'-o': '--outdir',
'-s': '--silent',
}
#!/usr/bin/env node
import { cyan } from '../lib/picocolors'
import * as Log from '../build/output/log'
import type { CliCommand } from '../lib/commands'
import { error } from '../build/output/log'
const nextExport: CliCommand = () => {
Log.error(`
The "next export" command has been removed in favor of "output: export" in next.config.js. Learn more: ${cyan(
'https://nextjs.org/docs/advanced-features/static-html-export'
const nextExport = () => {
error(`
\`next export\` has been removed in favor of 'output: export' in next.config.js.\nLearn more: ${cyan(
'https://nextjs.org/docs/app/building-your-application/deploying/static-exports'
)}
`)
process.exit(1)
}
......
import type arg from 'next/dist/compiled/arg/index.js'
/**
* Supported CLI arguments.
*/
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
// Aliases
'-h': '--help',
// Detailed diagnostics
'--verbose': Boolean,
}
......@@ -4,7 +4,6 @@ import os from 'os'
import childProcess from 'child_process'
import { bold, cyan, yellow } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import { PHASE_INFO } from '../shared/lib/constants'
import loadConfig from '../server/config'
import { getRegistry } from '../lib/helpers/get-registry'
......@@ -12,7 +11,9 @@ import { parseVersionInfo } from '../server/dev/parse-version-info'
import { getStaleness } from '../client/components/react-dev-overlay/internal/components/VersionStalenessInfo/VersionStalenessInfo'
import { warn } from '../build/output/log'
const dir = process.cwd()
type NextInfoOptions = {
verbose?: boolean
}
type TaskResult = {
// Additional messages to notify to the users, i.e certain script cannot be run due to missing xyz.
......@@ -23,6 +24,7 @@ type TaskResult = {
}
type TaskScript = () => Promise<TaskResult>
type PlatformTaskScript =
| {
win32: TaskScript
......@@ -59,7 +61,7 @@ function getPackageVersion(packageName: string) {
}
async function getNextConfig() {
const config = await loadConfig(PHASE_INFO, dir)
const config = await loadConfig(PHASE_INFO, process.cwd())
return {
output: config.output ?? 'N/A',
......@@ -84,37 +86,20 @@ function getBinaryVersion(binaryName: string) {
}
}
function printHelp() {
console.log(
`
Description
Prints relevant details about the current system which can be used to report Next.js bugs
Usage
$ next info
Options
--help, -h Displays this message
--verbose Collect additional information for debugging
Learn more: ${cyan('https://nextjs.org/docs/api-reference/cli#info')}`
)
}
/**
* Collect basic next.js installation information and print it to stdout.
*/
async function printDefaultInfo() {
async function printInfo() {
const installedRelease = getPackageVersion('next')
const nextConfig = await getNextConfig()
let stalenessWithTitle = ''
let title = ''
let versionInfo
try {
const registry = getRegistry()
const res = await fetch(`${registry}-/package/next/dist-tags`)
const tags = await res.json()
versionInfo = parseVersionInfo({
......@@ -122,8 +107,12 @@ async function printDefaultInfo() {
latest: tags.latest,
canary: tags.canary,
})
title = getStaleness(versionInfo).title
if (title) stalenessWithTitle = ` // ${title}`
if (title) {
stalenessWithTitle = ` // ${title}`
}
} catch (e) {
console.warn(
`${yellow(
......@@ -133,7 +122,9 @@ async function printDefaultInfo() {
}.)
Detected "${installedRelease}". Visit https://github.com/vercel/next.js/releases.
Make sure to try the latest canary version (eg.: \`npm install next@canary\`) to confirm the issue still exists before creating a new issue.
Read more - https://nextjs.org/docs/messages/opening-an-issue`
\nLearn more: ${cyan(
'https://nextjs.org/docs/messages/opening-an-issue'
)}`
)
}
......@@ -157,9 +148,7 @@ Relevant Packages:
react-dom: ${getPackageVersion('react-dom')}
typescript: ${getPackageVersion('typescript')}
Next.js Config:
output: ${nextConfig.output}
`)
output: ${nextConfig.output}`)
if (versionInfo?.staleness.startsWith('stale')) {
warn(`${title}
......@@ -249,7 +238,7 @@ async function runSharedDependencyCheck(
/**
* Collect additional diagnostics information.
*/
async function printVerbose() {
async function printVerboseInfo() {
const fs = require('fs')
const currentPlatform = os.platform()
......@@ -592,16 +581,11 @@ async function printVerbose() {
* There are 2 modes, by default it collects basic next.js installation with runtime information. If
* `--verbose` mode is enabled it'll try to collect, verify more data for next-swc installation and others.
*/
const nextInfo: CliCommand = async (args) => {
if (args['--help']) {
printHelp()
return
}
if (!args['--verbose']) {
await printDefaultInfo()
const nextInfo = async (options: NextInfoOptions) => {
if (options.verbose) {
await printVerboseInfo()
} else {
await printVerbose()
await printInfo()
}
}
......
import type arg from 'next/dist/compiled/arg/index.js'
const validEslintArgs: arg.Spec = {
// Types
'--config': String,
'--ext': [String],
'--resolve-plugins-relative-to': String,
'--rulesdir': [String],
'--fix': Boolean,
'--fix-type': [String],
'--ignore-path': String,
'--no-ignore': Boolean,
'--quiet': Boolean,
'--max-warnings': Number,
'--no-inline-config': Boolean,
'--report-unused-disable-directives': String,
'--cache': Boolean, // Although cache is enabled by default, this dummy flag still exists to not cause any breaking changes
'--no-cache': Boolean,
'--cache-location': String,
'--cache-strategy': String,
'--error-on-unmatched-pattern': Boolean,
'--format': String,
'--output-file': String,
// Aliases
'-c': '--config',
'-f': '--format',
'-o': '--output-file',
}
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--base-dir': String,
'--dir': [String],
'--file': [String],
'--strict': Boolean,
// Aliases
'-h': '--help',
'-b': '--base-dir',
'-d': '--dir',
...validEslintArgs,
}
#!/usr/bin/env node
import type arg from 'next/dist/compiled/arg/index.js'
import { existsSync } from 'fs'
import { join } from 'path'
import { green } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { Telemetry } from '../telemetry/storage'
import loadConfig from '../server/config'
import { green } from '../lib/picocolors'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { CompileError } from '../lib/compile-error'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { eventLintCheckCompleted } from '../telemetry/events'
import { CompileError } from '../lib/compile-error'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'
const eslintOptions = (args: arg.Spec, defaultCacheLocation: string) => ({
overrideConfigFile: args['--config'] || null,
extensions: args['--ext'] ?? [
'.js',
'.mjs',
'.cjs',
'.jsx',
'.ts',
'.mts',
'.cts',
'.tsx',
],
resolvePluginsRelativeTo: args['--resolve-plugins-relative-to'] || null,
rulePaths: args['--rulesdir'] ?? [],
fix: args['--fix'] ?? false,
fixTypes: args['--fix-type'] ?? null,
ignorePath: args['--ignore-path'] || null,
ignore: !Boolean(args['--no-ignore']),
allowInlineConfig: !Boolean(args['--no-inline-config']),
reportUnusedDisableDirectives:
args['--report-unused-disable-directives'] || null,
cache: !Boolean(args['--no-cache']),
cacheLocation: args['--cache-location'] || defaultCacheLocation,
cacheStrategy: args['--cache-strategy'] || 'metadata',
errorOnUnmatchedPattern: args['--error-on-unmatched-pattern']
? Boolean(args['--error-on-unmatched-pattern'])
: false,
})
type NextLintOptions = {
cache: boolean
cacheLocation?: string
cacheStrategy: string
config?: string
dir?: string[]
errorOnUnmatchedPattern?: boolean
ext: string[]
file?: string[]
fix?: boolean
fixType?: string
format?: string
ignore: boolean
ignorePath?: string
inlineConfig: boolean
maxWarnings: number
outputFile?: string
quiet?: boolean
reportUnusedDisableDirectives: string
resolvePluginsRelativeTo?: string
rulesdir?: string
strict?: boolean
}
const nextLint: CliCommand = async (args) => {
if (args['--help']) {
printAndExit(
`
Description
Run ESLint on every file in specified directories.
If not configured, ESLint will be set up for the first time.
Usage
$ next lint <baseDir> [options]
<baseDir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
Basic configuration:
-h, --help List this help
-d, --dir Array Include directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib'
--file Array Include file, or files, to run ESLint
-c, --config path::String Use this configuration file, overriding all other config options
--ext [String] Specify JavaScript file extensions - default: .js, .mjs, .cjs, .jsx, .ts, .mts, .cts, .tsx
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
Initial setup:
--strict Creates an .eslintrc.json file using the Next.js strict configuration (only possible if no .eslintrc.json file is present)
Specifying rules:
--rulesdir [path::String] Use additional rules from this directory
Fixing problems:
--fix Automatically fix problems
--fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)
Ignoring files:
--ignore-path path::String Specify path of ignore file
--no-ignore Disable use of ignore files and patterns
Handling warnings:
--quiet Report errors only - default: false
--max-warnings Int Number of warnings to trigger nonzero exit code - default: -1
Output:
-o, --output-file path::String Specify file to write report to
-f, --format String Use a specific output format - default: Next.js custom formatter
Inline configuration comments:
--no-inline-config Prevent comments from changing config or rules
--report-unused-disable-directives Adds reported errors for unused eslint-disable directives ("error" | "warn" | "off")
Caching:
--no-cache Disable caching
--cache-location path::String Path to the cache file or directory - default: .eslintcache
--cache-strategy String Strategy to use for detecting changed files in the cache, either metadata or content - default: metadata
Miscellaneous:
--error-on-unmatched-pattern Show errors when any file patterns are unmatched - default: false
`,
0
)
}
const eslintOptions = (
options: NextLintOptions,
defaultCacheLocation: string
) => ({
overrideConfigFile: options.config || null,
extensions: options.ext ?? [],
resolvePluginsRelativeTo: options.resolvePluginsRelativeTo || null,
rulePaths: options.rulesdir ?? [],
fix: options.fix ?? false,
fixTypes: options.fixType ?? null,
ignorePath: options.ignorePath || null,
ignore: options.ignore,
allowInlineConfig: options.inlineConfig,
reportUnusedDisableDirectives: options.reportUnusedDisableDirectives || null,
cache: options.cache,
cacheLocation: options.cacheLocation || defaultCacheLocation,
cacheStrategy: options.cacheStrategy,
errorOnUnmatchedPattern: options.errorOnUnmatchedPattern ?? false,
})
const baseDir = getProjectDir(args._[0])
const nextLint = async (options: NextLintOptions, directory?: string) => {
const baseDir = getProjectDir(directory)
// Check if the provided directory exists
if (!existsSync(baseDir)) {
......@@ -116,24 +70,28 @@ const nextLint: CliCommand = async (args) => {
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const files: string[] = args['--file'] ?? []
const dirs: string[] = args['--dir'] ?? nextConfig.eslint?.dirs
const files = options.file ?? []
const dirs = options.dir ?? nextConfig.eslint?.dirs
const filesToLint = [...(dirs ?? []), ...files]
const pathsToLint = (
filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
).reduce((res: string[], d: string) => {
const currDir = join(baseDir, d)
if (!existsSync(currDir)) return res
if (!existsSync(currDir)) {
return res
}
res.push(currDir)
return res
}, [])
const reportErrorsOnly = Boolean(args['--quiet'])
const maxWarnings = args['--max-warnings'] ?? -1
const formatter = args['--format'] || null
const strict = Boolean(args['--strict'])
const outputFile = args['--output-file'] || null
const reportErrorsOnly = Boolean(options.quiet)
const maxWarnings = options.maxWarnings
const formatter = options.format || null
const strict = Boolean(options.strict)
const outputFile = options.outputFile || null
const distDir = join(baseDir, nextConfig.distDir)
const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
......@@ -141,7 +99,7 @@ const nextLint: CliCommand = async (args) => {
await verifyTypeScriptSetup({
dir: baseDir,
distDir: nextConfig.distDir,
distDir: distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
......@@ -152,8 +110,8 @@ const nextLint: CliCommand = async (args) => {
runLintCheck(baseDir, pathsToLint, {
lintDuringBuild: false,
eslintOptions: eslintOptions(args, defaultCacheLocation),
reportErrorsOnly: reportErrorsOnly,
eslintOptions: eslintOptions(options, defaultCacheLocation),
reportErrorsOnly,
maxWarnings,
formatter,
outputFile,
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--port': Number,
'--hostname': String,
'--keepAliveTimeout': Number,
'--experimental-test-proxy': Boolean,
// Aliases
'-h': '--help',
'-p': '--port',
'-H': '--hostname',
}
#!/usr/bin/env node
import '../server/lib/cpu-profile'
import { startServer } from '../server/lib/start-server'
import { getPort, printAndExit } from '../server/lib/utils'
import { printAndExit } from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir'
import type { CliCommand } from '../lib/commands'
import {
getReservedPortExplanation,
isPortIsReserved,
} from '../lib/helpers/get-reserved-port'
const nextStart: CliCommand = async (args) => {
if (args['--help']) {
console.log(`
Description
Starts the application in production mode.
The application should be compiled with \`next build\` first.
Usage
$ next start <dir> -p <port>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--port, -p A port number on which to start the application
--hostname, -H Hostname on which to start the application (default: 0.0.0.0)
--keepAliveTimeout Max milliseconds to wait before closing inactive connections
--help, -h Displays this message
`)
process.exit(0)
}
type NextStartOptions = {
port: number
hostname?: string
keepAliveTimeout?: number
experimentalTestProxy?: boolean
}
const dir = getProjectDir(args._[0])
const host = args['--hostname']
const port = getPort(args)
const nextStart = async (options: NextStartOptions, directory?: string) => {
const dir = getProjectDir(directory)
const host = options.hostname
const port = options.port
const isExperimentalTestProxy = options.experimentalTestProxy
let keepAliveTimeout = options.keepAliveTimeout
if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1)
}
const isExperimentalTestProxy = args['--experimental-test-proxy']
const keepAliveTimeoutArg: number | undefined = args['--keepAliveTimeout']
if (
typeof keepAliveTimeoutArg !== 'undefined' &&
(Number.isNaN(keepAliveTimeoutArg) ||
!Number.isFinite(keepAliveTimeoutArg) ||
keepAliveTimeoutArg < 0)
) {
printAndExit(
`Invalid --keepAliveTimeout, expected a non negative number but received "${keepAliveTimeoutArg}"`,
1
)
}
const keepAliveTimeout = keepAliveTimeoutArg
? Math.ceil(keepAliveTimeoutArg)
: undefined
await startServer({
dir,
isDev: false,
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--enable': Boolean,
'--disable': Boolean,
'--help': Boolean,
// Aliases
'-h': '--help',
}
#!/usr/bin/env node
import { bold, cyan, green, red, yellow } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import { Telemetry } from '../telemetry/storage'
const nextTelemetry: CliCommand = (args) => {
if (args['--help']) {
console.log(
`
Description
Allows you to control Next.js' telemetry collection
Usage
$ next telemetry [enable/disable]
You may pass the 'enable' or 'disable' argument to turn Next.js' telemetry collection on or off.
Options
--enable Enables Next.js' telemetry collection
--disable Disables Next.js' telemetry collection
--help, -h Displays this message
Learn more: ${cyan('https://nextjs.org/telemetry')}
`
)
return
}
const telemetry = new Telemetry({ distDir: process.cwd() })
type NextTelemetryOptions = {
enable?: boolean
disable?: boolean
}
let isEnabled = telemetry.isEnabled
const telemetry = new Telemetry({ distDir: process.cwd() })
let isEnabled = telemetry.isEnabled
if (args['--enable'] || args._[0] === 'enable') {
const nextTelemetry = (options: NextTelemetryOptions, arg: string) => {
if (options.enable || arg === 'enable') {
telemetry.setEnabled(true)
console.log(cyan('Success!'))
console.log()
isEnabled = true
} else if (args['--disable'] || args._[0] === 'disable') {
console.log(cyan('Success!'))
} else if (options.disable || arg === 'disable') {
const path = telemetry.setEnabled(false)
if (isEnabled) {
console.log(
cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`)
......@@ -45,30 +27,27 @@ const nextTelemetry: CliCommand = (args) => {
} else {
console.log(yellow(`Next.js' telemetry collection is already disabled.`))
}
console.log()
isEnabled = false
} else {
console.log(bold('Next.js Telemetry'))
console.log()
}
console.log(
`Status: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}`
`\nStatus: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}`
)
console.log()
if (isEnabled) {
console.log(
`Next.js telemetry is completely anonymous. Thank you for participating!`
'\nNext.js telemetry is completely anonymous. Thank you for participating!'
)
} else {
console.log(`You have opted-out of Next.js' anonymous telemetry program.`)
console.log(`No data will be collected from your machine.`)
console.log(
`\nYou have opted-out of Next.js' anonymous telemetry program.\nNo data will be collected from your machine.`
)
}
console.log(`Learn more: https://nextjs.org/telemetry`)
console.log()
console.log(`\nLearn more: ${cyan('https://nextjs.org/telemetry')}`)
}
export { nextTelemetry }
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
{"name":"commander","main":"index.js","author":"TJ Holowaychuk <tj@vision-media.ca>","license":"MIT"}
import type { getValidatedArgs } from './get-validated-args'
export type CliCommand = (args: ReturnType<typeof getValidatedArgs>) => void
export const commandArgs: {
[command: string]: () => Parameters<typeof getValidatedArgs>[0]
} = {
build: () => require('../cli/next-build-args').validArgs,
start: () => require('../cli/next-start-args').validArgs,
export: () => require('../cli/next-export-args').validArgs,
dev: () => require('../cli/next-dev-args').validArgs,
lint: () => require('../cli/next-lint-args').validArgs,
telemetry: () => require('../cli/next-telemetry-args').validArgs,
info: () => require('../cli/next-info-args').validArgs,
'experimental-compile': () => require('../cli/next-build-args').validArgs,
'experimental-generate': () => require('../cli/next-build-args').validArgs,
}
import type { getValidatedArgs } from './get-validated-args'
export type CliCommand = (args: ReturnType<typeof getValidatedArgs>) => void
export const commands: { [command: string]: () => Promise<CliCommand> } = {
build: () => Promise.resolve(require('../cli/next-build').nextBuild),
start: () => Promise.resolve(require('../cli/next-start').nextStart),
export: () => Promise.resolve(require('../cli/next-export').nextExport),
dev: () => Promise.resolve(require('../cli/next-dev').nextDev),
lint: () => Promise.resolve(require('../cli/next-lint').nextLint),
telemetry: () =>
Promise.resolve(require('../cli/next-telemetry').nextTelemetry),
info: () => Promise.resolve(require('../cli/next-info').nextInfo),
'experimental-compile': () =>
Promise.resolve(require('../cli/next-build').nextBuild),
'experimental-generate': () =>
Promise.resolve(require('../cli/next-build').nextBuild),
}
import type { Command, Help } from 'next/dist/compiled/commander'
import { bold } from '../lib/picocolors'
// Copy-pasted from Commander's Help class -> formatHelp().
// TL;DR, we're overriding the built-in help to add a few niceties.
// Link: https://github.com/tj/commander.js/blob/master/lib/help.js
const formatCliHelpOutput = (cmd: Command, helper: Help) => {
const termWidth = helper.padWidth(cmd, helper)
const helpWidth = helper.helpWidth || 80
const itemIndentWidth = 2
const itemSeparatorWidth = 2 // between term and description
function formatItem(term: string, description: string) {
let value = term
if (description) {
if (term === 'directory') {
value = `[${term}]`
}
const fullText = `${value.padEnd(
termWidth + itemSeparatorWidth
)}${description}`
return helper.wrap(
fullText,
helpWidth - itemIndentWidth,
termWidth + itemSeparatorWidth
)
}
return term
}
function formatList(textArray: string[]) {
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth))
}
// Usage
let output = [`${bold('Usage:')} ${helper.commandUsage(cmd)}`, '']
// Description
const commandDescription = helper.commandDescription(cmd)
if (commandDescription.length > 0) {
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ''])
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return formatItem(
helper.argumentTerm(argument),
helper.argumentDescription(argument)
)
})
if (argumentList.length > 0) {
output = output.concat([
`${bold('Arguments:')}`,
formatList(argumentList),
'',
])
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return formatItem(
helper.optionTerm(option),
helper.optionDescription(option)
)
})
if (optionList.length > 0) {
output = output.concat([`${bold('Options:')}`, formatList(optionList), ''])
}
// Commands
const commandList = helper.visibleCommands(cmd).map((subCmd) => {
return formatItem(
helper.subcommandTerm(subCmd),
helper.subcommandDescription(subCmd)
)
})
if (commandList.length > 0) {
output = output.concat([
`${bold('Commands:')}`,
formatList(commandList),
'',
])
}
return output.join('\n')
}
export { formatCliHelpOutput }
import path from 'path'
import { commands } from './commands'
import * as Log from '../build/output/log'
import { error, warn } from '../build/output/log'
import { detectTypo } from './detect-typo'
import { realpathSync } from './realpath'
......@@ -13,7 +12,7 @@ export function getProjectDir(dir?: string) {
resolvedDir !== realDir &&
resolvedDir.toLowerCase() === realDir.toLowerCase()
) {
Log.warn(
warn(
`Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`
)
}
......@@ -22,17 +21,24 @@ export function getProjectDir(dir?: string) {
} catch (err: any) {
if (err.code === 'ENOENT') {
if (typeof dir === 'string') {
const detectedTypo = detectTypo(dir, Object.keys(commands))
const detectedTypo = detectTypo(dir, [
'build',
'dev',
'info',
'lint',
'start',
'telemetry',
])
if (detectedTypo) {
Log.error(
error(
`"next ${dir}" does not exist. Did you mean "next ${detectedTypo}"?`
)
process.exit(1)
}
}
Log.error(
error(
`Invalid project directory provided, no such directory: ${path.resolve(
dir || '.'
)}`
......
import arg from 'next/dist/compiled/arg/index.js'
import { printAndExit } from '../server/lib/utils'
import isError from './is-error'
export function getValidatedArgs(validArgs: arg.Spec, argv?: string[]) {
let args: arg.Result<arg.Spec>
try {
args = arg(validArgs, { argv })
} catch (error) {
if (isError(error) && error.code === 'ARG_UNKNOWN_OPTION') {
printAndExit(error.message, 1)
}
throw error
}
return args
}
......@@ -33,7 +33,7 @@ export interface StartServerOptions {
dir: string
port: number
isDev: boolean
hostname: string
hostname?: string
allowRetry?: boolean
customServer?: boolean
minimalMode?: boolean
......@@ -59,7 +59,7 @@ export async function getRequestHandlers({
port: number
isDev: boolean
server?: import('http').Server
hostname: string
hostname?: string
minimalMode?: boolean
isNodeDebugging?: boolean
keepAliveTimeout?: number
......
import type arg from 'next/dist/compiled/arg/index.js'
import { InvalidArgumentError } from 'next/dist/compiled/commander'
export function printAndExit(message: string, code = 1) {
if (code === 0) {
......@@ -28,17 +28,14 @@ export function getNodeOptionsWithoutInspect() {
return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '')
}
export function getPort(args: arg.Result<arg.Spec>): number {
if (typeof args['--port'] === 'number') {
return args['--port']
}
export function myParseInt(value: string) {
// parseInt takes a string and a radix
const parsedValue = parseInt(value, 10)
const parsed = process.env.PORT && parseInt(process.env.PORT, 10)
if (typeof parsed === 'number' && !Number.isNaN(parsed)) {
return parsed
if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {
throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)
}
return 3000
return parsedValue
}
export const RESTART_EXIT_CODE = 77
......
......@@ -1008,14 +1008,6 @@ export async function ncc_amp_optimizer(task, opts) {
.target('dist/compiled/@ampproject/toolbox-optimizer')
}
// eslint-disable-next-line camelcase
externals['arg'] = 'next/dist/compiled/arg'
export async function ncc_arg(task, opts) {
await task
.source(relative(__dirname, require.resolve('arg')))
.ncc({ packageName: 'arg' })
.target('src/compiled/arg')
}
// eslint-disable-next-line camelcase
externals['async-retry'] = 'next/dist/compiled/async-retry'
export async function ncc_async_retry(task, opts) {
await task
......@@ -1159,6 +1151,13 @@ export async function ncc_cli_select(task, opts) {
.ncc({ packageName: 'cli-select', externals })
.target('src/compiled/cli-select')
}
externals['commmander'] = 'next/dist/compiled/commander'
export async function ncc_commander(task, opts) {
await task
.source(relative(__dirname, require.resolve('commander')))
.ncc({ packageName: 'commander', externals })
.target('src/compiled/commander')
}
externals['comment-json'] = 'next/dist/compiled/comment-json'
export async function ncc_comment_json(task, opts) {
await task
......@@ -2178,6 +2177,7 @@ export async function ncc(task, opts) {
'ncc_image_size',
'ncc_get_orientation',
'ncc_hapi_accept',
'ncc_commander',
'ncc_node_fetch',
'ncc_node_anser',
'ncc_node_stacktrace_parser',
......@@ -2187,7 +2187,6 @@ export async function ncc(task, opts) {
'ncc_node_shell_quote',
'ncc_acorn',
'ncc_amphtml_validator',
'ncc_arg',
'ncc_async_retry',
'ncc_async_sema',
'ncc_postcss_plugin_stub_for_cssnano_simple',
......
......@@ -47,6 +47,12 @@ declare module 'next/dist/compiled/node-fetch' {
export default fetch
}
declare module 'next/dist/compiled/commander' {
import commander from 'commander'
export * from 'commander'
export default commander
}
declare module 'next/dist/compiled/node-html-parser' {
export * from 'node-html-parser'
}
......@@ -111,32 +117,6 @@ declare module 'next/dist/compiled/async-sema' {
import m from 'async-sema'
export = m
}
declare module 'next/dist/compiled/arg/index.js' {
function arg<T extends arg.Spec>(
spec: T,
options?: { argv?: string[]; permissive?: boolean }
): arg.Result<T>
namespace arg {
export type Handler = (value: string) => any
export interface Spec {
[key: string]: string | Handler | [Handler]
}
export type Result<T extends Spec> = { _: string[] } & {
[K in keyof T]: T[K] extends string
? never
: T[K] extends Handler
? ReturnType<T[K]>
: T[K] extends [Handler]
? Array<ReturnType<T[K][0]>>
: never
}
}
export = arg
}
declare module 'next/dist/compiled/babel/code-frame' {
export * from '@babel/code-frame'
......
......@@ -1124,6 +1124,9 @@ importers:
client-only:
specifier: 0.0.1
version: 0.0.1
commander:
specifier: 12.0.0
version: 12.0.0
comment-json:
specifier: 3.0.3
version: 3.0.3
......@@ -9582,13 +9585,14 @@ packages:
/comma-separated-tokens@2.0.3:
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
/commander@12.0.0:
resolution: {integrity: sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==}
engines: {node: '>=18'}
dev: true
/commander@2.20.0:
resolution: {integrity: sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==}
/commander@2.20.3:
resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}
dev: true
/commander@4.1.1:
resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}
engines: {node: '>= 6'}
......@@ -24940,7 +24944,7 @@ packages:
hasBin: true
dependencies:
chalk: 1.1.3
commander: 2.20.3
commander: 2.20.0
debug: 2.6.9
transitivePeerDependencies:
- supports-color
......
......@@ -13,7 +13,7 @@ createNextDescribe(
{
files: __dirname,
buildCommand: process.env.NEXT_EXPERIMENTAL_COMPILE
? 'pnpm next experimental-compile'
? `pnpm next build --experimental-build-mode=compile`
: undefined,
dependencies: {
nanoid: '4.0.1',
......
......@@ -57,7 +57,7 @@ describe('app dir - with output export (next dev / next build)', () => {
}
expect(error).toBeDefined()
expect(stderr).toContain(
'The "next export" command has been removed in favor of "output: export" in next.config.js'
`\`next export\` has been removed in favor of 'output: export' in next.config.js`
)
expect(stdout).not.toContain('Export successful. Files written to')
expect(await getFiles()).toEqual([])
......
......@@ -124,14 +124,14 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['start', '--help'], {
stdout: true,
})
expect(help.stdout).toMatch(/Starts the application in production mode/)
expect(help.stdout).toMatch(/Starts Next.js in production mode/)
})
test('-h', async () => {
const help = await runNextCommand(['start', '-h'], {
stdout: true,
})
expect(help.stdout).toMatch(/Starts the application in production mode/)
expect(help.stdout).toMatch(/Starts Next.js in production mode/)
})
test('should format IPv6 addresses correctly', async () => {
......@@ -167,7 +167,7 @@ describe('CLI Usage', () => {
const { stderr } = await runNextCommand(['start', '--random'], {
stderr: true,
})
expect(stderr).toEqual('Unknown or unexpected option: --random\n')
expect(stderr).toEqual(`error: unknown option '--random'\n`)
})
test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['start', '--random'], {
......@@ -211,7 +211,7 @@ describe('CLI Usage', () => {
}
)
expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "NaN"'
`error: option '--keepAliveTimeout <keepAliveTimeout>' argument 'string' is invalid. 'string' is not a non-negative number.`
)
})
......@@ -223,7 +223,7 @@ describe('CLI Usage', () => {
}
)
expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "-100"'
`error: option '--keepAliveTimeout <keepAliveTimeout>' argument '-100' is invalid. '-100' is not a non-negative number.`
)
})
......@@ -235,7 +235,7 @@ describe('CLI Usage', () => {
}
)
expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "Infinity"'
`error: option '--keepAliveTimeout <keepAliveTimeout>' argument 'Infinity' is invalid. 'Infinity' is not a non-negative number.`
)
})
......@@ -247,7 +247,7 @@ describe('CLI Usage', () => {
}
)
expect(stderr).not.toContain(
'Invalid keep alive timeout provided, expected a non negative number'
`error: option '--keepAliveTimeout <keepAliveTimeout>' argument '100' is invalid. '100' is not a non-negative number.`
)
})
......@@ -283,25 +283,21 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['telemetry', '--help'], {
stdout: true,
})
expect(help.stdout).toMatch(
/Allows you to control Next\.js' telemetry collection/
)
expect(help.stdout).toMatch(/Allows you to enable or disable Next\.js'/)
})
test('-h', async () => {
const help = await runNextCommand(['telemetry', '-h'], {
stdout: true,
})
expect(help.stdout).toMatch(
/Allows you to control Next\.js' telemetry collection/
)
expect(help.stdout).toMatch(/Allows you to enable or disable Next\.js'/)
})
test('should warn when unknown argument provided', async () => {
const { stderr } = await runNextCommand(['telemetry', '--random'], {
stderr: true,
})
expect(stderr).toEqual('Unknown or unexpected option: --random\n')
expect(stderr).toEqual(`error: unknown option '--random'\n`)
})
test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['telemetry', '--random'], {
......@@ -316,25 +312,21 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['build', '--help'], {
stdout: true,
})
expect(help.stdout).toMatch(
/Compiles the application for production deployment/
)
expect(help.stdout).toMatch(/Creates an optimized production build/)
})
test('-h', async () => {
const help = await runNextCommand(['build', '-h'], {
stdout: true,
})
expect(help.stdout).toMatch(
/Compiles the application for production deployment/
)
expect(help.stdout).toMatch(/Creates an optimized production build/)
})
test('should warn when unknown argument provided', async () => {
const { stderr } = await runNextCommand(['build', '--random'], {
stderr: true,
})
expect(stderr).toEqual('Unknown or unexpected option: --random\n')
expect(stderr).toEqual(`error: unknown option '--random'\n`)
})
test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['build', '--random'], {
......@@ -367,14 +359,18 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['--help'], {
stdout: true,
})
expect(help.stdout).toMatch(/Usage/)
expect(help.stdout).toMatch(
/The Next.js CLI allows you to develop, build, start/
)
})
test('-h', async () => {
const help = await runNextCommand(['-h'], {
stdout: true,
})
expect(help.stdout).toMatch(/Usage/)
expect(help.stdout).toMatch(
/The Next.js CLI allows you to develop, build, start/
)
})
test('--version', async () => {
......@@ -429,14 +425,14 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['dev', '--help'], {
stdout: true,
})
expect(help.stdout).toMatch(/Starts the application in development mode/)
expect(help.stdout).toMatch(/Starts Next.js in development mode/)
})
test('-h', async () => {
const help = await runNextCommand(['dev', '-h'], {
stdout: true,
})
expect(help.stdout).toMatch(/Starts the application in development mode/)
expect(help.stdout).toMatch(/Starts Next.js in development mode/)
})
test('custom directory', async () => {
......@@ -732,7 +728,7 @@ describe('CLI Usage', () => {
const { stderr } = await runNextCommand(['dev', '--random'], {
stderr: true,
})
expect(stderr).toEqual('Unknown or unexpected option: --random\n')
expect(stderr).toEqual(`error: unknown option '--random'\n`)
})
test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['dev', '--random'], {
......@@ -767,7 +763,18 @@ describe('CLI Usage', () => {
stderr: true,
})
expect(help.stderr).toMatch(
'The "next export" command has been removed in favor of "output: export" in next.config.js'
`error: unknown option '--help'\n(Did you mean --help?)`
)
expect(help.code).toBe(1)
})
test('run export command', async () => {
const help = await runNextCommand(['export'], {
stdout: true,
stderr: true,
})
expect(help.stderr).toMatch(
`\`next export\` has been removed in favor of 'output: export' in next.config.js`
)
expect(help.code).toBe(1)
})
......@@ -805,7 +812,7 @@ Next.js Config:
stdout: true,
})
expect(help.stdout).toMatch(
/Prints relevant details about the current system which can be used to report Next\.js bugs/
/Prints relevant details about the current system which can be used to report/
)
})
......@@ -814,7 +821,7 @@ Next.js Config:
stdout: true,
})
expect(help.stdout).toMatch(
/Prints relevant details about the current system which can be used to report Next\.js bugs/
/Prints relevant details about the current system which can be used to report/
)
})
......
import { nextStart } from 'next/dist/cli/next-start'
import httpMock, { Server } from 'http'
// Prevents bin from running
jest.mock('next/dist/bin/next', () => ({}))
jest.mock('next/dist/lib/get-project-dir', () => ({ getProjectDir: () => '' }))
jest.mock('http')
// this test is unreliable as nextStart is not synchronous and the
// server could be created at any point
describe.skip('start', () => {
test('--keepAliveTimeout changes server.keepAliveTimeout when passed', () => {
const server = {
on: () => {},
listen: () => {},
} as any as Server
;(httpMock as any).createServer.mockReturnValue(server)
expect(server.keepAliveTimeout).toBe(undefined)
nextStart(['--keepAliveTimeout', '1234'])
expect(server.keepAliveTimeout).toBe(1234)
})
test("--keepAliveTimeout doesn't change server.keepAliveTimeout when not passed", () => {
const server = {
on: () => {},
listen: () => {},
} as any as Server
;(httpMock as any).createServer.mockReturnValue(server)
expect(server.keepAliveTimeout).toBe(undefined)
nextStart([])
expect(server.keepAliveTimeout).toBe(undefined)
})
})
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