Unverified Commit 11b01e06 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update parallelizing tasks with webpackBuildWorker config (#56287)

This updates to make build/server tracing parallelized with our webpack
compilations so that it can start right after the server compilation is
finished instead of after all compilations are finished. This
parallelizing requires the `experimental.webpackBuildWorker` config be
enabled and doesn't change behavior without it.

Part of this also cleans up our plugin state restoring/handling to use
serializable structures instead of serializing/deserializing manually.
parent 1e8dca4a
...@@ -5,7 +5,6 @@ import type { __ApiPreviewProps } from '../server/api-utils' ...@@ -5,7 +5,6 @@ import type { __ApiPreviewProps } from '../server/api-utils'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import type { Span } from '../trace' import type { Span } from '../trace'
import type getBaseWebpackConfig from './webpack-config' import type getBaseWebpackConfig from './webpack-config'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import type { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
// A layer for storing data that is used by plugins to communicate with each // A layer for storing data that is used by plugins to communicate with each
...@@ -48,12 +47,6 @@ export function getPluginState() { ...@@ -48,12 +47,6 @@ export function getPluginState() {
export const NextBuildContext: Partial<{ export const NextBuildContext: Partial<{
compilerIdx?: number compilerIdx?: number
pluginState: Record<string, any> pluginState: Record<string, any>
serializedPagesManifestEntries: {
edgeServerPages?: PagesManifest
nodeServerPages?: PagesManifest
edgeServerAppPaths?: PagesManifest
nodeServerAppPaths?: PagesManifest
}
// core fields // core fields
dir: string dir: string
buildId: string buildId: string
......
import type { Span } from '../trace' import { Span } from '../trace'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import { import {
...@@ -18,12 +18,15 @@ import { PageInfo } from './utils' ...@@ -18,12 +18,15 @@ import { PageInfo } from './utils'
import { loadBindings } from './swc' import { loadBindings } from './swc'
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
import * as ciEnvironment from '../telemetry/ci-info' import * as ciEnvironment from '../telemetry/ci-info'
import debugOriginal from 'next/dist/compiled/debug'
import { isMatch } from 'next/dist/compiled/micromatch' import { isMatch } from 'next/dist/compiled/micromatch'
import { defaultOverrides } from '../server/require-hook' import { defaultOverrides } from '../server/require-hook'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
const debug = debugOriginal('next:build:build-traces')
export async function collectBuildTraces({ export async function collectBuildTraces({
dir, dir,
config, config,
...@@ -31,7 +34,7 @@ export async function collectBuildTraces({ ...@@ -31,7 +34,7 @@ export async function collectBuildTraces({
pageKeys, pageKeys,
pageInfos, pageInfos,
staticPages, staticPages,
nextBuildSpan, nextBuildSpan = new Span({ name: 'build' }),
hasSsrAmpPages, hasSsrAmpPages,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
...@@ -42,14 +45,16 @@ export async function collectBuildTraces({ ...@@ -42,14 +45,16 @@ export async function collectBuildTraces({
app?: string[] app?: string[]
pages: string[] pages: string[]
} }
staticPages: Set<string> staticPages: string[]
hasSsrAmpPages: boolean hasSsrAmpPages: boolean
outputFileTracingRoot: string outputFileTracingRoot: string
pageInfos: Map<string, PageInfo> pageInfos: [string, PageInfo][]
nextBuildSpan: Span nextBuildSpan?: Span
config: NextConfigComplete config: NextConfigComplete
buildTraceContext?: BuildTraceContext buildTraceContext?: BuildTraceContext
}) { }) {
const startTime = Date.now()
debug('starting build traces')
let turboTasksForTrace: unknown let turboTasksForTrace: unknown
let bindings = await loadBindings() let bindings = await loadBindings()
...@@ -99,7 +104,7 @@ export async function collectBuildTraces({ ...@@ -99,7 +104,7 @@ export async function collectBuildTraces({
// The turbo trace doesn't provide the traced file type and reason at present // The turbo trace doesn't provide the traced file type and reason at present
// let's write the traced files into the first [entry].nft.json // let's write the traced files into the first [entry].nft.json
const [[, entryName]] = Array.from<[string, string]>( const [[, entryName]] = Array.from<[string, string]>(
entryNameMap.entries() Object.entries(entryNameMap)
).filter(([k]) => k.startsWith(buildTraceContextAppDir)) ).filter(([k]) => k.startsWith(buildTraceContextAppDir))
const traceOutputPath = path.join( const traceOutputPath = path.join(
outputPath, outputPath,
...@@ -119,7 +124,7 @@ export async function collectBuildTraces({ ...@@ -119,7 +124,7 @@ export async function collectBuildTraces({
const outputPagesPath = path.join(outputPath, '..', 'pages') const outputPagesPath = path.join(outputPath, '..', 'pages')
return ( return (
!f.startsWith(outputPagesPath) || !f.startsWith(outputPagesPath) ||
!staticPages.has( !staticPages.includes(
// strip `outputPagesPath` and file ext from absolute // strip `outputPagesPath` and file ext from absolute
f.substring(outputPagesPath.length, f.length - 3) f.substring(outputPagesPath.length, f.length - 3)
) )
...@@ -369,10 +374,13 @@ export async function collectBuildTraces({ ...@@ -369,10 +374,13 @@ export async function collectBuildTraces({
} }
} }
const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}
await Promise.all( await Promise.all(
[ [
...(buildTraceContext?.chunksTrace?.entryNameFilesMap.entries() || ...(entryNameFilesMap
new Map()), ? Object.entries(entryNameFilesMap)
: new Map()),
].map(async ([entryName, entryNameFiles]) => { ].map(async ([entryName, entryNameFiles]) => {
const isApp = entryName.startsWith('app/') const isApp = entryName.startsWith('app/')
const isPages = entryName.startsWith('pages/') const isPages = entryName.startsWith('pages/')
...@@ -387,7 +395,7 @@ export async function collectBuildTraces({ ...@@ -387,7 +395,7 @@ export async function collectBuildTraces({
// we don't need to trace for automatically statically optimized // we don't need to trace for automatically statically optimized
// pages as they don't have server bundles // pages as they don't have server bundles
if (staticPages.has(route)) { if (staticPages.includes(route)) {
return return
} }
const entryOutputPath = path.join( const entryOutputPath = path.join(
...@@ -504,7 +512,7 @@ export async function collectBuildTraces({ ...@@ -504,7 +512,7 @@ export async function collectBuildTraces({
for (let page of pageKeys.pages) { for (let page of pageKeys.pages) {
// edge routes have no trace files // edge routes have no trace files
const pageInfo = pageInfos.get(page) const [, pageInfo] = pageInfos.find((item) => item[0] === page) || []
if (pageInfo?.runtime === 'edge') { if (pageInfo?.runtime === 'edge') {
continue continue
} }
...@@ -584,4 +592,6 @@ export async function collectBuildTraces({ ...@@ -584,4 +592,6 @@ export async function collectBuildTraces({
) )
} }
}) })
debug(`finished build tracing ${Date.now() - startTime}ms`)
} }
...@@ -1018,20 +1018,72 @@ export default async function build( ...@@ -1018,20 +1018,72 @@ export default async function build(
return { duration, buildTraceContext: null } return { duration, buildTraceContext: null }
} }
let buildTraceContext: undefined | BuildTraceContext let buildTraceContext: undefined | BuildTraceContext
let buildTracesPromise: Promise<any> | undefined = undefined
if (!isGenerate) { if (!isGenerate) {
const { duration: webpackBuildDuration, ...rest } = turboNextBuild if (isCompile && config.experimental.webpackBuildWorker) {
? await turbopackBuild() let durationInSeconds = 0
: await webpackBuild()
await webpackBuild(['server']).then((res) => {
buildTraceContext = res.buildTraceContext
durationInSeconds += res.duration
const buildTraceWorker = new Worker(
require.resolve('./collect-build-traces'),
{
numWorkers: 1,
exposedMethods: ['collectBuildTraces'],
}
) as Worker & typeof import('./collect-build-traces')
buildTraceContext = rest.buildTraceContext buildTracesPromise = buildTraceWorker
.collectBuildTraces({
dir,
config,
distDir,
pageKeys,
pageInfos: [],
staticPages: [],
hasSsrAmpPages: false,
buildTraceContext,
outputFileTracingRoot,
})
.catch((err) => {
console.error(err)
process.exit(1)
})
})
telemetry.record( await webpackBuild(['edge-server']).then((res) => {
eventBuildCompleted(pagesPaths, { durationInSeconds += res.duration
durationInSeconds: webpackBuildDuration,
totalAppPagesCount,
}) })
)
await webpackBuild(['client']).then((res) => {
durationInSeconds += res.duration
})
buildSpinner?.stopAndPersist()
Log.event('Compiled successfully')
telemetry.record(
eventBuildCompleted(pagesPaths, {
durationInSeconds,
totalAppPagesCount,
})
)
} else {
const { duration: webpackBuildDuration, ...rest } = turboNextBuild
? await turbopackBuild()
: await webpackBuild()
buildTraceContext = rest.buildTraceContext
telemetry.record(
eventBuildCompleted(pagesPaths, {
durationInSeconds: webpackBuildDuration,
totalAppPagesCount,
})
)
}
} }
// For app directory, we run type checking after build. // For app directory, we run type checking after build.
...@@ -1761,16 +1813,14 @@ export default async function build( ...@@ -1761,16 +1813,14 @@ export default async function build(
) )
} }
let buildTracesPromise: Promise<any> | undefined = undefined if (!isGenerate && config.outputFileTracing && !buildTracesPromise) {
if (!isGenerate && config.outputFileTracing) {
buildTracesPromise = collectBuildTraces({ buildTracesPromise = collectBuildTraces({
dir, dir,
config, config,
distDir, distDir,
pageKeys, pageKeys,
pageInfos, pageInfos: Object.entries(pageInfos),
staticPages, staticPages: [...staticPages],
nextBuildSpan, nextBuildSpan,
hasSsrAmpPages, hasSsrAmpPages,
buildTraceContext, buildTraceContext,
......
...@@ -28,7 +28,6 @@ import { ...@@ -28,7 +28,6 @@ import {
TraceEntryPointsPlugin, TraceEntryPointsPlugin,
} from '../webpack/plugins/next-trace-entrypoints-plugin' } from '../webpack/plugins/next-trace-entrypoints-plugin'
import { UnwrapPromise } from '../../lib/coalesced-function' import { UnwrapPromise } from '../../lib/coalesced-function'
import * as pagesPluginModule from '../webpack/plugins/pages-manifest-plugin'
import origDebug from 'next/dist/compiled/debug' import origDebug from 'next/dist/compiled/debug'
...@@ -62,7 +61,6 @@ export async function webpackBuildImpl( ...@@ -62,7 +61,6 @@ export async function webpackBuildImpl(
duration: number duration: number
pluginState: any pluginState: any
buildTraceContext?: BuildTraceContext buildTraceContext?: BuildTraceContext
serializedPagesManifestEntries?: (typeof NextBuildContext)['serializedPagesManifestEntries']
}> { }> {
let result: CompilerResult | null = { let result: CompilerResult | null = {
warnings: [], warnings: [],
...@@ -327,12 +325,6 @@ export async function webpackBuildImpl( ...@@ -327,12 +325,6 @@ export async function webpackBuildImpl(
duration: webpackBuildEnd[0], duration: webpackBuildEnd[0],
buildTraceContext: traceEntryPointsPlugin?.buildTraceContext, buildTraceContext: traceEntryPointsPlugin?.buildTraceContext,
pluginState: getPluginState(), pluginState: getPluginState(),
serializedPagesManifestEntries: {
edgeServerPages: pagesPluginModule.edgeServerPages,
edgeServerAppPaths: pagesPluginModule.edgeServerAppPaths,
nodeServerPages: pagesPluginModule.nodeServerPages,
nodeServerAppPaths: pagesPluginModule.nodeServerAppPaths,
},
} }
} }
} }
...@@ -348,16 +340,6 @@ export async function workerMain(workerData: { ...@@ -348,16 +340,6 @@ export async function workerMain(workerData: {
// Resume plugin state // Resume plugin state
resumePluginState(NextBuildContext.pluginState) resumePluginState(NextBuildContext.pluginState)
// restore module scope maps for flight plugins
const { serializedPagesManifestEntries } = NextBuildContext
for (const key of Object.keys(serializedPagesManifestEntries || {})) {
Object.assign(
(pagesPluginModule as any)[key],
(serializedPagesManifestEntries as any)?.[key]
)
}
/// load the config because it's not serializable /// load the config because it's not serializable
NextBuildContext.config = await loadConfig( NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
...@@ -373,17 +355,12 @@ export async function workerMain(workerData: { ...@@ -373,17 +355,12 @@ export async function workerMain(workerData: {
result.buildTraceContext!.entriesTrace!.depModArray = depModArray result.buildTraceContext!.entriesTrace!.depModArray = depModArray
} }
if (entryNameMap) { if (entryNameMap) {
const entryEntries = Array.from(entryNameMap?.entries() ?? []) const entryEntries = entryNameMap
// @ts-expect-error result.buildTraceContext!.entriesTrace!.entryNameMap = entryEntries
result.buildTraceContext.entriesTrace.entryNameMap = entryEntries
} }
} }
if (chunksTrace?.entryNameFilesMap) { if (chunksTrace?.entryNameFilesMap) {
const entryNameFilesMap = Array.from( const entryNameFilesMap = chunksTrace.entryNameFilesMap
chunksTrace.entryNameFilesMap.entries() ?? []
)
// @ts-expect-error
result.buildTraceContext!.chunksTrace!.entryNameFilesMap = entryNameFilesMap result.buildTraceContext!.chunksTrace!.entryNameFilesMap = entryNameFilesMap
} }
return result return result
......
...@@ -9,7 +9,29 @@ import path from 'path' ...@@ -9,7 +9,29 @@ import path from 'path'
const debug = origDebug('next:build:webpack-build') const debug = origDebug('next:build:webpack-build')
async function webpackBuildWithWorker() { const ORDERED_COMPILER_NAMES = [
'server',
'edge-server',
'client',
] as (keyof typeof COMPILER_INDEXES)[]
let pluginState: Record<any, any> = {}
function deepMerge(target: any, source: any) {
const result = { ...target, ...source }
for (const key of Object.keys(result)) {
result[key] = Array.isArray(target[key])
? (target[key] = [...target[key], ...(source[key] || [])])
: typeof target[key] == 'object' && typeof source[key] == 'object'
? deepMerge(target[key], source[key])
: structuredClone(result[key])
}
return result
}
async function webpackBuildWithWorker(
compilerNames: typeof ORDERED_COMPILER_NAMES = ORDERED_COMPILER_NAMES
) {
const { const {
config, config,
telemetryPlugin, telemetryPlugin,
...@@ -18,6 +40,8 @@ async function webpackBuildWithWorker() { ...@@ -18,6 +40,8 @@ async function webpackBuildWithWorker() {
...prunedBuildContext ...prunedBuildContext
} = NextBuildContext } = NextBuildContext
prunedBuildContext.pluginState = pluginState
const getWorker = (compilerName: string) => { const getWorker = (compilerName: string) => {
const _worker = new Worker(path.join(__dirname, 'impl.js'), { const _worker = new Worker(path.join(__dirname, 'impl.js'), {
exposedMethods: ['workerMain'], exposedMethods: ['workerMain'],
...@@ -37,7 +61,7 @@ async function webpackBuildWithWorker() { ...@@ -37,7 +61,7 @@ async function webpackBuildWithWorker() {
_child: ChildProcess _child: ChildProcess
}[]) { }[]) {
worker._child.on('exit', (code, signal) => { worker._child.on('exit', (code, signal) => {
if (code || signal) { if (code || (signal && signal !== 'SIGINT')) {
console.error( console.error(
`Compiler ${compilerName} unexpectedly exited with code: ${code} and signal: ${signal}` `Compiler ${compilerName} unexpectedly exited with code: ${code} and signal: ${signal}`
) )
...@@ -52,14 +76,8 @@ async function webpackBuildWithWorker() { ...@@ -52,14 +76,8 @@ async function webpackBuildWithWorker() {
duration: 0, duration: 0,
buildTraceContext: {} as BuildTraceContext, buildTraceContext: {} as BuildTraceContext,
} }
// order matters here
const ORDERED_COMPILER_NAMES = [ for (const compilerName of compilerNames) {
'server',
'edge-server',
'client',
] as (keyof typeof COMPILER_INDEXES)[]
for (const compilerName of ORDERED_COMPILER_NAMES) {
const worker = getWorker(compilerName) const worker = getWorker(compilerName)
const curResult = await worker.workerMain({ const curResult = await worker.workerMain({
...@@ -70,18 +88,8 @@ async function webpackBuildWithWorker() { ...@@ -70,18 +88,8 @@ async function webpackBuildWithWorker() {
await worker.end() await worker.end()
// Update plugin state // Update plugin state
prunedBuildContext.pluginState = curResult.pluginState pluginState = deepMerge(pluginState, curResult.pluginState)
prunedBuildContext.pluginState = pluginState
prunedBuildContext.serializedPagesManifestEntries = {
edgeServerAppPaths:
curResult.serializedPagesManifestEntries?.edgeServerAppPaths,
edgeServerPages:
curResult.serializedPagesManifestEntries?.edgeServerPages,
nodeServerAppPaths:
curResult.serializedPagesManifestEntries?.nodeServerAppPaths,
nodeServerPages:
curResult.serializedPagesManifestEntries?.nodeServerPages,
}
combinedResult.duration += curResult.duration combinedResult.duration += curResult.duration
...@@ -91,9 +99,8 @@ async function webpackBuildWithWorker() { ...@@ -91,9 +99,8 @@ async function webpackBuildWithWorker() {
if (entryNameMap) { if (entryNameMap) {
combinedResult.buildTraceContext.entriesTrace = combinedResult.buildTraceContext.entriesTrace =
curResult.buildTraceContext.entriesTrace curResult.buildTraceContext.entriesTrace
combinedResult.buildTraceContext.entriesTrace!.entryNameMap = new Map( combinedResult.buildTraceContext.entriesTrace!.entryNameMap =
entryNameMap entryNameMap
)
} }
if (curResult.buildTraceContext?.chunksTrace) { if (curResult.buildTraceContext?.chunksTrace) {
...@@ -104,23 +111,28 @@ async function webpackBuildWithWorker() { ...@@ -104,23 +111,28 @@ async function webpackBuildWithWorker() {
curResult.buildTraceContext.chunksTrace! curResult.buildTraceContext.chunksTrace!
combinedResult.buildTraceContext.chunksTrace!.entryNameFilesMap = combinedResult.buildTraceContext.chunksTrace!.entryNameFilesMap =
new Map(entryNameFilesMap) entryNameFilesMap
} }
} }
} }
} }
buildSpinner?.stopAndPersist()
Log.event('Compiled successfully') if (compilerNames.length === 3) {
buildSpinner?.stopAndPersist()
Log.event('Compiled successfully')
}
return combinedResult return combinedResult
} }
export async function webpackBuild() { export async function webpackBuild(
compilerNames?: typeof ORDERED_COMPILER_NAMES
) {
const config = NextBuildContext.config! const config = NextBuildContext.config!
if (config.experimental.webpackBuildWorker) { if (config.experimental.webpackBuildWorker) {
debug('using separate compiler workers') debug('using separate compiler workers')
return await webpackBuildWithWorker() return await webpackBuildWithWorker(compilerNames)
} else { } else {
debug('building all compilers in same process') debug('building all compilers in same process')
const webpackBuildImpl = require('./impl').webpackBuildImpl const webpackBuildImpl = require('./impl').webpackBuildImpl
......
...@@ -2036,8 +2036,9 @@ export default async function getBaseWebpackConfig( ...@@ -2036,8 +2036,9 @@ export default async function getBaseWebpackConfig(
isNodeOrEdgeCompilation && isNodeOrEdgeCompilation &&
new PagesManifestPlugin({ new PagesManifestPlugin({
dev, dev,
isEdgeRuntime: isEdgeServer,
appDirEnabled: hasAppDir, appDirEnabled: hasAppDir,
isEdgeRuntime: isEdgeServer,
distDir: !dev ? distDir : undefined,
}), }),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_* // MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling // replacement is done before its process.env.* handling
......
...@@ -120,12 +120,12 @@ export interface BuildTraceContext { ...@@ -120,12 +120,12 @@ export interface BuildTraceContext {
appDir: string appDir: string
outputPath: string outputPath: string
depModArray: string[] depModArray: string[]
entryNameMap: Map<string, string> entryNameMap: Record<string, string>
} }
chunksTrace?: { chunksTrace?: {
action: TurbotraceAction action: TurbotraceAction
outputPath: string outputPath: string
entryNameFilesMap: Map<string, Array<string>> entryNameFilesMap: Record<string, Array<string>>
} }
} }
...@@ -224,7 +224,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -224,7 +224,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
logLevel: this.turbotrace?.logLevel, logLevel: this.turbotrace?.logLevel,
}, },
outputPath, outputPath,
entryNameFilesMap, entryNameFilesMap: Object.fromEntries(entryNameFilesMap),
} }
for (const [entrypoint, entryFiles] of entryFilesMap) { for (const [entrypoint, entryFiles] of entryFilesMap) {
...@@ -436,7 +436,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -436,7 +436,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
}, },
appDir: this.rootDir, appDir: this.rootDir,
depModArray: Array.from(depModMap.keys()), depModArray: Array.from(depModMap.keys()),
entryNameMap, entryNameMap: Object.fromEntries(entryNameMap),
outputPath: compilation.outputOptions.path!, outputPath: compilation.outputOptions.path!,
} }
......
import path from 'path'
import fs from 'fs/promises'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
PAGES_MANIFEST, PAGES_MANIFEST,
...@@ -20,24 +22,28 @@ export default class PagesManifestPlugin ...@@ -20,24 +22,28 @@ export default class PagesManifestPlugin
implements webpack.WebpackPluginInstance implements webpack.WebpackPluginInstance
{ {
dev: boolean dev: boolean
distDir?: string
isEdgeRuntime: boolean isEdgeRuntime: boolean
appDirEnabled: boolean appDirEnabled: boolean
constructor({ constructor({
dev, dev,
distDir,
isEdgeRuntime, isEdgeRuntime,
appDirEnabled, appDirEnabled,
}: { }: {
dev: boolean dev: boolean
distDir?: string
isEdgeRuntime: boolean isEdgeRuntime: boolean
appDirEnabled: boolean appDirEnabled: boolean
}) { }) {
this.dev = dev this.dev = dev
this.distDir = distDir
this.isEdgeRuntime = isEdgeRuntime this.isEdgeRuntime = isEdgeRuntime
this.appDirEnabled = appDirEnabled this.appDirEnabled = appDirEnabled
} }
createAssets(compilation: any, assets: any) { async createAssets(compilation: any, assets: any) {
const entrypoints = compilation.entrypoints const entrypoints = compilation.entrypoints
const pages: PagesManifest = {} const pages: PagesManifest = {}
const appPaths: PagesManifest = {} const appPaths: PagesManifest = {}
...@@ -92,45 +98,91 @@ export default class PagesManifestPlugin ...@@ -92,45 +98,91 @@ export default class PagesManifestPlugin
nodeServerAppPaths = appPaths nodeServerAppPaths = appPaths
} }
assets[ // handle parallel compilers writing to the same
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + PAGES_MANIFEST // manifest path by merging existing manifest with new
] = new sources.RawSource( const writeMergedManifest = async (
JSON.stringify( manifestPath: string,
{ entries: Record<string, string>
...edgeServerPages, ) => {
...nodeServerPages, await fs.mkdir(path.dirname(manifestPath), { recursive: true })
}, await fs.writeFile(
null, manifestPath,
2 JSON.stringify(
{
...(await fs
.readFile(manifestPath, 'utf8')
.then((res) => JSON.parse(res))
.catch(() => ({}))),
...entries,
},
null,
2
)
) )
) }
if (this.appDirEnabled) { if (this.distDir) {
const pagesManifestPath = path.join(
this.distDir,
'server',
PAGES_MANIFEST
)
await writeMergedManifest(pagesManifestPath, {
...edgeServerPages,
...nodeServerPages,
})
} else {
assets[ assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + APP_PATHS_MANIFEST `${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + PAGES_MANIFEST
] = new sources.RawSource( ] = new sources.RawSource(
JSON.stringify( JSON.stringify(
{ {
...edgeServerAppPaths, ...edgeServerPages,
...nodeServerAppPaths, ...nodeServerPages,
}, },
null, null,
2 2
) )
) )
} }
if (this.appDirEnabled) {
if (this.distDir) {
const appPathsManifestPath = path.join(
this.distDir,
'server',
APP_PATHS_MANIFEST
)
await writeMergedManifest(appPathsManifestPath, {
...edgeServerAppPaths,
...nodeServerAppPaths,
})
} else {
assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` +
APP_PATHS_MANIFEST
] = new sources.RawSource(
JSON.stringify(
{
...edgeServerAppPaths,
...nodeServerAppPaths,
},
null,
2
)
)
}
}
} }
apply(compiler: webpack.Compiler): void { apply(compiler: webpack.Compiler): void {
compiler.hooks.make.tap('NextJsPagesManifest', (compilation) => { compiler.hooks.make.tap('NextJsPagesManifest', (compilation) => {
compilation.hooks.processAssets.tap( compilation.hooks.processAssets.tapPromise(
{ {
name: 'NextJsPagesManifest', name: 'NextJsPagesManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, },
(assets: any) => { (assets) => this.createAssets(compilation, assets)
this.createAssets(compilation, assets)
}
) )
}) })
} }
......
...@@ -69,7 +69,7 @@ export class Worker { ...@@ -69,7 +69,7 @@ export class Worker {
}[]) { }[]) {
worker._child?.on('exit', (code, signal) => { worker._child?.on('exit', (code, signal) => {
// log unexpected exit if .end() wasn't called // log unexpected exit if .end() wasn't called
if ((code || signal) && this._worker) { if ((code || (signal && signal !== 'SIGINT')) && this._worker) {
console.error( console.error(
`Static worker unexpectedly exited with code: ${code} and signal: ${signal}` `Static worker unexpectedly exited with code: ${code} and signal: ${signal}`
) )
......
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