Unverified Commit 1398de99 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Revert "Revert "Separate routing code from render servers (#52492)"" (#53029)

Reverts vercel/next.js#53016
parent 552bca46
use std::io::Write;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::indexmap;
use indoc::writedoc;
use next_core::{ use next_core::{
create_page_loader_entry_module, get_asset_path_from_pathname, create_page_loader_entry_module, get_asset_path_from_pathname,
mode::NextMode, mode::NextMode,
...@@ -20,10 +24,15 @@ use next_core::{ ...@@ -20,10 +24,15 @@ use next_core::{
}; };
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbopack_binding::{ use turbopack_binding::{
turbo::{tasks::Value, tasks_env::ProcessEnv, tasks_fs::FileSystemPath}, turbo::{
tasks::Value,
tasks_env::ProcessEnv,
tasks_fs::{rope::RopeBuilder, File, FileSystemPath},
},
turbopack::{ turbopack::{
build::BuildChunkingContext, build::BuildChunkingContext,
core::{ core::{
asset::AssetContent,
chunk::{ChunkableModule, ChunkingContext, EvaluatableAssets}, chunk::{ChunkableModule, ChunkingContext, EvaluatableAssets},
compile_time_info::CompileTimeInfo, compile_time_info::CompileTimeInfo,
context::AssetContext, context::AssetContext,
...@@ -31,6 +40,7 @@ use turbopack_binding::{ ...@@ -31,6 +40,7 @@ use turbopack_binding::{
output::OutputAsset, output::OutputAsset,
reference_type::{EntryReferenceSubType, ReferenceType}, reference_type::{EntryReferenceSubType, ReferenceType},
source::Source, source::Source,
virtual_source::VirtualSource,
}, },
ecmascript::{ ecmascript::{
chunk::{EcmascriptChunkPlaceable, EcmascriptChunkingContext}, chunk::{EcmascriptChunkPlaceable, EcmascriptChunkingContext},
...@@ -191,6 +201,8 @@ async fn get_page_entries_for_root_directory( ...@@ -191,6 +201,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(app.project_path)), Vc::upcast(FileSource::new(app.project_path)),
next_router_root, next_router_root,
app.next_router_path, app.next_router_path,
app.original_path,
PathType::Page,
)); ));
// This only makes sense on the server. // This only makes sense on the server.
...@@ -201,6 +213,8 @@ async fn get_page_entries_for_root_directory( ...@@ -201,6 +213,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(document.project_path)), Vc::upcast(FileSource::new(document.project_path)),
next_router_root, next_router_root,
document.next_router_path, document.next_router_path,
document.original_path,
PathType::Page,
)); ));
// This only makes sense on both the client and the server, but they should map // This only makes sense on both the client and the server, but they should map
...@@ -212,6 +226,8 @@ async fn get_page_entries_for_root_directory( ...@@ -212,6 +226,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(error.project_path)), Vc::upcast(FileSource::new(error.project_path)),
next_router_root, next_router_root,
error.next_router_path, error.next_router_path,
error.original_path,
PathType::Page,
)); ));
if let Some(api) = api { if let Some(api) = api {
...@@ -221,6 +237,7 @@ async fn get_page_entries_for_root_directory( ...@@ -221,6 +237,7 @@ async fn get_page_entries_for_root_directory(
api, api,
next_router_root, next_router_root,
&mut entries, &mut entries,
PathType::PagesAPI,
) )
.await?; .await?;
} }
...@@ -232,6 +249,7 @@ async fn get_page_entries_for_root_directory( ...@@ -232,6 +249,7 @@ async fn get_page_entries_for_root_directory(
pages, pages,
next_router_root, next_router_root,
&mut entries, &mut entries,
PathType::Page,
) )
.await?; .await?;
} }
...@@ -246,6 +264,7 @@ async fn get_page_entries_for_directory( ...@@ -246,6 +264,7 @@ async fn get_page_entries_for_directory(
pages_structure: Vc<PagesDirectoryStructure>, pages_structure: Vc<PagesDirectoryStructure>,
next_router_root: Vc<FileSystemPath>, next_router_root: Vc<FileSystemPath>,
entries: &mut Vec<Vc<PageEntry>>, entries: &mut Vec<Vc<PageEntry>>,
path_type: PathType,
) -> Result<()> { ) -> Result<()> {
let PagesDirectoryStructure { let PagesDirectoryStructure {
ref items, ref items,
...@@ -257,7 +276,7 @@ async fn get_page_entries_for_directory( ...@@ -257,7 +276,7 @@ async fn get_page_entries_for_directory(
let PagesStructureItem { let PagesStructureItem {
project_path, project_path,
next_router_path, next_router_path,
original_path: _, original_path,
} = *item.await?; } = *item.await?;
entries.push(get_page_entry_for_file( entries.push(get_page_entry_for_file(
ssr_module_context, ssr_module_context,
...@@ -265,6 +284,8 @@ async fn get_page_entries_for_directory( ...@@ -265,6 +284,8 @@ async fn get_page_entries_for_directory(
Vc::upcast(FileSource::new(project_path)), Vc::upcast(FileSource::new(project_path)),
next_router_root, next_router_root,
next_router_path, next_router_path,
original_path,
path_type,
)); ));
} }
...@@ -275,6 +296,7 @@ async fn get_page_entries_for_directory( ...@@ -275,6 +296,7 @@ async fn get_page_entries_for_directory(
*child, *child,
next_router_root, next_router_root,
entries, entries,
path_type,
) )
.await?; .await?;
} }
...@@ -300,13 +322,129 @@ async fn get_page_entry_for_file( ...@@ -300,13 +322,129 @@ async fn get_page_entry_for_file(
source: Vc<Box<dyn Source>>, source: Vc<Box<dyn Source>>,
next_router_root: Vc<FileSystemPath>, next_router_root: Vc<FileSystemPath>,
next_router_path: Vc<FileSystemPath>, next_router_path: Vc<FileSystemPath>,
next_original_path: Vc<FileSystemPath>,
path_type: PathType,
) -> Result<Vc<PageEntry>> { ) -> Result<Vc<PageEntry>> {
let reference_type = Value::new(ReferenceType::Entry(EntryReferenceSubType::Page)); let reference_type = Value::new(ReferenceType::Entry(match path_type {
PathType::Page => EntryReferenceSubType::Page,
PathType::PagesAPI => EntryReferenceSubType::PagesApi,
_ => bail!("Invalid path type"),
}));
let pathname = pathname_for_path(next_router_root, next_router_path, path_type);
let pathname = pathname_for_path(next_router_root, next_router_path, PathType::Page); let definition_page = format!("/{}", next_original_path.await?);
let definition_pathname = pathname.await?;
let ssr_module = ssr_module_context.process(source, reference_type.clone()); let ssr_module = ssr_module_context.process(source, reference_type.clone());
let mut result = RopeBuilder::default();
match path_type {
PathType::Page => {
// Sourced from https://github.com/vercel/next.js/blob/2848ce51d1552633119c89ab49ff7fe2e4e91c91/packages/next/src/build/webpack/loaders/next-route-loader/index.ts
writedoc!(
result,
r#"
import RouteModule from "next/dist/server/future/route-modules/pages/module"
import {{ hoist }} from "next/dist/build/webpack/loaders/next-route-loader/helpers"
import Document from "@vercel/turbopack-next/pages/_document"
import App from "@vercel/turbopack-next/pages/_app"
import * as userland from "INNER"
export default hoist(userland, "default")
export const getStaticProps = hoist(userland, "getStaticProps")
export const getStaticPaths = hoist(userland, "getStaticPaths")
export const getServerSideProps = hoist(userland, "getServerSideProps")
export const config = hoist(userland, "config")
export const reportWebVitals = hoist(userland, "reportWebVitals")
export const unstable_getStaticProps = hoist(userland, "unstable_getStaticProps")
export const unstable_getStaticPaths = hoist(userland, "unstable_getStaticPaths")
export const unstable_getStaticParams = hoist(userland, "unstable_getStaticParams")
export const unstable_getServerProps = hoist(userland, "unstable_getServerProps")
export const unstable_getServerSideProps = hoist(userland, "unstable_getServerSideProps")
export const routeModule = new RouteModule({{
definition: {{
kind: "PAGES",
page: "{definition_page}",
pathname: "{definition_pathname}",
// The following aren't used in production, but are
// required for the RouteModule constructor.
bundlePath: "",
filename: "",
}},
components: {{
App,
Document,
}},
userland,
}})
"#
)?;
// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
if definition_page == "/instrumentation" || definition_page == "/src/instrumentation" {
writeln!(
result,
r#"export const register = hoist(userland, "register")"#
)?;
}
}
PathType::PagesAPI => {
// Sourced from https://github.com/vercel/next.js/blob/2848ce51d1552633119c89ab49ff7fe2e4e91c91/packages/next/src/build/webpack/loaders/next-route-loader/index.ts
writedoc!(
result,
r#"
import RouteModule from "next/dist/server/future/route-modules/pages-api/module"
import {{ hoist }} from "next/dist/build/webpack/loaders/next-route-loader/helpers"
import * as userland from "INNER"
export default hoist(userland, "default")
export const config = hoist(userland, "config")
export const routeModule = new RouteModule({{
definition: {{
kind: "PAGES_API",
page: "{definition_page}",
pathname: "{definition_pathname}",
// The following aren't used in production, but are
// required for the RouteModule constructor.
bundlePath: "",
filename: "",
}},
userland,
}})
"#
)?;
}
_ => bail!("Invalid path type"),
};
let file = File::from(result.build());
let asset = VirtualSource::new(
source.ident().path().join(match path_type {
PathType::Page => "pages-entry.tsx".to_string(),
PathType::PagesAPI => "pages-api-entry.tsx".to_string(),
_ => bail!("Invalid path type"),
}),
AssetContent::file(file.into()),
);
let ssr_module = ssr_module_context.process(
Vc::upcast(asset),
Value::new(ReferenceType::Internal(Vc::cell(indexmap! {
"INNER".to_string() => ssr_module,
}))),
);
let client_module = create_page_loader_entry_module(client_module_context, source, pathname); let client_module = create_page_loader_entry_module(client_module_context, source, pathname);
let Some(client_module) = let Some(client_module) =
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
// the other imports // the other imports
import startHandler from '../internal/page-server-handler' import startHandler from '../internal/page-server-handler'
import App from '@vercel/turbopack-next/pages/_app'
import Document from '@vercel/turbopack-next/pages/_document' import Document from '@vercel/turbopack-next/pages/_document'
import App from '@vercel/turbopack-next/pages/_app'
import chunkGroup from 'INNER_CLIENT_CHUNK_GROUP' import chunkGroup from 'INNER_CLIENT_CHUNK_GROUP'
......
...@@ -29,6 +29,7 @@ use crate::next_config::{NextConfig, OutputType}; ...@@ -29,6 +29,7 @@ use crate::next_config::{NextConfig, OutputType};
#[derive(Debug, Clone, Copy, PartialEq, Eq, TaskInput)] #[derive(Debug, Clone, Copy, PartialEq, Eq, TaskInput)]
pub enum PathType { pub enum PathType {
Page, Page,
PagesAPI,
Data, Data,
} }
......
...@@ -55,6 +55,8 @@ import { fileExists } from '../lib/file-exists' ...@@ -55,6 +55,8 @@ import { fileExists } from '../lib/file-exists'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { isInternalComponent } from '../lib/is-internal-component' import { isInternalComponent } from '../lib/is-internal-component'
import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route' import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route'
import { RouteKind } from '../server/future/route-kind'
import { encodeToBase64 } from './webpack/loaders/utils'
export async function getStaticInfoIncludingLayouts({ export async function getStaticInfoIncludingLayouts({
isInsideAppDir, isInsideAppDir,
...@@ -589,9 +591,7 @@ export async function createEntrypoints( ...@@ -589,9 +591,7 @@ export async function createEntrypoints(
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from( middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}) })
} else if (isInstrumentationHookFile(page) && pagesType === 'root') { } else if (isInstrumentationHookFile(page) && pagesType === 'root') {
server[serverBundlePath.replace('src/', '')] = { server[serverBundlePath.replace('src/', '')] = {
...@@ -599,13 +599,23 @@ export async function createEntrypoints( ...@@ -599,13 +599,23 @@ export async function createEntrypoints(
// the '../' is needed to make sure the file is not chunked // the '../' is needed to make sure the file is not chunked
filename: `../${INSTRUMENTATION_HOOK_FILENAME}.js`, filename: `../${INSTRUMENTATION_HOOK_FILENAME}.js`,
} }
} else if (isAPIRoute(page)) {
server[serverBundlePath] = [
getRouteLoaderEntry({
kind: RouteKind.PAGES_API,
page,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware || {},
}),
]
} else if ( } else if (
!isAPIRoute(page) &&
!isMiddlewareFile(page) && !isMiddlewareFile(page) &&
!isInternalComponent(absolutePagePath) !isInternalComponent(absolutePagePath)
) { ) {
server[serverBundlePath] = [ server[serverBundlePath] = [
getRouteLoaderEntry({ getRouteLoaderEntry({
kind: RouteKind.PAGES,
page, page,
pages, pages,
absolutePagePath, absolutePagePath,
......
...@@ -17,7 +17,6 @@ import os from 'os' ...@@ -17,7 +17,6 @@ import os from 'os'
import { Worker } from '../lib/worker' import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared' import { defaultConfig } from '../server/config-shared'
import devalue from 'next/dist/compiled/devalue' import devalue from 'next/dist/compiled/devalue'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
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'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
...@@ -141,7 +140,12 @@ import { createClientRouterFilter } from '../lib/create-client-router-filter' ...@@ -141,7 +140,12 @@ import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { createValidFileMatcher } from '../server/lib/find-page-file' import { createValidFileMatcher } from '../server/lib/find-page-file'
import { startTypeChecking } from './type-check' import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites' import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { baseOverrides, experimentalOverrides } from '../server/require-hook' import { buildDataRoute } from '../server/lib/router-utils/build-data-route'
import {
baseOverrides,
defaultOverrides,
experimentalOverrides,
} from '../server/require-hook'
export type SsgRoute = { export type SsgRoute = {
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
...@@ -166,6 +170,66 @@ export type PrerenderManifest = { ...@@ -166,6 +170,66 @@ export type PrerenderManifest = {
preview: __ApiPreviewProps preview: __ApiPreviewProps
} }
type CustomRoute = {
regex: string
statusCode?: number | undefined
permanent?: undefined
source: string
locale?: false | undefined
basePath?: false | undefined
destination?: string | undefined
}
export type RoutesManifest = {
version: number
pages404: boolean
basePath: string
redirects: Array<CustomRoute>
rewrites?:
| Array<CustomRoute>
| {
beforeFiles: Array<CustomRoute>
afterFiles: Array<CustomRoute>
fallback: Array<CustomRoute>
}
headers: Array<CustomRoute>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}>
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
rsc: {
header: typeof RSC
varyHeader: typeof RSC_VARY_HEADER
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
}
async function generateClientSsgManifest( async function generateClientSsgManifest(
prerenderManifest: PrerenderManifest, prerenderManifest: PrerenderManifest,
{ {
...@@ -684,55 +748,9 @@ export default async function build( ...@@ -684,55 +748,9 @@ export default async function build(
} }
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: { const routesManifest: RoutesManifest = nextBuildSpan
version: number .traceChild('generate-routes-manifest')
pages404: boolean .traceFn(() => {
basePath: string
redirects: Array<ReturnType<typeof buildCustomRoute>>
rewrites?:
| Array<ReturnType<typeof buildCustomRoute>>
| {
beforeFiles: Array<ReturnType<typeof buildCustomRoute>>
afterFiles: Array<ReturnType<typeof buildCustomRoute>>
fallback: Array<ReturnType<typeof buildCustomRoute>>
}
headers: Array<ReturnType<typeof buildCustomRoute>>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}>
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
rsc: {
header: typeof RSC
varyHeader: typeof RSC_VARY_HEADER
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
} = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => {
const sortedRoutes = getSortedRoutes([ const sortedRoutes = getSortedRoutes([
...pageKeys.pages, ...pageKeys.pages,
...(pageKeys.app ?? []), ...(pageKeys.app ?? []),
...@@ -753,7 +771,9 @@ export default async function build( ...@@ -753,7 +771,9 @@ export default async function build(
pages404: true, pages404: true,
caseSensitive: !!config.experimental.caseSensitiveRoutes, caseSensitive: !!config.experimental.caseSensitiveRoutes,
basePath: config.basePath, basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')), redirects: redirects.map((r: any) =>
buildCustomRoute(r, 'redirect')
),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')), headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes, dynamicRoutes,
staticRoutes, staticRoutes,
...@@ -903,6 +923,7 @@ export default async function build( ...@@ -903,6 +923,7 @@ export default async function build(
] ]
: []), : []),
path.join(SERVER_DIRECTORY, APP_PATHS_MANIFEST), path.join(SERVER_DIRECTORY, APP_PATHS_MANIFEST),
path.join(APP_PATH_ROUTES_MANIFEST),
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
path.join( path.join(
SERVER_DIRECTORY, SERVER_DIRECTORY,
...@@ -1962,6 +1983,11 @@ export default async function build( ...@@ -1962,6 +1983,11 @@ export default async function build(
...Object.values(experimentalOverrides).map((override) => ...Object.values(experimentalOverrides).map((override) =>
require.resolve(override) require.resolve(override)
), ),
...(config.experimental.turbotrace
? []
: Object.values(defaultOverrides).map((value) =>
require.resolve(value)
)),
] ]
// ensure we trace any dependencies needed for custom // ensure we trace any dependencies needed for custom
...@@ -1979,9 +2005,7 @@ export default async function build( ...@@ -1979,9 +2005,7 @@ export default async function build(
const vanillaServerEntries = [ const vanillaServerEntries = [
...sharedEntriesSet, ...sharedEntriesSet,
isStandalone isStandalone
? require.resolve( ? require.resolve('next/dist/server/lib/start-server')
'next/dist/server/lib/render-server-standalone'
)
: null, : null,
require.resolve('next/dist/server/next-server'), require.resolve('next/dist/server/next-server'),
].filter(Boolean) as string[] ].filter(Boolean) as string[]
...@@ -2158,49 +2182,7 @@ export default async function build( ...@@ -2158,49 +2182,7 @@ export default async function build(
...serverPropsPages, ...serverPropsPages,
...ssgPages, ...ssgPages,
]).map((page) => { ]).map((page) => {
const pagePath = normalizePagePath(page) return buildDataRoute(page, buildId)
const dataRoute = path.posix.join(
'/_next/data',
buildId,
`${pagePath}.json`
)
let dataRouteRegex: string
let namedDataRouteRegex: string | undefined
let routeKeys: { [named: string]: string } | undefined
if (isDynamicRoute(page)) {
const routeRegex = getNamedRouteRegex(
dataRoute.replace(/\.json$/, ''),
true
)
dataRouteRegex = normalizeRouteRegex(
routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`)
)
namedDataRouteRegex = routeRegex.namedRegex!.replace(
/\(\?:\/\)\?\$$/,
`\\.json$`
)
routeKeys = routeRegex.routeKeys
} else {
dataRouteRegex = normalizeRouteRegex(
new RegExp(
`^${path.posix.join(
'/_next/data',
escapeStringRegexp(buildId),
`${pagePath}.json`
)}$`
).source
)
}
return {
page,
routeKeys,
dataRouteRegex,
namedDataRouteRegex,
}
}) })
await fs.writeFile( await fs.writeFile(
......
...@@ -1928,12 +1928,12 @@ export async function copyTracedFiles( ...@@ -1928,12 +1928,12 @@ export async function copyTracedFiles(
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url)) const __dirname = fileURLToPath(new URL('.', import.meta.url))
import { createServerHandler } from 'next/dist/server/lib/render-server-standalone.js' import { startServer } from 'next/dist/server/lib/start-server.js'
` `
: ` : `
const http = require('http') const http = require('http')
const path = require('path') const path = require('path')
const { createServerHandler } = require('next/dist/server/lib/render-server-standalone')` const { startServer } = require('next/dist/server/lib/start-server')`
} }
const dir = path.join(__dirname) const dir = path.join(__dirname)
...@@ -1950,11 +1950,7 @@ if (!process.env.NEXT_MANUAL_SIG_HANDLE) { ...@@ -1950,11 +1950,7 @@ if (!process.env.NEXT_MANUAL_SIG_HANDLE) {
const currentPort = parseInt(process.env.PORT, 10) || 3000 const currentPort = parseInt(process.env.PORT, 10) || 3000
const hostname = process.env.HOSTNAME || 'localhost' const hostname = process.env.HOSTNAME || 'localhost'
const keepAliveTimeout = parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10); let keepAliveTimeout = parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10);
const isValidKeepAliveTimeout =
!Number.isNaN(keepAliveTimeout) &&
Number.isFinite(keepAliveTimeout) &&
keepAliveTimeout >= 0;
const nextConfig = ${JSON.stringify({ const nextConfig = ${JSON.stringify({
...serverConfig, ...serverConfig,
distDir: `./${path.relative(dir, distDir)}`, distDir: `./${path.relative(dir, distDir)}`,
...@@ -1962,41 +1958,30 @@ const nextConfig = ${JSON.stringify({ ...@@ -1962,41 +1958,30 @@ const nextConfig = ${JSON.stringify({
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig) process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig)
createServerHandler({ if (
port: currentPort, Number.isNaN(keepAliveTimeout) ||
hostname, !Number.isFinite(keepAliveTimeout) ||
dir, keepAliveTimeout < 0
conf: nextConfig, ) {
keepAliveTimeout: isValidKeepAliveTimeout ? keepAliveTimeout : undefined, keepAliveTimeout = undefined
}).then((nextHandler) => { }
const server = http.createServer(async (req, res) => {
try {
await nextHandler(req, res)
} catch (err) {
console.error(err);
res.statusCode = 500
res.end('Internal Server Error')
}
})
if (isValidKeepAliveTimeout) {
server.keepAliveTimeout = keepAliveTimeout
}
server.listen(currentPort, async (err) => {
if (err) {
console.error("Failed to start server", err)
process.exit(1)
}
startServer({
dir,
isDev: false,
config: nextConfig,
hostname: hostname === 'localhost' ? '0.0.0.0' : hostname,
port: currentPort,
allowRetry: false,
keepAliveTimeout,
useWorkers: !!nextConfig.experimental?.appDir,
}).then(() => {
console.log( console.log(
'Listening on port', 'Listening on port',
currentPort, currentPort,
'url: http://' + hostname + ':' + currentPort 'url: http://' + hostname + ':' + currentPort
) )
}); }).catch((err) => {
}).catch(err => {
console.error(err); console.error(err);
process.exit(1); process.exit(1);
});` });`
......
...@@ -5,12 +5,7 @@ import type { ...@@ -5,12 +5,7 @@ import type {
} from '../../analysis/get-page-static-info' } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
/** export type ModuleBuildInfo = {
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/
export function getModuleBuildInfo(webpackModule: webpack.Module) {
return webpackModule.buildInfo as {
nextEdgeMiddleware?: EdgeMiddlewareMeta nextEdgeMiddleware?: EdgeMiddlewareMeta
nextEdgeApiFunction?: EdgeMiddlewareMeta nextEdgeApiFunction?: EdgeMiddlewareMeta
nextEdgeSSR?: EdgeSSRMeta nextEdgeSSR?: EdgeSSRMeta
...@@ -21,7 +16,14 @@ export function getModuleBuildInfo(webpackModule: webpack.Module) { ...@@ -21,7 +16,14 @@ export function getModuleBuildInfo(webpackModule: webpack.Module) {
importLocByPath?: Map<string, any> importLocByPath?: Map<string, any>
rootDir?: string rootDir?: string
rsc?: RSCMeta rsc?: RSCMeta
} }
/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/
export function getModuleBuildInfo(webpackModule: webpack.Module) {
return webpackModule.buildInfo as ModuleBuildInfo
} }
export interface RSCMeta { export interface RSCMeta {
......
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { getModuleBuildInfo } from '../get-module-build-info' import { ModuleBuildInfo, getModuleBuildInfo } from '../get-module-build-info'
import { PagesRouteModuleOptions } from '../../../../server/future/route-modules/pages/module' import { PagesRouteModuleOptions } from '../../../../server/future/route-modules/pages/module'
import { RouteKind } from '../../../../server/future/route-kind' import { RouteKind } from '../../../../server/future/route-kind'
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info' import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
import { decodeFromBase64, encodeToBase64 } from '../utils' import { decodeFromBase64, encodeToBase64 } from '../utils'
import { isInstrumentationHookFile } from '../../../worker' import { isInstrumentationHookFile } from '../../../worker'
import { PagesAPIRouteModuleOptions } from '../../../../server/future/route-modules/pages-api/module'
type RouteLoaderOptionsInput = { type RouteLoaderOptionsPagesAPIInput = {
kind: RouteKind.PAGES_API
page: string
preferredRegion: string | string[] | undefined
absolutePagePath: string
middlewareConfig: MiddlewareConfig
}
type RouteLoaderOptionsPagesInput = {
kind: RouteKind.PAGES
page: string page: string
pages: { [page: string]: string } pages: { [page: string]: string }
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
...@@ -17,10 +27,37 @@ type RouteLoaderOptionsInput = { ...@@ -17,10 +27,37 @@ type RouteLoaderOptionsInput = {
middlewareConfig: MiddlewareConfig middlewareConfig: MiddlewareConfig
} }
/** type RouteLoaderOptionsInput =
* The options for the route loader. | RouteLoaderOptionsPagesInput
| RouteLoaderOptionsPagesAPIInput
type RouteLoaderPagesAPIOptions = {
kind: RouteKind.PAGES_API
/**
* The page name for this particular route.
*/ */
type RouteLoaderOptions = { page: string
/**
* The preferred region for this route.
*/
preferredRegion: string | string[] | undefined
/**
* The absolute path to the userland page file.
*/
absolutePagePath: string
/**
* The middleware config for this route.
*/
middlewareConfigBase64: string
}
type RouteLoaderPagesOptions = {
kind: RouteKind.PAGES
/** /**
* The page name for this particular route. * The page name for this particular route.
*/ */
...@@ -35,11 +72,28 @@ type RouteLoaderOptions = { ...@@ -35,11 +72,28 @@ type RouteLoaderOptions = {
* The absolute path to the userland page file. * The absolute path to the userland page file.
*/ */
absolutePagePath: string absolutePagePath: string
/**
* The absolute paths to the app path file.
*/
absoluteAppPath: string absoluteAppPath: string
/**
* The absolute paths to the document path file.
*/
absoluteDocumentPath: string absoluteDocumentPath: string
/**
* The middleware config for this route.
*/
middlewareConfigBase64: string middlewareConfigBase64: string
} }
/**
* The options for the route loader.
*/
type RouteLoaderOptions = RouteLoaderPagesOptions | RouteLoaderPagesAPIOptions
/** /**
* Returns the loader entry for a given page. * Returns the loader entry for a given page.
* *
...@@ -47,7 +101,10 @@ type RouteLoaderOptions = { ...@@ -47,7 +101,10 @@ type RouteLoaderOptions = {
* @returns the encoded loader entry * @returns the encoded loader entry
*/ */
export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string { export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string {
const query: RouteLoaderOptions = { switch (options.kind) {
case RouteKind.PAGES: {
const query: RouteLoaderPagesOptions = {
kind: options.kind,
page: options.page, page: options.page,
preferredRegion: options.preferredRegion, preferredRegion: options.preferredRegion,
absolutePagePath: options.absolutePagePath, absolutePagePath: options.absolutePagePath,
...@@ -59,34 +116,40 @@ export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string { ...@@ -59,34 +116,40 @@ export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string {
} }
return `next-route-loader?${stringify(query)}!` return `next-route-loader?${stringify(query)}!`
}
case RouteKind.PAGES_API: {
const query: RouteLoaderPagesAPIOptions = {
kind: options.kind,
page: options.page,
preferredRegion: options.preferredRegion,
absolutePagePath: options.absolutePagePath,
middlewareConfigBase64: encodeToBase64(options.middlewareConfig),
}
return `next-route-loader?${stringify(query)}!`
}
default: {
throw new Error('Invariant: Unexpected route kind')
}
}
} }
/** const loadPages = (
* Handles the `next-route-loader` options. {
* @returns the loader definition function
*/
const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
function () {
const {
page, page,
preferredRegion,
absolutePagePath, absolutePagePath,
absoluteAppPath,
absoluteDocumentPath, absoluteDocumentPath,
absoluteAppPath,
preferredRegion,
middlewareConfigBase64, middlewareConfigBase64,
} = this.getOptions() }: RouteLoaderPagesOptions,
buildInfo: ModuleBuildInfo
// Ensure we only run this loader for as a module. ) => {
if (!this._module) {
throw new Error('Invariant: expected this to reference a module')
}
const middlewareConfig: MiddlewareConfig = decodeFromBase64( const middlewareConfig: MiddlewareConfig = decodeFromBase64(
middlewareConfigBase64 middlewareConfigBase64
) )
// Attach build info to the module. // Attach build info to the module.
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.route = { buildInfo.route = {
page, page,
absolutePagePath, absolutePagePath,
...@@ -111,8 +174,8 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -111,8 +174,8 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
import { hoist } from "next/dist/build/webpack/loaders/next-route-loader/helpers" import { hoist } from "next/dist/build/webpack/loaders/next-route-loader/helpers"
// Import the app and document modules. // Import the app and document modules.
import * as moduleDocument from ${JSON.stringify(absoluteDocumentPath)} import Document from ${JSON.stringify(absoluteDocumentPath)}
import * as moduleApp from ${JSON.stringify(absoluteAppPath)} import App from ${JSON.stringify(absoluteAppPath)}
// Import the userland code. // Import the userland code.
import * as userland from ${JSON.stringify(absolutePagePath)} import * as userland from ${JSON.stringify(absolutePagePath)}
...@@ -144,17 +207,96 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -144,17 +207,96 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
// Create and export the route module that will be consumed. // Create and export the route module that will be consumed.
const options = ${JSON.stringify(options)} const options = ${JSON.stringify(options)}
const routeModule = new RouteModule({ export const routeModule = new RouteModule({
...options, ...options,
components: { components: {
App: moduleApp.default, App,
Document: moduleDocument.default, Document,
}, },
userland, userland,
}) })
`
}
export { routeModule } const loadPagesAPI = (
{
page,
absolutePagePath,
preferredRegion,
middlewareConfigBase64,
}: RouteLoaderPagesAPIOptions,
buildInfo: ModuleBuildInfo
) => {
const middlewareConfig: MiddlewareConfig = decodeFromBase64(
middlewareConfigBase64
)
// Attach build info to the module.
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig,
}
const options: Omit<PagesAPIRouteModuleOptions, 'userland' | 'components'> = {
definition: {
kind: RouteKind.PAGES_API,
page: normalizePagePath(page),
pathname: page,
// The following aren't used in production.
bundlePath: '',
filename: '',
},
}
return `
// Next.js Route Loader
import RouteModule from "next/dist/server/future/route-modules/pages-api/module"
import { hoist } from "next/dist/build/webpack/loaders/next-route-loader/helpers"
// Import the userland code.
import * as userland from ${JSON.stringify(absolutePagePath)}
// Re-export the handler (should be the default export).
export default hoist(userland, "default")
// Re-export config.
export const config = hoist(userland, "config")
// Create and export the route module that will be consumed.
const options = ${JSON.stringify(options)}
export const routeModule = new RouteModule({
...options,
userland,
})
` `
}
/**
* Handles the `next-route-loader` options.
* @returns the loader definition function
*/
const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
function () {
if (!this._module) {
throw new Error('Invariant: expected this to reference a module')
}
const buildInfo = getModuleBuildInfo(this._module)
const opts = this.getOptions()
switch (opts.kind) {
case RouteKind.PAGES: {
return loadPages(opts, buildInfo)
}
case RouteKind.PAGES_API: {
return loadPagesAPI(opts, buildInfo)
}
default: {
throw new Error('Invariant: Unexpected route kind')
}
}
} }
export default loader export default loader
...@@ -35,10 +35,27 @@ function generateClientManifest( ...@@ -35,10 +35,27 @@ function generateClientManifest(
'NextJsBuildManifest-generateClientManifest' 'NextJsBuildManifest-generateClientManifest'
) )
const normalizeRewrite = (item: {
source: string
destination: string
has?: any
}) => {
return {
has: item.has,
source: item.source,
destination: item.destination,
}
}
return genClientManifestSpan?.traceFn(() => { return genClientManifestSpan?.traceFn(() => {
const clientManifest: ClientBuildManifest = { const clientManifest: ClientBuildManifest = {
// TODO: update manifest type to include rewrites __rewrites: {
__rewrites: rewrites as any, afterFiles: rewrites.afterFiles?.map((item) => normalizeRewrite(item)),
beforeFiles: rewrites.beforeFiles?.map((item) =>
normalizeRewrite(item)
),
fallback: rewrites.fallback?.map((item) => normalizeRewrite(item)),
} as any,
} }
const appDependencies = new Set(assetMap.pages['/_app']) const appDependencies = new Set(assetMap.pages['/_app'])
const sortedPageKeys = getSortedRoutes(Object.keys(assetMap.pages)) const sortedPageKeys = getSortedRoutes(Object.keys(assetMap.pages))
......
...@@ -20,9 +20,15 @@ const originModules = [ ...@@ -20,9 +20,15 @@ const originModules = [
const RUNTIME_NAMES = ['webpack-runtime', 'webpack-api-runtime'] const RUNTIME_NAMES = ['webpack-runtime', 'webpack-api-runtime']
const nextDeleteCacheRpc = async (filePaths: string[]) => {
if ((global as any)._nextDeleteCache) {
return (global as any)._nextDeleteCache(filePaths)
}
}
export function deleteAppClientCache() { export function deleteAppClientCache() {
if ((global as any)._nextDeleteAppClientCache) { if ((global as any)._nextDeleteAppClientCache) {
;(global as any)._nextDeleteAppClientCache() return (global as any)._nextDeleteAppClientCache()
} }
// ensure we reset the cache for rsc components // ensure we reset the cache for rsc components
// loaded via react-server-dom-webpack // loaded via react-server-dom-webpack
...@@ -41,10 +47,6 @@ export function deleteAppClientCache() { ...@@ -41,10 +47,6 @@ export function deleteAppClientCache() {
} }
export function deleteCache(filePath: string) { export function deleteCache(filePath: string) {
if ((global as any)._nextDeleteCache) {
;(global as any)._nextDeleteCache(filePath)
}
// try to clear it from the fs cache // try to clear it from the fs cache
clearManifestCache(filePath) clearManifestCache(filePath)
...@@ -86,7 +88,7 @@ export class NextJsRequireCacheHotReloader implements WebpackPluginInstance { ...@@ -86,7 +88,7 @@ export class NextJsRequireCacheHotReloader implements WebpackPluginInstance {
apply(compiler: Compiler) { apply(compiler: Compiler) {
compiler.hooks.assetEmitted.tap(PLUGIN_NAME, (_file, { targetPath }) => { compiler.hooks.assetEmitted.tap(PLUGIN_NAME, (_file, { targetPath }) => {
deleteCache(targetPath) nextDeleteCacheRpc([targetPath])
// Clear module context in other processes // Clear module context in other processes
if ((global as any)._nextClearModuleContext) { if ((global as any)._nextClearModuleContext) {
...@@ -96,35 +98,33 @@ export class NextJsRequireCacheHotReloader implements WebpackPluginInstance { ...@@ -96,35 +98,33 @@ export class NextJsRequireCacheHotReloader implements WebpackPluginInstance {
clearModuleContext(targetPath) clearModuleContext(targetPath)
}) })
compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => { compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (compilation) => {
RUNTIME_NAMES.forEach((name) => { const cacheEntriesToDelete = []
for (const name of RUNTIME_NAMES) {
const runtimeChunkPath = path.join( const runtimeChunkPath = path.join(
compilation.outputOptions.path!, compilation.outputOptions.path!,
`${name}.js` `${name}.js`
) )
deleteCache(runtimeChunkPath) cacheEntriesToDelete.push(runtimeChunkPath)
}) }
let hasAppPath = false
// we need to make sure to clear all server entries from cache // we need to make sure to clear all server entries from cache
// since they can have a stale webpack-runtime cache // since they can have a stale webpack-runtime cache
// which needs to always be in-sync // which needs to always be in-sync
const entries = [...compilation.entries.keys()].filter((entry) => { const entries = [...compilation.entries.keys()].filter((entry) => {
const isAppPath = entry.toString().startsWith('app/') const isAppPath = entry.toString().startsWith('app/')
hasAppPath = hasAppPath || isAppPath
return entry.toString().startsWith('pages/') || isAppPath return entry.toString().startsWith('pages/') || isAppPath
}) })
if (hasAppPath) { for (const page of entries) {
}
entries.forEach((page) => {
const outputPath = path.join( const outputPath = path.join(
compilation.outputOptions.path!, compilation.outputOptions.path!,
page + '.js' page + '.js'
) )
deleteCache(outputPath) cacheEntriesToDelete.push(outputPath)
}) }
await nextDeleteCacheRpc(cacheEntriesToDelete)
}) })
} }
} }
...@@ -8,11 +8,7 @@ import isError from '../lib/is-error' ...@@ -8,11 +8,7 @@ import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import path from 'path' import path from 'path'
import { import { defaultConfig, NextConfigComplete } from '../server/config-shared'
defaultConfig,
NextConfig,
NextConfigComplete,
} from '../server/config-shared'
import { traceGlobals } from '../trace/shared' import { traceGlobals } from '../trace/shared'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import loadConfig from '../server/config' import loadConfig from '../server/config'
...@@ -26,6 +22,7 @@ import { getPossibleInstrumentationHookFilenames } from '../build/worker' ...@@ -26,6 +22,7 @@ import { getPossibleInstrumentationHookFilenames } from '../build/worker'
import { resetEnv } from '@next/env' import { resetEnv } from '@next/env'
let dir: string let dir: string
let config: NextConfigComplete
let isTurboSession = false let isTurboSession = false
let sessionStopHandled = false let sessionStopHandled = false
let sessionStarted = Date.now() let sessionStarted = Date.now()
...@@ -38,13 +35,15 @@ const handleSessionStop = async () => { ...@@ -38,13 +35,15 @@ const handleSessionStop = async () => {
const { eventCliSession } = const { eventCliSession } =
require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped') require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped')
const config = await loadConfig( config =
config ||
(await loadConfig(
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
dir, dir,
undefined, undefined,
undefined, undefined,
true true
) ))
let telemetry = let telemetry =
(traceGlobals.get('telemetry') as InstanceType< (traceGlobals.get('telemetry') as InstanceType<
...@@ -211,12 +210,14 @@ const nextDev: CliCommand = async (argv) => { ...@@ -211,12 +210,14 @@ const nextDev: CliCommand = async (argv) => {
// We do not set a default host value here to prevent breaking // We do not set a default host value here to prevent breaking
// some set-ups that rely on listening on other interfaces // some set-ups that rely on listening on other interfaces
const host = args['--hostname'] const host = args['--hostname']
config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir)
const devServerOptions: StartServerOptions = { const devServerOptions: StartServerOptions = {
dir, dir,
port, port,
allowRetry, allowRetry,
isDev: true, isDev: true,
nextConfig: config,
hostname: host, hostname: host,
// This is required especially for app dir. // This is required especially for app dir.
useWorkers: true, useWorkers: true,
...@@ -237,14 +238,6 @@ const nextDev: CliCommand = async (argv) => { ...@@ -237,14 +238,6 @@ const nextDev: CliCommand = async (argv) => {
resetEnv() resetEnv()
let bindings = await loadBindings() let bindings = await loadBindings()
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
// Just testing code here: // Just testing code here:
const project = await bindings.turbo.createProject({ const project = await bindings.turbo.createProject({
...@@ -409,7 +402,6 @@ const nextDev: CliCommand = async (argv) => { ...@@ -409,7 +402,6 @@ const nextDev: CliCommand = async (argv) => {
try { try {
let shouldFilter = false let shouldFilter = false
let devServerTeardown: (() => Promise<void>) | undefined let devServerTeardown: (() => Promise<void>) | undefined
let config: NextConfig | undefined
watchConfigFiles(devServerOptions.dir, (filename) => { watchConfigFiles(devServerOptions.dir, (filename) => {
Log.warn( Log.warn(
...@@ -505,16 +497,6 @@ const nextDev: CliCommand = async (argv) => { ...@@ -505,16 +497,6 @@ const nextDev: CliCommand = async (argv) => {
// fallback to noop, if not provided // fallback to noop, if not provided
resolveCleanup(async () => {}) resolveCleanup(async () => {})
} }
if (!config) {
config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
}
} }
await setupFork() await setupFork()
......
...@@ -84,6 +84,7 @@ const nextStart: CliCommand = async (argv) => { ...@@ -84,6 +84,7 @@ const nextStart: CliCommand = async (argv) => {
await startServer({ await startServer({
dir, dir,
nextConfig: config,
isDev: false, isDev: false,
hostname: host, hostname: host,
port, port,
......
...@@ -36,6 +36,7 @@ const supportedTurbopackNextConfigOptions = [ ...@@ -36,6 +36,7 @@ const supportedTurbopackNextConfigOptions = [
'experimental.isrFlushToDisk', 'experimental.isrFlushToDisk',
'experimental.workerThreads', 'experimental.workerThreads',
'experimenatl.pageEnv', 'experimenatl.pageEnv',
'experimental.caseSensitiveRoutes',
] ]
// The following will need to be supported by `next build --turbo` // The following will need to be supported by `next build --turbo`
......
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import type { BaseNextRequest } from '../base-http' import type { BaseNextRequest } from '../base-http'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie' import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils' import type { NextApiResponse } from '../../shared/lib/utils'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers' import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import { import {
...@@ -186,7 +186,7 @@ export function sendError( ...@@ -186,7 +186,7 @@ export function sendError(
} }
interface LazyProps { interface LazyProps {
req: NextApiRequest req: IncomingMessage
} }
/** /**
......
...@@ -191,17 +191,17 @@ export async function parseBody( ...@@ -191,17 +191,17 @@ export async function parseBody(
} }
} }
type ApiContext = __ApiPreviewProps & { type RevalidateFn = (config: {
trustHostHeader?: boolean
allowedRevalidateHeaderKeys?: string[]
hostname?: string
revalidate?: (config: {
urlPath: string urlPath: string
revalidateHeaders: { [key: string]: string | string[] } revalidateHeaders: { [key: string]: string | string[] }
opts: { unstable_onlyGenerated?: boolean } opts: { unstable_onlyGenerated?: boolean }
}) => Promise<any> }) => Promise<void>
// (_req: IncomingMessage, _res: ServerResponse) => Promise<any> type ApiContext = __ApiPreviewProps & {
trustHostHeader?: boolean
allowedRevalidateHeaderKeys?: string[]
hostname?: string
revalidate?: RevalidateFn
} }
function getMaxContentLength(responseLimit?: ResponseLimit) { function getMaxContentLength(responseLimit?: ResponseLimit) {
...@@ -475,16 +475,7 @@ async function revalidate( ...@@ -475,16 +475,7 @@ async function revalidate(
headers: {}, headers: {},
} }
) )
const result = await res.json()
const chunks = []
for await (const chunk of res) {
if (chunk) {
chunks.push(chunk)
}
}
const body = Buffer.concat(chunks).toString()
const result = JSON.parse(body)
if (result.err) { if (result.err) {
throw new Error(result.err.message) throw new Error(result.err.message)
......
This diff is collapsed.
...@@ -297,6 +297,11 @@ export interface ExperimentalConfig { ...@@ -297,6 +297,11 @@ export interface ExperimentalConfig {
* Enables source maps generation for the server production bundle. * Enables source maps generation for the server production bundle.
*/ */
serverSourceMaps?: boolean serverSourceMaps?: boolean
/**
* @internal Used by the Next.js internals only.
*/
trustHostHeader?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
......
let installed: boolean = false let installed: boolean = false
export function loadWebpackHook({ init }: { init: boolean }) { export function loadWebpackHook() {
if (init) {
const { init: initWebpack } = require('next/dist/compiled/webpack/webpack') const { init: initWebpack } = require('next/dist/compiled/webpack/webpack')
if (installed) { if (installed) {
return return
} }
installed = true installed = true
initWebpack() initWebpack()
}
// hook the Node.js require so that webpack requires are // hook the Node.js require so that webpack requires are
// routed to the bundled and now initialized webpack version // routed to the bundled and now initialized webpack version
......
...@@ -711,24 +711,21 @@ export default async function loadConfig( ...@@ -711,24 +711,21 @@ export default async function loadConfig(
rawConfig?: boolean, rawConfig?: boolean,
silent?: boolean silent?: boolean
): Promise<NextConfigComplete> { ): Promise<NextConfigComplete> {
if (process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) { if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) {
return JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) try {
loadWebpackHook()
} catch (err) {
// this can fail in standalone mode as the files
// aren't traced/included
if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
throw err
}
} }
const curLog = silent
? {
warn: () => {},
info: () => {},
error: () => {},
} }
: Log
loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, curLog)
loadWebpackHook({ if (process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
// For render workers, there's no need to init webpack eagerly return JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG)
init: !process.env.__NEXT_PRIVATE_RENDER_WORKER, }
})
// For the render worker, we directly return the serialized config from the // For the render worker, we directly return the serialized config from the
// parent worker (router worker) to avoid loading it again. // parent worker (router worker) to avoid loading it again.
...@@ -740,6 +737,16 @@ export default async function loadConfig( ...@@ -740,6 +737,16 @@ export default async function loadConfig(
return JSON.parse(process.env.__NEXT_PRIVATE_RENDER_WORKER_CONFIG) return JSON.parse(process.env.__NEXT_PRIVATE_RENDER_WORKER_CONFIG)
} }
const curLog = silent
? {
warn: () => {},
info: () => {},
error: () => {},
}
: Log
loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, curLog)
let configFileName = 'next.config.js' let configFileName = 'next.config.js'
if (customConfig) { if (customConfig) {
......
...@@ -62,6 +62,7 @@ import { parseVersionInfo, VersionInfo } from './parse-version-info' ...@@ -62,6 +62,7 @@ import { parseVersionInfo, VersionInfo } from './parse-version-info'
import { isAPIRoute } from '../../lib/is-api-route' import { isAPIRoute } from '../../lib/is-api-route'
import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader'
import { isInternalComponent } from '../../lib/is-internal-component' import { isInternalComponent } from '../../lib/is-internal-component'
import { RouteKind } from '../future/route-kind'
function diff(a: Set<any>, b: Set<any>) { function diff(a: Set<any>, b: Set<any>) {
return new Set([...a].filter((v) => !b.has(v))) return new Set([...a].filter((v) => !b.has(v)))
...@@ -279,7 +280,7 @@ export default class HotReloader { ...@@ -279,7 +280,7 @@ export default class HotReloader {
parsedPageBundleUrl: UrlObject parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => { ): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl const { pathname } = parsedPageBundleUrl
const params = matchNextPageBundleRequest<{ path: string[] }>(pathname) const params = matchNextPageBundleRequest(pathname)
if (!params) { if (!params) {
return {} return {}
} }
...@@ -288,7 +289,7 @@ export default class HotReloader { ...@@ -288,7 +289,7 @@ export default class HotReloader {
try { try {
decodedPagePath = `/${params.path decodedPagePath = `/${params.path
.map((param) => decodeURIComponent(param)) .map((param: string) => decodeURIComponent(param))
.join('/')}` .join('/')}`
} catch (_) { } catch (_) {
throw new DecodeError('failed to decode param') throw new DecodeError('failed to decode param')
...@@ -906,12 +907,20 @@ export default class HotReloader { ...@@ -906,12 +907,20 @@ export default class HotReloader {
JSON.stringify(staticInfo.middleware || {}) JSON.stringify(staticInfo.middleware || {})
).toString('base64'), ).toString('base64'),
}) })
} else if (isAPIRoute(page)) {
value = getRouteLoaderEntry({
kind: RouteKind.PAGES_API,
page,
absolutePagePath: relativeRequest,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware || {},
})
} else if ( } else if (
!isAPIRoute(page) &&
!isMiddlewareFile(page) && !isMiddlewareFile(page) &&
!isInternalComponent(relativeRequest) !isInternalComponent(relativeRequest)
) { ) {
value = getRouteLoaderEntry({ value = getRouteLoaderEntry({
kind: RouteKind.PAGES,
page, page,
pages: this.pagesMapping, pages: this.pagesMapping,
absolutePagePath: relativeRequest, absolutePagePath: relativeRequest,
...@@ -1411,10 +1420,12 @@ export default class HotReloader { ...@@ -1411,10 +1420,12 @@ export default class HotReloader {
clientOnly, clientOnly,
appPaths, appPaths,
match, match,
isApp,
}: { }: {
page: string page: string
clientOnly: boolean clientOnly: boolean
appPaths?: string[] | null appPaths?: string[] | null
isApp?: boolean
match?: RouteMatch match?: RouteMatch
}): Promise<void> { }): Promise<void> {
// Make sure we don't re-build or dispose prebuilt pages // Make sure we don't re-build or dispose prebuilt pages
...@@ -1432,6 +1443,7 @@ export default class HotReloader { ...@@ -1432,6 +1443,7 @@ export default class HotReloader {
clientOnly, clientOnly,
appPaths, appPaths,
match, match,
isApp,
}) as any }) as any
} }
} }
...@@ -689,11 +689,13 @@ export function onDemandEntryHandler({ ...@@ -689,11 +689,13 @@ export function onDemandEntryHandler({
clientOnly, clientOnly,
appPaths = null, appPaths = null,
match, match,
isApp,
}: { }: {
page: string page: string
clientOnly: boolean clientOnly: boolean
appPaths?: ReadonlyArray<string> | null appPaths?: ReadonlyArray<string> | null
match?: RouteMatch match?: RouteMatch
isApp?: boolean
}): Promise<void> { }): Promise<void> {
const stalledTime = 60 const stalledTime = 60
const stalledEnsureTimeout = setTimeout(() => { const stalledEnsureTimeout = setTimeout(() => {
...@@ -722,6 +724,12 @@ export function onDemandEntryHandler({ ...@@ -722,6 +724,12 @@ export function onDemandEntryHandler({
const isInsideAppDir = const isInsideAppDir =
!!appDir && pagePathData.absolutePagePath.startsWith(appDir) !!appDir && pagePathData.absolutePagePath.startsWith(appDir)
if (typeof isApp === 'boolean' && !(isApp === isInsideAppDir)) {
throw new Error(
'Ensure bailed, found path does not match ensure type (pages/app)'
)
}
const pageBundleType = getPageBundleType(pagePathData.bundlePath) const pageBundleType = getPageBundleType(pagePathData.bundlePath)
const addEntry = ( const addEntry = (
compilerType: CompilerNameValues compilerType: CompilerNameValues
...@@ -894,11 +902,13 @@ export function onDemandEntryHandler({ ...@@ -894,11 +902,13 @@ export function onDemandEntryHandler({
clientOnly, clientOnly,
appPaths = null, appPaths = null,
match, match,
isApp,
}: { }: {
page: string page: string
clientOnly: boolean clientOnly: boolean
appPaths?: ReadonlyArray<string> | null appPaths?: ReadonlyArray<string> | null
match?: RouteMatch match?: RouteMatch
isApp?: boolean
}) { }) {
if (curEnsurePage.has(page)) { if (curEnsurePage.has(page)) {
return curEnsurePage.get(page) return curEnsurePage.get(page)
...@@ -908,6 +918,7 @@ export function onDemandEntryHandler({ ...@@ -908,6 +918,7 @@ export function onDemandEntryHandler({
clientOnly, clientOnly,
appPaths, appPaths,
match, match,
isApp,
}).finally(() => { }).finally(() => {
curEnsurePage.delete(page) curEnsurePage.delete(page)
}) })
......
...@@ -12,12 +12,11 @@ export class RouteModuleLoader { ...@@ -12,12 +12,11 @@ export class RouteModuleLoader {
id: string, id: string,
loader: ModuleLoader = new NodeModuleLoader() loader: ModuleLoader = new NodeModuleLoader()
): Promise<M> { ): Promise<M> {
if (process.env.NEXT_RUNTIME !== 'edge') { const module: AppLoaderModule<M> = await loader.load(id)
const { routeModule }: AppLoaderModule<M> = await loader.load(id) if ('routeModule' in module) {
return module.routeModule
return routeModule
} }
throw new Error('RouteModuleLoader is not supported in edge runtime.') throw new Error(`Module "${id}" does not export a routeModule.`)
} }
} }
import type { IncomingMessage, ServerResponse } from 'http'
import type { PagesAPIRouteDefinition } from '../../route-definitions/pages-api-route-definition'
import type { PageConfig } from '../../../../../types'
import type { ParsedUrlQuery } from 'querystring'
import {
RouteModule,
RouteModuleOptions,
type RouteModuleHandleContext,
} from '../route-module'
import { apiResolver } from '../../../api-utils/node'
import { __ApiPreviewProps } from '../../../api-utils'
type PagesAPIHandleFn = (
req: IncomingMessage,
res: ServerResponse
) => Promise<void>
type PagesAPIUserlandModule = {
/**
* The exported handler method.
*/
readonly default: PagesAPIHandleFn
/**
* The exported page config.
*/
readonly config?: PageConfig
}
type PagesAPIRouteHandlerContext = RouteModuleHandleContext & {
/**
* The incoming server request in non-edge runtime.
*/
req?: IncomingMessage
/**
* The outgoing server response in non-edge runtime.
*/
res?: ServerResponse
/**
* The revalidate method used by the `revalidate` API.
*
* @param config the configuration for the revalidation
*/
revalidate: (config: {
urlPath: string
revalidateHeaders: { [key: string]: string | string[] }
opts: { unstable_onlyGenerated?: boolean }
}) => Promise<void>
/**
* The hostname for the request.
*/
hostname?: string
/**
* Keys allowed in the revalidate call.
*/
allowedRevalidateHeaderKeys?: string[]
/**
* Whether to trust the host header.
*/
trustHostHeader?: boolean
/**
* The query for the request.
*/
query: ParsedUrlQuery
/**
* The preview props used by the `preview` API.
*/
previewProps: __ApiPreviewProps
/**
* True if the server is in development mode.
*/
dev: boolean
/**
* True if the server is in minimal mode.
*/
minimalMode: boolean
/**
* The page that's being rendered.
*/
page: string
}
export type PagesAPIRouteModuleOptions = RouteModuleOptions<
PagesAPIRouteDefinition,
PagesAPIUserlandModule
>
export class PagesAPIRouteModule extends RouteModule<
PagesAPIRouteDefinition,
PagesAPIUserlandModule
> {
public handle(): Promise<Response> {
throw new Error('Method not implemented.')
}
/**
*
* @param req the incoming server request
* @param res the outgoing server response
* @param context the context for the render
*/
public async render(
req: IncomingMessage,
res: ServerResponse,
context: PagesAPIRouteHandlerContext
): Promise<void> {
await apiResolver(
req,
res,
context.query,
this.userland,
{
...context.previewProps,
revalidate: context.revalidate,
trustHostHeader: context.trustHostHeader,
allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys,
hostname: context.hostname,
},
context.minimalMode,
context.dev,
context.page
)
}
}
export default PagesAPIRouteModule
import type { IncomingMessage, ServerResponse } from 'http'
import type { ChildProcess } from 'child_process'
import httpProxy from 'next/dist/compiled/http-proxy'
import { Worker } from 'next/dist/compiled/jest-worker'
import { normalizeRepeatedSlashes } from '../../shared/lib/utils'
export const createServerHandler = async ({
port,
hostname,
dir,
dev = false,
minimalMode,
keepAliveTimeout,
}: {
port: number
hostname: string
dir: string
dev?: boolean
minimalMode: boolean
keepAliveTimeout?: number
}) => {
const routerWorker = new Worker(require.resolve('./render-server'), {
numWorkers: 1,
maxRetries: 10,
forkOptions: {
env: {
FORCE_COLOR: '1',
...process.env,
},
},
exposedMethods: ['initialize'],
}) as any as InstanceType<typeof Worker> & {
initialize: typeof import('./render-server').initialize
}
let didInitialize = false
for (const _worker of ((routerWorker as any)._workerPool?._workers || []) as {
_child: ChildProcess
}[]) {
// eslint-disable-next-line no-loop-func
_worker._child.on('exit', (code, signal) => {
// catch failed initializing without retry
if ((code || signal) && !didInitialize) {
routerWorker?.end()
process.exit(1)
}
})
}
const workerStdout = routerWorker.getStdout()
const workerStderr = routerWorker.getStderr()
workerStdout.on('data', (data) => {
process.stdout.write(data)
})
workerStderr.on('data', (data) => {
process.stderr.write(data)
})
const { port: routerPort } = await routerWorker.initialize({
dir,
port,
dev,
hostname,
minimalMode,
workerType: 'router',
isNodeDebugging: false,
keepAliveTimeout,
})
didInitialize = true
const getProxyServer = (pathname: string) => {
const targetUrl = `http://${
hostname === 'localhost' ? '127.0.0.1' : hostname
}:${routerPort}${pathname}`
const proxyServer = httpProxy.createProxy({
target: targetUrl,
changeOrigin: false,
ignorePath: true,
xfwd: true,
ws: true,
followRedirects: false,
})
return proxyServer
}
// proxy to router worker
return async (req: IncomingMessage, res: ServerResponse) => {
const urlParts = (req.url || '').split('?')
const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world ->
// hello/world or backslashes to forward slashes, this does not
// handle trailing slash as that is handled the same as a next.config.js
// redirect
if (urlNoQuery?.match(/(\\|\/\/)/)) {
const cleanUrl = normalizeRepeatedSlashes(req.url!)
res.statusCode = 308
res.setHeader('Location', cleanUrl)
res.end(cleanUrl)
return
}
const proxyServer = getProxyServer(req.url || '/')
// http-proxy does not properly detect a client disconnect in newer
// versions of Node.js. This is caused because it only listens for the
// `aborted` event on the our request object, but it also fully reads and
// closes the request object. Node **will not** fire `aborted` when the
// request is already closed. Listening for `close` on our response object
// will detect the disconnect, and we can abort the proxy's connection.
proxyServer.on('proxyReq', (proxyReq) => {
res.on('close', () => proxyReq.destroy())
})
proxyServer.on('proxyRes', (proxyRes) => {
res.on('close', () => proxyRes.destroy())
})
proxyServer.web(req, res)
proxyServer.on('error', (err) => {
res.statusCode = 500
res.end('Internal Server Error')
console.error(err)
})
}
}
import type { RequestHandler } from '../next' import type { RequestHandler } from '../next'
import './cpu-profile' // this must come first as it includes require hooks
import v8 from 'v8' import { initializeServerWorker } from './setup-server-worker'
import http from 'http'
import { isIPv6 } from 'net'
// This is required before other imports to ensure the require hook is setup.
import '../require-hook'
import next from '../next' import next from '../next'
import { warn } from '../../build/output/log'
import { getFreePort } from '../lib/worker-utils'
export const WORKER_SELF_EXIT_CODE = 77 export const WORKER_SELF_EXIT_CODE = 77
const MAXIMUM_HEAP_SIZE_ALLOWED =
(v8.getHeapStatistics().heap_size_limit / 1024 / 1024) * 0.9
let result: let result:
| undefined | undefined
| { | {
...@@ -24,6 +13,8 @@ let result: ...@@ -24,6 +13,8 @@ let result:
hostname: string hostname: string
} }
let app: ReturnType<typeof next> | undefined
let sandboxContext: undefined | typeof import('../web/sandbox/context') let sandboxContext: undefined | typeof import('../web/sandbox/context')
let requireCacheHotReloader: let requireCacheHotReloader:
| undefined | undefined
...@@ -35,15 +26,46 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -35,15 +26,46 @@ if (process.env.NODE_ENV !== 'production') {
} }
export function clearModuleContext(target: string) { export function clearModuleContext(target: string) {
sandboxContext?.clearModuleContext(target) return sandboxContext?.clearModuleContext(target)
} }
export function deleteAppClientCache() { export function deleteAppClientCache() {
requireCacheHotReloader?.deleteAppClientCache() return requireCacheHotReloader?.deleteAppClientCache()
} }
export function deleteCache(filePath: string) { export function deleteCache(filePaths: string[]) {
for (const filePath of filePaths) {
requireCacheHotReloader?.deleteCache(filePath) requireCacheHotReloader?.deleteCache(filePath)
}
}
export async function propagateServerField(field: string, value: any) {
if (!app) {
throw new Error('Invariant cant propagate server field, no app initialized')
}
let appField = (app as any).server
if (field.includes('.')) {
const parts = field.split('.')
for (let i = 0; i < parts.length - 1; i++) {
if (appField) {
appField = appField[parts[i]]
}
}
field = parts[parts.length - 1]
}
if (appField) {
if (typeof appField[field] === 'function') {
appField[field].apply(
(app as any).server,
Array.isArray(value) ? value : []
)
} else {
appField[field] = value
}
}
} }
export async function initialize(opts: { export async function initialize(opts: {
...@@ -55,6 +77,7 @@ export async function initialize(opts: { ...@@ -55,6 +77,7 @@ export async function initialize(opts: {
workerType: 'router' | 'render' workerType: 'router' | 'render'
isNodeDebugging: boolean isNodeDebugging: boolean
keepAliveTimeout?: number keepAliveTimeout?: number
serverFields?: any
}): Promise<NonNullable<typeof result>> { }): Promise<NonNullable<typeof result>> {
// if we already setup the server return as we only need to do // if we already setup the server return as we only need to do
// this on first worker boot // this on first worker boot
...@@ -62,83 +85,27 @@ export async function initialize(opts: { ...@@ -62,83 +85,27 @@ export async function initialize(opts: {
return result return result
} }
const isRouterWorker = opts.workerType === 'router'
const isRenderWorker = opts.workerType === 'render'
if (isRouterWorker) {
process.title = 'next-router-worker'
} else if (isRenderWorker) {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER! const type = process.env.__NEXT_PRIVATE_RENDER_WORKER!
process.title = 'next-render-worker-' + type process.title = 'next-render-worker-' + type
}
let requestHandler: RequestHandler let requestHandler: RequestHandler
const server = http.createServer((req, res) => {
return requestHandler(req, res)
.catch((err) => {
res.statusCode = 500
res.end('Internal Server Error')
console.error(err)
})
.finally(() => {
if (
process.memoryUsage().heapUsed / 1024 / 1024 >
MAXIMUM_HEAP_SIZE_ALLOWED
) {
warn(
'The server is running out of memory, restarting to free up memory.'
)
server.close()
process.exit(WORKER_SELF_EXIT_CODE)
}
})
})
if (opts.keepAliveTimeout) {
server.keepAliveTimeout = opts.keepAliveTimeout
}
return new Promise(async (resolve, reject) => {
server.on('error', (err: NodeJS.ErrnoException) => {
console.error(`Invariant: failed to start render worker`, err)
process.exit(1)
})
let upgradeHandler: any let upgradeHandler: any
if (!opts.dev) { const { port, server, hostname } = await initializeServerWorker(
server.on('upgrade', (req, socket, upgrade) => { (...args) => {
upgradeHandler(req, socket, upgrade) return requestHandler(...args)
}) },
} (...args) => {
return upgradeHandler(...args)
server.on('listening', async () => { },
try { opts
const addr = server.address() )
const port = addr && typeof addr === 'object' ? addr.port : 0
if (!port) {
console.error(`Invariant failed to detect render worker port`, addr)
process.exit(1)
}
let hostname =
!opts.hostname || opts.hostname === '0.0.0.0'
? 'localhost'
: opts.hostname
if (isIPv6(hostname)) { app = next({
hostname = hostname === '::' ? '[::1]' : `[${hostname}]`
}
result = {
port,
hostname,
}
const app = next({
...opts, ...opts,
_routerWorker: isRouterWorker, _routerWorker: opts.workerType === 'router',
_renderWorker: isRenderWorker, _renderWorker: opts.workerType === 'render',
hostname, hostname: hostname === '0.0.0.0' ? 'localhost' : hostname,
customServer: false, customServer: false,
httpServer: server, httpServer: server,
port: opts.port, port: opts.port,
...@@ -147,12 +114,11 @@ export async function initialize(opts: { ...@@ -147,12 +114,11 @@ export async function initialize(opts: {
requestHandler = app.getRequestHandler() requestHandler = app.getRequestHandler()
upgradeHandler = app.getUpgradeHandler() upgradeHandler = app.getUpgradeHandler()
await app.prepare() await app.prepare(opts.serverFields)
resolve(result)
} catch (err) { result = {
return reject(err) port,
hostname: hostname === '0.0.0.0' ? '127.0.0.1' : hostname,
} }
}) return result
server.listen(await getFreePort(), '0.0.0.0')
})
} }
This diff is collapsed.
import path from '../../../shared/lib/isomorphic/path'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'
import { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { normalizeRouteRegex } from '../../../lib/load-custom-routes'
import { escapeStringRegexp } from '../../../shared/lib/escape-regexp'
export function buildDataRoute(page: string, buildId: string) {
const pagePath = normalizePagePath(page)
const dataRoute = path.posix.join('/_next/data', buildId, `${pagePath}.json`)
let dataRouteRegex: string
let namedDataRouteRegex: string | undefined
let routeKeys: { [named: string]: string } | undefined
if (isDynamicRoute(page)) {
const routeRegex = getNamedRouteRegex(
dataRoute.replace(/\.json$/, ''),
true
)
dataRouteRegex = normalizeRouteRegex(
routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`)
)
namedDataRouteRegex = routeRegex.namedRegex!.replace(
/\(\?:\/\)\?\$$/,
`\\.json$`
)
routeKeys = routeRegex.routeKeys
} else {
dataRouteRegex = normalizeRouteRegex(
new RegExp(
`^${path.posix.join(
'/_next/data',
escapeStringRegexp(buildId),
`${pagePath}.json`
)}$`
).source
)
}
return {
page,
routeKeys,
dataRouteRegex,
namedDataRouteRegex,
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -88,13 +88,14 @@ export const createWorker = async ( ...@@ -88,13 +88,14 @@ export const createWorker = async (
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
) => { ) => {
const { initialEnv } = require('@next/env') as typeof import('@next/env') const { initialEnv } = require('@next/env') as typeof import('@next/env')
const { Worker } = require('next/dist/compiled/jest-worker')
const useServerActions = !!nextConfig.experimental.serverActions const useServerActions = !!nextConfig.experimental.serverActions
const { Worker } =
require('next/dist/compiled/jest-worker') as typeof import('next/dist/compiled/jest-worker')
const worker = new Worker(require.resolve('../render-server'), { const worker = new Worker(require.resolve('../render-server'), {
numWorkers: 1, numWorkers: 1,
// TODO: do we want to allow more than 10 OOM restarts? // TODO: do we want to allow more than 8 OOM restarts?
maxRetries: 10, maxRetries: 8,
forkOptions: { forkOptions: {
env: { env: {
FORCE_COLOR: '1', FORCE_COLOR: '1',
...@@ -129,11 +130,14 @@ export const createWorker = async ( ...@@ -129,11 +130,14 @@ export const createWorker = async (
'deleteCache', 'deleteCache',
'deleteAppClientCache', 'deleteAppClientCache',
'clearModuleContext', 'clearModuleContext',
'propagateServerField',
], ],
}) as any as InstanceType<typeof Worker> & { }) as any as InstanceType<typeof Worker> & {
initialize: typeof import('../render-server').initialize initialize: typeof import('../render-server').initialize
deleteCache: typeof import('../render-server').deleteCache deleteCache: typeof import('../render-server').deleteCache
deleteAppClientCache: typeof import('../render-server').deleteAppClientCache deleteAppClientCache: typeof import('../render-server').deleteAppClientCache
clearModuleContext: typeof import('../render-server').clearModuleContext
propagateServerField: typeof import('../render-server').propagateServerField
} }
worker.getStderr().pipe(process.stderr) worker.getStderr().pipe(process.stderr)
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -14,6 +14,7 @@ describe('Production Usage without production build', () => { ...@@ -14,6 +14,7 @@ describe('Production Usage without production build', () => {
dir: appDir, dir: appDir,
dev: false, dev: false,
quiet: true, quiet: true,
customServer: false,
}) })
await srv.prepare() await srv.prepare()
}).rejects.toThrow(/Could not find a production build in the/) }).rejects.toThrow(/Could not find a production build in the/)
......
This diff is collapsed.
This diff is collapsed.
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