Skip to content

Commit

Permalink
Fixed middleware's edge-chunks not being copied in copyTracedFiles (#…
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
DuCanhGH authored May 1, 2023
1 parent 2d800df commit 1628260
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 47 deletions.
51 changes: 24 additions & 27 deletions packages/next/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import type {
CustomRoutes,
} from '../lib/load-custom-routes'
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 { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage'

Expand Down Expand Up @@ -1834,23 +1837,8 @@ export async function copyTracedFiles(
)
}

for (const middleware of Object.values(middlewareManifest.middleware) || []) {
if (isMiddlewareFilename(middleware.name)) {
for (const file of middleware.files) {
const originalPath = path.join(distDir, file)
const fileOutputPath = path.join(
outputPath,
path.relative(tracingRoot, distDir),
file
)
await fs.mkdir(path.dirname(fileOutputPath), { recursive: true })
await fs.copyFile(originalPath, fileOutputPath)
}
}
}

for (const page of Object.values(middlewareManifest.functions)) {
for (const file of page.files) {
async function handleEdgeFunction(page: EdgeFunctionDefinition) {
async function handleFile(file: string) {
const originalPath = path.join(distDir, file)
const fileOutputPath = path.join(
outputPath,
Expand All @@ -1860,18 +1848,27 @@ export async function copyTracedFiles(
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)
await Promise.all([
page.files.map(handleFile),
page.wasm?.map((file) => handleFile(file.filePath)),
page.assets?.map((file) => handleFile(file.filePath)),
])
}

const edgeFunctionHandlers: Promise<any>[] = []

for (const middleware of Object.values(middlewareManifest.middleware)) {
if (isMiddlewareFilename(middleware.name)) {
edgeFunctionHandlers.push(handleEdgeFunction(middleware))
}
}

for (const page of Object.values(middlewareManifest.functions)) {
edgeFunctionHandlers.push(handleEdgeFunction(page))
}

await Promise.all(edgeFunctionHandlers)

for (const page of pageKeys) {
if (middlewareManifest.functions.hasOwnProperty(page)) {
continue
Expand Down
32 changes: 18 additions & 14 deletions packages/next/src/server/image-optimizer.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import { mediaType } from 'next/dist/compiled/@hapi/accept'
import { createHash } from 'crypto'
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 imageSizeOf from 'next/dist/compiled/image-size'
import { IncomingMessage, ServerResponse } from 'http'
import isAnimated from 'next/dist/compiled/is-animated'
import contentDisposition from 'next/dist/compiled/content-disposition'
import { join } from 'path'
import nodeUrl, { UrlWithParsedQuery } from 'url'
import { NextConfigComplete } from './config-shared'
import nodeUrl, { type UrlWithParsedQuery } from 'url'

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
// 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.
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 { 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'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { NextResponse } from 'next/server'
import { ImageResponse, NextResponse } from 'next/server'

export async function middleware(req) {
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()
}
Original file line number Diff line number Diff line change
Expand Up @@ -1254,12 +1254,14 @@ describe('should set-up next', () => {
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 killApp(server)
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(
testServer,
(
Expand Down Expand Up @@ -1290,9 +1292,19 @@ describe('should set-up next', () => {
expect(res.status).toBe(200)
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
expect(
await fs.readFileSync(join(next.testDir, 'standalone/server.js'), 'utf8')
).toContain('"compress":true')
expect(fs.readFileSync(testServer, 'utf8')).toContain('"compress":true')
})
})

0 comments on commit 1628260

Please sign in to comment.