Unverified Commit b55a023b authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor flight-manifest-plugin to use compilation.entrypoints directly (#62636)

## What?

Currently flight-manifest-plugin relies on looping over all webpack
chunk groups and trying to infer the entrypoint name from them, which
can be brittle in cases where the chunk group doesn't match exactly with
the entrypoint, which happens for the `_not-found` entrypoint for
example.

This PR changes the implementation to use `compilation.entrypoints`
directly. `compilation.entrypoints` is a `Map` where the key is the
entrypoint name and the value is the entrypoint chunk group, exactly
what this logic was looking for in the current implementation.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-2637
parent f38dc188
......@@ -8,6 +8,7 @@
import path from 'path'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
APP_CLIENT_INTERNALS,
BARREL_OPTIMIZATION_PREFIX,
CLIENT_REFERENCE_MANIFEST,
SYSTEM_ENTRYPOINTS,
......@@ -20,6 +21,7 @@ import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-
import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP } from '../../../shared/lib/constants'
import { getDeploymentIdQueryOrEmptyString } from '../../deployment-id'
import { formatBarrelOptimizedResource } from '../utils'
import type { ChunkGroup } from 'webpack'
interface Options {
dev: boolean
......@@ -243,9 +245,16 @@ export class ClientReferenceManifestPlugin {
}
})
compilation.chunkGroups.forEach((chunkGroup) => {
// By default it's the shared chunkGroup (main-app) for every page.
let entryName = ''
for (let [entryName, entrypoint] of compilation.entrypoints) {
if (
entryName === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP ||
entryName === APP_CLIENT_INTERNALS
) {
entryName = ''
} else if (!/^app[\\/]/.test(entryName)) {
continue
}
const manifest: ClientReferenceManifest = {
moduleLoading: {
prefix,
......@@ -257,28 +266,17 @@ export class ClientReferenceManifestPlugin {
entryCSSFiles: {},
}
if (chunkGroup.name && /^app[\\/]/.test(chunkGroup.name)) {
// Absolute path without the extension
const chunkEntryName = (this.appDirBase + chunkGroup.name).replace(
/[\\/]/g,
path.sep
)
manifest.entryCSSFiles[chunkEntryName] = chunkGroup
.getFiles()
.filter(
(f) => !f.startsWith('static/css/pages/') && f.endsWith('.css')
)
entryName = chunkGroup.name
}
// Absolute path without the extension
const chunkEntryName = (this.appDirBase + entryName).replace(
/[\\/]/g,
path.sep
)
manifest.entryCSSFiles[chunkEntryName] = entrypoint
.getFiles()
.filter((f) => !f.startsWith('static/css/pages/') && f.endsWith('.css'))
const requiredChunks = getAppPathRequiredChunks(chunkGroup, rootMainFiles)
const requiredChunks = getAppPathRequiredChunks(entrypoint, rootMainFiles)
const recordModule = (id: ModuleId, mod: webpack.NormalModule) => {
// Skip all modules from the pages folder.
if (mod.layer !== WEBPACK_LAYERS.appPagesBrowser) {
return
}
let resource =
mod.type === 'css/mini-extract'
? // @ts-expect-error TODO: use `identifier()` instead.
......@@ -382,57 +380,74 @@ export class ClientReferenceManifestPlugin {
manifest.edgeSSRModuleMapping = edgeModuleIdMapping
}
// Only apply following logic to client module requests from client entry,
// or if the module is marked as client module. That's because other
// client modules don't need to be in the manifest at all as they're
// never be referenced by the server/client boundary.
// This saves a lot of bytes in the manifest.
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
const entryMods =
compilation.chunkGraph.getChunkEntryModulesIterable(chunk)
for (const mod of entryMods) {
if (mod.layer !== WEBPACK_LAYERS.appPagesBrowser) continue
const request = (mod as webpack.NormalModule).request
if (
!request ||
!request.includes('next-flight-client-entry-loader.js?')
) {
continue
}
const checkedChunkGroups = new Set()
const checkedChunks = new Set()
function recordChunkGroup(chunkGroup: ChunkGroup) {
// Ensure recursion is stopped if we've already checked this chunk group.
if (checkedChunkGroups.has(chunkGroup)) return
checkedChunkGroups.add(chunkGroup)
// Only apply following logic to client module requests from client entry,
// or if the module is marked as client module. That's because other
// client modules don't need to be in the manifest at all as they're
// never be referenced by the server/client boundary.
// This saves a lot of bytes in the manifest.
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
// Ensure recursion is stopped if we've already checked this chunk.
if (checkedChunks.has(chunk)) return
checkedChunks.add(chunk)
const entryMods =
compilation.chunkGraph.getChunkEntryModulesIterable(chunk)
for (const mod of entryMods) {
if (mod.layer !== WEBPACK_LAYERS.appPagesBrowser) continue
const request = (mod as webpack.NormalModule).request
if (
!request ||
!request.includes('next-flight-client-entry-loader.js?')
) {
continue
}
const connections =
compilation.moduleGraph.getOutgoingConnections(mod)
for (const connection of connections) {
const dependency = connection.dependency
if (!dependency) continue
const clientEntryMod = compilation.moduleGraph.getResolvedModule(
dependency
) as webpack.NormalModule
const modId = compilation.chunkGraph.getModuleId(clientEntryMod) as
| string
| number
| null
if (modId !== null) {
recordModule(modId, clientEntryMod)
} else {
// If this is a concatenation, register each child to the parent ID.
if (
connection.module?.constructor.name === 'ConcatenatedModule'
) {
const concatenatedMod = connection.module
const concatenatedModId =
compilation.chunkGraph.getModuleId(concatenatedMod)
recordModule(concatenatedModId, clientEntryMod)
const connections =
compilation.moduleGraph.getOutgoingConnections(mod)
for (const connection of connections) {
const dependency = connection.dependency
if (!dependency) continue
const clientEntryMod = compilation.moduleGraph.getResolvedModule(
dependency
) as webpack.NormalModule
const modId = compilation.chunkGraph.getModuleId(
clientEntryMod
) as string | number | null
if (modId !== null) {
recordModule(modId, clientEntryMod)
} else {
// If this is a concatenation, register each child to the parent ID.
if (
connection.module?.constructor.name === 'ConcatenatedModule'
) {
const concatenatedMod = connection.module
const concatenatedModId =
compilation.chunkGraph.getModuleId(concatenatedMod)
recordModule(concatenatedModId, clientEntryMod)
}
}
}
}
})
// Walk through all children chunk groups too.
for (const child of chunkGroup.childrenIterable) {
recordChunkGroup(child)
}
})
}
recordChunkGroup(entrypoint)
// A page's entry name can have extensions. For example, these are both valid:
// - app/foo/page
......@@ -453,7 +468,7 @@ export class ClientReferenceManifestPlugin {
manifestsPerGroup.set(groupName, [])
}
manifestsPerGroup.get(groupName)!.push(manifest)
})
}
// Generate per-page manifests.
for (const pageName of manifestEntryFiles) {
......
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