Unverified Commit 810f0e87 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

perf: create an experimental bundled version of the next server (#52206)

This PR:
- adds a minified bundled server for Next with some optimisations applied
- a test server in minimal-server.js
- misc changes:
   - makes some polyfills lazy
   - adds a cached version of node-html-parser
   -   
parent 4e710645
......@@ -147,6 +147,7 @@
},
{
"files": ["packages/**"],
"excludedFiles": ["packages/next/taskfile.js"],
"rules": {
"no-shadow": ["warn", { "builtinGlobals": false }],
"import/no-extraneous-dependencies": [
......
import type { NodeFileTraceResult } from '@vercel/nft'
import type { RemotePattern } from '../shared/lib/image-config'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
......@@ -140,6 +141,7 @@ import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { baseOverrides, experimentalOverrides } from '../server/require-hook'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -1745,6 +1747,10 @@ export default async function build(
distDir,
'next-server.js.nft.json'
)
const nextMinimalTraceOutput = path.join(
distDir,
'next-minimal-server.js.nft.json'
)
if (!isGenerate && config.outputFileTracing) {
let nodeFileTrace: any
......@@ -1937,19 +1943,20 @@ export default async function build(
const nextServerEntry = require.resolve(
'next/dist/server/next-server'
)
const toTrace = [
nextServerEntry,
isStandalone
? require.resolve(
'next/dist/server/lib/render-server-standalone'
)
: null,
].filter(nonNullable)
const sharedEntriesSet = [
...Object.values(baseOverrides).map((override) =>
require.resolve(override)
),
...Object.values(experimentalOverrides).map((override) =>
require.resolve(override)
),
]
// ensure we trace any dependencies needed for custom
// incremental cache handler
if (incrementalCacheHandlerPath) {
toTrace.push(
sharedEntriesSet.push(
require.resolve(
path.isAbsolute(incrementalCacheHandlerPath)
? incrementalCacheHandlerPath
......@@ -1958,7 +1965,25 @@ export default async function build(
)
}
let serverResult: import('next/dist/compiled/@vercel/nft').NodeFileTraceResult
const vanillaServerEntries = [
...sharedEntriesSet,
isStandalone
? require.resolve(
'next/dist/server/lib/render-server-standalone'
)
: null,
require.resolve('next/dist/server/next-server'),
].filter(Boolean) as string[]
const minimalServerEntries = [
...sharedEntriesSet,
require.resolve(
'next/dist/compiled/minimal-next-server/next-server-cached.js'
),
require.resolve(
'next/dist/compiled/minimal-next-server/next-server.js'
),
].filter(Boolean)
const additionalIgnores = new Set<string>()
......@@ -2004,9 +2029,14 @@ export default async function build(
}
const traceContext = path.join(nextServerEntry, '..', '..')
const tracedFiles = new Set<string>()
const minimalTracedFiles = new Set<string>()
function addToTracedFiles(base: string, file: string) {
tracedFiles.add(
function addToTracedFiles(
base: string,
file: string,
dest: Set<string>
) {
dest.add(
path
.relative(distDir, path.join(base, file))
.replace(/\\/g, '/')
......@@ -2016,54 +2046,93 @@ export default async function build(
if (isStandalone) {
addToTracedFiles(
'',
require.resolve('next/dist/compiled/jest-worker/processChild')
require.resolve('next/dist/compiled/jest-worker/processChild'),
tracedFiles
)
addToTracedFiles(
'',
require.resolve('next/dist/compiled/jest-worker/threadChild')
require.resolve('next/dist/compiled/jest-worker/threadChild'),
tracedFiles
)
}
if (config.experimental.turbotrace) {
const files: string[] = await nodeFileTrace(
{
action: 'print',
input: toTrace,
contextDirectory: traceContext,
logLevel: config.experimental.turbotrace.logLevel,
processCwd: config.experimental.turbotrace.processCwd,
logDetail: config.experimental.turbotrace.logDetail,
showAll: config.experimental.turbotrace.logAll,
},
turboTasksForTrace
)
for (const file of files) {
if (!ignoreFn(path.join(traceContext, file))) {
addToTracedFiles(traceContext, file)
const makeTrace = async (entries: string[]) =>
nodeFileTrace(
{
action: 'print',
input: entries,
contextDirectory: traceContext,
logLevel: config.experimental.turbotrace?.logLevel,
processCwd: config.experimental.turbotrace?.processCwd,
logDetail: config.experimental.turbotrace?.logDetail,
showAll: config.experimental.turbotrace?.logAll,
},
turboTasksForTrace
)
// turbotrace does not handle concurrent tracing
const vanillaFiles = await makeTrace(vanillaServerEntries)
const minimalFiles = await makeTrace(minimalServerEntries)
for (const [set, files] of [
[tracedFiles, vanillaFiles],
[minimalTracedFiles, minimalFiles],
] as [Set<string>, string[]][]) {
for (const file of files) {
if (!ignoreFn(path.join(traceContext, file))) {
addToTracedFiles(traceContext, file, set)
}
}
}
} else {
serverResult = await nodeFileTrace(toTrace, {
base: root,
processCwd: dir,
ignore: ignoreFn,
})
const makeTrace = async (entries: string[]) =>
nodeFileTrace(entries, {
base: root,
processCwd: dir,
ignore: ignoreFn,
})
serverResult.fileList.forEach((file) => {
addToTracedFiles(root, file)
})
const [vanillaFiles, minimalFiles]: NodeFileTraceResult[] =
await Promise.all([
makeTrace(vanillaServerEntries),
makeTrace(minimalServerEntries),
])
for (const [set, traceResult] of [
[tracedFiles, vanillaFiles],
[minimalTracedFiles, minimalFiles],
] as [Set<string>, NodeFileTraceResult][]) {
for (const file of traceResult.fileList) {
addToTracedFiles(root, file, set)
}
}
}
await fs.writeFile(
nextServerTraceOutput,
JSON.stringify({
version: 1,
cacheKey,
files: Array.from(tracedFiles),
} as {
version: number
files: string[]
})
)
await Promise.all([
fs.writeFile(
nextServerTraceOutput,
JSON.stringify({
version: 1,
cacheKey,
files: Array.from(tracedFiles),
} as {
version: number
files: string[]
})
),
fs.writeFile(
nextMinimalTraceOutput,
JSON.stringify({
version: 1,
cacheKey,
files: Array.from(minimalTracedFiles),
} as {
version: number
files: string[]
})
),
])
await fs.unlink(cachedTracePath).catch(() => {})
await fs
.copyFile(nextServerTraceOutput, cachedTracePath)
......
......@@ -52,7 +52,7 @@ import {
LoadComponentsReturnType,
} from '../server/load-components'
import { trace } from '../trace'
import { setHttpClientAndAgentOptions } from '../server/config'
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import { recursiveDelete } from '../lib/recursive-delete'
import { Sema } from 'next/dist/compiled/async-sema'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
......
......@@ -3,6 +3,7 @@ import { clearModuleContext } from '../../../server/web/sandbox'
import { realpathSync } from '../../../lib/realpath'
import path from 'path'
import isError from '../../../lib/is-error'
import { clearManifestCache } from '../../../server/load-manifest'
type Compiler = webpack.Compiler
type WebpackPluginInstance = webpack.WebpackPluginInstance
......@@ -43,6 +44,10 @@ export function deleteCache(filePath: string) {
if ((global as any)._nextDeleteCache) {
;(global as any)._nextDeleteCache(filePath)
}
// try to clear it from the fs cache
clearManifestCache(filePath)
try {
filePath = realpathSync(filePath)
} catch (e) {
......
......@@ -30,7 +30,7 @@ import { requireFontManifest } from '../server/require'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace'
import { isInAmpMode } from '../shared/lib/amp-mode'
import { setHttpClientAndAgentOptions } from '../server/config'
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import RenderResult from '../server/render-result'
import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta'
......
......@@ -755,9 +755,15 @@ export async function normalizeConfig(phase: string, config: any) {
export function validateConfig(userConfig: NextConfig): {
errors?: Array<any> | null
} {
const configValidator = require('next/dist/next-config-validate.js')
configValidator(userConfig)
return {
errors: configValidator.errors,
if (process.env.NEXT_MINIMAL) {
return {
errors: [],
}
} else {
const configValidator = require('next/dist/next-config-validate.js')
configValidator(userConfig)
return {
errors: configValidator.errors,
}
}
}
import { existsSync } from 'fs'
import { basename, extname, join, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url'
import { Agent as HttpAgent } from 'http'
import { Agent as HttpsAgent } from 'https'
import findUp from 'next/dist/compiled/find-up'
import chalk from '../lib/chalk'
import * as Log from '../build/output/log'
......@@ -21,6 +19,7 @@ import { ImageConfig, imageConfigDefault } from '../shared/lib/image-config'
import { loadEnvConfig, updateInitialEnv } from '@next/env'
import { flushAndExit } from '../telemetry/flush-and-exit'
import { findRootDir } from '../lib/find-root'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
export { DomainLocale, NextConfig, normalizeConfig } from './config-shared'
......@@ -43,28 +42,6 @@ const experimentalWarning = execOnce(
}
)
export function setHttpClientAndAgentOptions(config: {
httpAgentOptions?: NextConfig['httpAgentOptions']
}) {
if ((globalThis as any).__NEXT_HTTP_AGENT) {
// We only need to assign once because we want
// to reuse the same agent for all requests.
return
}
if (!config) {
throw new Error('Expected config.httpAgentOptions to be an object')
}
;(globalThis as any).__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions
;(globalThis as any).__NEXT_HTTP_AGENT = new HttpAgent(
config.httpAgentOptions
)
;(globalThis as any).__NEXT_HTTPS_AGENT = new HttpsAgent(
config.httpAgentOptions
)
}
export function warnOptionHasBeenMovedOutOfExperimental(
config: NextConfig,
oldKey: string,
......
......@@ -11,7 +11,7 @@ import {
GenerateParams,
} from '../../build/utils'
import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../config'
import { setHttpClientAndAgentOptions } from '../setup-http-agent-env'
import { IncrementalCache } from '../lib/incremental-cache'
import * as serverHooks from '../../client/components/hooks-server-context'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage'
......
......@@ -24,7 +24,7 @@ import { BuildManifest } from './get-page-files'
import { interopDefault } from '../lib/interop-default'
import { getTracer } from './lib/trace/tracer'
import { LoadComponentsSpan } from './lib/trace/constants'
import { loadManifest } from './load-manifest'
export type ManifestItem = {
id: number | string
files: string[]
......@@ -80,10 +80,13 @@ async function loadDefaultErrorComponentsImpl(
/**
* Load manifest file with retries, defaults to 3 attempts.
*/
async function loadManifest<T>(manifestPath: string, attempts = 3): Promise<T> {
async function loadManifestWithRetries<T>(
manifestPath: string,
attempts = 3
): Promise<T> {
while (true) {
try {
return require(manifestPath)
return loadManifest(manifestPath)
} catch (err) {
attempts--
if (attempts <= 0) throw err
......@@ -97,7 +100,10 @@ async function loadJSManifest<T>(
name: string,
entryname: string
): Promise<T | undefined> {
await loadManifest(manifestPath)
process.env.NEXT_MINIMAL
? // @ts-ignore
__non_webpack_require__(manifestPath)
: require(manifestPath)
try {
return JSON.parse((globalThis as any)[name][entryname]) as T
} catch (err) {
......@@ -139,8 +145,10 @@ async function loadComponentsImpl({
clientReferenceManifest,
serverActionsManifest,
] = await Promise.all([
loadManifest<BuildManifest>(join(distDir, BUILD_MANIFEST)),
loadManifest<ReactLoadableManifest>(join(distDir, REACT_LOADABLE_MANIFEST)),
loadManifestWithRetries<BuildManifest>(join(distDir, BUILD_MANIFEST)),
loadManifestWithRetries<ReactLoadableManifest>(
join(distDir, REACT_LOADABLE_MANIFEST)
),
hasClientManifest
? loadJSManifest<ClientReferenceManifest>(
join(
......@@ -157,7 +165,7 @@ async function loadComponentsImpl({
)
: undefined,
isAppPath
? loadManifest(
? loadManifestWithRetries(
join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json')
).catch(() => null)
: null,
......
import { readFileSync } from 'fs'
const cache = new Map<string, any>()
export function loadManifest(path: string, shouldCache: boolean = true) {
const cached = shouldCache && cache.get(path)
if (cached) {
return cached
}
const manifest = JSON.parse(readFileSync(path, 'utf8'))
if (shouldCache) {
cache.set(path, manifest)
}
return manifest
}
export function clearManifestCache(path: string): boolean {
return cache.delete(path)
}
......@@ -91,7 +91,7 @@ import ResponseCache from './response-cache'
import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { setHttpClientAndAgentOptions } from './config'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { RouteKind } from './future/route-kind'
import { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
......@@ -110,6 +110,7 @@ import { createRequestResponseMocks } from './lib/mock-request'
import chalk from 'next/dist/compiled/chalk'
import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import { signalFromNodeRequest } from './web/spec-extension/adapters/next-request'
import { loadManifest } from './load-manifest'
export * from './base-server'
......@@ -266,7 +267,7 @@ export default class NextNodeServer extends BaseServer {
}).catch(() => {})
}
if (this.isRouterWorker) {
if (this.isRouterWorker && !process.env.NEXT_MINIMAL) {
this.renderWorkers = {}
this.renderWorkerOpts = {
port: this.port || 0,
......@@ -432,14 +433,13 @@ export default class NextNodeServer extends BaseServer {
}
protected getPagesManifest(): PagesManifest | undefined {
return require(join(this.serverDistDir, PAGES_MANIFEST))
return loadManifest(join(this.serverDistDir, PAGES_MANIFEST))
}
protected getAppPathsManifest(): PagesManifest | undefined {
if (!this.hasAppDir) return undefined
const appPathsManifestPath = join(this.serverDistDir, APP_PATHS_MANIFEST)
return require(appPathsManifestPath)
return loadManifest(join(this.serverDistDir, APP_PATHS_MANIFEST))
}
protected async hasPage(pathname: string): Promise<boolean> {
......@@ -1168,7 +1168,9 @@ export default class NextNodeServer extends BaseServer {
}
protected getNextFontManifest() {
return require(join(this.distDir, 'server', `${NEXT_FONT_MANIFEST}.json`))
return loadManifest(
join(this.distDir, 'server', NEXT_FONT_MANIFEST + '.json')
)
}
protected async getFallback(page: string): Promise<string> {
......@@ -2746,13 +2748,15 @@ export default class NextNodeServer extends BaseServer {
}
return this._cachedPreviewManifest
}
const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
const manifest = loadManifest(join(this.distDir, PRERENDER_MANIFEST))
return (this._cachedPreviewManifest = manifest)
}
protected getRoutesManifest() {
return getTracer().trace(NextNodeServerSpan.getRoutesManifest, () =>
require(join(this.distDir, ROUTES_MANIFEST))
loadManifest(join(this.distDir, ROUTES_MANIFEST))
)
}
......
......@@ -8,5 +8,9 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
}
if (typeof (globalThis as any).WebSocket !== 'function') {
;(globalThis as any).WebSocket = require('next/dist/compiled/ws').WebSocket
Object.defineProperty(globalThis, 'WebSocket', {
get() {
return require('next/dist/compiled/ws').WebSocket
},
})
}
......@@ -2,14 +2,12 @@
* Polyfills `FormData` and `Blob` in the Node.js runtime.
*/
if (!(global as any).FormData) {
const { FormData } =
require('next/dist/compiled/@edge-runtime/ponyfill') as typeof import('next/dist/compiled/@edge-runtime/ponyfill')
;(global as any).FormData = FormData
if (!global.FormData) {
const { FormData } = require('next/dist/compiled/@edge-runtime/ponyfill')
global.FormData = FormData
}
if (!(global as any).Blob) {
const { Blob } =
require('next/dist/compiled/@edge-runtime/ponyfill') as typeof import('next/dist/compiled/@edge-runtime/ponyfill')
;(global as any).Blob = Blob
if (!global.Blob) {
const { Blob } = require('next/dist/compiled/@edge-runtime/ponyfill')
global.Blob = Blob
}
......@@ -11,6 +11,61 @@ const hookPropertyMap = new Map()
let aliasedPrebundledReact = false
const resolve = process.env.NEXT_MINIMAL
? // @ts-ignore
__non_webpack_require__.resolve
: require.resolve
const toResolveMap = (map: Record<string, string>): [string, string][] =>
Object.entries(map).map(([key, value]) => [key, resolve(value)])
export const baseOverrides = {
react: 'next/dist/compiled/react',
'react/package.json': 'next/dist/compiled/react/package.json',
'react/jsx-runtime': 'next/dist/compiled/react/jsx-runtime',
'react/jsx-dev-runtime': 'next/dist/compiled/react/jsx-dev-runtime',
'react-dom': 'next/dist/compiled/react-dom/server-rendering-stub',
'react-dom/package.json': 'next/dist/compiled/react-dom/package.json',
'react-dom/client': 'next/dist/compiled/react-dom/client',
'react-dom/server': 'next/dist/compiled/react-dom/server',
'react-dom/server.browser': 'next/dist/compiled/react-dom/server.browser',
'react-dom/server.edge': 'next/dist/compiled/react-dom/server.edge',
'react-server-dom-webpack/client':
'next/dist/compiled/react-server-dom-webpack/client',
'react-server-dom-webpack/client.edge':
'next/dist/compiled/react-server-dom-webpack/client.edge',
'react-server-dom-webpack/server.edge':
'next/dist/compiled/react-server-dom-webpack/server.edge',
'react-server-dom-webpack/server.node':
'next/dist/compiled/react-server-dom-webpack/server.node',
}
export const experimentalOverrides = {
react: 'next/dist/compiled/react-experimental',
'react/jsx-runtime': 'next/dist/compiled/react-experimental/jsx-runtime',
'react/jsx-dev-runtime':
'next/dist/compiled/react-experimental/jsx-dev-runtime',
'react-dom':
'next/dist/compiled/react-dom-experimental/server-rendering-stub',
'react/package.json': 'next/dist/compiled/react-experimental/package.json',
'react-dom/package.json':
'next/dist/compiled/react-dom-experimental/package.json',
'react-dom/client': 'next/dist/compiled/react-dom-experimental/client',
'react-dom/server': 'next/dist/compiled/react-dom-experimental/server',
'react-dom/server.browser':
'next/dist/compiled/react-dom-experimental/server.browser',
'react-dom/server.edge':
'next/dist/compiled/react-dom-experimental/server.edge',
'react-server-dom-webpack/client':
'next/dist/compiled/react-server-dom-webpack-experimental/client',
'react-server-dom-webpack/client.edge':
'next/dist/compiled/react-server-dom-webpack-experimental/client.edge',
'react-server-dom-webpack/server.edge':
'next/dist/compiled/react-server-dom-webpack-experimental/server.edge',
'react-server-dom-webpack/server.node':
'next/dist/compiled/react-server-dom-webpack-experimental/server.node',
}
export function addHookAliases(aliases: [string, string][] = []) {
for (const [key, value] of aliases) {
hookPropertyMap.set(key, value)
......@@ -21,8 +76,8 @@ export function addHookAliases(aliases: [string, string][] = []) {
addHookAliases([
// Use `require.resolve` explicitly to make them statically analyzable
// styled-jsx needs to be resolved as the external dependency.
['styled-jsx', dirname(require.resolve('styled-jsx/package.json'))],
['styled-jsx/style', require.resolve('styled-jsx/style')],
['styled-jsx', dirname(resolve('styled-jsx/package.json'))],
['styled-jsx/style', resolve('styled-jsx/style')],
])
// Override built-in React packages if necessary
......@@ -34,147 +89,10 @@ function overrideReact() {
// NFT when building the app in standalone mode, as we are now conditionally
// aliasing them it's tricky to track them in build time.
if (process.env.__NEXT_PRIVATE_PREBUNDLED_REACT === 'experimental') {
addHookAliases([
['react', require.resolve(`next/dist/compiled/react-experimental`)],
[
'react/jsx-runtime',
require.resolve(`next/dist/compiled/react-experimental/jsx-runtime`),
],
[
'react/jsx-dev-runtime',
require.resolve(
`next/dist/compiled/react-experimental/jsx-dev-runtime`
),
],
[
'react-dom',
require.resolve(
`next/dist/compiled/react-dom-experimental/server-rendering-stub`
),
],
[
'react/package.json',
require.resolve(`next/dist/compiled/react-experimental/package.json`),
],
[
'react-dom/package.json',
require.resolve(
`next/dist/compiled/react-dom-experimental/package.json`
),
],
[
'react-dom/client',
require.resolve(`next/dist/compiled/react-dom-experimental/client`),
],
[
'react-dom/server',
require.resolve(`next/dist/compiled/react-dom-experimental/server`),
],
[
'react-dom/server.browser',
require.resolve(
`next/dist/compiled/react-dom-experimental/server.browser`
),
],
[
'react-dom/server.edge',
require.resolve(
`next/dist/compiled/react-dom-experimental/server.edge`
),
],
[
'react-server-dom-webpack/client',
require.resolve(
`next/dist/compiled/react-server-dom-webpack-experimental/client`
),
],
[
'react-server-dom-webpack/client.edge',
require.resolve(
`next/dist/compiled/react-server-dom-webpack-experimental/client.edge`
),
],
[
'react-server-dom-webpack/server.edge',
require.resolve(
`next/dist/compiled/react-server-dom-webpack-experimental/server.edge`
),
],
[
'react-server-dom-webpack/server.node',
require.resolve(
`next/dist/compiled/react-server-dom-webpack-experimental/server.node`
),
],
])
addHookAliases(toResolveMap(experimentalOverrides))
} else {
addHookAliases([
['react', require.resolve(`next/dist/compiled/react`)],
[
'react/package.json',
require.resolve(`next/dist/compiled/react/package.json`),
],
[
'react/jsx-runtime',
require.resolve(`next/dist/compiled/react/jsx-runtime`),
],
[
'react/jsx-dev-runtime',
require.resolve(`next/dist/compiled/react/jsx-dev-runtime`),
],
[
'react-dom',
require.resolve(`next/dist/compiled/react-dom/server-rendering-stub`),
],
[
'react-dom/package.json',
require.resolve(`next/dist/compiled/react-dom/package.json`),
],
[
'react-dom/client',
require.resolve(`next/dist/compiled/react-dom/client`),
],
[
'react-dom/server',
require.resolve(`next/dist/compiled/react-dom/server`),
],
[
'react-dom/server.browser',
require.resolve(`next/dist/compiled/react-dom/server.browser`),
],
[
'react-dom/server.edge',
require.resolve(`next/dist/compiled/react-dom/server.edge`),
],
[
'react-server-dom-webpack/client',
require.resolve(`next/dist/compiled/react-server-dom-webpack/client`),
],
[
'react-server-dom-webpack/client.edge',
require.resolve(
`next/dist/compiled/react-server-dom-webpack/client.edge`
),
],
[
'react-server-dom-webpack/server.edge',
require.resolve(
`next/dist/compiled/react-server-dom-webpack/server.edge`
),
],
[
'react-server-dom-webpack/server.node',
require.resolve(
`next/dist/compiled/react-server-dom-webpack/server.node`
),
],
])
addHookAliases(toResolveMap(baseOverrides))
}
} else {
addHookAliases([
['react/jsx-runtime', require.resolve(`react/jsx-runtime`)],
['react/jsx-dev-runtime', require.resolve(`react/jsx-dev-runtime`)],
])
}
}
overrideReact()
......
import fs, { promises } from 'fs'
import { join } from 'path'
import {
FONT_MANIFEST,
......@@ -12,6 +11,8 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils'
import LRUCache from 'next/dist/compiled/lru-cache'
import { loadManifest } from './load-manifest'
import { promises } from 'fs'
const isDev = process.env.NODE_ENV === 'development'
const pagePathCache = isDev
......@@ -26,13 +27,6 @@ const pagePathCache = isDev
max: 1000,
})
const loadManifest = (manifestPath: string) => {
if (isDev) {
return JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
}
return require(manifestPath)
}
export function getMaybePagePath(
page: string,
distDir: string,
......@@ -49,10 +43,14 @@ export function getMaybePagePath(
let appPathsManifest: undefined | PagesManifest
if (isAppPath) {
appPathsManifest = loadManifest(join(serverBuildPath, APP_PATHS_MANIFEST))
appPathsManifest = loadManifest(
join(serverBuildPath, APP_PATHS_MANIFEST),
!isDev
)
}
const pagesManifest = loadManifest(
join(serverBuildPath, PAGES_MANIFEST)
join(serverBuildPath, PAGES_MANIFEST),
!isDev
) as PagesManifest
try {
......@@ -123,11 +121,15 @@ export function requirePage(
throw new MissingStaticPage(page, err.message)
})
}
return require(pagePath)
return process.env.NEXT_MINIMAL
? // @ts-ignore
__non_webpack_require__(pagePath)
: require(pagePath)
}
export function requireFontManifest(distDir: string) {
const serverBuildPath = join(distDir, SERVER_DIRECTORY)
const fontManifest = require(join(serverBuildPath, FONT_MANIFEST))
const fontManifest = loadManifest(join(serverBuildPath, FONT_MANIFEST))
return fontManifest
}
......@@ -554,6 +554,7 @@ let _makeResolver: any = () => {}
if (
// ensure this isn't bundled for edge runtime
process.env.NEXT_RUNTIME !== 'edge' &&
!process.env.NEXT_MINIMAL &&
// only load if we are inside of the turbopack handler
process.argv.some((arg) => arg.endsWith('router.js'))
) {
......
import { Agent as HttpAgent } from 'http'
import { Agent as HttpsAgent } from 'https'
import { NextConfig } from '../../types'
export function setHttpClientAndAgentOptions(config: {
httpAgentOptions?: NextConfig['httpAgentOptions']
}) {
if ((globalThis as any).__NEXT_HTTP_AGENT) {
// We only need to assign once because we want
// to reuse the same agent for all requests.
return
}
if (!config) {
throw new Error('Expected config.httpAgentOptions to be an object')
}
;(globalThis as any).__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions
;(globalThis as any).__NEXT_HTTP_AGENT = new HttpAgent(
config.httpAgentOptions
)
;(globalThis as any).__NEXT_HTTPS_AGENT = new HttpsAgent(
config.httpAgentOptions
)
}
......@@ -83,7 +83,11 @@ externals['node-html-parser'] = 'next/dist/compiled/node-html-parser'
export async function ncc_node_html_parser(task, opts) {
await task
.source(relative(__dirname, require.resolve('node-html-parser')))
.ncc({ packageName: 'node-html-parser', externals, target: 'es5' })
.ncc({
packageName: 'node-html-parser',
externals,
target: 'es5',
})
.target('src/compiled/node-html-parser')
}
......@@ -2359,6 +2363,7 @@ export async function compile(task, opts) {
'ncc_next__react_dev_overlay',
'ncc_next_font',
'capsize_metrics',
'minimal_next_server',
])
}
......@@ -2615,3 +2620,157 @@ export async function server_wasm(task, opts) {
export async function release(task) {
await task.clear('dist').start('build')
}
export async function minimal_next_server(task) {
const outputName = 'next-server.js'
const cachedOutputName = `${outputName}.cache`
const minimalExternals = [
'react',
'react/package.json',
'react/jsx-runtime',
'react/jsx-dev-runtime',
'react-dom',
'react-dom/package.json',
'react-dom/client',
'react-dom/server',
'react-dom/server.browser',
'react-dom/server.edge',
'react-server-dom-webpack/client',
'react-server-dom-webpack/client.edge',
'react-server-dom-webpack/server.edge',
'react-server-dom-webpack/server.node',
'styled-jsx',
'styled-jsx/style',
'@opentelemetry/api',
'next/dist/compiled/@next/react-dev-overlay/dist/middleware',
'next/dist/compiled/@ampproject/toolbox-optimizer',
'next/dist/compiled/edge-runtime',
'next/dist/compiled/@edge-runtime/ponyfill',
'next/dist/compiled/undici',
'next/dist/compiled/raw-body',
'next/dist/server/capsize-font-metrics.json',
'critters',
'next/dist/compiled/node-html-parser',
'next/dist/compiled/compression',
'next/dist/compiled/jsonwebtoken',
].reduce((acc, pkg) => {
acc[pkg] = pkg
return acc
}, {})
Object.assign(minimalExternals, {
'/(.*)config$/': 'next/dist/server/config',
'./web/sandbox': 'next/dist/server/web/sandbox',
})
const webpack = require('webpack')
const TerserPlugin = require('terser-webpack-plugin')
// const BundleAnalyzerPlugin =
// require('webpack-bundle-analyzer').BundleAnalyzerPlugin
/** @type {webpack.Configuration} */
const config = {
entry: join(__dirname, 'dist/server/next-server.js'),
target: 'node',
mode: 'production',
output: {
path: join(__dirname, 'dist/compiled/minimal-next-server'),
filename: outputName,
libraryTarget: 'commonjs2',
},
// left in for debugging
optimization: {
moduleIds: 'named',
// minimize: false,
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: {
format: {
comments: false,
},
compress: {
passes: 2,
},
},
}),
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.NEXT_MINIMAL': JSON.stringify('true'),
'process.env.NEXT_RUNTIME': JSON.stringify('nodejs'),
}),
// new BundleAnalyzerPlugin({}),
],
externals: [minimalExternals],
}
await new Promise((resolve, reject) => {
webpack(config, (err, stats) => {
if (err) return reject(err)
if (stats.hasErrors()) {
return reject(new Error(stats.toString('errors-only')))
}
resolve()
})
})
const wrappedTemplate = `
const filename = ${JSON.stringify(outputName)}
const { readFileSync } = require('fs'),
{ Script } = require('vm'),
{ wrap } = require('module'),
{ join } = require('path');
const basename = join(__dirname, filename)
const source = readFileSync(basename, 'utf-8')
const cachedData =
!process.pkg &&
require('process').platform !== 'win32' &&
readFileSync(join(__dirname, '${cachedOutputName}'))
const scriptOpts = { filename: basename, columnOffset: 0 }
const script = new Script(
wrap(source),
cachedData ? Object.assign({ cachedData }, scriptOpts) : scriptOpts
)
script.runInThisContext()(exports, require, module, __filename, __dirname)
`
await fs.writeFile(
join(__dirname, `dist/compiled/minimal-next-server/next-server-cached.js`),
wrappedTemplate
)
const Module = require('module')
const vm = require('vm')
const filename = resolve(
__dirname,
'dist/compiled/minimal-next-server',
outputName
)
const content = require('fs').readFileSync(filename, 'utf8')
const wrapper = Module.wrap(content)
var script = new vm.Script(wrapper, {
filename: filename,
lineOffset: 0,
displayErrors: true,
})
script.runInThisContext()(exports, require, module, __filename, __dirname)
const buffer = script.createCachedData()
await fs.writeFile(
join(__dirname, `dist/compiled/minimal-next-server/${cachedOutputName}`),
buffer
)
}
// Usage: node scripts/minimal-server.js <path-to-app-dir>
// This script is used to run a minimal Next.js server in production mode.
process.env.NODE_ENV = 'production'
// Change this to 'experimental' for server actions
process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = 'next'
if (process.env.LOG_REQUIRE) {
const originalRequire = require('module').prototype.require
require('module').prototype.require = function (path) {
const start = performance.now()
const result = originalRequire.apply(this, arguments)
const end = performance.now()
console.log(`${path}, ${end - start}`)
return result
}
}
if (process.env.LOG_COMPILE) {
const originalCompile = require('module').prototype._compile
const currentDir = process.cwd()
require('module').prototype._compile = function (content, filename) {
const strippedFilename = filename.replace(currentDir, '')
console.time(`Module '${strippedFilename}' compiled`)
const result = originalCompile.apply(this, arguments)
console.timeEnd(`Module '${strippedFilename}' compiled`)
return result
}
}
const appDir = process.argv[2]
const absoluteAppDir = require('path').resolve(appDir)
process.chdir(absoluteAppDir)
let readFileCount = 0
let readFileSyncCount = 0
if (process.env.LOG_READFILE) {
const originalReadFile = require('fs').readFile
const originalReadFileSync = require('fs').readFileSync
require('fs').readFile = function (path, options, callback) {
readFileCount++
return originalReadFile.apply(this, arguments)
}
require('fs').readFileSync = function (path, options) {
readFileSyncCount++
return originalReadFileSync.apply(this, arguments)
}
}
console.time('next-cold-start')
const NextServer = process.env.USE_BUNDLED_NEXT
? require('next/dist/compiled/minimal-next-server/next-server-cached').default
: require('next/dist/server/next-server').default
console.timeEnd('next-cold-start')
if (process.env.LOG_READFILE) {
console.log(`readFileCount: ${readFileCount + readFileSyncCount}`)
}
const path = require('path')
const distDir = '.next'
const compiledConfig = require(path.join(
absoluteAppDir,
distDir,
'required-server-files.json'
)).config
const nextServer = new NextServer({
conf: compiledConfig,
dir: '.',
distDir: distDir,
minimalMode: true,
customServer: false,
})
const requestHandler = nextServer.getRequestHandler()
require('http')
.createServer((req, res) => {
console.time('next-request')
readFileCount = 0
readFileSyncCount = 0
return requestHandler(req, res)
.catch((err) => {
console.error(err)
res.statusCode = 500
res.end('Internal Server Error')
})
.finally(() => {
console.timeEnd('next-request')
if (process.env.LOG_READFILE) {
console.log(`readFileCount: ${readFileCount + readFileSyncCount}`)
}
require('process').exit(0)
})
})
.listen(3000, () => {
console.timeEnd('next-cold-start')
})
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