Unverified Commit 1628260b authored by Ngô Đức Anh's avatar Ngô Đức Anh Committed by GitHub

Fixed middleware's edge-chunks not being copied in copyTracedFiles (#48723)



### What?

This PR fixes middleware's edge-chunks not being copied in copyTracedFiles.

### How?

Merging its files' handling with other pages' ones.

### Note

I also want to exclude `process.turbopack` from the unsupported APIs list by checking if `key === 'turbopack'` in `createProcessPolyfill` and `warnForUnsupportedProcessApi`, but I want to have some opinion on this first as I don't know if `process.turbopack` works with the Edge runtime.
parent 2d800df0
...@@ -10,7 +10,10 @@ import type { ...@@ -10,7 +10,10 @@ import type {
CustomRoutes, CustomRoutes,
} from '../lib/load-custom-routes' } from '../lib/load-custom-routes'
import type { UnwrapPromise } from '../lib/coalesced-function' import type { UnwrapPromise } from '../lib/coalesced-function'
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import type {
EdgeFunctionDefinition,
MiddlewareManifest,
} from './webpack/plugins/middleware-plugin'
import type { AppRouteUserlandModule } from '../server/future/route-modules/app-route/module' import type { AppRouteUserlandModule } from '../server/future/route-modules/app-route/module'
import type { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage' import type { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage'
...@@ -1834,9 +1837,8 @@ export async function copyTracedFiles( ...@@ -1834,9 +1837,8 @@ export async function copyTracedFiles(
) )
} }
for (const middleware of Object.values(middlewareManifest.middleware) || []) { async function handleEdgeFunction(page: EdgeFunctionDefinition) {
if (isMiddlewareFilename(middleware.name)) { async function handleFile(file: string) {
for (const file of middleware.files) {
const originalPath = path.join(distDir, file) const originalPath = path.join(distDir, file)
const fileOutputPath = path.join( const fileOutputPath = path.join(
outputPath, outputPath,
...@@ -1846,32 +1848,27 @@ export async function copyTracedFiles( ...@@ -1846,32 +1848,27 @@ export async function copyTracedFiles(
await fs.mkdir(path.dirname(fileOutputPath), { recursive: true }) await fs.mkdir(path.dirname(fileOutputPath), { recursive: true })
await fs.copyFile(originalPath, fileOutputPath) await fs.copyFile(originalPath, fileOutputPath)
} }
} await Promise.all([
page.files.map(handleFile),
page.wasm?.map((file) => handleFile(file.filePath)),
page.assets?.map((file) => handleFile(file.filePath)),
])
} }
for (const page of Object.values(middlewareManifest.functions)) { const edgeFunctionHandlers: Promise<any>[] = []
for (const file of page.files) {
const originalPath = path.join(distDir, file) for (const middleware of Object.values(middlewareManifest.middleware)) {
const fileOutputPath = path.join( if (isMiddlewareFilename(middleware.name)) {
outputPath, edgeFunctionHandlers.push(handleEdgeFunction(middleware))
path.relative(tracingRoot, distDir),
file
)
await fs.mkdir(path.dirname(fileOutputPath), { recursive: true })
await fs.copyFile(originalPath, fileOutputPath)
} }
for (const file of [...(page.wasm ?? []), ...(page.assets ?? [])]) {
const originalPath = path.join(distDir, file.filePath)
const fileOutputPath = path.join(
outputPath,
path.relative(tracingRoot, distDir),
file.filePath
)
await fs.mkdir(path.dirname(fileOutputPath), { recursive: true })
await fs.copyFile(originalPath, fileOutputPath)
} }
for (const page of Object.values(middlewareManifest.functions)) {
edgeFunctionHandlers.push(handleEdgeFunction(page))
} }
await Promise.all(edgeFunctionHandlers)
for (const page of pageKeys) { for (const page of pageKeys) {
if (middlewareManifest.functions.hasOwnProperty(page)) { if (middlewareManifest.functions.hasOwnProperty(page)) {
continue continue
......
import { mediaType } from 'next/dist/compiled/@hapi/accept'
import { createHash } from 'crypto' import { createHash } from 'crypto'
import { promises } from 'fs' import { promises } from 'fs'
import type { IncomingMessage, ServerResponse } from 'http'
import { mediaType } from 'next/dist/compiled/@hapi/accept'
import chalk from 'next/dist/compiled/chalk'
import contentDisposition from 'next/dist/compiled/content-disposition'
import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation' import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation'
import imageSizeOf from 'next/dist/compiled/image-size' import imageSizeOf from 'next/dist/compiled/image-size'
import { IncomingMessage, ServerResponse } from 'http'
import isAnimated from 'next/dist/compiled/is-animated' import isAnimated from 'next/dist/compiled/is-animated'
import contentDisposition from 'next/dist/compiled/content-disposition'
import { join } from 'path' import { join } from 'path'
import nodeUrl, { UrlWithParsedQuery } from 'url' import nodeUrl, { type UrlWithParsedQuery } from 'url'
import { NextConfigComplete } from './config-shared'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import { hasMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request'
// Do not import anything other than types from this module // Do not import anything other than types from this module
// because it will throw an error when using `outputFileTracing` // because it will throw an error when using `outputFileTracing`
// because `jest-worker` is ignored in file tracing. Use `await import` // as `jest-worker` is ignored in file tracing. Use `await import`
// or `require` instead. // or `require` instead.
import { Operation } from './lib/squoosh/main' import type { Operation } from './lib/squoosh/main'
import type { NextUrlWithParsedQuery } from './request-meta'
import type {
IncrementalCacheEntry,
IncrementalCacheValue,
} from './response-cache'
import { sendEtagResponse } from './send-payload' import { sendEtagResponse } from './send-payload'
import { getContentType, getExtension } from './serve-static' import { getContentType, getExtension } from './serve-static'
import chalk from 'next/dist/compiled/chalk'
import { NextUrlWithParsedQuery } from './request-meta'
import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache'
import { createRequestResponseMocks } from './lib/mock-request'
import { hasMatch } from '../shared/lib/match-remote-pattern'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import { ImageConfigComplete } from '../shared/lib/image-config'
type XCacheHeader = 'MISS' | 'HIT' | 'STALE' type XCacheHeader = 'MISS' | 'HIT' | 'STALE'
......
import { NextResponse } from 'next/server' import { ImageResponse, NextResponse } from 'next/server'
export async function middleware(req) { export async function middleware(req) {
console.log('middleware', req.url) console.log('middleware', req.url)
if (req.nextUrl.pathname === '/a-non-existent-page/to-test-with-middleware') {
return new ImageResponse(<div>Hello world</div>, {
width: 1200,
height: 600,
})
}
return NextResponse.next() return NextResponse.next()
} }
...@@ -1254,12 +1254,14 @@ describe('should set-up next', () => { ...@@ -1254,12 +1254,14 @@ describe('should set-up next', () => {
expect(envVariables.envLocal).toBeUndefined() expect(envVariables.envLocal).toBeUndefined()
}) })
it('should run middleware correctly without minimalMode', async () => { it('should run middleware correctly (without minimalMode, with wasm)', async () => {
await next.destroy() await next.destroy()
await killApp(server) await killApp(server)
await setupNext({ nextEnv: false, minimalMode: false }) await setupNext({ nextEnv: false, minimalMode: false })
const testServer = join(next.testDir, 'standalone/server.js') const standaloneDir = join(next.testDir, 'standalone')
const testServer = join(standaloneDir, 'server.js')
await fs.writeFile( await fs.writeFile(
testServer, testServer,
( (
...@@ -1290,9 +1292,19 @@ describe('should set-up next', () => { ...@@ -1290,9 +1292,19 @@ describe('should set-up next', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.text()).toContain('index page') expect(await res.text()).toContain('index page')
expect(fs.existsSync(join(standaloneDir, '.next/server/edge-chunks'))).toBe(
true
)
const resImageResponse = await fetchViaHTTP(
appPort,
'/a-non-existent-page/to-test-with-middleware'
)
expect(resImageResponse.status).toBe(200)
expect(resImageResponse.headers.get('content-type')).toBe('image/png')
// when not in next env should be compress: true // when not in next env should be compress: true
expect( expect(fs.readFileSync(testServer, 'utf8')).toContain('"compress":true')
await fs.readFileSync(join(next.testDir, 'standalone/server.js'), 'utf8')
).toContain('"compress":true')
}) })
}) })
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