Unverified Commit 5b31c18e authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Generate functions manifest (#33770)

## Feature

Reuse most of the part from manifest plugin to generate similar assets

Resolves #33667

- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
parent 030666b5
...@@ -48,6 +48,7 @@ import { regexLikeCss } from './webpack/config/blocks/css' ...@@ -48,6 +48,7 @@ import { regexLikeCss } from './webpack/config/blocks/css'
import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin' import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { FlightManifestPlugin } from './webpack/plugins/flight-manifest-plugin' import { FlightManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import FunctionsManifestPlugin from './webpack/plugins/functions-manifest-plugin'
import type { Span } from '../trace' import type { Span } from '../trace'
import { getRawPageExtensions } from './utils' import { getRawPageExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist' import browserslist from 'next/dist/compiled/browserslist'
...@@ -1460,6 +1461,9 @@ export default async function getBaseWebpackConfig( ...@@ -1460,6 +1461,9 @@ export default async function getBaseWebpackConfig(
// replacement is done before its process.env.* handling // replacement is done before its process.env.* handling
(!isServer || webServerRuntime) && (!isServer || webServerRuntime) &&
new MiddlewarePlugin({ dev, webServerRuntime }), new MiddlewarePlugin({ dev, webServerRuntime }),
process.env.ENABLE_FILE_SYSTEM_API === '1' &&
webServerRuntime &&
new FunctionsManifestPlugin({ dev, webServerRuntime }),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
!isServer && !isServer &&
new BuildManifestPlugin({ new BuildManifestPlugin({
......
import { sources, webpack5 } from 'next/dist/compiled/webpack/webpack'
import { collectAssets, getEntrypointInfo } from './middleware-plugin'
import { FUNCTIONS_MANIFEST } from '../../../shared/lib/constants'
const PLUGIN_NAME = 'FunctionsManifestPlugin'
export interface FunctionsManifest {
version: 1
pages: {
[page: string]: {
runtime: string
env: string[]
files: string[]
name: string
page: string
regexp: string
}
}
}
export default class FunctionsManifestPlugin {
dev: boolean
webServerRuntime: boolean
constructor({
dev,
webServerRuntime,
}: {
dev: boolean
webServerRuntime: boolean
}) {
this.dev = dev
this.webServerRuntime = webServerRuntime
}
createAssets(
compilation: webpack5.Compilation,
assets: any,
envPerRoute: Map<string, string[]>,
webServerRuntime: boolean
) {
const functionsManifest: FunctionsManifest = {
version: 1,
pages: {},
}
const infos = getEntrypointInfo(compilation, envPerRoute, webServerRuntime)
infos.forEach((info) => {
functionsManifest.pages[info.page] = {
runtime: 'web',
...info,
}
})
const assetPath =
(this.webServerRuntime ? '' : 'server/') + FUNCTIONS_MANIFEST
assets[assetPath] = new sources.RawSource(
JSON.stringify(functionsManifest, null, 2)
)
}
apply(compiler: webpack5.Compiler) {
collectAssets(compiler, this.createAssets.bind(this), {
dev: this.dev,
pluginName: PLUGIN_NAME,
webServerRuntime: this.webServerRuntime,
})
}
}
...@@ -37,35 +37,21 @@ const middlewareManifest: MiddlewareManifest = { ...@@ -37,35 +37,21 @@ const middlewareManifest: MiddlewareManifest = {
middleware: {}, middleware: {},
version: 1, version: 1,
} }
export default class MiddlewarePlugin {
dev: boolean
webServerRuntime: boolean
constructor({
dev,
webServerRuntime,
}: {
dev: boolean
webServerRuntime: boolean
}) {
this.dev = dev
this.webServerRuntime = webServerRuntime
}
createAssets( export function getEntrypointInfo(
compilation: webpack5.Compilation, compilation: webpack5.Compilation,
assets: any, envPerRoute: Map<string, string[]>,
envPerRoute: Map<string, string[]> webServerRuntime: boolean
) { ) {
const entrypoints = compilation.entrypoints const entrypoints = compilation.entrypoints
const infos = []
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
if (!entrypoint.name) continue if (!entrypoint.name) continue
const result = MIDDLEWARE_FULL_ROUTE_REGEX.exec(entrypoint.name) const result = MIDDLEWARE_FULL_ROUTE_REGEX.exec(entrypoint.name)
const ssrEntryInfo = ssrEntries.get(entrypoint.name) const ssrEntryInfo = ssrEntries.get(entrypoint.name)
if (ssrEntryInfo && !this.webServerRuntime) continue
if (!ssrEntryInfo && this.webServerRuntime) continue if (ssrEntryInfo && !webServerRuntime) continue
if (!ssrEntryInfo && webServerRuntime) continue
const location = result const location = result
? `/${result[1]}` ? `/${result[1]}`
...@@ -92,15 +78,43 @@ export default class MiddlewarePlugin { ...@@ -92,15 +78,43 @@ export default class MiddlewarePlugin {
].filter(nonNullable) ].filter(nonNullable)
: entryFiles.map((file: string) => file) : entryFiles.map((file: string) => file)
middlewareManifest.middleware[location] = { infos.push({
env: envPerRoute.get(entrypoint.name) || [], env: envPerRoute.get(entrypoint.name) || [],
files, files,
name: entrypoint.name, name: entrypoint.name,
page: location, page: location,
regexp: getMiddlewareRegex(location, !ssrEntryInfo).namedRegex!, regexp: getMiddlewareRegex(location, !ssrEntryInfo).namedRegex!,
})
} }
return infos
}
export default class MiddlewarePlugin {
dev: boolean
webServerRuntime: boolean
constructor({
dev,
webServerRuntime,
}: {
dev: boolean
webServerRuntime: boolean
}) {
this.dev = dev
this.webServerRuntime = webServerRuntime
} }
createAssets(
compilation: webpack5.Compilation,
assets: any,
envPerRoute: Map<string, string[]>,
webServerRuntime: boolean
) {
const infos = getEntrypointInfo(compilation, envPerRoute, webServerRuntime)
infos.forEach((info) => {
middlewareManifest.middleware[info.page] = info
})
middlewareManifest.sortedMiddleware = getSortedRoutes( middlewareManifest.sortedMiddleware = getSortedRoutes(
Object.keys(middlewareManifest.middleware) Object.keys(middlewareManifest.middleware)
) )
...@@ -120,12 +134,33 @@ export default class MiddlewarePlugin { ...@@ -120,12 +134,33 @@ export default class MiddlewarePlugin {
} }
apply(compiler: webpack5.Compiler) { apply(compiler: webpack5.Compiler) {
const { dev } = this collectAssets(compiler, this.createAssets.bind(this), {
dev: this.dev,
pluginName: PLUGIN_NAME,
webServerRuntime: this.webServerRuntime,
})
}
}
export function collectAssets(
compiler: webpack5.Compiler,
createAssets: (
compilation: webpack5.Compilation,
assets: any,
envPerRoute: Map<string, string[]>,
webServerRuntime: boolean
) => void,
options: {
dev: boolean
pluginName: string
webServerRuntime: boolean
}
) {
const wp = compiler.webpack const wp = compiler.webpack
compiler.hooks.compilation.tap( compiler.hooks.compilation.tap(
PLUGIN_NAME, options.pluginName,
(compilation, { normalModuleFactory }) => { (compilation, { normalModuleFactory }) => {
compilation.hooks.afterChunks.tap(PLUGIN_NAME, () => { compilation.hooks.afterChunks.tap(options.pluginName, () => {
const middlewareRuntimeChunk = compilation.namedChunks.get( const middlewareRuntimeChunk = compilation.namedChunks.get(
MIDDLEWARE_RUNTIME_WEBPACK MIDDLEWARE_RUNTIME_WEBPACK
) )
...@@ -164,7 +199,7 @@ export default class MiddlewarePlugin { ...@@ -164,7 +199,7 @@ export default class MiddlewarePlugin {
for (const module of queue) { for (const module of queue) {
const { buildInfo } = module const { buildInfo } = module
if ( if (
!dev && !options.dev &&
buildInfo && buildInfo &&
isUsedByExports({ isUsedByExports({
module, module,
...@@ -218,7 +253,7 @@ export default class MiddlewarePlugin { ...@@ -218,7 +253,7 @@ export default class MiddlewarePlugin {
const wrapExpression = (expr: any) => { const wrapExpression = (expr: any) => {
if (!isMiddlewareModule()) return if (!isMiddlewareModule()) return
if (dev) { if (options.dev) {
const dep1 = new wp.dependencies.ConstDependency( const dep1 = new wp.dependencies.ConstDependency(
'__next_eval__(function() { return ', '__next_eval__(function() { return ',
expr.range[0] expr.range[0]
...@@ -273,14 +308,10 @@ export default class MiddlewarePlugin { ...@@ -273,14 +308,10 @@ export default class MiddlewarePlugin {
.for('global.Function') .for('global.Function')
.tap(PLUGIN_NAME, wrapExpression) .tap(PLUGIN_NAME, wrapExpression)
parser.hooks.new.for('Function').tap(PLUGIN_NAME, wrapExpression) parser.hooks.new.for('Function').tap(PLUGIN_NAME, wrapExpression)
parser.hooks.new parser.hooks.new.for('global.Function').tap(PLUGIN_NAME, wrapExpression)
.for('global.Function')
.tap(PLUGIN_NAME, wrapExpression)
// fallbacks // fallbacks
parser.hooks.expression parser.hooks.expression.for('eval').tap(PLUGIN_NAME, expressionHandler)
.for('eval')
.tap(PLUGIN_NAME, expressionHandler)
parser.hooks.expression parser.hooks.expression
.for('Function') .for('Function')
.tap(PLUGIN_NAME, expressionHandler) .tap(PLUGIN_NAME, expressionHandler)
...@@ -339,12 +370,16 @@ export default class MiddlewarePlugin { ...@@ -339,12 +370,16 @@ export default class MiddlewarePlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, },
(assets: any) => { (assets: any) => {
this.createAssets(compilation, assets, envPerRoute) createAssets(
} compilation,
assets,
envPerRoute,
options.webServerRuntime
) )
} }
) )
} }
)
} }
function isUsedByExports(args: { function isUsedByExports(args: {
......
...@@ -12,6 +12,7 @@ export const ROUTES_MANIFEST = 'routes-manifest.json' ...@@ -12,6 +12,7 @@ export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json' export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files.json' export const SERVER_FILES_MANIFEST = 'required-server-files.json'
export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json' export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'
export const FUNCTIONS_MANIFEST = 'functions-manifest.json'
export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json' export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'
export const DEV_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json' export const DEV_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json' export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
......
...@@ -99,8 +99,9 @@ export default function Page404() { ...@@ -99,8 +99,9 @@ export default function Page404() {
} }
` `
async function nextBuild(dir) { async function nextBuild(dir, options) {
return await _nextBuild(dir, [], { return await _nextBuild(dir, [], {
...options,
stdout: true, stdout: true,
stderr: true, stderr: true,
nodeArgs, nodeArgs,
...@@ -212,6 +213,38 @@ describe('concurrentFeatures - prod', () => { ...@@ -212,6 +213,38 @@ describe('concurrentFeatures - prod', () => {
runBasicTests(context, 'prod') runBasicTests(context, 'prod')
}) })
describe('Functions manifest', () => {
it('should not generate functions manifest when filesystem API is not enabled', async () => {
await nextBuild(appDir)
const functionsManifestPath = join(
distDir,
'server',
'functions-manifest.json'
)
expect(fs.existsSync(functionsManifestPath)).toBe(false)
})
it('should contain rsc paths in functions manifest', async () => {
await nextBuild(appDir, { env: { ENABLE_FILE_SYSTEM_API: '1' } })
const functionsManifestPath = join(
distDir,
'server',
'functions-manifest.json'
)
const content = JSON.parse(await fs.readFile(functionsManifestPath, 'utf8'))
const { pages } = content
const pageNames = Object.keys(pages)
const paths = ['/', '/next-api/link', '/routes/[dynamic]']
paths.forEach((path) => {
expect(pageNames).toContain(path)
expect(pages[path].runtime).toBe('web')
expect(pages[path].files.every((f) => f.startsWith('server/'))).toBe(true)
})
expect(content.version).toBe(1)
})
})
const customAppPageSuite = { const customAppPageSuite = {
runTests: (context) => { runTests: (context) => {
it('should render container in app', async () => { it('should render container in app', async () => {
......
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