Unverified Commit 45f0c790 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Introduce NextConfigRuntime (#86812)

To only include the keys we actually at runtime in the server in `required-server-files.json` and in `.next/standalone/server.js`

There is some chance I missed some property that's needed at runtime (and is incorrectly filtered out by `getNextConfigRuntime`)
parent 6ff2d98c
......@@ -964,5 +964,6 @@
"963": "Fast setImmediate is not available in the edge runtime.",
"964": "An unexpected error occurred while starting to capture immediates",
"965": "Expected setImmediate to reject invalid arguments",
"966": "Expected process.nextTick to reject invalid arguments"
"966": "Expected process.nextTick to reject invalid arguments",
"967": "The key \"%s\" under \"env\" in %sconfig is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed"
}
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type {
ExportPathMap,
NextConfigComplete,
NextConfigRuntime,
} from '../server/config-shared'
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import type { CacheControl, Revalidate } from '../server/lib/cache-control'
......@@ -12,7 +16,7 @@ import { makeRe } from 'next/dist/compiled/picomatch'
import { existsSync, promises as fs } from 'fs'
import os from 'os'
import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared'
import { defaultConfig, getNextConfigRuntime } from '../server/config-shared'
import devalue from 'next/dist/compiled/devalue'
import findUp from 'next/dist/compiled/find-up'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
......@@ -605,7 +609,7 @@ async function writeFunctionsConfigManifest(
export interface RequiredServerFilesManifest {
version: number
config: NextConfigComplete
config: NextConfigRuntime
appDir: string
relativeAppDir: string
files: string[]
......@@ -2412,8 +2416,6 @@ export default async function build(
)
}
const { cacheHandler } = config
const instrumentationHookEntryFiles: string[] = []
if (hasInstrumentationHook) {
instrumentationHookEntryFiles.push(
......@@ -2437,10 +2439,11 @@ export default async function build(
const requiredServerFilesManifest = nextBuildSpan
.traceChild('generate-required-server-files')
.traceFn(() => {
const normalizedCacheHandlers: Record<string, string> = {}
let runtimeConfig = getNextConfigRuntime(config)
const normalizedCacheHandlers: Record<string, string> = {}
for (const [key, value] of Object.entries(
config.cacheHandlers || {}
runtimeConfig.cacheHandlers || {}
)) {
if (key && value) {
normalizedCacheHandlers[key] = path.relative(distDir, value)
......@@ -2450,19 +2453,18 @@ export default async function build(
const serverFilesManifest: RequiredServerFilesManifest = {
version: 1,
config: {
...config,
configFile: undefined,
...runtimeConfig,
...(ciEnvironment.hasNextSupport
? {
compress: false,
}
: {}),
cacheHandler: cacheHandler
? path.relative(distDir, cacheHandler)
: config.cacheHandler,
cacheHandler: runtimeConfig.cacheHandler
? path.relative(distDir, runtimeConfig.cacheHandler)
: runtimeConfig.cacheHandler,
cacheHandlers: normalizedCacheHandlers,
experimental: {
...config.experimental,
...runtimeConfig.experimental,
trustHostHeader: ciEnvironment.hasNextSupport,
isExperimentalCompile: isCompileMode,
},
......
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { NextConfigComplete } from '../../server/config-shared'
import type { NextConfigRuntime } from '../../server/config-shared'
import type { EdgeHandler } from '../../server/web/adapter'
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'
......@@ -7,7 +7,7 @@ import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapp
import * as module from 'VAR_USERLAND'
// injected by the loader afterwards.
declare const nextConfig: NextConfigComplete
declare const nextConfig: NextConfigRuntime
// INJECT:nextConfig
const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
......
......@@ -8,7 +8,7 @@ import { IncrementalCache } from '../../server/lib/incremental-cache'
import * as pageMod from 'VAR_USERLAND'
import type { NextConfigComplete } from '../../server/config-shared'
import type { NextConfigRuntime } from '../../server/config-shared'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { initializeCacheHandlers } from '../../server/use-cache/handlers'
import { BaseServerSpan } from '../../server/lib/trace/constants'
......@@ -29,7 +29,7 @@ import { checkIsOnDemandRevalidate } from '../../server/api-utils'
import { CloseController } from '../../server/web/web-on-close'
declare const incrementalCacheHandler: any
declare const nextConfig: NextConfigComplete
declare const nextConfig: NextConfigRuntime
// OPTIONAL_IMPORT:incrementalCacheHandler
// INJECT:nextConfig
......
......@@ -22,7 +22,7 @@ import RouteModule, {
} from '../../server/route-modules/pages/module'
import { WebNextRequest, WebNextResponse } from '../../server/base-http/web'
import type { NextConfigComplete } from '../../server/config-shared'
import type { NextConfigRuntime } from '../../server/config-shared'
import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'
import type RenderResult from '../../server/render-result'
import type { RenderResultMetadata } from '../../server/render-result'
......@@ -31,7 +31,7 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
// injected by the loader afterwards.
declare const nextConfig: NextConfigComplete
declare const nextConfig: NextConfigRuntime
declare const pageRouteModuleOptions: any
declare const errorRouteModuleOptions: any
declare const user500RouteModuleOptions: any
......
import type { NextConfigComplete } from '../server/config-shared'
import type {
NextConfigComplete,
NextConfigRuntime,
} from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { AssetBinding } from './webpack/loaders/get-module-build-info'
......@@ -1211,7 +1214,7 @@ export async function copyTracedFiles(
pageKeys: readonly string[],
appPageKeys: readonly string[] | undefined,
tracingRoot: string,
serverConfig: NextConfigComplete,
serverConfig: NextConfigRuntime,
middlewareManifest: MiddlewareManifest,
hasNodeMiddleware: boolean,
hasInstrumentationHook: boolean,
......
import type { NextConfigComplete } from '../server/config-shared'
import type {
NextConfigComplete,
NextConfigRuntime,
} from '../server/config-shared'
function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
function errorIfEnvConflicted(
config: NextConfigComplete | NextConfigRuntime,
key: string
) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
const hasNextRuntimeKey = key === 'NEXT_RUNTIME'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
`The key "${key}" under "env" in ${config.configFileName || 'config'} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
}
......@@ -31,7 +37,9 @@ export function getNextPublicEnvironmentVariables() {
/**
* Collects the `env` config value from the Next.js config.
*/
export function getNextConfigEnv(config: NextConfigComplete) {
export function getNextConfigEnv(
config: NextConfigComplete | NextConfigRuntime
) {
// Refactored code below to use for-of
const defineEnv: Record<string, string | undefined> = {}
const env = config.env
......@@ -45,7 +53,7 @@ export function getNextConfigEnv(config: NextConfigComplete) {
return defineEnv
}
export function getStaticEnv(config: NextConfigComplete) {
export function getStaticEnv(config: NextConfigComplete | NextConfigRuntime) {
const staticEnv: Record<string, string | undefined> = {
...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config),
......@@ -54,7 +62,9 @@ export function getStaticEnv(config: NextConfigComplete) {
return staticEnv
}
export function populateStaticEnv(config: NextConfigComplete) {
export function populateStaticEnv(
config: NextConfigComplete | NextConfigRuntime
) {
// since inlining comes after static generation we need
// to ensure this value is assigned to process env so it
// can still be accessed
......
......@@ -5,7 +5,7 @@ import type {
} from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from './request/params'
import type { NextConfig, NextConfigComplete } from './config-shared'
import type { NextConfig, NextConfigRuntime } from './config-shared'
import type {
NextParsedUrlQuery,
NextUrlWithParsedQuery,
......@@ -311,7 +311,7 @@ export default abstract class Server<
public readonly port?: number
protected readonly dir: string
protected readonly quiet: boolean
protected readonly nextConfig: NextConfigComplete
protected readonly nextConfig: NextConfigRuntime
protected readonly distDir: string
protected readonly publicDir: string
protected readonly hasStaticDir: boolean
......@@ -446,7 +446,7 @@ export default abstract class Server<
// TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigComplete
this.nextConfig = conf as NextConfigRuntime
this.hostname = hostname
if (this.hostname) {
// we format the hostname so that it can be fetched
......
......@@ -1571,3 +1571,183 @@ export async function normalizeConfig(phase: string, config: any) {
// Support `new Promise` and `async () =>` as return values of the config export
return await config
}
// This should be a supertype of NextConfigComplete
//
// The Vercel builder needs these fields (read `config` in required-server-files.json)
// {
// pageExtensions: string[];
// experimental?: {
// cacheComponents?: boolean;
// clientParamParsingOrigins?: string[];
// clientSegmentCache?: boolean;
// ppr?: boolean | 'incremental';
// serverActions?: Record<string, never>;
// };
// };
export interface NextConfigRuntime {
// TODO remove in some cases
deploymentId: NextConfigComplete['deploymentId']
configFileName?: string
// Should only be included when using isExperimentalCompile
env?: NextConfigComplete['env']
distDir: NextConfigComplete['distDir']
cacheComponents: NextConfigComplete['cacheComponents']
htmlLimitedBots: NextConfigComplete['htmlLimitedBots']
assetPrefix: NextConfigComplete['assetPrefix']
output: NextConfigComplete['output']
crossOrigin: NextConfigComplete['crossOrigin']
trailingSlash: NextConfigComplete['trailingSlash']
images: NextConfigComplete['images']
reactMaxHeadersLength: NextConfigComplete['reactMaxHeadersLength']
cacheLife: NextConfigComplete['cacheLife']
basePath: NextConfigComplete['basePath']
expireTime: NextConfigComplete['expireTime']
generateEtags: NextConfigComplete['generateEtags']
poweredByHeader: NextConfigComplete['poweredByHeader']
cacheHandler: NextConfigComplete['cacheHandler']
cacheHandlers: NextConfigComplete['cacheHandlers']
cacheMaxMemorySize: NextConfigComplete['cacheMaxMemorySize']
compress: NextConfigComplete['compress']
i18n: NextConfigComplete['i18n']
httpAgentOptions: NextConfigComplete['httpAgentOptions']
skipProxyUrlNormalize: NextConfigComplete['skipProxyUrlNormalize']
pageExtensions: NextConfigComplete['pageExtensions']
useFileSystemPublicRoutes: NextConfigComplete['useFileSystemPublicRoutes']
experimental: Pick<
NextConfigComplete['experimental'],
| 'ppr'
| 'taint'
| 'serverActions'
| 'staleTimes'
| 'dynamicOnHover'
| 'inlineCss'
| 'authInterrupts'
| 'clientTraceMetadata'
| 'clientParamParsingOrigins'
| 'adapterPath'
| 'allowedRevalidateHeaderKeys'
| 'fetchCacheKeyPrefix'
| 'isrFlushToDisk'
| 'optimizeCss'
| 'nextScriptWorkers'
| 'disableOptimizedLoading'
| 'largePageDataBytes'
| 'serverComponentsHmrCache'
| 'caseSensitiveRoutes'
| 'validateRSCRequestHeaders'
| 'sri'
| 'useSkewCookie'
| 'preloadEntriesOnStart'
| 'hideLogsAfterAbort'
| 'removeUncaughtErrorAndRejectionListeners'
| 'imgOptConcurrency'
| 'imgOptMaxInputPixels'
| 'imgOptSequentialRead'
| 'imgOptSkipMetadata'
| 'imgOptTimeoutInSeconds'
| 'proxyClientMaxBodySize'
| 'proxyTimeout'
| 'testProxy'
> & {
// Pick on @internal fields generates invalid .d.ts files
/** @internal */
trustHostHeader?: NextConfigComplete['experimental']['trustHostHeader']
/** @internal */
isExperimentalCompile?: NextConfigComplete['experimental']['isExperimentalCompile']
}
}
export function getNextConfigRuntime(
config: NextConfigComplete | NextConfigRuntime
): NextConfigRuntime {
let ex = config.experimental
type Requiredish<T> = {
[K in keyof Required<T>]: T[K]
}
let experimental = ex
? ({
ppr: ex.ppr,
taint: ex.taint,
serverActions: ex.serverActions,
staleTimes: ex.staleTimes,
dynamicOnHover: ex.dynamicOnHover,
inlineCss: ex.inlineCss,
authInterrupts: ex.authInterrupts,
clientTraceMetadata: ex.clientTraceMetadata,
clientParamParsingOrigins: ex.clientParamParsingOrigins,
adapterPath: ex.adapterPath,
allowedRevalidateHeaderKeys: ex.allowedRevalidateHeaderKeys,
fetchCacheKeyPrefix: ex.fetchCacheKeyPrefix,
isrFlushToDisk: ex.isrFlushToDisk,
optimizeCss: ex.optimizeCss,
nextScriptWorkers: ex.nextScriptWorkers,
disableOptimizedLoading: ex.disableOptimizedLoading,
largePageDataBytes: ex.largePageDataBytes,
serverComponentsHmrCache: ex.serverComponentsHmrCache,
caseSensitiveRoutes: ex.caseSensitiveRoutes,
validateRSCRequestHeaders: ex.validateRSCRequestHeaders,
sri: ex.sri,
useSkewCookie: ex.useSkewCookie,
preloadEntriesOnStart: ex.preloadEntriesOnStart,
hideLogsAfterAbort: ex.hideLogsAfterAbort,
removeUncaughtErrorAndRejectionListeners:
ex.removeUncaughtErrorAndRejectionListeners,
imgOptConcurrency: ex.imgOptConcurrency,
imgOptMaxInputPixels: ex.imgOptMaxInputPixels,
imgOptSequentialRead: ex.imgOptSequentialRead,
imgOptSkipMetadata: ex.imgOptSkipMetadata,
imgOptTimeoutInSeconds: ex.imgOptTimeoutInSeconds,
proxyClientMaxBodySize: ex.proxyClientMaxBodySize,
proxyTimeout: ex.proxyTimeout,
testProxy: ex.testProxy,
trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile,
} satisfies Requiredish<NextConfigRuntime['experimental']>)
: {}
let runtimeConfig: Requiredish<NextConfigRuntime> = {
deploymentId: config.deploymentId,
configFileName: undefined,
env: undefined,
distDir: config.distDir,
cacheComponents: config.cacheComponents,
htmlLimitedBots: config.htmlLimitedBots,
assetPrefix: config.assetPrefix,
output: config.output,
crossOrigin: config.crossOrigin,
trailingSlash: config.trailingSlash,
images: config.images,
reactMaxHeadersLength: config.reactMaxHeadersLength,
cacheLife: config.cacheLife,
basePath: config.basePath,
expireTime: config.expireTime,
generateEtags: config.generateEtags,
poweredByHeader: config.poweredByHeader,
cacheHandler: config.cacheHandler,
cacheHandlers: config.cacheHandlers,
cacheMaxMemorySize: config.cacheMaxMemorySize,
compress: config.compress,
i18n: config.i18n,
httpAgentOptions: config.httpAgentOptions,
skipProxyUrlNormalize: config.skipProxyUrlNormalize,
pageExtensions: config.pageExtensions,
useFileSystemPublicRoutes: config.useFileSystemPublicRoutes,
experimental,
}
if (config.experimental.isExperimentalCompile) {
runtimeConfig.env = config.env
}
return runtimeConfig
}
......@@ -9,6 +9,7 @@ import {
PHASE_DEVELOPMENT_SERVER,
PHASE_EXPORT,
PHASE_PRODUCTION_BUILD,
type PHASE_PRODUCTION_SERVER,
type PHASE_TYPE,
} from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared'
......@@ -16,6 +17,7 @@ import type {
ExperimentalConfig,
NextConfigComplete,
NextConfig,
NextConfigRuntime,
} from './config-shared'
import { loadWebpackHook } from './config-utils'
......@@ -1411,6 +1413,34 @@ function getCacheKey(
return djb2Hash(keyData).toString(36)
}
type LoadConfigOptions = {
customConfig?: object | null
rawConfig?: boolean
silent?: boolean
reportExperimentalFeatures?: (
configuredExperimentalFeatures: ConfiguredExperimentalFeature[]
) => void
reactProductionProfiling?: boolean
debugPrerender?: boolean
}
export default async function loadConfig(
phase: typeof PHASE_DEVELOPMENT_SERVER,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigComplete>
export default async function loadConfig(
phase: typeof PHASE_PRODUCTION_SERVER | typeof PHASE_DEVELOPMENT_SERVER,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigRuntime | NextConfigComplete>
export default async function loadConfig(
phase: PHASE_TYPE,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigComplete>
export default async function loadConfig(
phase: PHASE_TYPE,
dir: string,
......@@ -1421,16 +1451,7 @@ export default async function loadConfig(
reportExperimentalFeatures,
reactProductionProfiling,
debugPrerender,
}: {
customConfig?: object | null
rawConfig?: boolean
silent?: boolean
reportExperimentalFeatures?: (
configuredExperimentalFeatures: ConfiguredExperimentalFeature[]
) => void
reactProductionProfiling?: boolean
debugPrerender?: boolean
} = {}
}: LoadConfigOptions = {}
): Promise<NextConfigComplete> {
// Generate cache key based on parameters that affect config output
// Include process.pid to invalidate cache on server restart
......
......@@ -51,7 +51,7 @@ import {
import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'
import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error'
import { defaultConfig } from '../config-shared'
import { defaultConfig, type NextConfigComplete } from '../config-shared'
import { isMiddlewareFile } from '../../build/utils'
import { formatServerError } from '../../lib/format-server-error'
import { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'
......@@ -95,6 +95,8 @@ const ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {
}
export interface Options extends ServerOptions {
// Override type to make the full config available instead of only NextConfigRuntime
conf: NextConfigComplete
/**
* Tells of Next.js is running from the `next dev` command
*/
......@@ -112,6 +114,9 @@ export interface Options extends ServerOptions {
}
export default class DevServer extends Server {
// Override type to make the full config available instead of only NextConfigRuntime
protected readonly nextConfig: NextConfigComplete
/**
* The promise that resolves when the server is ready. When this is unset
* the server is ready.
......@@ -171,6 +176,7 @@ export default class DevServer extends Server {
Error.stackTraceLimit = 50
} catch {}
super({ ...options, dev: true })
this.nextConfig = options.conf
this.bundlerService = options.bundlerService
this.startServerSpan =
options.startServerSpan ?? trace('start-next-dev-server')
......
......@@ -13,7 +13,7 @@ import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import { hasLocalMatch } from '../shared/lib/match-local-pattern'
import { hasRemoteMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete } from './config-shared'
import type { NextConfigComplete, NextConfigRuntime } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request'
import type { NextUrlWithParsedQuery } from './request-meta'
import {
......@@ -314,12 +314,12 @@ export async function detectContentType(
export class ImageOptimizerCache {
private cacheDir: string
private nextConfig: NextConfigComplete
private nextConfig: NextConfigRuntime
static validateParams(
req: IncomingMessage,
query: UrlWithParsedQuery['query'],
nextConfig: NextConfigComplete,
nextConfig: NextConfigRuntime,
isDev: boolean
): ImageParamsResult | { errorMessage: string } {
const imageData = nextConfig.images
......@@ -497,7 +497,7 @@ export class ImageOptimizerCache {
nextConfig,
}: {
distDir: string
nextConfig: NextConfigComplete
nextConfig: NextConfigRuntime
}) {
this.cacheDir = join(/* turbopackIgnore: true */ distDir, 'cache', 'images')
this.nextConfig = nextConfig
......
import type { ServerResponse } from 'http'
import type { NextConfigComplete } from '../config-shared'
import type { NextConfigRuntime } from '../config-shared'
import { randomUUID } from 'crypto'
import * as fs from 'fs'
......@@ -18,7 +18,7 @@ export function isChromeDevtoolsWorkspaceUrl(
export async function handleChromeDevtoolsWorkspaceRequest(
response: ServerResponse,
opts: { dir: string },
config: NextConfigComplete
config: NextConfigRuntime
): Promise<void> {
response.setHeader('Content-Type', 'application/json')
response.end(
......
......@@ -59,6 +59,7 @@ import {
handleChromeDevtoolsWorkspaceRequest,
isChromeDevtoolsWorkspaceUrl,
} from './chrome-devtools-workspace'
import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'
const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) =>
......@@ -118,9 +119,13 @@ export async function initialize(opts: {
const renderServer: LazyRenderServerInstance = {}
let developmentBundler: DevBundler | undefined
let devBundlerService: DevBundlerService | undefined
let development:
| {
bundler: DevBundler
service: DevBundlerService
config: NextConfigComplete
}
| undefined = undefined
let originalFetch = globalThis.fetch
......@@ -146,7 +151,11 @@ export async function initialize(opts: {
const setupDevBundlerSpan = opts.startServerSpan
? opts.startServerSpan.traceChild('setup-dev-bundler')
: trace('setup-dev-bundler')
developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>
// In development, it's always the complete config.
let developmentConfig = config as NextConfigComplete
let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>
setupDevBundler({
// Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.
renderServer,
......@@ -155,7 +164,7 @@ export async function initialize(opts: {
telemetry,
fsChecker,
dir: opts.dir,
nextConfig: config,
nextConfig: developmentConfig,
isCustomServer: opts.customServer,
turbo: !!process.env.TURBOPACK,
port: opts.port,
......@@ -164,7 +173,7 @@ export async function initialize(opts: {
})
)
devBundlerService = new DevBundlerService(
let devBundlerService = new DevBundlerService(
developmentBundler,
// The request handler is assigned below, this allows us to create a lazy
// reference to it.
......@@ -172,6 +181,12 @@ export async function initialize(opts: {
return requestHandlers[opts.dir](req, res)
}
)
development = {
bundler: developmentBundler,
service: devBundlerService,
config: developmentConfig,
}
}
renderServer.instance =
......@@ -328,8 +343,15 @@ export async function initialize(opts: {
}
// handle hot-reloader first
if (developmentBundler) {
if (blockCrossSite(req, res, config.allowedDevOrigins, opts.hostname)) {
if (development) {
if (
blockCrossSite(
req,
res,
development.config.allowedDevOrigins,
opts.hostname
)
) {
return
}
......@@ -348,7 +370,7 @@ export async function initialize(opts: {
const parsedUrl = url.parse(req.url || '/')
const hotReloaderResult = await developmentBundler.hotReloader.run(
const hotReloaderResult = await development.bundler.hotReloader.run(
req,
res,
parsedUrl
......@@ -380,7 +402,7 @@ export async function initialize(opts: {
return
}
if (developmentBundler && matchedOutput?.type === 'devVirtualFsItem') {
if (development && matchedOutput?.type === 'devVirtualFsItem') {
const origUrl = req.url || '/'
if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {
......@@ -397,7 +419,7 @@ export async function initialize(opts: {
res.setHeader(key, resHeaders[key])
}
}
const result = await developmentBundler.requestHandler(req, res)
const result = await development.bundler.requestHandler(req, res)
if (result.finished) {
return
......@@ -576,7 +598,7 @@ export async function initialize(opts: {
}
// We want the original pathname without any basePath or proxy rewrites.
if (opts.dev && isChromeDevtoolsWorkspaceUrl(req.url)) {
if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {
await handleChromeDevtoolsWorkspaceRequest(res, opts, config)
return
}
......@@ -625,7 +647,7 @@ export async function initialize(opts: {
}
const appNotFound = opts.dev
? developmentBundler?.serverFields.hasAppNotFound
? development?.bundler?.serverFields.hasAppNotFound
: await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)
res.statusCode = 404
......@@ -692,12 +714,14 @@ export async function initialize(opts: {
dev: !!opts.dev,
server: opts.server,
serverFields: {
...(developmentBundler?.serverFields || {}),
setIsrStatus: devBundlerService?.setIsrStatus.bind(devBundlerService),
...(development?.bundler?.serverFields || {}),
setIsrStatus: development?.service?.setIsrStatus.bind(
development?.service
),
} satisfies ServerFields,
experimentalTestProxy: !!config.experimental.testProxy,
experimentalHttpsServer: !!opts.experimentalHttpsServer,
bundlerService: devBundlerService,
bundlerService: development?.service,
startServerSpan: opts.startServerSpan,
quiet: opts.quiet,
onDevServerCleanup: opts.onDevServerCleanup,
......@@ -715,7 +739,7 @@ export async function initialize(opts: {
const relativeProjectDir = path.relative(process.cwd(), opts.dir)
routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {
nextConfig: config,
nextConfig: getNextConfigRuntime(config),
hostname: handlers.server.hostname,
revalidate: handlers.server.revalidate.bind(handlers.server),
render404: handlers.server.render404.bind(handlers.server),
......@@ -724,14 +748,15 @@ export async function initialize(opts: {
? handlers.server.logErrorWithOriginalStack.bind(handlers.server)
: (err: unknown) => !opts.quiet && Log.error(err),
setCacheStatus: config.cacheComponents
? devBundlerService?.setCacheStatus.bind(devBundlerService)
? development?.service?.setCacheStatus.bind(development?.service)
: undefined,
setIsrStatus: devBundlerService?.setIsrStatus.bind(devBundlerService),
setReactDebugChannel: config.experimental.reactDebugChannel
? devBundlerService?.setReactDebugChannel.bind(devBundlerService)
setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),
setReactDebugChannel: development?.config.experimental.reactDebugChannel
? development?.service?.setReactDebugChannel.bind(development?.service)
: undefined,
sendErrorsToBrowser:
devBundlerService?.sendErrorsToBrowser.bind(devBundlerService),
sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(
development?.service
),
}
const logError = async (
......@@ -759,7 +784,7 @@ export async function initialize(opts: {
opts,
renderServer.instance,
renderServerOpts,
developmentBundler?.ensureMiddleware
development?.bundler?.ensureMiddleware
)
const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {
......@@ -773,9 +798,14 @@ export async function initialize(opts: {
// console.error(_err);
})
if (opts.dev && developmentBundler && req.url) {
if (opts.dev && development && req.url) {
if (
blockCrossSite(req, socket, config.allowedDevOrigins, opts.hostname)
blockCrossSite(
req,
socket,
development.config.allowedDevOrigins,
opts.hostname
)
) {
return
}
......@@ -802,7 +832,7 @@ export async function initialize(opts: {
// only handle HMR requests if the basePath in the request
// matches the basePath for the handler responding to the request
if (isHMRRequest) {
return developmentBundler.hotReloader.onHMR(
return development.bundler.hotReloader.onHMR(
req,
socket,
head,
......@@ -818,7 +848,7 @@ export async function initialize(opts: {
client.send(
JSON.stringify({
type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,
data: devBundlerService?.appIsrManifest || {},
data: development.service?.appIsrManifest || {},
} satisfies AppIsrManifestMessage)
)
}
......@@ -864,7 +894,7 @@ export async function initialize(opts: {
upgradeHandler,
server: handlers.server,
closeUpgraded() {
developmentBundler?.hotReloader?.close()
development?.bundler?.hotReloader?.close()
},
}
}
......@@ -4,7 +4,7 @@ import type {
PrerenderManifest,
RoutesManifest,
} from '../../../build'
import type { NextConfigComplete } from '../../config-shared'
import type { NextConfigRuntime } from '../../config-shared'
import type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'
import type { UnwrapPromise } from '../../../lib/coalesced-function'
import type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'
......@@ -109,7 +109,7 @@ export async function setupFsCheck(opts: {
dir: string
dev: boolean
minimalMode?: boolean
config: NextConfigComplete
config: NextConfigRuntime
}) {
const getItemsLru = !opts.dev
? new LRUCache<FsOutput | null>(1024 * 1024, function length(value) {
......
import type { FsOutput } from './filesystem'
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextConfigComplete } from '../../config-shared'
import type { NextConfigRuntime } from '../../config-shared'
import type { RenderServer, initialize } from '../router-server'
import type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'
import type { Redirect } from '../../../types'
......@@ -51,7 +51,7 @@ export function getResolveRoutes(
fsChecker: UnwrapPromise<
ReturnType<typeof import('./filesystem').setupFsCheck>
>,
config: NextConfigComplete,
config: NextConfigRuntime,
opts: Parameters<typeof initialize>[0],
renderServer: RenderServer,
renderServerOpts: Parameters<RenderServer['initialize']>[0],
......
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { NextConfigComplete } from '../../config-shared'
import type { NextConfigRuntime } from '../../config-shared'
import type { UrlWithParsedQuery } from 'node:url'
import type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache-indicator'
......@@ -30,7 +30,7 @@ export type RouterServerContext = Record<
setHeaders?: boolean
) => Promise<void>
// exposing nextConfig for dev mode specifically
nextConfig?: NextConfigComplete
nextConfig?: NextConfigRuntime
// whether running in custom server mode
isCustomServer?: boolean
// whether test proxy is enabled
......
......@@ -3,12 +3,13 @@
* an extension itself but it exposes a function to install config based global
* behaviors that should be loaded whenever a Node Server or Node Worker are created.
*/
import type { NextConfigComplete } from '../config-shared'
import { InvariantError } from '../../shared/lib/invariant-error'
import { setAbortedLogsStyle } from './console-dim.external'
export function installGlobalBehaviors(config: NextConfigComplete) {
export function installGlobalBehaviors(config: {
experimental?: { hideLogsAfterAbort?: boolean }
}) {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'Expected not to install Node.js global behaviors in the edge runtime.'
......
......@@ -50,7 +50,7 @@ import { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'
import { interopDefault } from '../app-render/interop-default'
import { RouteKind } from '../route-kind'
import type { BaseNextRequest } from '../base-http'
import type { I18NConfig, NextConfigComplete } from '../config-shared'
import type { I18NConfig, NextConfigRuntime } from '../config-shared'
import ResponseCache, { type ResponseGenerator } from '../response-cache'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import {
......@@ -378,7 +378,7 @@ export abstract class RouteModule<
public async loadCustomCacheHandlers(
req: IncomingMessage | BaseNextRequest,
nextConfig: NextConfigComplete
nextConfig: NextConfigRuntime
) {
if (process.env.NEXT_RUNTIME !== 'edge') {
const { cacheMaxMemorySize, cacheHandlers } = nextConfig
......@@ -418,7 +418,7 @@ export abstract class RouteModule<
public async getIncrementalCache(
req: IncomingMessage | BaseNextRequest,
nextConfig: NextConfigComplete,
nextConfig: NextConfigRuntime,
prerenderManifest: DeepReadonly<PrerenderManifest>,
isMinimalMode: boolean
): Promise<IncrementalCache> {
......@@ -542,7 +542,7 @@ export abstract class RouteModule<
subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>
isOnDemandRevalidate: boolean
revalidateOnlyGenerated: boolean
nextConfig: NextConfigComplete
nextConfig: NextConfigRuntime
routerServerContext?: RouterServerContext[string]
interceptionRoutePatterns?: any
}
......@@ -923,7 +923,7 @@ export abstract class RouteModule<
isMinimalMode,
}: {
req: IncomingMessage | BaseNextRequest
nextConfig: NextConfigComplete
nextConfig: NextConfigRuntime
cacheKey: string | null
routeKind: RouteKind
isFallback?: boolean
......
......@@ -15,10 +15,10 @@ import { getServerUtils } from '../server-utils'
import { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring'
import { CloseController, trackStreamConsumed } from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props'
import type { NextConfigComplete } from '../config-shared'
import type { NextConfigRuntime } from '../config-shared'
export interface WrapOptions {
nextConfig: NextConfigComplete
nextConfig: NextConfigRuntime
page: string
}
......@@ -38,7 +38,7 @@ export class EdgeRouteModuleWrapper {
*/
private constructor(
private readonly routeModule: AppRouteRouteModule,
private readonly nextConfig: NextConfigComplete
private readonly nextConfig: NextConfigRuntime
) {
// TODO: (wyattjoh) possibly allow the module to define it's own matcher
this.matcher = new RouteMatcher(routeModule.definition)
......
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