Unverified Commit d1dabe42 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Remove esm loader (#55509)

Now that we are bundling the react runtime for app router we can remove
the esm loader as that was the reason it was added when bringing the
server back into a single process.

x-ref: https://github.com/vercel/next.js/pull/55362

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent dc9ba02f
......@@ -5,14 +5,7 @@ import arg from 'next/dist/compiled/arg/index.js'
import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import { commands } from '../lib/commands'
import { commandArgs } from '../lib/command-args'
import loadConfig from '../server/config'
import {
PHASE_PRODUCTION_SERVER,
PHASE_DEVELOPMENT_SERVER,
} from '../shared/lib/constants'
import { getProjectDir } from '../lib/get-project-dir'
import { getValidatedArgs } from '../lib/get-validated-args'
import { findPagesDir } from '../lib/find-pages-dir'
const defaultCommand = 'dev'
const args = arg(
......@@ -126,48 +119,6 @@ async function main() {
const currentArgsSpec = commandArgs[command]()
const validatedArgs = getValidatedArgs(currentArgsSpec, forwardedArgs)
if (
(command === 'start' || command === 'dev') &&
!process.env.NEXT_PRIVATE_WORKER
) {
const dir = getProjectDir(
process.env.NEXT_PRIVATE_DEV_DIR || validatedArgs._[0]
)
process.env.NEXT_PRIVATE_DIR = dir
const origEnv = Object.assign({}, process.env)
// TODO: set config to env variable to be re-used so we don't reload
// un-necessarily
const config = await loadConfig(
command === 'dev' ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
dir,
{
silent: false,
}
)
let dirsResult: ReturnType<typeof findPagesDir> | undefined = undefined
try {
dirsResult = findPagesDir(dir)
} catch (_) {
// handle this error further down
}
if (dirsResult?.appDir || process.env.NODE_ENV === 'development') {
process.env = origEnv
}
if (dirsResult?.appDir) {
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
// initial env state is correct
process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = config.experimental
.serverActions
? 'experimental'
: 'next'
}
}
for (const dependency of ['react', 'react-dom']) {
try {
// When 'npm link' is used it checks the clone location. Not the project.
......
......@@ -147,10 +147,9 @@ import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { buildDataRoute } from '../server/lib/router-utils/build-data-route'
import { defaultOverrides } from '../server/import-overrides'
import { defaultOverrides } from '../server/require-hook'
import { initialize as initializeIncrementalCache } from '../server/lib/incremental-cache-server'
import { nodeFs } from '../server/lib/node-fs-methods'
import { getEsmLoaderPath } from '../server/lib/get-esm-loader-path'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -1251,11 +1250,6 @@ export default async function build(
},
numWorkers,
forkOptions: {
execArgv: [
'--experimental-loader',
getEsmLoaderPath(),
'--no-warnings',
],
env: {
...process.env,
__NEXT_INCREMENTAL_CACHE_IPC_PORT: incrementalCacheIpcPort + '',
......@@ -2135,8 +2129,7 @@ export default async function build(
? [
require.resolve('next/dist/server/lib/start-server'),
require.resolve('next/dist/server/next'),
require.resolve('next/dist/esm/server/esm-loader.mjs'),
require.resolve('next/dist/server/import-overrides'),
require.resolve('next/dist/server/require-hook'),
]
: []),
require.resolve('next/dist/server/next-server'),
......
......@@ -69,7 +69,7 @@ import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plu
import { getSupportedBrowsers } from './utils'
import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin'
import { getBabelConfigFile } from './get-babel-config-file'
import { defaultOverrides } from '../server/import-overrides'
import { defaultOverrides } from '../server/require-hook'
type ExcludesFalse = <T>(x: T | false) => x is T
type ClientEntries = {
......
......@@ -17,23 +17,28 @@ import { fileExists, FileType } from '../lib/file-exists'
import { getNpxCommand } from '../lib/helpers/get-npx-command'
import { createSelfSignedCertificate } from '../lib/mkcert'
import uploadTrace from '../trace/upload-trace'
import { startServer } from '../server/lib/start-server'
import { loadEnvConfig } from '@next/env'
import { initialEnv, loadEnvConfig } from '@next/env'
import { trace } from '../trace'
import { validateTurboNextConfig } from '../lib/turbopack-warning'
import { fork } from 'child_process'
import { RESTART_EXIT_CODE } from '../server/lib/setup-server-worker'
import {
getReservedPortExplanation,
isPortIsReserved,
} from '../lib/helpers/get-reserved-port'
import { validateTurboNextConfig } from '../lib/turbopack-warning'
let dir: string
let child: undefined | ReturnType<typeof fork>
let config: NextConfigComplete
let isTurboSession = false
let traceUploadUrl: string
let sessionStopHandled = false
let sessionStarted = Date.now()
const handleSessionStop = async () => {
const handleSessionStop = async (signal: string | null) => {
if (child) {
child.kill((signal as any) || 0)
}
if (sessionStopHandled) return
sessionStopHandled = true
......@@ -96,8 +101,8 @@ const handleSessionStop = async () => {
process.exit(0)
}
process.on('SIGINT', handleSessionStop)
process.on('SIGTERM', handleSessionStop)
process.on('SIGINT', () => handleSessionStop('SIGINT'))
process.on('SIGTERM', () => handleSessionStop('SIGTERM'))
const nextDev: CliCommand = async (args) => {
if (args['--help']) {
......@@ -193,6 +198,14 @@ const nextDev: CliCommand = async (args) => {
},
})
process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = config.experimental
.serverActions
? 'experimental'
: 'next'
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
// initial env state is correct
let envInfo: string[] = []
if (loadedEnvFiles.length > 0) {
envInfo = loadedEnvFiles.map((f) => f.path)
......@@ -231,6 +244,42 @@ const nextDev: CliCommand = async (args) => {
setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
setGlobal('distDir', distDir)
const startServerPath = require.resolve('../server/lib/start-server')
async function startServer(options: StartServerOptions) {
return new Promise<void>((resolve) => {
let resolved = false
child = fork(startServerPath, {
stdio: 'inherit',
env: {
...((initialEnv || process.env) as typeof process.env),
NEXT_PRIVATE_WORKER: '1',
},
})
child.on('message', (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) {
child?.send({ nextWorkerOptions: options })
} else if (msg.nextServerReady && !resolved) {
resolved = true
resolve()
}
}
})
child.on('exit', async (code, signal) => {
if (sessionStopHandled || signal) {
return
}
if (code === RESTART_EXIT_CODE) {
return startServer(options)
}
await handleSessionStop(signal)
})
})
}
const runDevServer = async (reboot: boolean) => {
try {
if (!!args['--experimental-https']) {
......
......@@ -10,7 +10,7 @@ export function loadWebpackHook() {
// hook the Node.js require so that webpack requires are
// routed to the bundled and now initialized webpack version
require('../server/import-overrides').addHookAliases(
require('../server/require-hook').addHookAliases(
[
['webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/package', 'next/dist/compiled/webpack/package'],
......
......@@ -865,7 +865,7 @@ export default async function loadConfig(
if (shouldExit) {
for (const message of messages) {
curLog.error(message)
console.error(message)
}
await flushAndExit(1)
} else {
......
import module from 'module'
const require = module.createRequire(import.meta.url)
export function resolve(specifier: string, context: any, nextResolve: any) {
const { hookPropertyMap } = require(process.env.NEXT_YARN_PNP
? './import-overrides'
: 'next/dist/server/import-overrides') as typeof import('./import-overrides')
const hookResolved = hookPropertyMap.get(specifier)
if (hookResolved) {
specifier = hookResolved
}
if (specifier.endsWith('next/dist/bin/next')) {
return {
url: specifier,
shortCircuit: true,
format: 'commonjs',
}
}
return nextResolve(specifier, context)
}
const { dirname } = require('path') as typeof import('path')
let resolve: typeof require.resolve = process.env.NEXT_MINIMAL
? // @ts-ignore
__non_webpack_require__.resolve
: require.resolve
let nextPaths: undefined | { paths: string[] | undefined } = undefined
if (!process.env.NEXT_MINIMAL) {
nextPaths = {
paths: resolve.paths('next/package.json') || undefined,
}
}
export const hookPropertyMap = new Map()
export const defaultOverrides = {
'styled-jsx': process.env.NEXT_MINIMAL
? dirname(resolve('styled-jsx/package.json'))
: dirname(resolve('styled-jsx/package.json', nextPaths)),
'styled-jsx/style': process.env.NEXT_MINIMAL
? resolve('styled-jsx/style')
: resolve('styled-jsx/style', nextPaths),
}
const toResolveMap = (map: Record<string, string>): [string, string][] =>
Object.entries(map).map(([key, value]) => [key, resolve(value, nextPaths)])
export function addHookAliases(aliases: [string, string][] = []) {
for (const [key, value] of aliases) {
hookPropertyMap.set(key, value)
}
}
addHookAliases(toResolveMap(defaultOverrides))
export function getEsmLoaderPath() {
let esmLoaderPath = 'next/dist/esm/server/esm-loader.mjs'
// Since loaders don't stack Yarn PnP's loader isn't
// applied when loading our loader so we need to move
// it outside of the PnP cache
// x-ref: https://github.com/yarnpkg/berry/issues/3700
if (process.versions.pnp) {
process.env.NEXT_YARN_PNP = '1'
const fs = require('fs') as typeof import('fs')
const path = require('path') as typeof import('path')
const tmpDir = path.join(
process.env.NEXT_PRIVATE_DIR || process.cwd(),
`.next/loader`
)
fs.mkdirSync(tmpDir, { recursive: true })
for (const file of [esmLoaderPath, 'next/dist/server/import-overrides']) {
const resolvedFile = require.resolve(file)
const newFile = path.join(tmpDir, path.basename(file))
fs.copyFileSync(resolvedFile, newFile)
if (file === esmLoaderPath) {
esmLoaderPath = newFile
}
}
}
return esmLoaderPath
}
......@@ -84,7 +84,8 @@ export async function initialize(opts: {
const config = await loadConfig(
opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
opts.dir
opts.dir,
{ silent: false }
)
let compress: ReturnType<typeof setupCompression> | undefined
......
......@@ -358,3 +358,13 @@ export async function startServer({
})
}
}
if (process.env.NEXT_PRIVATE_WORKER && process.send) {
process.addListener('message', async (msg: any) => {
if (msg && typeof msg && msg.nextWorkerOptions && process.send) {
await startServer(msg.nextWorkerOptions)
process.send({ nextServerReady: true })
}
})
process.send({ nextWorkerReady: true })
}
......@@ -4,57 +4,11 @@ import type { UrlWithParsedQuery } from 'url'
import type { NextConfigComplete } from './config-shared'
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextUrlWithParsedQuery } from './request-meta'
import { spawnSync } from 'child_process'
import { getEsmLoaderPath } from './lib/get-esm-loader-path'
import {
RESTART_EXIT_CODE,
WorkerRequestHandler,
WorkerUpgradeHandler,
} from './lib/setup-server-worker'
// if we are not inside of the esm loader enabled
// worker we need to re-spawn with correct args
// we can't do this if imported in jest test file otherwise
// it duplicates tests
if (
typeof jest === 'undefined' &&
!process.env.NEXT_PRIVATE_WORKER &&
(process.env.__NEXT_PRIVATE_PREBUNDLED_REACT ||
process.env.NODE_ENV === 'development')
) {
const nodePath = process.argv0
const newArgs = [
'--experimental-loader',
getEsmLoaderPath(),
'--no-warnings',
...process.argv.splice(1),
]
function startWorker() {
try {
const result = spawnSync(nodePath, newArgs, {
stdio: 'inherit',
env: {
...process.env,
NEXT_PRIVATE_WORKER: '1',
},
})
if (
result.status === RESTART_EXIT_CODE &&
process.env.NODE_ENV === 'development'
) {
startWorker()
}
process.exit(0)
} catch (err) {
console.error(err)
process.exit(1)
}
}
startWorker()
}
import './require-hook'
import './node-polyfill-fetch'
import './node-polyfill-crypto'
......
......@@ -8,16 +8,43 @@ const mod = require('module')
const originalRequire = mod.prototype.require
const resolveFilename = mod._resolveFilename
const { hookPropertyMap } = require('./import-overrides')
const { PHASE_PRODUCTION_BUILD } = require('../shared/lib/constants')
let resolve: typeof require.resolve = process.env.NEXT_MINIMAL
? // @ts-ignore
__non_webpack_require__.resolve
: require.resolve
export const hookPropertyMap = new Map()
export const defaultOverrides = {
'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),
'styled-jsx/style': resolve('styled-jsx/style'),
}
const toResolveMap = (map: Record<string, string>): [string, string][] =>
Object.entries(map).map(([key, value]) => [key, resolve(value)])
export function addHookAliases(aliases: [string, string][] = []) {
for (const [key, value] of aliases) {
hookPropertyMap.set(key, value)
}
}
addHookAliases(toResolveMap(defaultOverrides))
mod._resolveFilename = function (
originalResolveFilename,
requestMap,
request,
parent,
isMain,
options
originalResolveFilename: (
request: string,
parent: string,
isMain: boolean,
opts: any
) => string,
requestMap: Map<string, string>,
request: string,
parent: string,
isMain: boolean,
options: any
) {
const hookResolved = requestMap.get(request)
if (hookResolved) request = hookResolved
......@@ -30,7 +57,7 @@ mod._resolveFilename = function (
// This is a hack to make sure that if a user requires a Next.js module that wasn't bundled
// that needs to point to the rendering runtime version, it will point to the correct one.
// This can happen on `pages` when a user requires a dependency that uses next/image for example.
mod.prototype.require = function (request) {
mod.prototype.require = function (request: string) {
if (
(process.env.NEXT_PHASE !== PHASE_PRODUCTION_BUILD ||
process.env.NEXT_IS_EXPORT_WORKER) &&
......
......@@ -8,7 +8,6 @@ import {
nextBuild,
runNextCommand,
runNextCommandDev,
killProcess,
} from 'next-test-utils'
import fs from 'fs-extra'
import path, { join } from 'path'
......@@ -53,8 +52,7 @@ const runAndCaptureOutput = async ({ port }) => {
const testExitSignal = async (
killSignal = '',
args = [],
readyRegex = /Creating an optimized production/,
expectedExitSignal
readyRegex = /Creating an optimized production/
) => {
let instance
const killSigint = (inst) => {
......@@ -71,18 +69,14 @@ const testExitSignal = async (
}).catch((err) => expect.fail(err.message))
await check(() => output, readyRegex)
await killProcess(instance.pid, killSignal)
instance.kill(killSignal)
const { code, signal } = await cmdPromise
if (!expectedExitSignal) {
// Node can only partially emulate signals on Windows. Our signal handlers won't affect the exit code.
// See: https://nodejs.org/api/process.html#process_signal_events
expectedExitSignal = process.platform === `win32` ? killSignal : null
expect(code).toBe(0)
} else {
expect(signal).toBe(expectedExitSignal)
}
// Node can only partially emulate signals on Windows. Our signal handlers won't affect the exit code.
// See: https://nodejs.org/api/process.html#process_signal_events
const expectedExitSignal = process.platform === `win32` ? killSignal : null
expect(signal).toBe(expectedExitSignal)
expect(code).toBe(0)
}
describe('CLI Usage', () => {
......@@ -706,21 +700,11 @@ describe('CLI Usage', () => {
test('should exit when SIGINT is signalled', async () => {
const port = await findPort()
await testExitSignal(
'SIGINT',
['dev', dirBasic, '-p', port],
/- Local:/,
'SIGINT'
)
await testExitSignal('SIGINT', ['dev', dirBasic, '-p', port], /- Local:/)
})
test('should exit when SIGTERM is signalled', async () => {
const port = await findPort()
await testExitSignal(
'SIGTERM',
['dev', dirBasic, '-p', port],
/- Local:/,
'SIGTERM'
)
await testExitSignal('SIGTERM', ['dev', dirBasic, '-p', port], /- Local:/)
})
test('invalid directory', async () => {
......
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