Unverified Commit f507b0e6 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update types and more test coverage for adapters (#82919)

This tweaks the output structure a bit and makes types more
strong/specific for easier handling. Also adds additional test coverage.
parent da54d104
...@@ -391,8 +391,8 @@ export type ManifestHeaderRoute = ManifestBuiltRoute & Header ...@@ -391,8 +391,8 @@ export type ManifestHeaderRoute = ManifestBuiltRoute & Header
export type ManifestRoute = ManifestBuiltRoute & { export type ManifestRoute = ManifestBuiltRoute & {
page: string page: string
namedRegex?: string namedRegex: string
routeKeys?: { [key: string]: string } routeKeys: { [key: string]: string }
/** /**
* If true, this indicates that the route has fallback root params. This is * If true, this indicates that the route has fallback root params. This is
...@@ -4112,6 +4112,9 @@ export default async function build( ...@@ -4112,6 +4112,9 @@ export default async function build(
await handleBuildComplete({ await handleBuildComplete({
dir, dir,
distDir, distDir,
config,
staticPages,
nextVersion: process.env.__NEXT_VERSION as string,
tracingRoot: outputFileTracingRoot, tracingRoot: outputFileTracingRoot,
hasNodeMiddleware, hasNodeMiddleware,
hasInstrumentationHook, hasInstrumentationHook,
......
...@@ -55,6 +55,7 @@ export type Redirect = { ...@@ -55,6 +55,7 @@ export type Redirect = {
locale?: false locale?: false
has?: RouteHas[] has?: RouteHas[]
missing?: RouteHas[] missing?: RouteHas[]
priority?: boolean
/** /**
* @internal - used internally for routing * @internal - used internally for routing
...@@ -740,6 +741,7 @@ export default async function loadCustomRoutes( ...@@ -740,6 +741,7 @@ export default async function loadCustomRoutes(
permanent: true, permanent: true,
locale: config.i18n ? false : undefined, locale: config.i18n ? false : undefined,
internal: true, internal: true,
priority: true,
// don't run this redirect for _next/data requests // don't run this redirect for _next/data requests
missing: [ missing: [
{ {
...@@ -754,6 +756,7 @@ export default async function loadCustomRoutes( ...@@ -754,6 +756,7 @@ export default async function loadCustomRoutes(
permanent: true, permanent: true,
locale: config.i18n ? false : undefined, locale: config.i18n ? false : undefined,
internal: true, internal: true,
priority: true,
} }
) )
if (config.basePath) { if (config.basePath) {
...@@ -764,6 +767,7 @@ export default async function loadCustomRoutes( ...@@ -764,6 +767,7 @@ export default async function loadCustomRoutes(
basePath: false, basePath: false,
locale: config.i18n ? false : undefined, locale: config.i18n ? false : undefined,
internal: true, internal: true,
priority: true,
}) })
} }
} else { } else {
...@@ -773,6 +777,7 @@ export default async function loadCustomRoutes( ...@@ -773,6 +777,7 @@ export default async function loadCustomRoutes(
permanent: true, permanent: true,
locale: config.i18n ? false : undefined, locale: config.i18n ? false : undefined,
internal: true, internal: true,
priority: true,
}) })
if (config.basePath) { if (config.basePath) {
redirects.unshift({ redirects.unshift({
...@@ -782,6 +787,7 @@ export default async function loadCustomRoutes( ...@@ -782,6 +787,7 @@ export default async function loadCustomRoutes(
basePath: false, basePath: false,
locale: config.i18n ? false : undefined, locale: config.i18n ? false : undefined,
internal: true, internal: true,
priority: true,
}) })
} }
} }
......
import os from 'os' import os from 'os'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
Header,
Redirect,
Rewrite,
RouteHas,
} from '../lib/load-custom-routes'
import { imageConfigDefault } from '../shared/lib/image-config' import { imageConfigDefault } from '../shared/lib/image-config'
import type { import type {
ImageConfig, ImageConfig,
...@@ -18,17 +13,7 @@ import type { SizeLimit } from '../types' ...@@ -18,17 +13,7 @@ import type { SizeLimit } from '../types'
import type { SupportedTestRunners } from '../cli/next-test' import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr' import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
import { INFINITE_CACHE } from '../lib/constants' import { INFINITE_CACHE } from '../lib/constants'
import type {
ManifestRewriteRoute,
ManifestHeaderRoute,
ManifestRedirectRoute,
ManifestRoute,
} from '../build'
import { isStableBuild } from '../shared/lib/canary-only' import { isStableBuild } from '../shared/lib/canary-only'
import type { RenderingMode } from '../build/rendering-mode'
import type { Revalidate } from './lib/cache-control'
import type { AdapterOutputType } from '../shared/lib/constants'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { FallbackRouteParam } from '../build/static-paths/types' import type { FallbackRouteParam } from '../build/static-paths/types'
export type NextConfigComplete = Required<NextConfig> & { export type NextConfigComplete = Required<NextConfig> & {
...@@ -43,146 +28,6 @@ export type NextConfigComplete = Required<NextConfig> & { ...@@ -43,146 +28,6 @@ export type NextConfigComplete = Required<NextConfig> & {
experimental: Omit<ExperimentalConfig, 'turbo'> experimental: Omit<ExperimentalConfig, 'turbo'>
} }
export type AdapterOutputs = Array<{
/**
* id is a unique identifier for the output
*/
id: string
/**
* pathname is the URL path that the output is meant to
* be routable to at e.g. /blog/[slug] or /_next/static/chunks/chunk.js
*/
pathname: string
/**
* runtime for the route, this doesn't apply for prerender or static
*/
runtime?: 'nodejs' | 'edge'
/**
* config related to the route
*/
config?: {
/**
* maxDuration is a segment config to signal the max
* execution duration a route should be allowed before
* it's timed out
*/
maxDuration?: number
/**
* preferredRegion is a segment config to signal deployment
* region preferences to the provider being used
*/
preferredRegion?: string | string[]
/**
* allowQuery is the allowed query values to be passed
* to an ISR function and what should be considered for the cacheKey
* e.g. for /blog/[slug], "slug" is the only allowQuery
*/
allowQuery?: string[]
/**
* allowHeader is the allowed headers to be passed to an
* ISR function to prevent accidentally poisoning the cache
* from leaking additional information that can impact the render
*/
allowHeader?: string[]
/**
* bypass for is a list of has conditions the cache
* should be bypassed and invoked directly e.g. action header
*/
bypassFor?: RouteHas[]
/**
* renderingMode signals PPR or not for a prerender
*/
renderingMode?: RenderingMode
/**
* matchers are the configured matchers for middleware
*/
matchers?: MiddlewareMatcher[]
/**
* bypassToken is the generated token that signals a prerender cache
* should be bypassed
*/
bypassToken?: string
/**
* postponed is the PPR state when it postponed and is used for resuming
*/
postponed?: string
}
/**
* For prerenders the parent output is the originating
* page that the prerender is created from
*/
parentOutputId?: string
/**
* fallback is initial cache data generated during build for a prerender
*/
fallback?: {
/**
* path to the fallback file can be HTML/JSON/RSC
*/
filePath: string
/**
* initialStatus is the status code that should be applied
* when serving the fallback
*/
initialStatus?: number
/**
* initialHeaders are the headers that should be sent when
* serving the fallback
*/
initialHeaders?: Record<string, string | string[]>
/**
* initial expiration is how long until the fallback entry
* is considered expired and no longer valid to serve
*/
initialExpiration?: number
/**
* initial revalidate is how long until the fallback is
* considered stale and should be revalidated
*/
initialRevalidate?: Revalidate
}
/**
* assets are all necessary traced assets that could be
* loaded by the output to handle a request e.g. traced
* node_modules or necessary manifests for Next.js
*/
assets?: Record<string, string>
/**
* filePath is present for all cases except a Prerender
* which may or may not have a fallback (initial cache entry).
* The parent output will have a filePath for a prerender though
*/
filePath?: string
/**
* type of output
*/
type: AdapterOutputType
}>
export interface NextAdapter {
name: string
modifyConfig?: (
config: NextConfigComplete
) => Promise<NextConfigComplete> | NextConfigComplete
onBuildComplete?: (ctx: {
routes: {
headers: Array<ManifestHeaderRoute>
redirects: Array<ManifestRedirectRoute>
rewrites: {
beforeFiles: Array<ManifestRewriteRoute>
afterFiles: Array<ManifestRewriteRoute>
fallback: Array<ManifestRewriteRoute>
}
dynamicRoutes: ReadonlyArray<ManifestRoute>
}
outputs: AdapterOutputs
}) => Promise<void> | void
}
export type I18NDomains = readonly DomainLocale[] export type I18NDomains = readonly DomainLocale[]
export interface I18NConfig { export interface I18NConfig {
......
import { PHASE_PRODUCTION_BUILD } from '../api/constants'
describe('loadConfig', () => { describe('loadConfig', () => {
let loadConfig: typeof import('./config').default let loadConfig: typeof import('./config').default
...@@ -12,7 +14,7 @@ describe('loadConfig', () => { ...@@ -12,7 +14,7 @@ describe('loadConfig', () => {
}) })
describe('nextConfig.images defaults', () => { describe('nextConfig.images defaults', () => {
it('should assign a `images.remotePatterns` when using assetPrefix', async () => { it('should assign a `images.remotePatterns` when using assetPrefix', async () => {
const result = await loadConfig('', __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
assetPrefix: 'https://cdn.example.com', assetPrefix: 'https://cdn.example.com',
images: { images: {
...@@ -33,7 +35,7 @@ describe('loadConfig', () => { ...@@ -33,7 +35,7 @@ describe('loadConfig', () => {
}) })
it('should not assign a duplicate `images.remotePatterns` value when using assetPrefix', async () => { it('should not assign a duplicate `images.remotePatterns` value when using assetPrefix', async () => {
let result = await loadConfig('', __dirname, { let result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
assetPrefix: 'https://cdn.example.com', assetPrefix: 'https://cdn.example.com',
images: { images: {
...@@ -51,7 +53,7 @@ describe('loadConfig', () => { ...@@ -51,7 +53,7 @@ describe('loadConfig', () => {
expect(result.images.remotePatterns.length).toBe(1) expect(result.images.remotePatterns.length).toBe(1)
result = await loadConfig('', __dirname, { result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
assetPrefix: 'https://cdn.example.com/foobar', assetPrefix: 'https://cdn.example.com/foobar',
images: { images: {
...@@ -81,7 +83,7 @@ describe('loadConfig', () => { ...@@ -81,7 +83,7 @@ describe('loadConfig', () => {
}) })
it('should not print a stack trace when throwing an error', async () => { it('should not print a stack trace when throwing an error', async () => {
const loadConfigPromise = loadConfig('', __dirname, { const loadConfigPromise = loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
ppr: true, ppr: true,
...@@ -105,7 +107,7 @@ describe('loadConfig', () => { ...@@ -105,7 +107,7 @@ describe('loadConfig', () => {
it('errors when using PPR if not in canary', async () => { it('errors when using PPR if not in canary', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
ppr: true, ppr: true,
...@@ -119,7 +121,7 @@ describe('loadConfig', () => { ...@@ -119,7 +121,7 @@ describe('loadConfig', () => {
it('errors when using cacheComponents if not in canary', async () => { it('errors when using cacheComponents if not in canary', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
cacheComponents: true, cacheComponents: true,
...@@ -133,7 +135,7 @@ describe('loadConfig', () => { ...@@ -133,7 +135,7 @@ describe('loadConfig', () => {
it('errors when using persistentCaching if not in canary', async () => { it('errors when using persistentCaching if not in canary', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
turbopackPersistentCaching: true, turbopackPersistentCaching: true,
...@@ -157,7 +159,7 @@ describe('loadConfig', () => { ...@@ -157,7 +159,7 @@ describe('loadConfig', () => {
it('errors when cacheComponents is enabled but PPR is disabled', async () => { it('errors when cacheComponents is enabled but PPR is disabled', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
cacheComponents: true, cacheComponents: true,
...@@ -172,7 +174,7 @@ describe('loadConfig', () => { ...@@ -172,7 +174,7 @@ describe('loadConfig', () => {
it('errors when rdcForNavigations is enabled but ppr is disabled', async () => { it('errors when rdcForNavigations is enabled but ppr is disabled', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
rdcForNavigations: true, rdcForNavigations: true,
...@@ -186,7 +188,7 @@ describe('loadConfig', () => { ...@@ -186,7 +188,7 @@ describe('loadConfig', () => {
}) })
it('defaults rdcForNavigations to true when ppr is enabled', async () => { it('defaults rdcForNavigations to true when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
ppr: true, ppr: true,
...@@ -198,7 +200,7 @@ describe('loadConfig', () => { ...@@ -198,7 +200,7 @@ describe('loadConfig', () => {
}) })
it('allows explicitly disabling rdcForNavigations when ppr is enabled', async () => { it('allows explicitly disabling rdcForNavigations when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
ppr: true, ppr: true,
...@@ -212,7 +214,7 @@ describe('loadConfig', () => { ...@@ -212,7 +214,7 @@ describe('loadConfig', () => {
it('errors when cacheComponents is enabled but PPR set to "incremental"', async () => { it('errors when cacheComponents is enabled but PPR set to "incremental"', async () => {
await expect( await expect(
loadConfig('', __dirname, { loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
cacheComponents: true, cacheComponents: true,
...@@ -228,7 +230,7 @@ describe('loadConfig', () => { ...@@ -228,7 +230,7 @@ describe('loadConfig', () => {
it('migrates experimental.dynamicIO to experimental.cacheComponents', async () => { it('migrates experimental.dynamicIO to experimental.cacheComponents', async () => {
process.env.__NEXT_VERSION = 'canary' process.env.__NEXT_VERSION = 'canary'
const result = await loadConfig('', __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
dynamicIO: true, dynamicIO: true,
...@@ -246,7 +248,7 @@ describe('loadConfig', () => { ...@@ -246,7 +248,7 @@ describe('loadConfig', () => {
it('preserves cacheComponents when both dynamicIO and cacheComponents are set', async () => { it('preserves cacheComponents when both dynamicIO and cacheComponents are set', async () => {
process.env.__NEXT_VERSION = 'canary' process.env.__NEXT_VERSION = 'canary'
const result = await loadConfig('', __dirname, { const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
dynamicIO: true, dynamicIO: true,
...@@ -267,7 +269,7 @@ describe('loadConfig', () => { ...@@ -267,7 +269,7 @@ describe('loadConfig', () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation() const consoleSpy = jest.spyOn(console, 'warn').mockImplementation()
await loadConfig('', __dirname, { await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: { customConfig: {
experimental: { experimental: {
dynamicIO: true, dynamicIO: true,
......
...@@ -9,7 +9,7 @@ import { ...@@ -9,7 +9,7 @@ import {
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
PHASE_EXPORT, PHASE_EXPORT,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
PHASE_PRODUCTION_SERVER, type PHASE_TYPE,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared' import { defaultConfig, normalizeConfig } from './config-shared'
import type { import type {
...@@ -17,7 +17,6 @@ import type { ...@@ -17,7 +17,6 @@ import type {
NextConfigComplete, NextConfigComplete,
NextConfig, NextConfig,
TurbopackLoaderItem, TurbopackLoaderItem,
NextAdapter,
} from './config-shared' } from './config-shared'
import { loadWebpackHook } from './config-utils' import { loadWebpackHook } from './config-utils'
...@@ -43,6 +42,7 @@ import { findDir } from '../lib/find-pages-dir' ...@@ -43,6 +42,7 @@ import { findDir } from '../lib/find-pages-dir'
import { CanaryOnlyError, isStableBuild } from '../shared/lib/canary-only' import { CanaryOnlyError, isStableBuild } from '../shared/lib/canary-only'
import { interopDefault } from '../lib/interop-default' import { interopDefault } from '../lib/interop-default'
import { djb2Hash } from '../shared/lib/hash' import { djb2Hash } from '../shared/lib/hash'
import type { NextAdapter } from '../build/adapter/build-complete'
export { normalizeConfig } from './config-shared' export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared' export type { DomainLocale, NextConfig } from './config-shared'
...@@ -1203,15 +1203,12 @@ function assignDefaultsAndValidate( ...@@ -1203,15 +1203,12 @@ function assignDefaultsAndValidate(
async function applyModifyConfig( async function applyModifyConfig(
config: NextConfigComplete, config: NextConfigComplete,
phase: string, phase: PHASE_TYPE,
silent: boolean silent: boolean
): Promise<NextConfigComplete> { ): Promise<NextConfigComplete> {
if ( // we always call modify config and phase can be used to only
// TODO: should this be called for server start as // modify for specific times
// adapters shouldn't be relying on "next start" if (config.experimental?.adapterPath) {
[PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER].includes(phase) &&
config.experimental?.adapterPath
) {
const adapterMod = interopDefault( const adapterMod = interopDefault(
await import( await import(
pathToFileURL(require.resolve(config.experimental.adapterPath)).href pathToFileURL(require.resolve(config.experimental.adapterPath)).href
...@@ -1222,7 +1219,10 @@ async function applyModifyConfig( ...@@ -1222,7 +1219,10 @@ async function applyModifyConfig(
if (!silent) { if (!silent) {
Log.info(`Applying modifyConfig from ${adapterMod.name}`) Log.info(`Applying modifyConfig from ${adapterMod.name}`)
} }
config = await adapterMod.modifyConfig(config)
config = await adapterMod.modifyConfig(config, {
phase,
})
} }
} }
return config return config
...@@ -1241,7 +1241,7 @@ const configCache = new Map< ...@@ -1241,7 +1241,7 @@ const configCache = new Map<
// Generate cache key based on parameters that affect config output // Generate cache key based on parameters that affect config output
// We need a unique key for cache because there can be multiple values // We need a unique key for cache because there can be multiple values
function getCacheKey( function getCacheKey(
phase: string, phase: PHASE_TYPE,
dir: string, dir: string,
customConfig?: object | null, customConfig?: object | null,
reactProductionProfiling?: boolean, reactProductionProfiling?: boolean,
...@@ -1261,7 +1261,7 @@ function getCacheKey( ...@@ -1261,7 +1261,7 @@ function getCacheKey(
} }
export default async function loadConfig( export default async function loadConfig(
phase: string, phase: PHASE_TYPE,
dir: string, dir: string,
{ {
customConfig, customConfig,
...@@ -1656,7 +1656,7 @@ function enforceExperimentalFeatures( ...@@ -1656,7 +1656,7 @@ function enforceExperimentalFeatures(
isDefaultConfig: boolean isDefaultConfig: boolean
configuredExperimentalFeatures: ConfiguredExperimentalFeature[] | undefined configuredExperimentalFeatures: ConfiguredExperimentalFeature[] | undefined
debugPrerender: boolean | undefined debugPrerender: boolean | undefined
phase: string phase: PHASE_TYPE
} }
) { ) {
const { const {
......
...@@ -22,7 +22,10 @@ import { recursiveReadDir } from '../../../lib/recursive-readdir' ...@@ -22,7 +22,10 @@ import { recursiveReadDir } from '../../../lib/recursive-readdir'
import { isDynamicRoute } from '../../../shared/lib/router/utils' import { isDynamicRoute } from '../../../shared/lib/router/utils'
import { escapeStringRegexp } from '../../../shared/lib/escape-regexp' import { escapeStringRegexp } from '../../../shared/lib/escape-regexp'
import { getPathMatch } from '../../../shared/lib/router/utils/path-match' import { getPathMatch } from '../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex' import {
getNamedRouteRegex,
getRouteRegex,
} from '../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix' import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
...@@ -255,10 +258,14 @@ export async function setupFsCheck(opts: { ...@@ -255,10 +258,14 @@ export async function setupFsCheck(opts: {
for (const route of routesManifest.dataRoutes) { for (const route of routesManifest.dataRoutes) {
if (isDynamicRoute(route.page)) { if (isDynamicRoute(route.page)) {
const routeRegex = getRouteRegex(route.page) const routeRegex = getNamedRouteRegex(route.page, {
prefixRouteKeys: true,
})
dynamicRoutes.push({ dynamicRoutes.push({
...route, ...route,
regex: routeRegex.re.toString(), regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
match: getRouteMatcher({ match: getRouteMatcher({
// TODO: fix this in the manifest itself, must also be fixed in // TODO: fix this in the manifest itself, must also be fixed in
// upstream builder that relies on this // upstream builder that relies on this
......
...@@ -37,7 +37,7 @@ import { ...@@ -37,7 +37,7 @@ import {
} from '../../../build/entries' } from '../../../build/entries'
import { verifyTypeScriptSetup } from '../../../lib/verify-typescript-setup' import { verifyTypeScriptSetup } from '../../../lib/verify-typescript-setup'
import { verifyPartytownSetup } from '../../../lib/verify-partytown-setup' import { verifyPartytownSetup } from '../../../lib/verify-partytown-setup'
import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
import { buildDataRoute } from './build-data-route' import { buildDataRoute } from './build-data-route'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
...@@ -970,9 +970,13 @@ async function startWatcher( ...@@ -970,9 +970,13 @@ async function startWatcher(
opts.fsChecker.dynamicRoutes = sortedRoutes.map( opts.fsChecker.dynamicRoutes = sortedRoutes.map(
(page): FilesystemDynamicRoute => { (page): FilesystemDynamicRoute => {
const regex = getRouteRegex(page) const regex = getNamedRouteRegex(page, {
prefixRouteKeys: true,
})
return { return {
regex: regex.re.toString(), regex: regex.re.toString(),
namedRegex: regex.namedRegex,
routeKeys: regex.routeKeys,
match: getRouteMatcher(regex), match: getRouteMatcher(regex),
page, page,
} }
...@@ -983,10 +987,14 @@ async function startWatcher( ...@@ -983,10 +987,14 @@ async function startWatcher(
for (const page of sortedRoutes) { for (const page of sortedRoutes) {
const route = buildDataRoute(page, 'development') const route = buildDataRoute(page, 'development')
const routeRegex = getRouteRegex(route.page) const routeRegex = getNamedRouteRegex(route.page, {
prefixRouteKeys: true,
})
dataRoutes.push({ dataRoutes.push({
...route, ...route,
regex: routeRegex.re.toString(), regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
match: getRouteMatcher({ match: getRouteMatcher({
// TODO: fix this in the manifest itself, must also be fixed in // TODO: fix this in the manifest itself, must also be fixed in
// upstream builder that relies on this // upstream builder that relies on this
......
...@@ -12,6 +12,22 @@ export const COMPILER_NAMES = { ...@@ -12,6 +12,22 @@ export const COMPILER_NAMES = {
export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES> export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
// Re-export entry constants for backward compatibility
export {
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
} from './entry-constants'
export enum AdapterOutputType { export enum AdapterOutputType {
/** /**
* `PAGES` represents all the React pages that are under `pages/`. * `PAGES` represents all the React pages that are under `pages/`.
...@@ -51,28 +67,21 @@ export enum AdapterOutputType { ...@@ -51,28 +67,21 @@ export enum AdapterOutputType {
MIDDLEWARE = 'MIDDLEWARE', MIDDLEWARE = 'MIDDLEWARE',
} }
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
// Re-export entry constants for backward compatibility
export {
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
} from './entry-constants'
export const PHASE_EXPORT = 'phase-export' export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build' export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server' export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server' export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PHASE_TEST = 'phase-test' export const PHASE_TEST = 'phase-test'
export const PHASE_INFO = 'phase-info' export const PHASE_INFO = 'phase-info'
export type PHASE_TYPE =
| typeof PHASE_INFO
| typeof PHASE_TEST
| typeof PHASE_EXPORT
| typeof PHASE_PRODUCTION_BUILD
| typeof PHASE_PRODUCTION_SERVER
| typeof PHASE_DEVELOPMENT_SERVER
export const PAGES_MANIFEST = 'pages-manifest.json' export const PAGES_MANIFEST = 'pages-manifest.json'
export const WEBPACK_STATS = 'webpack-stats.json' export const WEBPACK_STATS = 'webpack-stats.json'
export const APP_PATHS_MANIFEST = 'app-paths-manifest.json' export const APP_PATHS_MANIFEST = 'app-paths-manifest.json'
......
...@@ -29,7 +29,7 @@ export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined ...@@ -29,7 +29,7 @@ export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined
// @ts-ignore This path is generated at build time and conflicts otherwise // @ts-ignore This path is generated at build time and conflicts otherwise
export { NextConfig } from './server/config' export { NextConfig } from './server/config'
export type { NextAdapter } from './server/config-shared' export type { NextAdapter, AdapterOutput } from './build/adapter/build-complete'
export type { export type {
Metadata, Metadata,
......
...@@ -1857,6 +1857,7 @@ const runTests = (isDev = false) => { ...@@ -1857,6 +1857,7 @@ const runTests = (isDev = false) => {
{ {
"destination": "/:path+", "destination": "/:path+",
"internal": true, "internal": true,
"priority": true,
"regex": "^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$", "regex": "^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$",
"source": "/:path+/", "source": "/:path+/",
"statusCode": 308, "statusCode": 308,
......
...@@ -1456,6 +1456,7 @@ function runTests({ dev }) { ...@@ -1456,6 +1456,7 @@ function runTests({ dev }) {
{ {
"destination": "/:path+", "destination": "/:path+",
"internal": true, "internal": true,
"priority": true,
"regex": "^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$", "regex": "^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$",
"source": "/:path+/", "source": "/:path+/",
"statusCode": 308, "statusCode": 308,
......
import fs from 'fs' import fs from 'fs'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next' import type { AdapterOutput, NextAdapter } from 'next'
import { AdapterOutputType } from 'next/constants' import { version as nextVersion } from 'next/package.json'
describe('adapter-config', () => { describe('adapter-config', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -23,56 +23,64 @@ describe('adapter-config', () => { ...@@ -23,56 +23,64 @@ describe('adapter-config', () => {
it('should call onBuildComplete with correct context', async () => { it('should call onBuildComplete with correct context', async () => {
expect(next.cliOutput).toContain('onBuildComplete called') expect(next.cliOutput).toContain('onBuildComplete called')
const buildContext: Parameters<NextAdapter['onBuildComplete']>[0] = const {
await next.readJSON('build-complete.json') outputs,
routes,
config,
...ctx
}: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
'build-complete.json'
)
const outputMap = new Map<string, (typeof buildContext.outputs)[0]>() for (const field of ['distDir', 'projectDir', 'repoRoot']) {
const prerenderOutputs: typeof buildContext.outputs = [] expect(ctx[field]).toBeString()
const staticOutputs: typeof buildContext.outputs = []
const nodeOutputs: typeof buildContext.outputs = []
const edgeOutputs: typeof buildContext.outputs = []
for (const output of buildContext.outputs) { if (!fs.existsSync(ctx[field])) {
if (outputMap.has(output.id)) {
throw new Error( throw new Error(
`multiple outputs with same ID ${JSON.stringify( `Invalid dir value provided for ${field} value ${ctx[field]}`
{
first: outputMap.get(output.id),
second: output,
},
null,
2
)}`
) )
} }
}
switch (output.type) { expect(ctx.nextVersion).toBe(nextVersion)
case AdapterOutputType.PRERENDER: { expect(config?.basePath).toBe('/docs')
prerenderOutputs.push(output)
break const combinedRouteOutputs = [
} ...outputs.appPages,
case AdapterOutputType.STATIC_FILE: { ...outputs.appRoutes,
staticOutputs.push(output) ...outputs.pages,
break ...outputs.pagesApi,
} ]
case AdapterOutputType.APP_PAGE:
case AdapterOutputType.APP_ROUTE: type PageRoutesType =
case AdapterOutputType.PAGES: | AdapterOutput['APP_PAGE']
case AdapterOutputType.PAGES_API: { | AdapterOutput['APP_ROUTE']
if (output.runtime === 'nodejs') { | AdapterOutput['PAGES']
nodeOutputs.push(output) | AdapterOutput['PAGES_API']
} else if (output.runtime === 'edge') {
edgeOutputs.push(output) const outputMap = new Map<string, PageRoutesType>()
} else { const prerenderOutputs: AdapterOutput['PRERENDER'][] = outputs.prerenders
throw new Error( const staticOutputs: AdapterOutput['STATIC_FILE'][] = outputs.staticFiles
`unrecognized runtime on ${JSON.stringify(output, null, 2)}` const nodeOutputs: PageRoutesType[] = []
) const edgeOutputs: PageRoutesType[] = []
}
break for (const routeOutput of combinedRouteOutputs) {
} if (outputMap.has(routeOutput.id)) {
default: { require('console').error({
throw new Error(`unrecognized output type ${output.type}`) existingOutput: outputMap.get(routeOutput.id),
} newOutput: routeOutput,
})
throw new Error(`duplicate id on route outputs ${routeOutput.id}`)
}
outputMap.set(routeOutput.id, routeOutput)
if (routeOutput.runtime === 'edge') {
edgeOutputs.push(routeOutput)
} else if (routeOutput.runtime === 'nodejs') {
nodeOutputs.push(routeOutput)
} else {
require('console').error(routeOutput)
throw new Error(`Unexpected runtime on output ${routeOutput.runtime}`)
} }
} }
...@@ -83,17 +91,25 @@ describe('adapter-config', () => { ...@@ -83,17 +91,25 @@ describe('adapter-config', () => {
for (const output of staticOutputs) { for (const output of staticOutputs) {
expect(output.id).toBeTruthy() expect(output.id).toBeTruthy()
expect(output.pathname).toStartWith('/_next/static')
expect(fs.existsSync(output.filePath)).toBe(true) if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false)
} else {
expect(output.pathname).toStartWith('/_next/static')
}
const stats = await fs.promises.stat(output.filePath)
expect(stats.isFile()).toBe(true)
} }
for (const prerenderOutput of prerenderOutputs) { for (const prerenderOutput of prerenderOutputs) {
try { try {
expect(prerenderOutput.parentOutputId).toBeTruthy() expect(prerenderOutput.parentOutputId).toBeTruthy()
if (prerenderOutput.fallback) { if (prerenderOutput.fallback) {
expect(await fs.existsSync(prerenderOutput.fallback.filePath)).toBe( const stats = await fs.promises.stat(
true prerenderOutput.fallback.filePath
) )
expect(stats.isFile()).toBe(true)
expect(prerenderOutput.fallback.initialRevalidate).toBeDefined() expect(prerenderOutput.fallback.initialRevalidate).toBeDefined()
} }
...@@ -106,7 +122,57 @@ describe('adapter-config', () => { ...@@ -106,7 +122,57 @@ describe('adapter-config', () => {
} }
} }
expect(buildContext.routes).toEqual({ for (const route of nodeOutputs) {
try {
expect(route.id).toBeString()
expect(route.config).toBeObject()
expect(route.pathname).toBeString()
expect(route.runtime).toBe('nodejs')
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
const missingAssets: string[] = []
for (const filePath of Object.values(route.assets)) {
if (!fs.existsSync(filePath)) {
missingAssets.push(filePath)
}
}
expect(missingAssets).toEqual([])
} catch (err) {
require('console').error(`Invalid fields for ${route.id}`, route, err)
throw err
}
}
for (const route of edgeOutputs) {
try {
expect(route.id).toBeString()
expect(route.config).toBeObject()
expect(route.pathname).toBeString()
expect(route.runtime).toBe('edge')
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
const missingAssets: string[] = []
for (const filePath of Object.values(route.assets)) {
if (!fs.existsSync(filePath)) {
missingAssets.push(filePath)
}
}
expect(missingAssets).toEqual([])
} catch (err) {
require('console').error(`Invalid fields for ${route.id}`, route, err)
throw err
}
}
expect(routes).toEqual({
dynamicRoutes: expect.toBeArray(), dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(), rewrites: expect.toBeObject(),
redirects: expect.toBeArray(), redirects: expect.toBeArray(),
......
...@@ -4,8 +4,11 @@ import fs from 'fs' ...@@ -4,8 +4,11 @@ import fs from 'fs'
/** @type {import('next').NextAdapter } */ /** @type {import('next').NextAdapter } */
const myAdapter = { const myAdapter = {
name: 'my-custom-adapter', name: 'my-custom-adapter',
modifyConfig: (config) => { modifyConfig: (config, { phase }) => {
console.log('called modify config in adapter') if (typeof phase !== 'string') {
throw new Error(`invalid phase value provided to modifyConfig ${phase}`)
}
console.log('called modify config in adapter with phase', phase)
config.basePath = '/docs' config.basePath = '/docs'
return config return config
}, },
......
export default function Pages() {
return <p>automatic-static-pages</p>
}
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