Skip to content

Commit

Permalink
Revert "support runtime: edge in api endpoints" (vercel#37337)
Browse files Browse the repository at this point in the history
Revert "support `runtime: edge` in api endpoints (vercel#36947)"

This reverts commit 3d1a287.
  • Loading branch information
shuding committed May 31, 2022
1 parent 3d1a287 commit ed0b580
Show file tree
Hide file tree
Showing 12 changed files with 35 additions and 271 deletions.
13 changes: 1 addition & 12 deletions packages/next/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,6 @@ export function getEdgeServerEntry(opts: {
return `next-middleware-loader?${stringify(loaderParams)}!`
}

if (opts.page.startsWith('/api/')) {
const loaderParams: MiddlewareLoaderOptions = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
}

return `next-edge-function-loader?${stringify(loaderParams)}!`
}

const loaderParams: MiddlewareSSRLoaderQuery = {
absolute500Path: opts.pages['/500'] || '',
absoluteAppPath: opts.pages['/_app'],
Expand Down Expand Up @@ -418,9 +409,7 @@ export function runDependingOnPageType<T>(params: {
if (params.page === MIDDLEWARE_FILE) {
return [params.onEdgeServer()]
} else if (params.page.match(API_ROUTE)) {
return params.pageRuntime === 'edge'
? [params.onEdgeServer()]
: [params.onServer()]
return [params.onServer()]
} else if (params.page === '/_document') {
return [params.onServer()]
} else if (
Expand Down
6 changes: 5 additions & 1 deletion packages/next/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ import {
getUnresolvedModuleFromError,
copyTracedFiles,
isReservedPage,
isCustomErrorPage,
isServerComponentPage,
} from './utils'
import getBaseWebpackConfig from './webpack-config'
Expand Down Expand Up @@ -1254,7 +1255,10 @@ export default async function build(
isHybridAmp,
ssgPageRoutes,
initialRevalidateSeconds: false,
runtime: pageRuntime,
runtime:
!isReservedPage(page) && !isCustomErrorPage(page)
? pageRuntime
: undefined,
pageDuration: undefined,
ssgPageDurations: undefined,
})
Expand Down
1 change: 0 additions & 1 deletion packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1232,7 +1232,6 @@ export default async function getBaseWebpackConfig(
'next-flight-client-entry-loader',
'noop-loader',
'next-middleware-loader',
'next-edge-function-loader',
'next-middleware-ssr-loader',
'next-middleware-wasm-loader',
'next-app-loader',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { webpack5 } from 'next/dist/compiled/webpack/webpack'
export function getModuleBuildInfo(webpackModule: webpack5.Module) {
return webpackModule.buildInfo as {
nextEdgeMiddleware?: EdgeMiddlewareMeta
nextEdgeApiFunction?: EdgeMiddlewareMeta
nextEdgeSSR?: EdgeSSRMeta
nextUsedEnvVars?: Set<string>
nextWasmMiddlewareBinding?: WasmBinding
Expand Down
43 changes: 0 additions & 43 deletions packages/next/build/webpack/loaders/next-edge-function-loader.ts

This file was deleted.

40 changes: 13 additions & 27 deletions packages/next/build/webpack/plugins/middleware-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,24 @@ import {
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
} from '../../../shared/lib/constants'

interface EdgeFunctionDefinition {
env: string[]
files: string[]
name: string
page: string
regexp: string
wasm?: WasmBinding[]
}

export interface MiddlewareManifest {
version: 1
sortedMiddleware: string[]
clientInfo: [location: string, isSSR: boolean][]
middleware: { [page: string]: EdgeFunctionDefinition }
functions: { [page: string]: EdgeFunctionDefinition }
middleware: {
[page: string]: {
env: string[]
files: string[]
name: string
page: string
regexp: string
wasm?: WasmBinding[]
}
}
}

interface EntryMetadata {
edgeMiddleware?: EdgeMiddlewareMeta
edgeApiFunction?: EdgeMiddlewareMeta
edgeSSR?: EdgeSSRMeta
env: Set<string>
wasmBindings: Set<WasmBinding>
Expand All @@ -44,7 +42,6 @@ const middlewareManifest: MiddlewareManifest = {
sortedMiddleware: [],
clientInfo: [],
middleware: {},
functions: {},
version: 1,
}

Expand Down Expand Up @@ -313,8 +310,6 @@ function getExtractMetadata(params: {
entryMetadata.edgeSSR = buildInfo.nextEdgeSSR
} else if (buildInfo?.nextEdgeMiddleware) {
entryMetadata.edgeMiddleware = buildInfo.nextEdgeMiddleware
} else if (buildInfo?.nextEdgeApiFunction) {
entryMetadata.edgeApiFunction = buildInfo.nextEdgeApiFunction
}

/**
Expand Down Expand Up @@ -391,32 +386,23 @@ function getCreateAssets(params: {

// There should always be metadata for the entrypoint.
const metadata = metadataByEntry.get(entrypoint.name)
const page =
metadata?.edgeMiddleware?.page ||
metadata?.edgeSSR?.page ||
metadata?.edgeApiFunction?.page
const page = metadata?.edgeMiddleware?.page || metadata?.edgeSSR?.page
if (!page) {
continue
}

const { namedRegex } = getNamedMiddlewareRegex(page, {
catchAll: !metadata.edgeSSR && !metadata.edgeApiFunction,
catchAll: !metadata.edgeSSR,
})

const edgeFunctionDefinition: EdgeFunctionDefinition = {
middlewareManifest.middleware[page] = {
env: Array.from(metadata.env),
files: getEntryFiles(entrypoint.getFiles(), metadata),
name: entrypoint.name,
page: page,
regexp: namedRegex,
wasm: Array.from(metadata.wasmBindings),
}

if (metadata.edgeApiFunction /* || metadata.edgeSSR */) {
middlewareManifest.functions[page] = edgeFunctionDefinition
} else {
middlewareManifest.middleware[page] = edgeFunctionDefinition
}
}

middlewareManifest.sortedMiddleware = getSortedRoutes(
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/body-streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function requestToBodyStream(request: IncomingMessage): BodyStream {
return transform.readable as unknown as ReadableStream<Uint8Array>
}

export function bodyStreamToNodeStream(bodyStream: BodyStream): Readable {
function bodyStreamToNodeStream(bodyStream: BodyStream): Readable {
const reader = bodyStream.getReader()
return Readable.from(
(async function* () {
Expand Down
4 changes: 1 addition & 3 deletions packages/next/server/dev/next-dev-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,9 +354,7 @@ export default class DevServer extends Server {
onClient: () => {},
onServer: () => {},
onEdgeServer: () => {
if (!pageName.startsWith('/api/')) {
routedMiddleware.push(pageName)
}
routedMiddleware.push(pageName)
ssrMiddleware.add(pageName)
},
})
Expand Down
121 changes: 10 additions & 111 deletions packages/next/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ import { getCustomRoute } from './server-route-utils'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import ResponseCache from '../server/response-cache'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { clonableBodyForRequest } from './body-streams'
import { getMiddlewareRegex } from '../shared/lib/router/utils/route-regex'
import { bodyStreamToNodeStream, clonableBodyForRequest } from './body-streams'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'

export * from './base-server'

Expand Down Expand Up @@ -540,19 +540,6 @@ export default class NextNodeServer extends BaseServer {
page: string,
builtPagePath: string
): Promise<boolean> {
const handledAsEdgeFunction = await this.runEdgeFunctionApiEndpoint({
req,
res,
query,
params,
page,
builtPagePath,
})

if (handledAsEdgeFunction) {
return true
}

const pageModule = await require(builtPagePath)
query = { ...query, ...params }

Expand Down Expand Up @@ -1044,15 +1031,11 @@ export default class NextNodeServer extends BaseServer {
}

/**
* Get information for the edge function located in the provided page
* folder. If the edge function info can't be found it will throw
* Get information for the middleware located in the provided page
* folder. If the middleware info can't be found it will throw
* an error.
*/
protected getEdgeFunctionInfo(params: {
page: string
/** Whether we should look for a middleware or not */
middleware: boolean
}) {
protected getMiddlewareInfo(page: string) {
const manifest: MiddlewareManifest = require(join(
this.serverDistDir,
MIDDLEWARE_MANIFEST
Expand All @@ -1061,14 +1044,12 @@ export default class NextNodeServer extends BaseServer {
let foundPage: string

try {
foundPage = denormalizePagePath(normalizePagePath(params.page))
foundPage = denormalizePagePath(normalizePagePath(page))
} catch (err) {
throw pageNotFoundError(params.page)
throw pageNotFoundError(page)
}

let pageInfo = params.middleware
? manifest.middleware[foundPage]
: manifest.functions[foundPage]
let pageInfo = manifest.middleware[foundPage]
if (!pageInfo) {
throw pageNotFoundError(foundPage)
}
Expand All @@ -1094,10 +1075,7 @@ export default class NextNodeServer extends BaseServer {
_isSSR?: boolean
): Promise<boolean> {
try {
return (
this.getEdgeFunctionInfo({ page: pathname, middleware: true }).paths
.length > 0
)
return this.getMiddlewareInfo(pathname).paths.length > 0
} catch (_) {}

return false
Expand Down Expand Up @@ -1164,10 +1142,7 @@ export default class NextNodeServer extends BaseServer {
}

await this.ensureMiddleware(middleware.page, middleware.ssr)
const middlewareInfo = this.getEdgeFunctionInfo({
page: middleware.page,
middleware: true,
})
const middlewareInfo = this.getMiddlewareInfo(middleware.page)

result = await run({
name: middlewareInfo.name,
Expand Down Expand Up @@ -1436,80 +1411,4 @@ export default class NextNodeServer extends BaseServer {
this.warnIfQueryParametersWereDeleted = () => {}
}
}

private async runEdgeFunctionApiEndpoint(params: {
req: NodeNextRequest
res: NodeNextResponse
query: ParsedUrlQuery
params: Params | false
page: string
builtPagePath: string
}): Promise<boolean> {
let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined

try {
middlewareInfo = this.getEdgeFunctionInfo({
page: params.page,
middleware: false,
})
} catch {
return false
}

// For middleware to "fetch" we must always provide an absolute URL
const url = getRequestMeta(params.req, '__NEXT_INIT_URL')!
if (!url.startsWith('http')) {
throw new Error(
'To use middleware you must provide a `hostname` and `port` to the Next.js Server'
)
}

const result = await run({
name: middlewareInfo.name,
paths: middlewareInfo.paths,
env: middlewareInfo.env,
wasm: middlewareInfo.wasm,
request: {
headers: params.req.headers,
method: params.req.method,
nextConfig: {
basePath: this.nextConfig.basePath,
i18n: this.nextConfig.i18n,
trailingSlash: this.nextConfig.trailingSlash,
},
url,
page: {
name: params.page,
...(params.params && { params: params.params }),
},
// TODO(gal): complete body
// body: originalBody?.cloneBodyStream(),
},
useCache: !this.nextConfig.experimental.runtime,
onWarning: (_warning: Error) => {
// if (params.onWarning) {
// warning.message += ` "./${middlewareInfo.name}"`
// params.onWarning(warning)
// }
},
})

params.res.statusCode = result.response.status
params.res.statusMessage = result.response.statusText

result.response.headers.forEach((value, key) => {
params.res.appendHeader(key, value)
})

if (result.response.body) {
// TODO(gal): not sure that we always need to stream
bodyStreamToNodeStream(result.response.body).pipe(
params.res.originalResponse
)
} else {
params.res.originalResponse.end()
}

return true
}
}

This file was deleted.

Loading

0 comments on commit ed0b580

Please sign in to comment.