Unverified Commit baae7b1f authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Clean up leftover loaders (#46801)

More cleanup flowing out of the removal of the `target` option.

<!--
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:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)

---------
Co-authored-by: 's avatarShu Ding <g@shud.in>
parent beeefdb1
......@@ -48,8 +48,7 @@ export function processEnv(
) {
return process.env as Env
}
// flag that we processed the environment values in case a serverless
// function is re-used or we are running in `next start` mode
// flag that we processed the environment values already.
process.env.__NEXT_PROCESSED_ENV = 'true'
const origEnv = Object.assign({}, initialEnv)
......
......@@ -927,7 +927,6 @@ export default async function build(
)
// We need to write the manifest with rewrites before build
// so serverless can import the manifest
await nextBuildSpan
.traceChild('write-routes-manifest')
.traceAsyncFn(() =>
......
......@@ -100,7 +100,6 @@ async function webpackBuildImpl(
isServer: false,
buildId: NextBuildContext.buildId!,
config: config,
target: config.target!,
appDir: NextBuildContext.appDir!,
pagesDir: NextBuildContext.pagesDir!,
rewrites: NextBuildContext.rewrites!,
......
......@@ -633,7 +633,6 @@ export default async function getBaseWebpackConfig(
originalRewrites,
originalRedirects,
runWebpackSpan,
target = COMPILER_NAMES.server,
appDir,
middlewareMatchers,
noMangling = false,
......@@ -654,7 +653,6 @@ export default async function getBaseWebpackConfig(
originalRewrites: CustomRoutes['rewrites'] | undefined
originalRedirects: CustomRoutes['redirects'] | undefined
runWebpackSpan: Span
target?: string
appDir?: string
middlewareMatchers?: MiddlewareMatcher[]
noMangling?: boolean
......@@ -1705,7 +1703,6 @@ export default async function getBaseWebpackConfig(
'next-client-pages-loader',
'next-image-loader',
'next-metadata-image-loader',
'next-serverless-loader',
'next-style-loader',
'next-flight-loader',
'next-flight-client-entry-loader',
......@@ -2422,7 +2419,6 @@ export default async function getBaseWebpackConfig(
excludeDefaultMomentLocales: config.excludeDefaultMomentLocales,
assetPrefix: config.assetPrefix,
disableOptimizedLoading,
target,
isEdgeRuntime: isEdgeServer,
reactProductionProfiling,
webpack: !!config.webpack,
......
import { parse as parseUrl } from 'url'
import { IncomingMessage, ServerResponse } from 'http'
import { apiResolver } from '../../../../server/api-utils/node'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { DecodeError } from '../../../../shared/lib/utils'
import {
NodeNextResponse,
NodeNextRequest,
} from '../../../../server/base-http/node'
export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
const {
handleRewrites,
handleBasePath,
dynamicRouteMatcher,
normalizeDynamicRouteParams,
} = getUtils(ctx)
return async (
rawReq: NodeNextRequest | IncomingMessage,
rawRes: NodeNextResponse | ServerResponse
) => {
const req =
rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq
const res =
rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = req.headers[vercelHeader]
const parsedUrl = parseUrl(req.url!, true)
handleRewrites(req, parsedUrl)
if (parsedUrl.query.nextInternalLocale) {
delete parsedUrl.query.nextInternalLocale
}
handleBasePath(req, parsedUrl)
let params = {}
if (pageIsDynamic) {
const result = normalizeDynamicRouteParams(
trustQuery
? parsedUrl.query
: (dynamicRouteMatcher!(parsedUrl.pathname) as Record<
string,
string | string[]
>)
)
params = result.params
}
await apiResolver(
req.originalRequest,
res.originalResponse,
Object.assign({}, parsedUrl.query, params),
await pageModule,
encodedPreviewProps,
true
)
} catch (err) {
console.error(err)
if (err instanceof DecodeError) {
res.statusCode = 400
res.body('Bad Request').send()
} else {
// Throw the error to crash the serverless function
throw err
}
}
}
}
import devalue from 'next/dist/compiled/devalue'
import { join } from 'path'
import { parse } from 'querystring'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { isAPIRoute } from '../../../../lib/is-api-route'
import { isDynamicRoute } from '../../../../shared/lib/router/utils'
import { escapeStringRegexp } from '../../../../shared/lib/escape-regexp'
import { __ApiPreviewProps } from '../../../../server/api-utils'
import {
BUILD_MANIFEST,
ROUTES_MANIFEST,
REACT_LOADABLE_MANIFEST,
} from '../../../../shared/lib/constants'
import { stringifyRequest } from '../../stringify-request'
export type ServerlessLoaderQuery = {
page: string
distDir: string
absolutePagePath: string
absoluteAppPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
absolute404Path: string
buildId: string
assetPrefix: string
generateEtags: string
poweredByHeader: string
canonicalBase: string
basePath: string
runtimeConfig: string
previewProps: string
loadedEnvFiles: string
i18n: string
}
const nextServerlessLoader: webpack.LoaderDefinitionFunction = function () {
const {
distDir,
absolutePagePath,
page,
buildId,
canonicalBase,
assetPrefix,
absoluteAppPath,
absoluteDocumentPath,
absoluteErrorPath,
absolute404Path,
generateEtags,
poweredByHeader,
basePath,
runtimeConfig,
previewProps,
loadedEnvFiles,
i18n,
}: ServerlessLoaderQuery = (
typeof this.query === 'string' ? parse(this.query.slice(1)) : this.query
) as any
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
/\\/g,
'/'
)
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')
const escapedBuildId = escapeStringRegexp(buildId)
const pageIsDynamicRoute = isDynamicRoute(page)
const encodedPreviewProps = devalue(
JSON.parse(previewProps) as __ApiPreviewProps
)
const envLoading = `
const { processEnv } = require('@next/env')
processEnv(${Buffer.from(loadedEnvFiles, 'base64').toString()})
`
const runtimeConfigImports = runtimeConfig
? `
const { setConfig } = require('next/config')
`
: ''
const runtimeConfigSetter = runtimeConfig
? `
const runtimeConfig = ${runtimeConfig}
setConfig(runtimeConfig)
`
: 'const runtimeConfig = {}'
if (isAPIRoute(page)) {
return `
${envLoading}
${runtimeConfigImports}
${
/*
this needs to be called first so its available for any other imports
*/
runtimeConfigSetter
}
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const apiHandler = getApiHandler({
pageModule: require(${stringifyRequest(this, absolutePagePath)}),
rewrites: rewrites,
i18n: ${i18n || 'undefined'},
page: "${page}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export default apiHandler
`
} else {
return `
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import buildManifest from '${buildManifest}'
import reactLoadableManifest from '${reactLoadableManifest}'
${envLoading}
${runtimeConfigImports}
${
// this needs to be called first so its available for any other imports
runtimeConfigSetter
}
import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler'
const documentModule = require(${stringifyRequest(
this,
absoluteDocumentPath
)})
const appMod = require(${stringifyRequest(this, absoluteAppPath)})
let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
const compMod = require(${stringifyRequest(this, absolutePagePath)})
const Component = compMod.default || compMod.then && compMod.then(mod => mod.default)
export default Component
export const getStaticProps = compMod['getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['getStaticProp' + 's'])
export const getStaticPaths = compMod['getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['getStaticPath' + 's'])
export const getServerSideProps = compMod['getServerSideProp' + 's'] || compMod.then && compMod.then(mod => mod['getServerSideProp' + 's'])
// kept for detecting legacy exports
export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod,
pageComponent: Component,
pageConfig: config,
appModule: App,
documentModule: documentModule,
errorModule: require(${stringifyRequest(this, absoluteErrorPath)}),
notFoundModule: ${
absolute404Path
? `require(${stringifyRequest(this, absolute404Path)})`
: undefined
},
pageGetStaticProps: getStaticProps,
pageGetStaticPaths: getStaticPaths,
pageGetServerSideProps: getServerSideProps,
assetPrefix: "${assetPrefix}",
canonicalBase: "${canonicalBase}",
generateEtags: ${generateEtags || 'false'},
poweredByHeader: ${poweredByHeader || 'false'},
runtimeConfig,
buildManifest,
reactLoadableManifest,
rewrites: rewrites,
i18n: ${i18n || 'undefined'},
page: "${page}",
buildId: "${buildId}",
escapedBuildId: "${escapedBuildId}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export { renderReqToHTML, render }
`
}
}
export default nextServerlessLoader
......@@ -542,7 +542,6 @@ export default async function exportPage({
return { ...results, duration: Date.now() - start }
}
// TODO: de-dupe the logic here between serverless and server mode
if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {
// make sure it ends with .html if the name contains a dot
htmlFilepath += '.html'
......@@ -555,7 +554,7 @@ export default async function exportPage({
} else {
/**
* This sets environment variable to be used at the time of static export by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/
......
......@@ -63,7 +63,7 @@ export class RequestAsyncStorageWrapper
): Result {
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
// invoke.
const previewData: PreviewData =
renderOpts && RequestAsyncStorageWrapper.tryGetPreviewData
? // TODO: investigate why previewProps isn't on RenderOpts
......
......@@ -59,7 +59,7 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log'
import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
import { getUtils } from '../build/webpack/loaders/next-serverless-loader/utils'
import { getUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error'
import { addRequestMeta, getRequestMeta } from './request-meta'
......@@ -132,7 +132,7 @@ export interface Options {
*/
dir?: string
/**
* Tells if Next.js is running in a Serverless platform
* Tells if Next.js is at the platform-level
*/
minimalMode?: boolean
/**
......
......@@ -16,7 +16,6 @@ export type NextConfigComplete = Required<NextConfig> & {
configOrigin?: string
configFile?: string
configFileName: string
target?: string
}
export interface I18NConfig {
......@@ -615,7 +614,6 @@ export const defaultConfig: NextConfig = {
generateBuildId: () => null,
generateEtags: true,
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
target: 'server',
poweredByHeader: true,
compress: true,
analyticsId: process.env.VERCEL_ANALYTICS_ID || '',
......
......@@ -183,7 +183,7 @@ export default class NextNodeServer extends BaseServer {
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_CSS`.
*/
if (this.renderOpts.optimizeFonts) {
......
......@@ -576,7 +576,7 @@ export async function renderToHTML(
) {
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
// invoke.
previewData = tryGetPreviewData(req, res, previewProps)
isPreview = previewData !== false
}
......
import type { IncomingMessage, ServerResponse } from 'http'
import type { Rewrite } from '../../../../lib/load-custom-routes'
import type { BuildManifest } from '../../../../server/get-page-files'
import type { RouteMatchFn } from '../../../../shared/lib/router/utils/route-matcher'
import type { NextConfig } from '../../../../server/config'
import type {
GetServerSideProps,
GetStaticPaths,
GetStaticProps,
} from '../../../../../types'
import type { BaseNextRequest } from '../../../../server/base-http'
import type { __ApiPreviewProps } from '../../../../server/api-utils'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring'
import { format as formatUrl, UrlWithParsedQuery, parse as parseUrl } from 'url'
import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-locale-path'
import { getPathMatch } from '../../../../shared/lib/router/utils/path-match'
import { getNamedRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import {
matchHas,
prepareDestination,
} from '../../../../shared/lib/router/utils/prepare-destination'
import { acceptLanguage } from '../../../../server/accept-header'
import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie'
import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
} from '../shared/lib/router/utils/prepare-destination'
import { acceptLanguage } from './accept-header'
import { detectLocaleCookie } from '../shared/lib/i18n/detect-locale-cookie'
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { addRequestMeta } from '../../../../server/request-meta'
import { removeTrailingSlash } from '../../../../shared/lib/router/utils/remove-trailing-slash'
import { normalizeRscPath } from '../../../../shared/lib/router/utils/app-paths'
export const vercelHeader = 'x-vercel-id'
export type ServerlessHandlerCtx = {
page: string
pageModule: any
pageComponent?: any
pageConfig?: any
pageGetStaticProps?: GetStaticProps
pageGetStaticPaths?: GetStaticPaths
pageGetServerSideProps?: GetServerSideProps
appModule?: any
errorModule?: any
documentModule?: any
notFoundModule?: any
runtimeConfig: any
buildManifest?: BuildManifest
reactLoadableManifest?: any
basePath: string
rewrites: {
fallback?: Rewrite[]
afterFiles?: Rewrite[]
beforeFiles?: Rewrite[]
}
pageIsDynamic: boolean
generateEtags: boolean
distDir: string
buildId: string
escapedBuildId: string
assetPrefix: string
poweredByHeader: boolean
canonicalBase: string
encodedPreviewProps: __ApiPreviewProps
i18n?: NextConfig['i18n']
}
import { TEMPORARY_REDIRECT_STATUS } from '../shared/lib/constants'
import { addRequestMeta } from './request-meta'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { normalizeRscPath } from '../shared/lib/router/utils/app-paths'
export function normalizeVercelUrl(
req: BaseNextRequest | IncomingMessage,
......@@ -136,11 +91,15 @@ export function getUtils({
pageIsDynamic,
trailingSlash,
}: {
page: ServerlessHandlerCtx['page']
i18n?: ServerlessHandlerCtx['i18n']
basePath: ServerlessHandlerCtx['basePath']
rewrites: ServerlessHandlerCtx['rewrites']
pageIsDynamic: ServerlessHandlerCtx['pageIsDynamic']
page: string
i18n?: NextConfig['i18n']
basePath: string
rewrites: {
fallback?: Rewrite[]
afterFiles?: Rewrite[]
beforeFiles?: Rewrite[]
}
pageIsDynamic: boolean
trailingSlash?: boolean
}) {
let defaultRouteRegex: ReturnType<typeof getNamedRouteRegex> | undefined
......@@ -532,7 +491,7 @@ export function getUtils({
if (
!shouldNotRedirect &&
!req.headers[vercelHeader] &&
!req.headers['x-vercel-id'] &&
i18n.localeDetection !== false &&
(localeDomainRedirect ||
shouldAddLocalePrefix ||
......
......@@ -20,10 +20,7 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { isDynamicRoute } from '../shared/lib/router/utils'
import {
interpolateDynamicPath,
normalizeVercelUrl,
} from '../build/webpack/loaders/next-serverless-loader/utils'
import { interpolateDynamicPath, normalizeVercelUrl } from './server-utils'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { IncrementalCache } from './lib/incremental-cache'
interface WebServerOptions extends Options {
......
......@@ -259,7 +259,7 @@ export async function ncc_node_platform(task, opts) {
const clientFile = join(__dirname, 'src/compiled/platform/platform.js')
const content = fs.readFileSync(clientFile, 'utf8')
// remove AMD define branch as this forces the module to not
// be treated as commonjs in serverless/client mode
// be treated as commonjs
fs.writeFileSync(
clientFile,
content.replace(
......@@ -509,7 +509,7 @@ export async function ncc_next__react_dev_overlay(task, opts) {
)
const content = fs.readFileSync(clientFile, 'utf8')
// remove AMD define branch as this forces the module to not
// be treated as commonjs in serverless/client mode
// be treated as commonjs
fs.writeFileSync(
clientFile,
content.replace(
......
......@@ -96,18 +96,4 @@ describe('config', () => {
)
expect(config.__test__ext).toBe('js')
})
it('Should ignore configs set to `undefined`', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
target: undefined,
})
expect(config.target).toBe('server')
})
it('Should ignore configs set to `null`', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
target: null,
})
expect(config.target).toBe('server')
})
})
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