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