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