Unverified Commit 1c1a4de0 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Refactor base server to remove native dependencies (#33499)

Part of #31506, this PR removes `loadEnvConfig` and `chalk` from the base server while keeping the same behavior for the node server.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `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`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent c879fce0
...@@ -4,7 +4,7 @@ import { stringify } from 'querystring' ...@@ -4,7 +4,7 @@ import { stringify } from 'querystring'
import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants' import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants'
import { MIDDLEWARE_ROUTE } from '../lib/constants' import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
import { isTargetLikeServerless } from '../server/config' import { isTargetLikeServerless } from '../server/utils'
import { normalizePagePath } from '../server/normalize-page-path' import { normalizePagePath } from '../server/normalize-page-path'
import { warn } from './output/log' import { warn } from './output/log'
import { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' import { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader'
......
...@@ -57,7 +57,8 @@ import { ...@@ -57,7 +57,8 @@ import {
isDynamicRoute, isDynamicRoute,
} from '../shared/lib/router/utils' } from '../shared/lib/router/utils'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
import loadConfig, { isTargetLikeServerless } from '../server/config' import loadConfig from '../server/config'
import { isTargetLikeServerless } from '../server/utils'
import { BuildManifest } from '../server/get-page-files' import { BuildManifest } from '../server/get-page-files'
import { normalizePagePath } from '../server/normalize-page-path' import { normalizePagePath } from '../server/normalize-page-path'
import { getPagePath } from '../server/require' import { getPagePath } from '../server/require'
......
import chalk from 'next/dist/compiled/chalk' import chalk from '../../lib/chalk'
export const prefixes = { export const prefixes = {
wait: chalk.cyan('wait') + ' -', wait: chalk.cyan('wait') + ' -',
......
import { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { Rewrite } from '../../../../lib/load-custom-routes'
import type { BuildManifest } from '../../../../server/get-page-files'
import type { NextConfig } from '../../../../server/config'
import type {
GetServerSideProps,
GetStaticPaths,
GetStaticProps,
} from '../../../../types'
import { format as formatUrl, UrlWithParsedQuery, parse as parseUrl } from 'url' import { format as formatUrl, UrlWithParsedQuery, parse as parseUrl } from 'url'
import { parse as parseQs, ParsedUrlQuery } from 'querystring' import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-locale-path'
import pathMatch from '../../../../shared/lib/router/utils/path-match' import pathMatch from '../../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
...@@ -11,19 +19,12 @@ import { ...@@ -11,19 +19,12 @@ import {
prepareDestination, prepareDestination,
} from '../../../../shared/lib/router/utils/prepare-destination' } from '../../../../shared/lib/router/utils/prepare-destination'
import { __ApiPreviewProps } from '../../../../server/api-utils' import { __ApiPreviewProps } from '../../../../server/api-utils'
import { BuildManifest } from '../../../../server/get-page-files'
import {
GetServerSideProps,
GetStaticPaths,
GetStaticProps,
} from '../../../../types'
import { acceptLanguage } from '../../../../server/accept-header' import { acceptLanguage } from '../../../../server/accept-header'
import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie' import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie'
import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale'
import { denormalizePagePath } from '../../../../server/denormalize-page-path' import { denormalizePagePath } from '../../../../server/denormalize-page-path'
import cookie from 'next/dist/compiled/cookie' import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants' import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta' import { addRequestMeta } from '../../../../server/request-meta'
import { BaseNextRequest } from '../../../../server/base-http' import { BaseNextRequest } from '../../../../server/base-http'
......
...@@ -28,7 +28,8 @@ import { ...@@ -28,7 +28,8 @@ import {
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
SERVER_DIRECTORY, SERVER_DIRECTORY,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import loadConfig, { isTargetLikeServerless } from '../server/config' import loadConfig from '../server/config'
import { isTargetLikeServerless } from '../server/utils'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import { eventCliSession } from '../telemetry/events' import { eventCliSession } from '../telemetry/events'
import { hasNextSupport } from '../telemetry/ci-info' import { hasNextSupport } from '../telemetry/ci-info'
......
let chalk: typeof import('next/dist/compiled/chalk')
if (typeof window === 'undefined') {
chalk = require('next/dist/compiled/chalk')
} else {
chalk = require('./web/chalk').default
}
export default chalk
import type { NextConfig } from '../server/config' import type { NextConfig } from '../server/config'
import chalk from 'next/dist/compiled/chalk' import chalk from './chalk'
import { parse as parseUrl } from 'url' import { parse as parseUrl } from 'url'
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp' import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
import { escapeStringRegexp } from '../shared/lib/escape-regexp' import { escapeStringRegexp } from '../shared/lib/escape-regexp'
......
// In the web runtime, we create an alternative object that just outputs the
// message to the console without any styling. The same APIs are supported
// for compatibility:
// - chalk.red('error')
// - chalk.bold.cyan('message')
// - chalk.hex('#fff').underline('hello')
const log = console.log
const chalk: any = new Proxy(log, {
get(_, prop: string) {
if (
['hex', 'rgb', 'ansi256', 'bgHex', 'bgRgb', 'bgAnsi256'].includes(prop)
) {
return () => chalk
}
return chalk
},
})
export default chalk
import { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import { parse } from 'next/dist/compiled/content-type' import { parse } from 'next/dist/compiled/content-type'
import { CookieSerializeOptions } from 'next/dist/compiled/cookie' import { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import getRawBody from 'next/dist/compiled/raw-body'
import { PageConfig, PreviewData } from 'next/types' import { PageConfig, PreviewData } from 'next/types'
import { Stream } from 'stream' import { Stream } from 'stream'
import { isResSent, NextApiRequest, NextApiResponse } from '../shared/lib/utils' import { isResSent, NextApiRequest, NextApiResponse } from '../shared/lib/utils'
...@@ -157,6 +157,8 @@ export async function parseBody( ...@@ -157,6 +157,8 @@ export async function parseBody(
let buffer let buffer
try { try {
const getRawBody =
require('next/dist/compiled/raw-body') as typeof import('next/dist/compiled/raw-body')
buffer = await getRawBody(req, { encoding, limit }) buffer = await getRawBody(req, { encoding, limit })
} catch (e) { } catch (e) {
if (isError(e) && e.type === 'entity.too.large') { if (isError(e) && e.type === 'entity.too.large') {
......
import type { ServerResponse, IncomingMessage, IncomingHttpHeaders } from 'http' import type { ServerResponse, IncomingMessage, IncomingHttpHeaders } from 'http'
import type { Writable, Readable } from 'stream' import type { Writable, Readable } from 'stream'
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants' import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import { import {
getCookieParser, getCookieParser,
......
...@@ -43,7 +43,7 @@ import { ...@@ -43,7 +43,7 @@ import {
import * as envConfig from '../shared/lib/runtime-config' import * as envConfig from '../shared/lib/runtime-config'
import { DecodeError, normalizeRepeatedSlashes } from '../shared/lib/utils' import { DecodeError, normalizeRepeatedSlashes } from '../shared/lib/utils'
import { setLazyProp, getCookieParser, tryGetPreviewData } from './api-utils' import { setLazyProp, getCookieParser, tryGetPreviewData } from './api-utils'
import { isTargetLikeServerless } from './config' import { isTargetLikeServerless } from './utils'
import pathMatch from '../shared/lib/router/utils/path-match' import pathMatch from '../shared/lib/router/utils/path-match'
import Router, { replaceBasePath, route } from './router' import Router, { replaceBasePath, route } from './router'
import { import {
...@@ -55,7 +55,6 @@ import { IncrementalCache } from './incremental-cache' ...@@ -55,7 +55,6 @@ import { IncrementalCache } from './incremental-cache'
import { execOnce } from '../shared/lib/utils' import { execOnce } from '../shared/lib/utils'
import { isBlockedPage, isBot } from './utils' import { isBlockedPage, isBot } from './utils'
import RenderResult from './render-result' import RenderResult from './render-result'
import { loadEnvConfig } from '@next/env'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { denormalizePagePath } from './denormalize-page-path' import { denormalizePagePath } from './denormalize-page-path'
...@@ -274,6 +273,8 @@ export default abstract class Server { ...@@ -274,6 +273,8 @@ export default abstract class Server {
onWarning?: (warning: Error) => void onWarning?: (warning: Error) => void
}): Promise<FetchEventResult | null> }): Promise<FetchEventResult | null>
protected abstract loadEnvConfig(params: { dev: boolean }): void
public constructor({ public constructor({
dir = '.', dir = '.',
quiet = false, quiet = false,
...@@ -286,7 +287,7 @@ export default abstract class Server { ...@@ -286,7 +287,7 @@ export default abstract class Server {
}: Options) { }: Options) {
this.dir = resolve(dir) this.dir = resolve(dir)
this.quiet = quiet this.quiet = quiet
loadEnvConfig(this.dir, dev, Log) this.loadEnvConfig({ dev })
// TODO: should conf be normalized to prevent missing // TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided // values from causing issues as this can be user provided
...@@ -376,22 +377,6 @@ export default abstract class Server { ...@@ -376,22 +377,6 @@ export default abstract class Server {
flushToDisk: !minimalMode && this.nextConfig.experimental.isrFlushToDisk, flushToDisk: !minimalMode && this.nextConfig.experimental.isrFlushToDisk,
}) })
this.responseCache = new ResponseCache(this.incrementalCache) this.responseCache = new ResponseCache(this.incrementalCache)
/**
* 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
* `process.env.__NEXT_OPTIMIZE_IMAGES`.
* TODO(atcastle@): Remove this when experimental.optimizeImages are being cleaned up.
*/
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (this.renderOpts.optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
} }
public logError(err: Error): void { public logError(err: Error): void {
......
import chalk from 'next/dist/compiled/chalk' import chalk from '../lib/chalk'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { basename, extname, relative, isAbsolute, resolve } from 'path' import { basename, extname, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url' import { pathToFileURL } from 'url'
...@@ -656,12 +656,6 @@ export default async function loadConfig( ...@@ -656,12 +656,6 @@ export default async function loadConfig(
return completeConfig return completeConfig
} }
export function isTargetLikeServerless(target: string) {
const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
return isServerless || isServerlessTrace
}
export function setHttpAgentOptions( export function setHttpAgentOptions(
options: NextConfigComplete['httpAgentOptions'] options: NextConfigComplete['httpAgentOptions']
) { ) {
......
import { join, sep as pathSeparator, normalize } from 'path' import { join, sep as pathSeparator, normalize } from 'path'
import chalk from 'next/dist/compiled/chalk' import chalk from '../../lib/chalk'
import { warn } from '../../build/output/log' import { warn } from '../../build/output/log'
import { promises } from 'fs' import { promises } from 'fs'
import { denormalizePagePath } from '../normalize-page-path' import { denormalizePagePath } from '../normalize-page-path'
......
import type { Params, Route } from './router' import type { Params, Route } from './router'
import { CacheFs, execOnce } from '../shared/lib/utils' import type { CacheFs } from '../shared/lib/utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types'
import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url'
import { execOnce } from '../shared/lib/utils'
import { import {
addRequestMeta, addRequestMeta,
getRequestMeta, getRequestMeta,
NextParsedUrlQuery, NextParsedUrlQuery,
NextUrlWithParsedQuery, NextUrlWithParsedQuery,
} from './request-meta' } from './request-meta'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types'
import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url'
import fs from 'fs' import fs from 'fs'
import { join, relative, resolve, sep } from 'path' import { join, relative, resolve, sep } from 'path'
...@@ -46,6 +48,7 @@ import { ParsedUrl } from '../shared/lib/router/utils/parse-url' ...@@ -46,6 +48,7 @@ import { ParsedUrl } from '../shared/lib/router/utils/parse-url'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import BaseServer, { import BaseServer, {
Options,
FindComponentsResult, FindComponentsResult,
prepareServerlessUrl, prepareServerlessUrl,
stringifyQuery, stringifyQuery,
...@@ -62,6 +65,7 @@ import { prepareDestination } from '../shared/lib/router/utils/prepare-destinati ...@@ -62,6 +65,7 @@ import { prepareDestination } from '../shared/lib/router/utils/prepare-destinati
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getMiddlewareRegex, getRouteMatcher } from '../shared/lib/router/utils' import { getMiddlewareRegex, getRouteMatcher } from '../shared/lib/router/utils'
import { MIDDLEWARE_ROUTE } from '../lib/constants' import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { loadEnvConfig } from '@next/env'
export * from './base-server' export * from './base-server'
...@@ -80,11 +84,34 @@ export interface NodeRequestHandler { ...@@ -80,11 +84,34 @@ export interface NodeRequestHandler {
} }
export default class NextNodeServer extends BaseServer { export default class NextNodeServer extends BaseServer {
constructor(options: Options) {
super(options)
/**
* 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
* `process.env.__NEXT_OPTIMIZE_IMAGES`.
* TODO(atcastle@): Remove this when experimental.optimizeImages are being cleaned up.
*/
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (this.renderOpts.optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
}
private compression = private compression =
this.nextConfig.compress && this.nextConfig.target === 'server' this.nextConfig.compress && this.nextConfig.target === 'server'
? (compression() as ExpressMiddleware) ? (compression() as ExpressMiddleware)
: undefined : undefined
protected loadEnvConfig({ dev }: { dev: boolean }) {
loadEnvConfig(this.dir, dev, Log)
}
protected getHasStaticDir(): boolean { protected getHasStaticDir(): boolean {
return fs.existsSync(join(this.dir, 'static')) return fs.existsSync(join(this.dir, 'static'))
} }
......
import { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { BaseNextResponse } from './base-http'
import { isResSent } from '../shared/lib/utils' import { isResSent } from '../shared/lib/utils'
import generateETag from 'next/dist/compiled/etag' import generateETag from 'next/dist/compiled/etag'
import fresh from 'next/dist/compiled/fresh' import fresh from 'next/dist/compiled/fresh'
import RenderResult from './render-result' import RenderResult from './render-result'
import { BaseNextResponse } from './base-http'
export type PayloadOptions = export type PayloadOptions =
| { private: true } | { private: true }
......
...@@ -20,3 +20,9 @@ export function isBot(userAgent: string): boolean { ...@@ -20,3 +20,9 @@ export function isBot(userAgent: string): boolean {
userAgent userAgent
) )
} }
export function isTargetLikeServerless(target: string) {
const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
return isServerless || isServerlessTrace
}
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