Unverified Commit a90f0c91 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Use `compilation.{emitAsset,updateAsset}` api rather than mutating `assets` object (#75927)

parent 99bf5e9a
......@@ -31,12 +31,12 @@ export class AppBuildManifestPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => this.createAsset(assets, compilation)
() => this.createAsset(compilation)
)
})
}
private createAsset(assets: any, compilation: webpack.Compilation) {
private createAsset(compilation: webpack.Compilation) {
const manifest: AppBuildManifest = {
pages: {},
}
......@@ -67,6 +67,9 @@ export class AppBuildManifestPlugin {
const json = JSON.stringify(manifest, null, 2)
assets[APP_BUILD_MANIFEST] = new sources.RawSource(json)
compilation.emitAsset(
APP_BUILD_MANIFEST,
new sources.RawSource(json) as unknown as webpack.sources.RawSource
)
}
}
......@@ -200,7 +200,7 @@ export default class BuildManifestPlugin {
this.rewrites.fallback = options.rewrites.fallback.map(processRoute)
}
createAssets(compiler: any, compilation: any, assets: any) {
createAssets(compiler: any, compilation: any) {
const compilationSpan = spans.get(compilation) || spans.get(compiler)
const createAssetsSpan = compilationSpan?.traceChild(
'NextJsBuildManifest-createassets'
......@@ -297,7 +297,10 @@ export default class BuildManifestPlugin {
this.buildId
)
assetMap.lowPriorityFiles.push(buildManifestPath, ssgManifestPath)
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest)
compilation.emitAsset(
ssgManifestPath,
new sources.RawSource(srcEmptySsgManifest)
)
}
assetMap.pages = Object.keys(assetMap.pages)
......@@ -314,29 +317,30 @@ export default class BuildManifestPlugin {
buildManifestName = `fallback-${BUILD_MANIFEST}`
}
assets[buildManifestName] = new sources.RawSource(
JSON.stringify(assetMap, null, 2)
compilation.emitAsset(
buildManifestName,
new sources.RawSource(JSON.stringify(assetMap, null, 2))
)
assets[`server/${MIDDLEWARE_BUILD_MANIFEST}.js`] = new sources.RawSource(
`${createEdgeRuntimeManifest(assetMap)}`
compilation.emitAsset(
`server/${MIDDLEWARE_BUILD_MANIFEST}.js`,
new sources.RawSource(`${createEdgeRuntimeManifest(assetMap)}`)
)
if (!this.isDevFallback) {
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
assets[clientManifestPath] = new sources.RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap,
this.rewrites,
this.clientRouterFilters,
compiler,
compilation
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
compilation.emitAsset(
`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`,
new sources.RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap,
this.rewrites,
this.clientRouterFilters,
compiler,
compilation
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
)
)
}
return assets
})
}
......@@ -347,8 +351,8 @@ export default class BuildManifestPlugin {
name: 'NextJsBuildManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compiler, compilation, assets)
() => {
this.createAssets(compiler, compilation)
}
)
})
......
......@@ -79,10 +79,8 @@ export class CssMinimizerPlugin {
assetSpan.setAttribute('file', file)
return assetSpan.traceAsyncFn(async () => {
const asset = assets[file]
const etag = cache.getLazyHashedEtag(asset)
const assetSource = compilation.getAsset(file).source
const etag = cache.getLazyHashedEtag(assetSource)
const cachedResult = await cache.getPromise(file, etag)
assetSpan.setAttribute(
......@@ -90,13 +88,13 @@ export class CssMinimizerPlugin {
cachedResult ? 'HIT' : 'MISS'
)
if (cachedResult) {
assets[file] = cachedResult
compilation.updateAsset(file, cachedResult)
return
}
const result = await this.optimizeAsset(file, asset)
const result = await this.optimizeAsset(file, assetSource)
await cache.storePromise(file, etag, result)
assets[file] = result
compilation.updateAsset(file, result)
})
})
)
......
......@@ -263,7 +263,7 @@ export class FlightClientEntryPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => this.createActionAssets(compilation, assets)
() => this.createActionAssets(compilation)
)
})
}
......@@ -976,10 +976,7 @@ export class FlightClientEntryPlugin {
})
}
async createActionAssets(
compilation: webpack.Compilation,
assets: webpack.Compilation['assets']
) {
async createActionAssets(compilation: webpack.Compilation) {
const serverActions: ActionManifest['node'] = {}
const edgeServerActions: ActionManifest['edge'] = {}
......@@ -1052,12 +1049,16 @@ export class FlightClientEntryPlugin {
this.dev ? 2 : undefined
)
assets[`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.js`] =
compilation.emitAsset(
`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.js`,
new sources.RawSource(
`self.__RSC_SERVER_MANIFEST=${JSON.stringify(edgeJson)}`
) as unknown as webpack.sources.RawSource
assets[`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.json`] =
)
compilation.emitAsset(
`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.json`,
new sources.RawSource(json) as unknown as webpack.sources.RawSource
)
}
}
......
......@@ -231,16 +231,12 @@ export class ClientReferenceManifestPlugin {
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => this.createAsset(assets, compilation, compiler.context)
() => this.createAsset(compilation, compiler.context)
)
})
}
createAsset(
assets: webpack.Compilation['assets'],
compilation: webpack.Compilation,
context: string
) {
createAsset(compilation: webpack.Compilation, context: string) {
const manifestsPerGroup = new Map<string, ClientReferenceManifest[]>()
const manifestEntryFiles: string[] = []
......@@ -305,7 +301,7 @@ export class ClientReferenceManifestPlugin {
.getFiles()
.filter((f) => !f.startsWith('static/css/pages/') && f.endsWith('.css'))
.map((file) => {
const source = compilation.assets[file].source()
const source = compilation.getAsset(file)!.source.source()
if (
this.experimentalInlineCss &&
// Inline CSS currently does not work properly with HMR, so we only
......@@ -599,13 +595,14 @@ export class ClientReferenceManifestPlugin {
const pagePath = pageName.replace(/%5F/g, '_')
const pageBundlePath = normalizePagePath(pagePath.slice('app'.length))
assets[
'server/app' + pageBundlePath + '_' + CLIENT_REFERENCE_MANIFEST + '.js'
] = new sources.RawSource(
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST[${JSON.stringify(
pagePath.slice('app'.length)
)}]=${json}`
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
'server/app' + pageBundlePath + '_' + CLIENT_REFERENCE_MANIFEST + '.js',
new sources.RawSource(
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST[${JSON.stringify(
pagePath.slice('app'.length)
)}]=${json}`
) as unknown as webpack.sources.RawSource
)
}
}
}
......@@ -154,7 +154,7 @@ function getCreateAssets(params: {
opts: Options
}) {
const { compilation, metadataByEntry, opts } = params
return (assets: any) => {
return () => {
const middlewareManifest: MiddlewareManifest = {
version: MANIFEST_VERSION,
middleware: {},
......@@ -171,11 +171,14 @@ function getCreateAssets(params: {
const interceptionRewrites = JSON.stringify(
opts.rewrites.beforeFiles.filter(isInterceptionRouteRewrite)
)
assets[`${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`] = new sources.RawSource(
`self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(
interceptionRewrites
)}`
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
`${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`,
new sources.RawSource(
`self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(
interceptionRewrites
)}`
) as unknown as webpack.sources.RawSource
)
for (const entrypoint of compilation.entrypoints.values()) {
if (!entrypoint.name) {
......@@ -242,8 +245,11 @@ function getCreateAssets(params: {
Object.keys(middlewareManifest.middleware)
)
assets[MIDDLEWARE_MANIFEST] = new sources.RawSource(
JSON.stringify(middlewareManifest, null, 2)
compilation.emitAsset(
MIDDLEWARE_MANIFEST,
new sources.RawSource(
JSON.stringify(middlewareManifest, null, 2)
) as unknown as webpack.sources.RawSource
)
}
}
......
......@@ -67,7 +67,7 @@ export class NextFontManifestPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
() => {
const nextFontManifest: NextFontManifest = {
pages: {},
app: {},
......@@ -156,12 +156,19 @@ export class NextFontManifestPlugin {
const manifest = JSON.stringify(nextFontManifest, null)
// Create manifest for edge
assets[`server/${NEXT_FONT_MANIFEST}.js`] = new sources.RawSource(
`self.__NEXT_FONT_MANIFEST=${JSON.stringify(manifest)}`
compilation.emitAsset(
`server/${NEXT_FONT_MANIFEST}.js`,
new sources.RawSource(
`self.__NEXT_FONT_MANIFEST=${JSON.stringify(manifest)}`
) as unknown as webpack.sources.RawSource
)
// Create manifest for server
assets[`server/${NEXT_FONT_MANIFEST}.json`] = new sources.RawSource(
manifest
compilation.emitAsset(
`server/${NEXT_FONT_MANIFEST}.json`,
new sources.RawSource(
manifest
) as unknown as webpack.sources.RawSource
)
}
)
......
......@@ -174,11 +174,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
// Here we output all traced assets and webpack chunks to a
// ${page}.js.nft.json file
async createTraceAssets(
compilation: webpack.Compilation,
assets: any,
span: Span
) {
async createTraceAssets(compilation: webpack.Compilation, span: Span) {
const outputPath = compilation.outputOptions.path || ''
await span.traceChild('create-trace-assets').traceAsyncFn(async () => {
......@@ -292,11 +288,14 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
})
)
assets[traceOutputName] = new sources.RawSource(
JSON.stringify({
version: TRACE_OUTPUT_VERSION,
files: finalFiles,
})
compilation.emitAsset(
traceOutputName,
new sources.RawSource(
JSON.stringify({
version: TRACE_OUTPUT_VERSION,
files: finalFiles,
})
) as unknown as webpack.sources.RawSource
)
}
})
......@@ -631,12 +630,8 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
(assets: any, callback: any) => {
this.createTraceAssets(
compilation,
assets,
traceEntrypointsPluginSpan
)
(_, callback: any) => {
this.createTraceAssets(compilation, traceEntrypointsPluginSpan)
.then(() => callback())
.catch((err) => callback(err))
}
......
......@@ -754,13 +754,13 @@ function createCustomCacheLifeDefinitions(cacheLife: {
/**
* Cache this \`"use cache"\` using a custom timespan.
* \`\`\`
* stale: ... // seconds
* stale: ... // seconds
* revalidate: ... // seconds
* expire: ... // seconds
* \`\`\`
*
*
* This is similar to Cache-Control: max-age=\`stale\`,s-max-age=\`revalidate\`,stale-while-revalidate=\`expire-revalidate\`
*
*
* If a value is left out, the lowest of other cacheLife() calls or the default, is used instead.
*/
export function unstable_cacheLife(profile: {
......@@ -898,7 +898,10 @@ export class NextTypesPlugin {
? '..'
: '../..'
const handleModule = async (mod: webpack.NormalModule, assets: any) => {
const handleModule = async (
mod: webpack.NormalModule,
compilation: webpack.Compilation
) => {
if (!mod.resource) return
const pageExtensionsRegex = new RegExp(
......@@ -970,23 +973,32 @@ export class NextTypesPlugin {
pluginState.collectedRootParams[rootLayoutPath] = foundParams
const slots = await collectNamedSlots(mod.resource)
assets[assetPath] = new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'layout',
slots,
})
compilation.emitAsset(
assetPath,
new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'layout',
slots,
})
) as unknown as webpack.sources.RawSource
)
} else if (IS_PAGE) {
assets[assetPath] = new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'page',
})
compilation.emitAsset(
assetPath,
new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'page',
})
) as unknown as webpack.sources.RawSource
)
} else if (IS_ROUTE) {
assets[assetPath] = new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'route',
})
compilation.emitAsset(
assetPath,
new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'route',
})
) as unknown as webpack.sources.RawSource
)
}
}
......@@ -997,7 +1009,7 @@ export class NextTypesPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
async (assets, callback) => {
async (_, callback) => {
const promises: Promise<any>[] = []
// Clear routes
......@@ -1030,7 +1042,7 @@ export class NextTypesPlugin {
chunk
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
promises.push(handleModule(mod, assets))
promises.push(handleModule(mod, compilation))
// If this is a concatenation, register each child to the parent ID.
const anyModule = mod as unknown as {
......@@ -1038,7 +1050,7 @@ export class NextTypesPlugin {
}
if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod) => {
promises.push(handleModule(concatenatedMod, assets))
promises.push(handleModule(concatenatedMod, compilation))
})
}
}
......@@ -1058,9 +1070,12 @@ export class NextTypesPlugin {
'types/server.d.ts'
)
assets[serverTypesPath] = new sources.RawSource(
createServerDefinitions(rootParams)
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
serverTypesPath,
new sources.RawSource(
createServerDefinitions(rootParams)
) as unknown as webpack.sources.RawSource
)
}
// Support `"moduleResolution": "Node16" | "NodeNext"` with `"type": "module"`
......@@ -1070,9 +1085,12 @@ export class NextTypesPlugin {
'types/package.json'
)
assets[packageJsonAssetPath] = new sources.RawSource(
'{"type": "module"}'
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
packageJsonAssetPath,
new sources.RawSource(
'{"type": "module"}'
) as unknown as webpack.sources.RawSource
)
if (this.typedRoutes) {
if (this.dev && !this.isEdgeServer) {
......@@ -1083,9 +1101,12 @@ export class NextTypesPlugin {
const linkAssetPath = path.join(assetDirRelative, 'types/link.d.ts')
assets[linkAssetPath] = new sources.RawSource(
createRouteDefinitions()
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
linkAssetPath,
new sources.RawSource(
createRouteDefinitions()
) as unknown as webpack.sources.RawSource
)
}
if (this.cacheLifeConfig) {
......@@ -1094,9 +1115,12 @@ export class NextTypesPlugin {
'types/cache-life.d.ts'
)
assets[cacheLifeAssetPath] = new sources.RawSource(
createCustomCacheLifeDefinitions(this.cacheLifeConfig)
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
cacheLifeAssetPath,
new sources.RawSource(
createCustomCacheLifeDefinitions(this.cacheLifeConfig)
) as unknown as webpack.sources.RawSource
)
}
callback()
......
......@@ -43,7 +43,7 @@ export default class PagesManifestPlugin
this.appDirEnabled = appDirEnabled
}
async createAssets(compilation: any, assets: any) {
async createAssets(compilation: any) {
const entrypoints = compilation.entrypoints
const pages: PagesManifest = {}
const appPaths: PagesManifest = {}
......@@ -134,14 +134,17 @@ export default class PagesManifestPlugin
} else {
const pagesManifestPath =
(!this.dev && !this.isEdgeRuntime ? '../' : '') + PAGES_MANIFEST
assets[pagesManifestPath] = new sources.RawSource(
JSON.stringify(
{
...edgeServerPages,
...nodeServerPages,
},
null,
2
compilation.emitAsset(
pagesManifestPath,
new sources.RawSource(
JSON.stringify(
{
...edgeServerPages,
...nodeServerPages,
},
null,
2
)
)
)
}
......@@ -158,17 +161,18 @@ export default class PagesManifestPlugin
...nodeServerAppPaths,
})
} else {
assets[
(!this.dev && !this.isEdgeRuntime ? '../' : '') + APP_PATHS_MANIFEST
] = new sources.RawSource(
JSON.stringify(
{
...edgeServerAppPaths,
...nodeServerAppPaths,
},
null,
2
)
compilation.emitAsset(
(!this.dev && !this.isEdgeRuntime ? '../' : '') + APP_PATHS_MANIFEST,
new sources.RawSource(
JSON.stringify(
{
...edgeServerAppPaths,
...nodeServerAppPaths,
},
null,
2
)
) as unknown as webpack.sources.RawSource
)
}
}
......@@ -181,7 +185,7 @@ export default class PagesManifestPlugin
name: 'NextJsPagesManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets) => this.createAssets(compilation, assets)
() => this.createAssets(compilation)
)
})
}
......
......@@ -186,7 +186,7 @@ export class ReactLoadablePlugin {
this.dev = opts.dev
}
createAssets(compiler: any, compilation: any, assets: any) {
createAssets(compiler: any, compilation: any) {
const projectSrcDir = this.pagesOrAppDir
? path.dirname(this.pagesOrAppDir)
: undefined
......@@ -199,14 +199,19 @@ export class ReactLoadablePlugin {
shouldCreateDynamicCssManifest
)
assets[this.filename] = new sources.RawSource(
JSON.stringify(reactLoadableManifest, null, 2)
compilation.emitAsset(
this.filename,
new sources.RawSource(JSON.stringify(reactLoadableManifest, null, 2))
)
if (this.runtimeAsset) {
assets[this.runtimeAsset] = new sources.RawSource(
`self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(
JSON.stringify(reactLoadableManifest)
)}`
compilation.emitAsset(
this.runtimeAsset,
new sources.RawSource(
`self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(
JSON.stringify(reactLoadableManifest)
)}`
)
)
}
......@@ -214,18 +219,21 @@ export class ReactLoadablePlugin {
// navigation. This is only needed under Pages dir && Production && Webpack.
// x-ref: https://github.com/vercel/next.js/pull/72959
if (shouldCreateDynamicCssManifest) {
assets[`${DYNAMIC_CSS_MANIFEST}.json`] = new sources.RawSource(
JSON.stringify(dynamicCssManifest, null, 2)
compilation.emitAsset(
`${DYNAMIC_CSS_MANIFEST}.json`,
new sources.RawSource(JSON.stringify(dynamicCssManifest, null, 2))
)
// This is for edge runtime.
assets[`server/${DYNAMIC_CSS_MANIFEST}.js`] = new sources.RawSource(
`self.__DYNAMIC_CSS_MANIFEST=${JSON.stringify(
JSON.stringify(dynamicCssManifest)
)}`
compilation.emitAsset(
`server/${DYNAMIC_CSS_MANIFEST}.js`,
new sources.RawSource(
`self.__DYNAMIC_CSS_MANIFEST=${JSON.stringify(
JSON.stringify(dynamicCssManifest)
)}`
)
)
}
return assets
}
apply(compiler: webpack.Compiler) {
......@@ -235,8 +243,8 @@ export class ReactLoadablePlugin {
name: 'ReactLoadableManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compiler, compilation, assets)
() => {
this.createAssets(compiler, compilation)
}
)
})
......
......@@ -16,7 +16,7 @@ export class SubresourceIntegrityPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets) => {
() => {
// Collect all the assets.
let files = new Set<string>()
for (const asset of compilation.getAssets()) {
......@@ -27,13 +27,13 @@ export class SubresourceIntegrityPlugin {
const hashes: Record<string, string> = {}
for (const file of files.values()) {
// Get the buffer for the asset.
const asset = assets[file]
const asset = compilation.getAsset(file)
if (!asset) {
throw new Error(`could not get asset: ${file}`)
}
// Get the buffer for the asset.
const buffer = asset.buffer()
const buffer = asset.source.buffer()
// Create the hash for the content.
const hash = crypto
......@@ -47,16 +47,22 @@ export class SubresourceIntegrityPlugin {
const json = JSON.stringify(hashes, null, 2)
const file = 'server/' + SUBRESOURCE_INTEGRITY_MANIFEST
assets[file + '.js'] = new sources.RawSource(
`self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(json)}`
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
assets[file + '.json'] = new sources.RawSource(
json
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
compilation.emitAsset(
file + '.js',
new sources.RawSource(
`self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(json)}`
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
)
compilation.emitAsset(
file + '.json',
new sources.RawSource(
json
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
)
}
)
})
......
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