Unverified Commit 799a05ce authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Support preferredRegion and Support runtime/preferredRegion on layouts (#48959)

### What?

Implements resolving of `runtime` and `preferredRegion` in layouts. It
will resolve from the root layout down, each layout can override
`runtime` or `preferredRegion`.

```
app
├── layout.js -> export const runtime = 'edge'
├── page.js -> Edge runtime
└── dashboard
    ├── page.js -> Edge runtime
    └── settings
        ├── layout.js -> export const runtime = 'nodejs'
        └── page.js -> Node.js runtime
```

Adds support for `preferredRegion`. This is similar to `export const
config = { region: ['sfo1'] }` in `pages`.

However, there is a difference. It supports `export const
preferredRegion = 'home'` and `export const preferredRegion = 'edge'`.
`home` refers to the configured default region on your deployment
platform and `edge` refers to "all regions".

### How?

I've implemented a temporary resolving in `entries.ts`.
`preferredRegion` is tracked through the entry module in webpack which
is why it's added to all the loaders that create an entry module, this
prevents having to resolve/parse again later on.

Fixes NEXT-880
Fixes NEXT-1064
Fixes #48905
Closes #48933
parent 7bfd5829
...@@ -35,6 +35,7 @@ export interface MiddlewareMatcher { ...@@ -35,6 +35,7 @@ export interface MiddlewareMatcher {
export interface PageStaticInfo { export interface PageStaticInfo {
runtime?: ServerRuntime runtime?: ServerRuntime
preferredRegion?: string | string[]
ssg?: boolean ssg?: boolean
ssr?: boolean ssr?: boolean
rsc?: RSCModuleType rsc?: RSCModuleType
...@@ -81,10 +82,12 @@ function checkExports(swcAST: any): { ...@@ -81,10 +82,12 @@ function checkExports(swcAST: any): {
ssr: boolean ssr: boolean
ssg: boolean ssg: boolean
runtime?: string runtime?: string
preferredRegion?: string | string[]
} { } {
if (Array.isArray(swcAST?.body)) { if (Array.isArray(swcAST?.body)) {
try { try {
let runtime: string | undefined let runtime: string | undefined
let preferredRegion: string | string[] | undefined
let ssr: boolean = false let ssr: boolean = false
let ssg: boolean = false let ssg: boolean = false
...@@ -97,6 +100,22 @@ function checkExports(swcAST: any): { ...@@ -97,6 +100,22 @@ function checkExports(swcAST: any): {
if (declaration.id.value === 'runtime') { if (declaration.id.value === 'runtime') {
runtime = declaration.init.value runtime = declaration.init.value
} }
if (declaration.id.value === 'preferredRegion') {
if (declaration.init.type === 'ArrayExpression') {
const elements: string[] = []
for (const element of declaration.init.elements) {
const { expression } = element
if (expression.type !== 'StringLiteral') {
continue
}
elements.push(expression.value)
}
preferredRegion = elements
} else {
preferredRegion = declaration.init.value
}
}
} }
} }
...@@ -137,7 +156,7 @@ function checkExports(swcAST: any): { ...@@ -137,7 +156,7 @@ function checkExports(swcAST: any): {
} }
} }
return { ssr, ssg, runtime } return { ssr, ssg, runtime, preferredRegion }
} catch (err) {} } catch (err) {}
} }
...@@ -322,12 +341,12 @@ export async function getPageStaticInfo(params: { ...@@ -322,12 +341,12 @@ export async function getPageStaticInfo(params: {
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || '' const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if ( if (
/runtime|getStaticProps|getServerSideProps|export const config/.test( /runtime|preferredRegion|getStaticProps|getServerSideProps|export const config/.test(
fileContent fileContent
) )
) { ) {
const swcAST = await parseModule(pageFilePath, fileContent) const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr, runtime } = checkExports(swcAST) const { ssg, ssr, runtime, preferredRegion } = checkExports(swcAST)
const rsc = getRSCModuleInformation(fileContent).type const rsc = getRSCModuleInformation(fileContent).type
// default / failsafe value for config // default / failsafe value for config
...@@ -420,6 +439,7 @@ export async function getPageStaticInfo(params: { ...@@ -420,6 +439,7 @@ export async function getPageStaticInfo(params: {
rsc, rsc,
...(middlewareConfig && { middleware: middlewareConfig }), ...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }), ...(resolvedRuntime && { runtime: resolvedRuntime }),
preferredRegion,
} }
} }
......
...@@ -7,12 +7,13 @@ import type { webpack } from 'next/dist/compiled/webpack/webpack' ...@@ -7,12 +7,13 @@ import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { import type {
MiddlewareConfig, MiddlewareConfig,
MiddlewareMatcher, MiddlewareMatcher,
PageStaticInfo,
} from './analysis/get-page-static-info' } from './analysis/get-page-static-info'
import type { LoadedEnvFiles } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import type { AppLoaderOptions } from './webpack/loaders/next-app-loader' import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path' import { posix, join, dirname } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { import {
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
...@@ -50,6 +51,83 @@ import { encodeMatchers } from './webpack/loaders/next-middleware-loader' ...@@ -50,6 +51,83 @@ import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route' import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route'
import { fileExists } from '../lib/file-exists'
export async function getStaticInfoIncludingLayouts({
isInsideAppDir,
pageExtensions,
pageFilePath,
appDir,
config,
isDev,
page,
}: {
isInsideAppDir: boolean
pageExtensions: string[]
pageFilePath: string
appDir: string | undefined
config: NextConfigComplete
isDev: boolean | undefined
page: string
}): Promise<PageStaticInfo> {
const pageStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath,
isDev,
page,
pageType: isInsideAppDir ? 'app' : 'pages',
})
const staticInfo: PageStaticInfo = isInsideAppDir
? {
// TODO-APP: Remove the rsc key altogether. It's no longer required.
rsc: 'server',
}
: pageStaticInfo
if (isInsideAppDir) {
const layoutFiles = []
const potentialLayoutFiles = pageExtensions.map((ext) => 'layout.' + ext)
let dir = dirname(pageFilePath)
while (dir !== appDir) {
for (const potentialLayoutFile of potentialLayoutFiles) {
const layoutFile = join(dir, potentialLayoutFile)
if (!(await fileExists(layoutFile))) {
continue
}
layoutFiles.unshift(layoutFile)
}
// Walk up the directory tree
dir = join(dir, '..')
}
for (const layoutFile of layoutFiles) {
const layoutStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath: layoutFile,
isDev,
page,
pageType: isInsideAppDir ? 'app' : 'pages',
})
// Only runtime is relevant here.
if (layoutStaticInfo.runtime) {
staticInfo.runtime = layoutStaticInfo.runtime
}
if (layoutStaticInfo.preferredRegion) {
staticInfo.preferredRegion = layoutStaticInfo.preferredRegion
}
}
if (pageStaticInfo.runtime) {
staticInfo.runtime = pageStaticInfo.runtime
}
if (pageStaticInfo.preferredRegion) {
staticInfo.preferredRegion = pageStaticInfo.preferredRegion
}
}
return staticInfo
}
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
...@@ -204,6 +282,7 @@ export function getEdgeServerEntry(opts: { ...@@ -204,6 +282,7 @@ export function getEdgeServerEntry(opts: {
pagesType: 'app' | 'pages' | 'root' pagesType: 'app' | 'pages' | 'root'
appDirLoader?: string appDirLoader?: string
hasInstrumentationHook?: boolean hasInstrumentationHook?: boolean
preferredRegion: string | string[] | undefined
}) { }) {
if ( if (
opts.pagesType === 'app' && opts.pagesType === 'app' &&
...@@ -215,6 +294,7 @@ export function getEdgeServerEntry(opts: { ...@@ -215,6 +294,7 @@ export function getEdgeServerEntry(opts: {
page: opts.page, page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfigOutput: opts.config.output, nextConfigOutput: opts.config.output,
preferredRegion: opts.preferredRegion,
} }
return { return {
...@@ -240,6 +320,7 @@ export function getEdgeServerEntry(opts: { ...@@ -240,6 +320,7 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
page: opts.page, page: opts.page,
rootDir: opts.rootDir, rootDir: opts.rootDir,
preferredRegion: opts.preferredRegion,
} }
return `next-edge-function-loader?${stringify(loaderParams)}!` return `next-edge-function-loader?${stringify(loaderParams)}!`
...@@ -268,6 +349,7 @@ export function getEdgeServerEntry(opts: { ...@@ -268,6 +349,7 @@ export function getEdgeServerEntry(opts: {
sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm, sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm,
incrementalCacheHandlerPath: incrementalCacheHandlerPath:
opts.config.experimental.incrementalCacheHandlerPath, opts.config.experimental.incrementalCacheHandlerPath,
preferredRegion: opts.preferredRegion,
} }
return { return {
...@@ -426,12 +508,14 @@ export async function createEntrypoints( ...@@ -426,12 +508,14 @@ export async function createEntrypoints(
(absolutePagePath.startsWith(APP_DIR_ALIAS) || (absolutePagePath.startsWith(APP_DIR_ALIAS) ||
absolutePagePath.startsWith(appDir)) absolutePagePath.startsWith(appDir))
const staticInfo = await getPageStaticInfo({ const staticInfo: PageStaticInfo = await getStaticInfoIncludingLayouts({
nextConfig: config, isInsideAppDir,
pageExtensions,
pageFilePath, pageFilePath,
appDir,
config,
isDev, isDev,
page, page,
pageType: isInsideAppDir ? 'app' : 'pages',
}) })
const isServerComponent = const isServerComponent =
...@@ -470,6 +554,7 @@ export async function createEntrypoints( ...@@ -470,6 +554,7 @@ export async function createEntrypoints(
pageExtensions, pageExtensions,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion,
}) })
} else { } else {
if (isInstrumentationHookFile(page) && pagesType === 'root') { if (isInstrumentationHookFile(page) && pagesType === 'root') {
...@@ -496,6 +581,9 @@ export async function createEntrypoints( ...@@ -496,6 +581,9 @@ export async function createEntrypoints(
pageExtensions, pageExtensions,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
// Still passing it here for consistency.
preferredRegion: staticInfo.preferredRegion,
}).import }).import
} }
const normalizedServerBundlePath = const normalizedServerBundlePath =
...@@ -513,6 +601,7 @@ export async function createEntrypoints( ...@@ -513,6 +601,7 @@ export async function createEntrypoints(
middleware: staticInfo?.middleware, middleware: staticInfo?.middleware,
pagesType, pagesType,
appDirLoader, appDirLoader,
preferredRegion: staticInfo.preferredRegion,
}) })
}, },
}) })
......
...@@ -36,6 +36,7 @@ export interface RSCMeta { ...@@ -36,6 +36,7 @@ export interface RSCMeta {
export interface RouteMeta { export interface RouteMeta {
page: string page: string
absolutePagePath: string absolutePagePath: string
preferredRegion: string | string[] | undefined
} }
export interface EdgeMiddlewareMeta { export interface EdgeMiddlewareMeta {
......
...@@ -27,6 +27,7 @@ export type AppLoaderOptions = { ...@@ -27,6 +27,7 @@ export type AppLoaderOptions = {
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: readonly string[] | null appPaths: readonly string[] | null
preferredRegion: string | string[] | undefined
pageExtensions: string[] pageExtensions: string[]
assetPrefix: string assetPrefix: string
rootDir?: string rootDir?: string
...@@ -421,6 +422,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -421,6 +422,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
tsconfigPath, tsconfigPath,
isDev, isDev,
nextConfigOutput, nextConfigOutput,
preferredRegion,
} = loaderOptions } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
...@@ -428,6 +430,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -428,6 +430,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
buildInfo.route = { buildInfo.route = {
page, page,
absolutePagePath: createAbsolutePath(appDir, pagePath), absolutePagePath: createAbsolutePath(appDir, pagePath),
preferredRegion,
} }
const extensions = pageExtensions.map((extension) => `.${extension}`) const extensions = pageExtensions.map((extension) => `.${extension}`)
......
...@@ -7,6 +7,7 @@ export type EdgeAppRouteLoaderQuery = { ...@@ -7,6 +7,7 @@ export type EdgeAppRouteLoaderQuery = {
absolutePagePath: string absolutePagePath: string
page: string page: string
appDirLoader: string appDirLoader: string
preferredRegion: string | string[] | undefined
nextConfigOutput: NextConfig['output'] nextConfigOutput: NextConfig['output']
} }
...@@ -15,6 +16,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -15,6 +16,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
const { const {
page, page,
absolutePagePath, absolutePagePath,
preferredRegion,
appDirLoader: appDirLoaderBase64 = '', appDirLoader: appDirLoaderBase64 = '',
} = this.getOptions() } = this.getOptions()
...@@ -33,6 +35,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -33,6 +35,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
buildInfo.route = { buildInfo.route = {
page, page,
absolutePagePath, absolutePagePath,
preferredRegion,
} }
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
......
import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
...@@ -5,19 +6,30 @@ export type EdgeFunctionLoaderOptions = { ...@@ -5,19 +6,30 @@ export type EdgeFunctionLoaderOptions = {
absolutePagePath: string absolutePagePath: string
page: string page: string
rootDir: string rootDir: string
preferredRegion: string | string[] | undefined
} }
export default function middlewareLoader(this: any) { const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> =
const { absolutePagePath, page, rootDir }: EdgeFunctionLoaderOptions = function nextEdgeFunctionLoader(this) {
this.getOptions() const {
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) absolutePagePath,
const buildInfo = getModuleBuildInfo(this._module) page,
buildInfo.nextEdgeApiFunction = { rootDir,
page: page || '/', preferredRegion,
} }: EdgeFunctionLoaderOptions = this.getOptions()
buildInfo.rootDir = rootDir const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module as any)
buildInfo.route = {
page: page || '/',
absolutePagePath,
preferredRegion,
}
buildInfo.nextEdgeApiFunction = {
page: page || '/',
}
buildInfo.rootDir = rootDir
return ` return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache' import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
...@@ -39,4 +51,6 @@ export default function middlewareLoader(this: any) { ...@@ -39,4 +51,6 @@ export default function middlewareLoader(this: any) {
}) })
} }
` `
} }
export default nextEdgeFunctionLoader
import type webpack from 'webpack'
import { getModuleBuildInfo } from '../get-module-build-info' import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
...@@ -16,6 +17,7 @@ export type EdgeSSRLoaderQuery = { ...@@ -16,6 +17,7 @@ export type EdgeSSRLoaderQuery = {
pagesType: 'app' | 'pages' | 'root' pagesType: 'app' | 'pages' | 'root'
sriEnabled: boolean sriEnabled: boolean
incrementalCacheHandlerPath?: string incrementalCacheHandlerPath?: string
preferredRegion: string | string[] | undefined
} }
/* /*
...@@ -30,64 +32,68 @@ function swapDistFolderWithEsmDistFolder(path: string) { ...@@ -30,64 +32,68 @@ function swapDistFolderWithEsmDistFolder(path: string) {
return path.replace('next/dist/pages', 'next/dist/esm/pages') return path.replace('next/dist/pages', 'next/dist/esm/pages')
} }
export default async function edgeSSRLoader(this: any) { const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
const { async function edgeSSRLoader(this) {
dev, const {
page, dev,
buildId, page,
absolutePagePath, buildId,
absoluteAppPath, absolutePagePath,
absoluteDocumentPath, absoluteAppPath,
absolute500Path, absoluteDocumentPath,
absoluteErrorPath, absolute500Path,
isServerComponent, absoluteErrorPath,
stringifiedConfig, isServerComponent,
appDirLoader: appDirLoaderBase64, stringifiedConfig,
pagesType, appDirLoader: appDirLoaderBase64,
sriEnabled, pagesType,
incrementalCacheHandlerPath, sriEnabled,
} = this.getOptions() incrementalCacheHandlerPath,
preferredRegion,
} = this.getOptions()
const appDirLoader = Buffer.from( const appDirLoader = Buffer.from(
appDirLoaderBase64 || '', appDirLoaderBase64 || '',
'base64' 'base64'
).toString() ).toString()
const isAppDir = pagesType === 'app' const isAppDir = pagesType === 'app'
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module as any)
buildInfo.nextEdgeSSR = { buildInfo.nextEdgeSSR = {
isServerComponent: isServerComponent === 'true', // @ts-expect-error === 'true' is correct because loader options are serialized as searchParams. Type needs to be fixed somehow.
page: page, isServerComponent: isServerComponent === 'true',
isAppDir, page: page,
} isAppDir,
buildInfo.route = { }
page, buildInfo.route = {
absolutePagePath, page,
} absolutePagePath,
preferredRegion,
}
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest( const stringifiedAppPath = stringifyRequest(
this, this,
swapDistFolderWithEsmDistFolder(absoluteAppPath) swapDistFolderWithEsmDistFolder(absoluteAppPath)
) )
const stringifiedErrorPath = stringifyRequest( const stringifiedErrorPath = stringifyRequest(
this, this,
swapDistFolderWithEsmDistFolder(absoluteErrorPath) swapDistFolderWithEsmDistFolder(absoluteErrorPath)
) )
const stringifiedDocumentPath = stringifyRequest( const stringifiedDocumentPath = stringifyRequest(
this, this,
swapDistFolderWithEsmDistFolder(absoluteDocumentPath) swapDistFolderWithEsmDistFolder(absoluteDocumentPath)
) )
const stringified500Path = absolute500Path const stringified500Path = absolute500Path
? stringifyRequest(this, absolute500Path) ? stringifyRequest(this, absolute500Path)
: null : null
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring( const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(
1, 1,
stringifiedPagePath.length - 1 stringifiedPagePath.length - 1
)}${isAppDir ? '?__edge_ssr_entry__' : ''}` )}${isAppDir ? '?__edge_ssr_entry__' : ''}`
const transformed = ` const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render' import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache' import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
...@@ -170,5 +176,6 @@ export default async function edgeSSRLoader(this: any) { ...@@ -170,5 +176,6 @@ export default async function edgeSSRLoader(this: any) {
}) })
}` }`
return transformed return transformed
} }
export default edgeSSRLoader
...@@ -636,7 +636,7 @@ function getExtractMetadata(params: { ...@@ -636,7 +636,7 @@ function getExtractMetadata(params: {
entryDependency, entryDependency,
resolver resolver
) )
const { rootDir } = getModuleBuildInfo( const { rootDir, route } = getModuleBuildInfo(
compilation.moduleGraph.getResolvedModule(entryDependency) compilation.moduleGraph.getResolvedModule(entryDependency)
) )
...@@ -739,6 +739,15 @@ function getExtractMetadata(params: { ...@@ -739,6 +739,15 @@ function getExtractMetadata(params: {
entryMetadata.regions = edgeFunctionConfig.config.regions entryMetadata.regions = edgeFunctionConfig.config.regions
} }
if (route?.preferredRegion) {
const preferredRegion = route.preferredRegion
entryMetadata.regions =
// Ensures preferredRegion is always an array in the manifest.
typeof preferredRegion === 'string'
? [preferredRegion]
: preferredRegion
}
/** /**
* The entry module has to be either a page or a middleware and hold * The entry module has to be either a page or a middleware and hold
* the corresponding metadata. * the corresponding metadata.
......
...@@ -14,6 +14,7 @@ import { ...@@ -14,6 +14,7 @@ import {
getEdgeServerEntry, getEdgeServerEntry,
getAppEntry, getAppEntry,
runDependingOnPageType, runDependingOnPageType,
getStaticInfoIncludingLayouts,
} from '../../build/entries' } from '../../build/entries'
import { watchCompilers } from '../../build/output' import { watchCompilers } from '../../build/output'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
...@@ -47,7 +48,6 @@ import { Span, trace } from '../../trace' ...@@ -47,7 +48,6 @@ import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error' import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws' import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { UnwrapPromise } from '../../lib/coalesced-function' import { UnwrapPromise } from '../../lib/coalesced-function'
import { getRegistry } from '../../lib/helpers/get-registry' import { getRegistry } from '../../lib/helpers/get-registry'
import { RouteMatch } from '../future/route-matches/route-match' import { RouteMatch } from '../future/route-matches/route-match'
...@@ -713,12 +713,14 @@ export default class HotReloader { ...@@ -713,12 +713,14 @@ export default class HotReloader {
const hasAppDir = !!this.appDir const hasAppDir = !!this.appDir
const isAppPath = hasAppDir && bundlePath.startsWith('app/') const isAppPath = hasAppDir && bundlePath.startsWith('app/')
const staticInfo = isEntry const staticInfo = isEntry
? await getPageStaticInfo({ ? await getStaticInfoIncludingLayouts({
page, isInsideAppDir: isAppPath,
pageExtensions: this.config.pageExtensions,
pageFilePath: entryData.absolutePagePath, pageFilePath: entryData.absolutePagePath,
nextConfig: this.config, appDir: this.appDir,
config: this.config,
isDev: true, isDev: true,
pageType: isAppPath ? 'app' : 'pages', page,
}) })
: {} : {}
const isServerComponent = const isServerComponent =
...@@ -755,6 +757,7 @@ export default class HotReloader { ...@@ -755,6 +757,7 @@ export default class HotReloader {
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion,
}).import }).import
: undefined : undefined
...@@ -774,6 +777,7 @@ export default class HotReloader { ...@@ -774,6 +777,7 @@ export default class HotReloader {
isServerComponent, isServerComponent,
appDirLoader, appDirLoader,
pagesType: isAppPath ? 'app' : 'pages', pagesType: isAppPath ? 'app' : 'pages',
preferredRegion: staticInfo.preferredRegion,
}), }),
hasAppDir, hasAppDir,
}) })
...@@ -838,6 +842,7 @@ export default class HotReloader { ...@@ -838,6 +842,7 @@ export default class HotReloader {
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion,
}) })
: relativeRequest, : relativeRequest,
hasAppDir, hasAppDir,
......
...@@ -7,3 +7,4 @@ export default function HelloPage(props) { ...@@ -7,3 +7,4 @@ export default function HelloPage(props) {
} }
export const runtime = 'experimental-edge' export const runtime = 'experimental-edge'
export const preferredRegion = ['iad1', 'sfo1']
...@@ -9,3 +9,5 @@ export default function DashboardLayout(props) { ...@@ -9,3 +9,5 @@ export default function DashboardLayout(props) {
</div> </div>
) )
} }
export const preferredRegion = 'iad1'
...@@ -16,4 +16,4 @@ export default function DashboardPage(props) { ...@@ -16,4 +16,4 @@ export default function DashboardPage(props) {
) )
} }
export const runtime = 'experimental-edge' export const runtime = 'edge'
...@@ -14,3 +14,4 @@ export default function SlowPage(props) { ...@@ -14,3 +14,4 @@ export default function SlowPage(props) {
} }
export const runtime = 'experimental-edge' export const runtime = 'experimental-edge'
export const preferredRegion = 'edge'
export default function Page() { export default function Page() {
return <p id="page">Page</p> return <p id="page">Page</p>
} }
export const runtime = 'experimental-edge'
export const preferredRegion = 'home'
...@@ -10,6 +10,28 @@ createNextDescribe( ...@@ -10,6 +10,28 @@ createNextDescribe(
files: __dirname, files: __dirname,
}, },
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => { ({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
if (isNextStart) {
it('should have correct preferredRegion values in manifest', async () => {
const middlewareManifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(
middlewareManifest.functions['/(rootonly)/dashboard/hello/page']
.regions
).toEqual(['iad1', 'sfo1'])
expect(middlewareManifest.functions['/dashboard/page'].regions).toEqual(
['iad1']
)
expect(
middlewareManifest.functions['/slow-page-no-loading/page'].regions
).toEqual(['edge'])
expect(middlewareManifest.functions['/test-page/page'].regions).toEqual(
['home']
)
})
}
it('should have correct searchParams and params (server)', async () => { it('should have correct searchParams and params (server)', async () => {
const html = await next.render('/dynamic/category-1/id-2?query1=value2') const html = await next.render('/dynamic/category-1/id-2?query1=value2')
const $ = cheerio.load(html) const $ = cheerio.load(html)
......
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