New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add entrypoint tracing #25538
Add entrypoint tracing #25538
Changes from 38 commits
5ddd237
7645c51
2c8df87
963a210
6d4bd43
5b1ed01
11d1c38
61fb021
03f1235
3b5c026
9376530
20aafbc
8b69270
7419cd7
3ab3cd9
02cfd01
21f1752
71ccfd2
3c1e604
8ae2785
b2a6b41
0dbf716
620121f
1631552
e401004
7cab94e
a2fb21f
010ee05
a0138e9
cbd1b3a
4829836
0aa38fd
98daa68
55111a3
1f1f6e3
076d001
8bae9aa
b0133b8
5cfee37
9823923
2997ee2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
import nodePath from 'path' | ||
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' | ||
import { | ||
webpack, | ||
isWebpack5, | ||
sources, | ||
} from 'next/dist/compiled/webpack/webpack' | ||
import { TRACE_OUTPUT_VERSION } from '../../../shared/lib/constants' | ||
|
||
const PLUGIN_NAME = 'TraceEntryPointsPlugin' | ||
const TRACE_IGNORES = [ | ||
'**/*/node_modules/react/**/*.development.js', | ||
'**/*/node_modules/react-dom/**/*.development.js', | ||
] | ||
|
||
function getModuleFromDependency( | ||
compilation: any, | ||
dep: any | ||
): webpack.Module & { resource?: string } { | ||
if (isWebpack5) { | ||
return compilation.moduleGraph.getModule(dep) | ||
} | ||
|
||
return dep.module | ||
} | ||
|
||
export class TraceEntryPointsPlugin implements webpack.Plugin { | ||
private appDir: string | ||
private entryTraces: Map<string, string[]> | ||
|
||
constructor({ appDir }: { appDir: string }) { | ||
this.appDir = appDir | ||
this.entryTraces = new Map() | ||
} | ||
|
||
// Here we output all traced assets and webpack chunks to a | ||
// ${page}.js.nft.json file | ||
createTraceAssets(compilation: any, assets: any) { | ||
const outputPath = compilation.outputOptions.path | ||
|
||
for (const entrypoint of compilation.entrypoints.values()) { | ||
const entryFiles = new Set<string>() | ||
|
||
for (const chunk of entrypoint | ||
.getEntrypointChunk() | ||
.getAllReferencedChunks()) { | ||
for (const file of chunk.files) { | ||
entryFiles.add(nodePath.join(outputPath, file)) | ||
} | ||
for (const file of chunk.auxiliaryFiles) { | ||
entryFiles.add(nodePath.join(outputPath, file)) | ||
} | ||
} | ||
// don't include the entry itself in the trace | ||
entryFiles.delete( | ||
nodePath.join( | ||
outputPath, | ||
`${isWebpack5 ? '../' : ''}${entrypoint.name}.js` | ||
) | ||
) | ||
const traceOutputName = `${isWebpack5 ? '../' : ''}${ | ||
entrypoint.name | ||
}.js.nft.json` | ||
const traceOutputPath = nodePath.join(outputPath, traceOutputName) | ||
|
||
assets[traceOutputName] = new sources.RawSource( | ||
JSON.stringify({ | ||
version: TRACE_OUTPUT_VERSION, | ||
files: [...entryFiles, ...this.entryTraces.get(entrypoint.name)!].map( | ||
(file) => { | ||
return nodePath | ||
.relative(traceOutputPath, file) | ||
.replace(/\\/g, '/') | ||
} | ||
), | ||
}) | ||
) | ||
} | ||
} | ||
|
||
apply(compiler: webpack.Compiler) { | ||
if (isWebpack5) { | ||
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { | ||
// @ts-ignore TODO: Remove ignore when webpack 5 is stable | ||
compilation.hooks.processAssets.tap( | ||
{ | ||
name: PLUGIN_NAME, | ||
// @ts-ignore TODO: Remove ignore when webpack 5 is stable | ||
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE, | ||
}, | ||
(assets: any) => { | ||
this.createTraceAssets(compilation, assets) | ||
} | ||
) | ||
}) | ||
} else { | ||
compiler.hooks.emit.tap(PLUGIN_NAME, (compilation: any) => { | ||
this.createTraceAssets(compilation, compilation.assets) | ||
}) | ||
} | ||
|
||
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { | ||
compilation.hooks.finishModules.tapAsync( | ||
PLUGIN_NAME, | ||
async (_stats: any, callback: any) => { | ||
// we create entry -> module maps so that we can | ||
// look them up faster instead of having to iterate | ||
// over the compilation modules list | ||
const entryNameMap = new Map<string, string>() | ||
const entryModMap = new Map<string, any>() | ||
|
||
try { | ||
const depModMap = new Map<string, any>() | ||
|
||
compilation.entries.forEach((entry) => { | ||
const name = entry.name || entry.options?.name | ||
|
||
if (name?.startsWith('pages/') && entry.dependencies[0]) { | ||
const entryMod = getModuleFromDependency( | ||
compilation, | ||
entry.dependencies[0] | ||
) | ||
|
||
if (entryMod.resource) { | ||
entryNameMap.set(entryMod.resource, name) | ||
entryModMap.set(entryMod.resource, entryMod) | ||
} | ||
} | ||
}) | ||
|
||
// TODO: investigate allowing non-sync fs calls in node-file-trace | ||
// for better performance | ||
const readFile = (path: string) => { | ||
const mod = depModMap.get(path) || entryModMap.get(path) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This doesn't cover all modules in the compilation. Only a subset. |
||
|
||
// map the transpiled source when available to avoid | ||
// parse errors in node-file-trace | ||
const source = mod?.originalSource?.() | ||
|
||
if (source) { | ||
return source.buffer() | ||
} | ||
|
||
try { | ||
return compilation.inputFileSystem.readFileSync(path) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reading the files directly from fs is probably not the best idea. A loader could have modified the source code after filesystem. Or it could be transpiled from a language nft doesn't understand. There is a Note that some modules might not end up at all in the output, so best use the list of chunks from There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like we can't use the list of files from |
||
} catch (e) { | ||
if (e.code === 'ENOENT' || e.code === 'EISDIR') { | ||
return null | ||
} | ||
throw e | ||
} | ||
} | ||
const readlink = (path: string) => { | ||
try { | ||
return compilation.inputFileSystem.readlinkSync(path) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sync fs calls might have a performance influence... There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It seems |
||
} catch (e) { | ||
if ( | ||
e.code !== 'EINVAL' && | ||
e.code !== 'ENOENT' && | ||
e.code !== 'UNKNOWN' | ||
) { | ||
throw e | ||
} | ||
return null | ||
} | ||
} | ||
const stat = (path: string) => { | ||
try { | ||
return compilation.inputFileSystem.statSync(path) | ||
} catch (e) { | ||
if (e.code === 'ENOENT') { | ||
return null | ||
} | ||
throw e | ||
} | ||
} | ||
|
||
const nftCache = {} | ||
const entryPaths = Array.from(entryModMap.keys()) | ||
|
||
for (const entry of entryPaths) { | ||
depModMap.clear() | ||
const entryMod = entryModMap.get(entry) | ||
// TODO: investigate caching, will require ensuring no traced | ||
// files in the cache have changed, we could potentially hash | ||
// all traced files and only leverage the cache if the hashes | ||
// match | ||
// const cachedTraces = entryMod.buildInfo?.cachedNextEntryTrace | ||
|
||
// Use cached trace if available and trace version matches | ||
// if ( | ||
// isWebpack5 && | ||
// cachedTraces && | ||
// cachedTraces.version === TRACE_OUTPUT_VERSION | ||
// ) { | ||
// this.entryTraces.set( | ||
// entryNameMap.get(entry)!, | ||
// cachedTraces.tracedDeps | ||
// ) | ||
// continue | ||
// } | ||
const collectDependencies = (mod: any) => { | ||
if (!mod || !mod.dependencies) return | ||
|
||
for (const dep of mod.dependencies) { | ||
const depMod = getModuleFromDependency(compilation, dep) | ||
|
||
if (depMod?.resource && !depModMap.get(depMod.resource)) { | ||
depModMap.set(depMod.resource, depMod) | ||
collectDependencies(depMod) | ||
} | ||
} | ||
} | ||
collectDependencies(entryMod) | ||
|
||
const toTrace: string[] = [entry, ...depModMap.keys()] | ||
|
||
const root = nodePath.parse(process.cwd()).root | ||
styfle marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const result = await nodeFileTrace(toTrace, { | ||
base: root, | ||
cache: nftCache, | ||
processCwd: this.appDir, | ||
readFile, | ||
readlink, | ||
stat, | ||
ignore: TRACE_IGNORES, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we also need to ignore the user's input from There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was currently applying this at the end of the build where There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suspect it will impact performance because you can stop tracing earlier so we don't look up deps of deps. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added this to the ignore config here 9823923 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Or actually it seems we can't pass this to the plugin since we need the built pages to gather the page configs 🤔 we might need to make this a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh I assumed thats what it was: a |
||
}) | ||
|
||
const tracedDeps: string[] = [] | ||
|
||
for (const file of result.fileList) { | ||
if (result.reasons[file].type === 'initial') { | ||
styfle marked this conversation as resolved.
Show resolved
Hide resolved
|
||
continue | ||
} | ||
tracedDeps.push(nodePath.join(root, file)) | ||
} | ||
|
||
// entryMod.buildInfo.cachedNextEntryTrace = { | ||
// version: TRACE_OUTPUT_VERSION, | ||
// tracedDeps, | ||
// } | ||
this.entryTraces.set(entryNameMap.get(entry)!, tracedDeps) | ||
} | ||
|
||
callback() | ||
} catch (err) { | ||
callback(err) | ||
} | ||
} | ||
) | ||
}) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2019 Vercel, Inc. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
{"name":"@vercel/nft","main":"index.js","license":"MIT"} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here you should iterate over all
entry.dependencies
to handle cases likeentry: { "pages/a": ["./pages/a.js", "./something-else.js"] }