Unverified Commit 81379615 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Distinguish build Page identifiers from Route patterns

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 78fe5180
import { pageToRoute } from '../utils'
import { collectFallbackShellRuns } from './fallback-shell-runs'
import type { RoutesManifest } from '..'
import { createRoute } from '../../shared/lib/route-types'
// The suites in `test/production/app-dir/adapter-dynamic-routes` cover the
// shapes that a build produces, and they pin the entries that come out of them.
......@@ -13,26 +13,25 @@ import type { RoutesManifest } from '..'
// shape of a result.
/**
* A fallback shell, which the build derives from a source page.
* A fallback shell, which the build derives from a normalized source URL pattern.
*/
function shell(page: string, sourcePage: string) {
return pageToRoute(page, sourcePage)
return pageToRoute(createRoute(page), createRoute(sourcePage))
}
/**
* Any other dynamic route, which carries no source page.
*/
function plain(page: string) {
return pageToRoute(page, undefined)
return pageToRoute(createRoute(page), undefined)
}
function collect(
routes: ReturnType<typeof plain>[],
fallbackFalsePages: string[] = []
) {
const result = collectFallbackShellRuns(
routes as RoutesManifest['dynamicRoutes'],
(page) => fallbackFalsePages.includes(page)
const result = collectFallbackShellRuns(routes, (page) =>
fallbackFalsePages.includes(page)
)
return {
......
......@@ -15,6 +15,7 @@
* place relative to the routes around it.
*/
import type { Route } from '../../shared/lib/route-types'
import type { RoutesManifest } from '..'
import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { escapeStringRegexp } from '../../shared/lib/escape-regexp'
......@@ -37,12 +38,12 @@ export type FallbackShellRuns = {
/**
* The runs, keyed by the page of the representative of each.
*/
byRepresentativePage: Map<string, FallbackShellRun>
byRepresentativePage: Map<Route, FallbackShellRun>
/**
* The pages of the shells that a run serves, apart from the representative
* that keys it. The caller emits no entry of its own for these.
*/
replacedPages: Set<string>
replacedPages: Set<Route>
}
/**
......@@ -53,7 +54,7 @@ type PendingRun = {
/**
* The source page that every shell of the run repeats.
*/
sourcePage: string
sourcePage: Route
/**
* The path that every shell of the run has after its prefix.
*/
......@@ -70,7 +71,7 @@ type PendingRun = {
/**
* The page of the shell.
*/
page: string
page: Route
/**
* The leading part of that page, which holds the values that the shell
* resolves for the params of the source page.
......@@ -87,8 +88,8 @@ type PendingRun = {
* segments are not consecutive from the first segment onwards.
*/
function splitShellPage(
page: string,
sourcePage: string
page: Route,
sourcePage: Route
): { prefix: string; tail: string } | undefined {
const pageSegments = page.split('/')
const sourceSegments = sourcePage.split('/')
......@@ -176,8 +177,8 @@ function splitShellPage(
* shell out of the result.
*/
export function collectFallbackShellRuns(
dynamicRoutes: RoutesManifest['dynamicRoutes'],
hasFallbackFalse: (page: string) => boolean
dynamicRoutes: RoutesManifest<Route>['dynamicRoutes'],
hasFallbackFalse: (page: Route) => boolean
): FallbackShellRuns {
const runs: PendingRun[] = []
let current: PendingRun | undefined
......@@ -224,8 +225,8 @@ export function collectFallbackShellRuns(
current.shells.push({ page: route.page, prefix: split.prefix })
}
const byRepresentativePage = new Map<string, FallbackShellRun>()
const replacedPages = new Set<string>()
const byRepresentativePage = new Map<Route, FallbackShellRun>()
const replacedPages = new Set<Route>()
for (const run of runs) {
if (run.shells.length < 2) {
......
import type { Page } from '../shared/lib/route-types'
import type { LoadedEnvFiles } from '@next/env'
import type { Rewrite } from '../lib/load-custom-routes'
import type { __ApiPreviewProps } from '../server/api-utils'
......@@ -40,9 +41,9 @@ export function getPluginState() {
return pluginState
}
export interface MappedPages {
[page: string]: string
}
// Dev callers retain string-compatible module lookup keys. Build-owned context
// and discovery opt into the Page-keyed view.
export type MappedPages<Key extends string = string> = Record<Key, string>
// a global object to store context for the current build
// this is used to pass data between different steps of the build without having
......@@ -67,10 +68,10 @@ export const NextBuildContext: Partial<{
hasRewrites: boolean
loadedEnvFiles: LoadedEnvFiles
previewProps: __ApiPreviewProps
mappedPages: MappedPages | undefined
mappedAppPages: MappedPages | undefined
mappedAppDefaults: MappedPages | undefined
mappedRootPaths: MappedPages
mappedPages: MappedPages<Page> | undefined
mappedAppPages: MappedPages<Page> | undefined
mappedAppDefaults: MappedPages<Page> | undefined
mappedRootPaths: MappedPages<Page>
hasInstrumentationHook: boolean
// misc fields
......
This diff is collapsed.
import type { Page, Route } from '../shared/lib/route-types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { isParallelRouteSegment } from '../shared/lib/segment'
// Slot information for parallel routes
export type SlotInfo = { name: string; parent: string }
export type SlotInfo<Path extends string = string> = {
name: string
parent: Path
}
// Route information for route manifests
export type RouteInfo = { route: string; filePath: string }
export type RouteInfo<Path extends string = string> = {
route: Path
filePath: string
}
/**
* Extract slot info from a page path if it contains a parallel route
*/
export function extractSlotFromPath(pagePath: string): SlotInfo | undefined {
export function extractSlotFromPath(
pagePath: string
): SlotInfo<Route> | undefined {
const segments = pagePath.split('/')
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (isParallelRouteSegment(segment)) {
return {
name: segment.slice(1),
parent: normalizeAppPath(segments.slice(0, i).join('/')),
// TODO: Human review: this slot-parent directory prefix is not a
// complete Page module; a real trailing page/route directory may be
// stripped as a leaf. Preserve existing discovery and scope its URL
// result view here, rather than branding the prefix as a module ID.
parent: normalizeAppPath(segments.slice(0, i).join('/')) as Route,
}
}
}
......@@ -40,11 +53,11 @@ export function addSlotIfNew(slots: SlotInfo[], pagePath: string): boolean {
* Extract slots from a route mapping object
*/
export function extractSlotsFromRoutes(
routes: { [page: string]: string },
skipRoutes?: Set<string>
): SlotInfo[] {
const slots: SlotInfo[] = []
for (const [route] of Object.entries(routes)) {
routes: Record<Page, string>,
skipRoutes?: ReadonlySet<string>
): SlotInfo<Route>[] {
const slots: SlotInfo<Route>[] = []
for (const [route] of Object.entries(routes) as [Page, string][]) {
if (skipRoutes?.has(route)) continue
addSlotIfNew(slots, route)
}
......@@ -54,9 +67,11 @@ export function extractSlotsFromRoutes(
/**
* Combine and deduplicate slot arrays
*/
export function combineSlots(...slotArrays: SlotInfo[][]): SlotInfo[] {
export function combineSlots<Path extends string>(
...slotArrays: SlotInfo<Path>[][]
): SlotInfo<Path>[] {
const slotSet = new Set<string>()
const result: SlotInfo[] = []
const result: SlotInfo<Path>[] = []
for (const slots of slotArrays) {
for (const slot of slots) {
const key = `${slot.name}:${slot.parent}`
......
import type { Route } from '../shared/lib/route-types'
import type { NextConfigComplete } from '../server/config-shared'
import type { CustomRoutes } from '../lib/load-custom-routes'
import {
......@@ -25,8 +26,8 @@ import { sortPages } from '../shared/lib/router/utils/sortable-routes'
export interface GenerateRoutesManifestOptions {
pageKeys: {
pages: string[]
app?: string[]
pages: Route[]
app?: Route[]
}
config: NextConfigComplete
redirects: CustomRoutes['redirects']
......@@ -40,9 +41,9 @@ export interface GenerateRoutesManifestOptions {
}
export interface GenerateRoutesManifestResult {
routesManifest: RoutesManifest
dynamicRoutes: Array<DynamicManifestRoute>
sourcePages: Map<string, string>
routesManifest: RoutesManifest<Route>
dynamicRoutes: Array<DynamicManifestRoute<Route>>
sourcePages: Map<Route, Route>
}
/**
......@@ -67,14 +68,15 @@ export function generateRoutesManifest(
} = options
const sortedRoutes = sortPages([...pageKeys.pages, ...(pageKeys.app ?? [])])
const staticRoutes: Array<ManifestRoute> = []
const dynamicRoutes: Array<DynamicManifestRoute> = []
const staticRoutes: Array<ManifestRoute<Route>> = []
const dynamicRoutes: Array<DynamicManifestRoute<Route>> = []
/**
* A map of all the pages to their sourcePage value. This is only used for
* A map of URL route patterns to their normalized source URL route pattern.
* This is only used for
* routes that have PPR enabled and clientSegmentEnabled is true.
*/
const sourcePages = new Map<string, string>()
const sourcePages = new Map<Route, Route>()
for (const route of sortedRoutes) {
if (isDynamicRoute(route)) {
......@@ -94,7 +96,7 @@ export function generateRoutesManifest(
}
}
const routesManifest: RoutesManifest = {
const routesManifest: RoutesManifest<Route> = {
version: 3,
pages404: true,
appType,
......
import {
type Page,
createPage,
createRoute,
pagesRouteToPage,
} from '../shared/lib/route-types'
import type { TurbopackManifestLoader } from '../shared/lib/turbopack/manifest-loader'
import type {
Entrypoints,
......@@ -10,19 +16,25 @@ import * as Log from './output/log'
export async function rawEntrypointsToEntrypoints(
entrypointsOp: RawEntrypoints
): Promise<Entrypoints> {
const page = new Map()
const app = new Map()
): Promise<Entrypoints<Page>> {
const page: Entrypoints<Page>['page'] = new Map()
const app: Entrypoints<Page>['app'] = new Map()
for (const [pathname, route] of entrypointsOp.routes) {
switch (route.type) {
case 'page':
case 'page-api':
page.set(pathname, route)
// At the native pages-router boundary, a URL pathname also identifies
// the page; there are no app modifiers or leaf suffixes to preserve.
// Native transport has primitive string keys; this paired Pages case
// owns their URL ingestion before the proven module-ID identity bridge.
page.set(pagesRouteToPage(createRoute(pathname)), route)
break
case 'app-page': {
for (const p of route.pages) {
app.set(p.originalName, {
// Native originalName is the complete raw App module ID, not the
// normalized outer route key. Ingest only at this owned boundary.
app.set(createPage(p.originalName), {
type: 'app-page',
...p,
})
......@@ -30,7 +42,7 @@ export async function rawEntrypointsToEntrypoints(
break
}
case 'app-route': {
app.set(route.originalName, route)
app.set(createPage(route.originalName), route)
break
}
case 'conflict':
......@@ -59,6 +71,8 @@ export async function handleRouteType({
route,
manifestLoader,
}: {
// Untouched dev callers retain their module-ID string contract. This
// dispatcher forwards to legacy manifest readers without reconstructing it.
page: string
route: PageRoute | AppRoute
manifestLoader: TurbopackManifestLoader
......@@ -77,7 +91,7 @@ export async function handleRouteType({
manifestLoader.deleteMiddlewareManifest(serverKey)
}
await manifestLoader.loadFontManifest('/_app', 'pages')
await manifestLoader.loadFontManifest(createPage('/_app'), 'pages')
await manifestLoader.loadFontManifest(page, 'pages')
await manifestLoader.loadSriManifest(page, 'pages')
......
This diff is collapsed.
import type { Page, Route } from '../shared/lib/route-types'
import {
findIncompatibleParallelRouteSlots,
normalizeCatchAllRoutes as normalizeCatchAllRoutesInternal,
......@@ -6,6 +7,18 @@ import {
export { findIncompatibleParallelRouteSlots }
// The legacy matcher returns unmatched module IDs only by filtering and sorting
// original input values (not by constructing new IDs). Retain their Page role in
// this build-owned overload without changing the shared matcher or its result.
export function normalizeCatchAllRoutes(
appPaths: Record<Route, Page[]>,
options?: NormalizeCatchAllRoutesOptions
): Omit<
ReturnType<typeof normalizeCatchAllRoutesInternal>,
'unmatchedAppPages'
> & {
unmatchedAppPages: Page[]
}
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
options: NormalizeCatchAllRoutesOptions = {}
......
import {
pagesRouteToPage,
type Page,
type Route,
} from '../shared/lib/route-types'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import path from 'path'
import { promises as fs, statSync } from 'fs'
import {
......@@ -11,7 +17,7 @@ import { filterAndSortList } from './utils'
const ROUTE_BUNDLE_STATS_FILE = 'route-bundle-stats.json'
type RouteBundleStat = {
route: string
route: Route
firstLoadUncompressedJsBytes: number
firstLoadChunkPaths: string[]
}
......@@ -48,14 +54,14 @@ function toProjectRelativePaths(
}
function buildRouteToAppPathsMap(
appPathsManifest: Record<string, string>
): Map<string, string[]> {
appPathsManifest: PagesManifest
): Map<Route, Page[]> {
const { normalizeAppPath } =
require('../shared/lib/router/utils/app-paths') as typeof import('../shared/lib/router/utils/app-paths')
// Keys in appPathsManifest are app paths like /blog/[slug]/page;
// values are server bundle file paths. Normalize the key to get the route.
const routeToAppPaths = new Map<string, string[]>()
for (const appPath of Object.keys(appPathsManifest)) {
const routeToAppPaths = new Map<Route, Page[]>()
for (const appPath of Object.keys(appPathsManifest) as Page[]) {
const route = normalizeAppPath(appPath)
const existing = routeToAppPaths.get(route)
if (existing) {
......@@ -72,8 +78,8 @@ function buildRouteToAppPathsMap(
// it with a save/restore of the global
function readEntryJSFiles(
distDir: string,
pagePath: string,
appRoute: string
pagePath: Page,
appRoute: Route
): Record<string, string[]> | undefined {
const manifestFile = path.join(
distDir,
......@@ -87,11 +93,12 @@ function readEntryJSFiles(
g.__RSC_MANIFEST = undefined
require(manifestFile)
const rscManifest = g.__RSC_MANIFEST as
| Record<string, { entryJSFiles?: Record<string, string[]> }>
| Record<Page, { entryJSFiles?: Record<string, string[]> }>
| undefined
g.__RSC_MANIFEST = prev
// The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page)
// @ts-ignore -- TODO: Human review: the fallback probe uses a normalized App URL in a raw App-module-keyed RSC manifest. This may be an intentional legacy miss; preserve it without claiming the URL is a raw Page.
const manifestEntry = rscManifest?.[pagePath] ?? rscManifest?.[appRoute]
return manifestEntry?.entryJSFiles
} catch {
......@@ -100,7 +107,7 @@ function readEntryJSFiles(
}
function collectPagesRouterStats(
pages: ReadonlyArray<string>,
pages: ReadonlyArray<Route>,
buildManifest: BuildManifest,
distDir: string,
dir: string,
......@@ -113,8 +120,9 @@ function collectPagesRouterStats(
// Don't report on layouts directly
continue
const allFiles = (buildManifest.pages[page] ?? []).filter((f) =>
f.endsWith('.js')
// This list contains only Pages-router URL keys, sharing the module namespace.
const allFiles = (buildManifest.pages[pagesRouteToPage(page)] ?? []).filter(
(f) => f.endsWith('.js')
)
const sharedJs = sharedFiles.filter((f) => f.endsWith('.js'))
const chunks = [...new Set([...allFiles, ...sharedJs])]
......@@ -129,13 +137,13 @@ function collectPagesRouterStats(
}
async function collectAppRouterStats(
appRoutes: ReadonlyArray<string>,
appRoutes: ReadonlyArray<Route>,
buildManifest: BuildManifest,
distDir: string,
dir: string,
cache: Map<string, number>
): Promise<RouteBundleStat[]> {
let appPathsManifest: Record<string, string> = {}
let appPathsManifest: PagesManifest = {}
try {
const manifestPath = path.join(
distDir,
......@@ -184,8 +192,8 @@ async function collectAppRouterStats(
export async function writeRouteBundleStats(
lists: {
pages: ReadonlyArray<string>
app: ReadonlyArray<string> | undefined
pages: ReadonlyArray<Route>
app: ReadonlyArray<Route> | undefined
},
buildManifest: BuildManifest,
distDir: string,
......
import {
createPage,
pagesPageToRoute,
type Page,
type Route,
} from '../shared/lib/route-types'
import { join } from 'path'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { recursiveReadDir } from '../lib/recursive-readdir'
......@@ -47,7 +53,7 @@ const PAGES_SUPPORT_ROUTES = new Set([
])
const PAGES_FRAMEWORK_ROUTES = new Set(['/_app', '/_document', '/_error'])
function isRenderablePagesRoute(page: string): boolean {
function isRenderablePagesRoute(page: Page): boolean {
return (
!PAGES_FRAMEWORK_ROUTES.has(page) &&
page !== '/api' &&
......@@ -60,15 +66,18 @@ function removeSuffix(value: string, suffix: string): string {
}
/** Normalize a route for the app router */
function normalizeAppRoute(pageName: string): string {
function normalizeAppRoute(pageName: Page): Route {
return normalizeAppPath(normalizePathSep(pageName))
}
/** Normalize a layout route (strip /layout suffix) */
function normalizeLayoutRoute(pageName: string): string {
function normalizeLayoutRoute(pageName: Page): Route {
// The suffix removal may yield empty text for the root layout. Establish the
// Route only after the existing leading-slash step completes this normalizer.
// TODO: Guard this normalizer's completed Route boundary without changing its string helpers.
return ensureLeadingSlash(
removeSuffix(normalizeAppPath(normalizePathSep(pageName)), '/layout')
)
) as Route
}
/**
......@@ -77,7 +86,7 @@ function normalizeLayoutRoute(pageName: string): string {
export function getPageFromPath(
pagePath: string,
pageExtensions: PageExtensions
) {
): Page {
let page = normalizePathSep(pagePath)
// Try longer extensions first so compound extensions like 'page.js'
// match before shorter ones like 'js'
......@@ -92,11 +101,13 @@ export function getPageFromPath(
page = removeSuffix(page, '/index')
return page === '' ? '/' : page
return createPage(page === '' ? '/' : page)
}
/**
* Collect app pages, layouts, and default files from the app directory
* Collect app pages, layouts, and default files from the app directory.
* These arrays hold discovered filenames, including extensions, not Page
* identifiers; createPagesMapping performs that boundary conversion later.
*/
export async function collectAppFiles(
appDir: string,
......@@ -164,7 +175,7 @@ export function createRelativeFilePath(
* Process pages routes from mapped pages
*/
export function processPageRoutes(
mappedPages: { [page: string]: string },
mappedPages: MappedPages<Page>,
baseDir: string,
isSrcDir: boolean
): {
......@@ -174,7 +185,12 @@ export function processPageRoutes(
const pageRoutes: RouteInfo[] = []
const pageApiRoutes: RouteInfo[] = []
for (const [route, filePath] of Object.entries(mappedPages)) {
// Pages-router mapping keys already spell the URL pathname; unlike app
// keys, they have no groups, slots or leaf suffixes to remove.
for (const [route, filePath] of Object.entries(mappedPages) as [
Page,
string,
][]) {
const relativeFilePath = createRelativeFilePath(
baseDir,
filePath,
......@@ -184,14 +200,14 @@ export function processPageRoutes(
if (route.startsWith('/api/')) {
pageApiRoutes.push({
route: normalizePathSep(route),
route: pagesPageToRoute(normalizePathSep(route)),
filePath: relativeFilePath,
})
} else {
if (isReservedPage(route)) continue
pageRoutes.push({
route: normalizePathSep(route),
route: pagesPageToRoute(normalizePathSep(route)),
filePath: relativeFilePath,
})
}
......@@ -204,7 +220,7 @@ export function processPageRoutes(
* Process app routes from mapped app pages
*/
export function processAppRoutes(
mappedAppPages: { [page: string]: string },
mappedAppPages: MappedPages<Page>,
validFileMatcher: ReturnType<typeof createValidFileMatcher>,
baseDir: string,
isSrcDir: boolean
......@@ -215,7 +231,11 @@ export function processAppRoutes(
const appRoutes: RouteInfo[] = []
const appRouteHandlers: RouteInfo[] = []
for (const [page, filePath] of Object.entries(mappedAppPages)) {
// Object.entries erases the module-key role already established by mapping.
for (const [page, filePath] of Object.entries(mappedAppPages) as [
Page,
string,
][]) {
if (
page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY ||
page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
......@@ -245,14 +265,17 @@ export function processAppRoutes(
* Process layout routes from mapped app layouts
*/
export function processLayoutRoutes(
mappedAppLayouts: { [page: string]: string },
mappedAppLayouts: MappedPages<Page>,
baseDir: string,
isSrcDir: boolean
): RouteInfo[] {
return Object.entries(mappedAppLayouts).map(([route, filePath]) => ({
route: normalizeLayoutRoute(route),
filePath: createRelativeFilePath(baseDir, filePath, 'app', isSrcDir),
}))
// Preserve the mapped module-key role through Object.entries, not new branding.
return (Object.entries(mappedAppLayouts) as [Page, string][]).map(
([route, filePath]) => ({
route: normalizeLayoutRoute(route),
filePath: createRelativeFilePath(baseDir, filePath, 'app', isSrcDir),
})
)
}
/**
......@@ -274,10 +297,10 @@ export async function createPagesMapping({
pagesDir: string | undefined
appDir: string | undefined
appDirOnly: boolean
}): Promise<MappedPages> {
}): Promise<MappedPages<Page>> {
const isAppRoute = pagesType === 'app'
const promises = pagePaths.map<Promise<[string, string] | undefined>>(
const promises = pagePaths.map<Promise<[Page, string] | undefined>>(
async (pagePath) => {
if (pagePath.endsWith('.d.ts') && pageExtensions.includes('ts')) {
return
......@@ -286,12 +309,12 @@ export async function createPagesMapping({
let pageKey = getPageFromPath(pagePath, pageExtensions)
if (isAppRoute) {
// Turbopack encodes '_' as '%5F' in app paths; normalize to underscores.
pageKey = pageKey.replace(/%5F/g, '_')
pageKey = createPage(pageKey.replace(/%5F/g, '_'))
if (pageKey === UNDERSCORE_NOT_FOUND_ROUTE) {
pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
pageKey = createPage(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)
}
if (pageKey === UNDERSCORE_GLOBAL_ERROR_ROUTE) {
pageKey = UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
pageKey = createPage(UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY)
}
}
......@@ -332,7 +355,7 @@ export async function createPagesMapping({
}
)
const pages: MappedPages = Object.fromEntries(
const pages: MappedPages<Page> = Object.fromEntries(
(await Promise.all(promises)).filter((entry) => entry != null)
)
......@@ -359,9 +382,9 @@ export async function createPagesMapping({
}
case PAGE_TYPES.PAGES: {
if (isDev) {
delete pages['/_app']
delete pages['/_error']
delete pages['/_document']
delete pages[createPage('/_app')]
delete pages[createPage('/_error')]
delete pages[createPage('/_document')]
}
const root = isDev && pagesDir ? PAGES_DIR_ALIAS : 'next/dist/pages'
......@@ -406,10 +429,10 @@ export interface RouteDiscoveryResult {
slots: SlotInfo[]
pageRoutes: RouteInfo[]
pageApiRoutes: RouteInfo[]
mappedAppPages?: MappedPages
mappedAppLayouts?: MappedPages
mappedAppDefaults?: MappedPages
mappedPages?: MappedPages
mappedAppPages?: MappedPages<Page>
mappedAppLayouts?: MappedPages<Page>
mappedAppDefaults?: MappedPages<Page>
mappedPages?: MappedPages<Page>
/** Raw page file paths (post-filtering), useful for telemetry */
pagesPaths: string[]
/** Resolved app-dir-only state (may have been updated during discovery) */
......@@ -449,7 +472,8 @@ export async function discoverRoutes(
appDirOnly,
})
// Helper to apply debugBuildPaths filtering
// Helper to apply debugBuildPaths filtering. Both arrays contain filesystem
// names resolved from CLI globs, not normalized route identities.
const applyDebugFilter = (
paths: string[],
debugPaths: string[]
......@@ -480,7 +504,7 @@ export async function discoverRoutes(
let pageRoutes: RouteInfo[] = []
let pageApiRoutes: RouteInfo[] = []
let mappedPages: MappedPages | undefined
let mappedPages: MappedPages<Page> | undefined
let pagesPaths: string[] = []
if (pagesDir && !appDirOnly) {
......@@ -513,9 +537,9 @@ export async function discoverRoutes(
let appRouteHandlers: RouteInfo[] = []
let layoutRoutes: RouteInfo[] = []
let slots: SlotInfo[] = []
let mappedAppPages: MappedPages | undefined
let mappedAppLayouts: MappedPages | undefined
let mappedAppDefaults: MappedPages | undefined
let mappedAppPages: MappedPages<Page> | undefined
let mappedAppLayouts: MappedPages<Page> | undefined
let mappedAppDefaults: MappedPages<Page> | undefined
if (appDir) {
let appPaths: string[]
......
......@@ -175,7 +175,7 @@ const AppSegmentConfigSchema = z.object({
/**
* Parse the app segment config.
* @param data - The data to parse.
* @param route - The route of the app.
* @param route - The normalized URL route used in configuration diagnostics.
* @returns The parsed app segment config.
*/
export function parseAppSegmentConfig(
......
......@@ -36,7 +36,7 @@ const PagesSegmentConfigSchema = z.object({
/**
* Parse the page segment config.
* @param data - The data to parse.
* @param route - The route of the page.
* @param route - The Pages module's file counterpart used in configuration diagnostics.
* @returns The parsed page segment config.
*/
export function parsePagesSegmentConfig(
......
import { createRoute, type Route } from '../../shared/lib/route-types'
import type { Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type {
......@@ -331,7 +332,7 @@ export function calculateFallbackMode(
* @returns The list of validated parameters.
*/
function validateParams(
page: string,
page: Route,
isRoutePPREnabled: boolean,
pathnameSegments: ReadonlyArray<{
readonly paramName: string
......@@ -864,7 +865,7 @@ function createReplacements(
*/
export async function buildAppStaticPaths({
dir,
page,
page: legacyPage,
route,
distDir,
cacheComponents,
......@@ -915,6 +916,10 @@ export async function buildAppStaticPaths({
deploymentId: string
rootParamKeys: readonly string[]
}): Promise<StaticPathsResult> {
// The dev worker's legacy page field is a normalized URL pattern. This
// static-path stage owns the scoped Route view; no raw reconstruction or
// generic JSON-reader assertion is involved, and known Routes stay intact.
const page = legacyPage as Route
if (
segments.some((generate) => generate.config?.dynamicParams === true) &&
nextConfigOutput === 'export'
......@@ -1198,17 +1203,17 @@ export async function buildAppStaticPaths({
)
}
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>()
const blockingCandidatesByPathname = new Map<string, PrerenderedRoute>()
const prerenderedRoutesByPathname = new Map<Route, PrerenderedRoute>()
const blockingCandidatesByPathname = new Map<Route, PrerenderedRoute>()
const prerenderRouteMatchersByPathname = new Map<
string,
Route,
PrerenderRouteMatcher
>()
const addPrerenderCandidate = (
params: Params,
pathname: string,
encodedPathname: string,
pathname: Route,
encodedPathname: Route,
fallbackRouteParams: readonly FallbackRouteParam[],
fallbackRootParams: readonly string[]
): void => {
......@@ -1372,18 +1377,22 @@ export async function buildAppStaticPaths({
const replacements = createReplacements({ paramType }, paramValue)
pathname = pathname.replace(
name,
// We're replacing the segment name with the replacement pathname
// which will include the interception marker prefix if it exists.
replacements.pathname
pathname = createRoute(
pathname.replace(
name,
// We're replacing the segment name with the replacement pathname
// which will include the interception marker prefix if it exists.
replacements.pathname
)
)
encodedPathname = encodedPathname.replace(
name,
// We're replacing the segment name with the replacement encoded
// pathname which will include the encoded param value.
replacements.encodedPathname
encodedPathname = createRoute(
encodedPathname.replace(
name,
// We're replacing the segment name with the replacement encoded
// pathname which will include the encoded param value.
replacements.encodedPathname
)
)
}
......
import { createRoute, type Route } from '../../shared/lib/route-types'
import type { GetStaticPaths } from '../../types'
import type { PrerenderedRoute, StaticPathsResult } from './types'
......@@ -10,7 +11,7 @@ import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { encodeParam, normalizePathname } from './utils'
export async function buildPagesStaticPaths({
page,
page: legacyPage,
getStaticPaths,
configFileName,
locales,
......@@ -22,7 +23,11 @@ export async function buildPagesStaticPaths({
locales?: readonly string[]
defaultLocale?: string
}): Promise<StaticPathsResult> {
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>()
// The dev worker still supplies a string URL pattern. Keep that public
// contract; this Pages static-path stage owns its URL view, not a module ID.
// Known Route inputs pass through intact rather than being reconstructed.
const page = legacyPage as Route
const prerenderedRoutesByPathname = new Map<Route, PrerenderedRoute>()
const _routeRegex = getRouteRegex(page)
const _routeMatcher = getRouteMatcher(_routeRegex)
......@@ -98,7 +103,7 @@ export async function buildPagesStaticPaths({
entry = `/${defaultLocale}${entry}`
}
const params = _routeMatcher(cleanedEntry)
const params = _routeMatcher(createRoute(cleanedEntry))
if (!params) {
throw new Error(
`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`
......@@ -108,18 +113,20 @@ export async function buildPagesStaticPaths({
// If leveraging the string paths variant the entry should already be
// encoded so we decode the segments ensuring we only escape path
// delimiters
const pathname = entry
.split('/')
.map((segment) =>
escapePathDelimiters(decodeURIComponent(segment), true)
)
.join('/')
const pathname = createRoute(
entry
.split('/')
.map((segment) =>
escapePathDelimiters(decodeURIComponent(segment), true)
)
.join('/')
)
if (!prerenderedRoutesByPathname.has(pathname)) {
prerenderedRoutesByPathname.set(pathname, {
params,
pathname,
encodedPathname: entry,
encodedPathname: createRoute(entry),
fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined,
......@@ -179,14 +186,20 @@ export async function buildPagesStaticPaths({
replaced = `[${replaced}]`
}
builtPage = builtPage.replace(
replaced,
encodeParam(paramValue, (value) => escapePathDelimiters(value, true))
builtPage = createRoute(
builtPage.replace(
replaced,
encodeParam(paramValue, (value) =>
escapePathDelimiters(value, true)
)
)
)
encodedBuiltPage = encodedBuiltPage.replace(
replaced,
encodeParam(paramValue, encodeURIComponent)
encodedBuiltPage = createRoute(
encodedBuiltPage.replace(
replaced,
encodeParam(paramValue, encodeURIComponent)
)
)
})
......@@ -202,7 +215,9 @@ export async function buildPagesStaticPaths({
const curLocale = entry.locale || defaultLocale || ''
const pathname = normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}`
createRoute(
`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}`
)
)
if (!prerenderedRoutesByPathname.has(pathname)) {
......@@ -210,9 +225,11 @@ export async function buildPagesStaticPaths({
params,
pathname,
encodedPathname: normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${
curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage
}`
createRoute(
`${curLocale ? `/${curLocale}` : ''}${
curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage
}`
)
),
fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
......
import type { Page, Route } from '../../shared/lib/route-types'
import {
PARAM_MATCHING_MODES,
type AppSegment,
......@@ -16,7 +17,7 @@ type PolicyCandidate = {
}
export async function resolveParamMatching(
page: string,
page: Route,
segmentTree: readonly AppSegmentTree[],
pathnameSegments: ReadonlyArray<{ readonly paramName: string }>
): Promise<ParamMatching | undefined> {
......@@ -159,9 +160,9 @@ export async function resolveParamMatching(
* definition when their URL prefixes match.
*/
export function validateParamMatchingCoherence(
paramMatchingByRoute: ReadonlyMap<string, ParamMatching | undefined>
paramMatchingByRoute: ReadonlyMap<Page, ParamMatching | undefined>
): void {
const parameters = new Map<string, [route: string, notFound: boolean]>()
const parameters = new Map<string, [route: Route, notFound: boolean]>()
for (const [appPath, paramMatching] of [...paramMatchingByRoute].sort(
([a], [b]) => a.localeCompare(b)
......@@ -221,7 +222,7 @@ export function getParamMatchingFallbackMode(
}
export function validateParamMatchingParams(
page: string,
page: Route,
paramMatching: Readonly<ParamMatching>,
generatedParamNames: ReadonlySet<string>,
missingParamNames: ReadonlySet<string>,
......
import type { Route } from '../../shared/lib/route-types'
import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params'
import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
......@@ -5,8 +6,8 @@ import type { ParamMatching } from '../segment-config/app/app-segments'
type StaticPrerenderedRoute = {
readonly params: Params
readonly pathname: string
readonly encodedPathname: string
readonly pathname: Route
readonly encodedPathname: Route
readonly fallbackRouteParams: undefined
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined
......@@ -34,8 +35,8 @@ export type FallbackRouteParam = {
type FallbackPrerenderedRoute = {
readonly params: Params
readonly pathname: string
readonly encodedPathname: string
readonly pathname: Route
readonly encodedPathname: Route
/**
* The fallback route params for the route. This includes all route parameters
......@@ -82,7 +83,7 @@ export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute
* must not assume pathname identifies a single candidate or render result.
*/
export type PrerenderRouteMatcher = {
readonly pathname: string
readonly pathname: Route
readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined
/**
......
import { createRoute, type Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { Params } from '../../server/request/params'
import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled'
......@@ -41,8 +42,8 @@ export function encodeParam(
* @param pathname - The pathname to normalize.
* @returns The normalized pathname.
*/
export function normalizePathname(pathname: string) {
return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '')
export function normalizePathname(pathname: Route): Route {
return createRoute(pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, ''))
}
/**
......
......@@ -1214,7 +1214,9 @@ function bindingToApi(
function napiEntrypointsToRawEntrypoints(
entrypoints: TurbopackResult<NapiEntrypoints>
): TurbopackResult<RawEntrypoints> {
const routes = new Map()
// Preserve the native transport's primitive identifiers for untouched dev
// callers. The build converter owns URL/module ingestion after dispatch.
const routes = new Map<string, Route>()
for (const { pathname, ...nativeRoute } of entrypoints.value.routes) {
let route: Route
const routeType = nativeRoute.type
......
......@@ -202,6 +202,8 @@ export interface Instrumentation {
}
export interface RawEntrypoints {
// Native serialization delivers primitive URL-pattern keys. Role ingestion
// belongs to the build converter, not the public SWC transport declaration.
routes: Map<string, Route>
middleware?: Middleware
instrumentation?: Instrumentation
......@@ -564,14 +566,20 @@ export type AppRoute =
endpoint: Endpoint
}
// pathname -> route
export type PageEntrypoints = Map<string, PageRoute>
// Pages-router page identifiers use the same spelling as their URL pathname.
export type PageEntrypoints<ModulePage extends string = string> = Map<
ModulePage,
PageRoute
>
// originalName / page -> route
export type AppEntrypoints = Map<string, AppRoute>
export type AppEntrypoints<ModulePage extends string = string> = Map<
ModulePage,
AppRoute
>
export type Entrypoints = {
export type Entrypoints<ModulePage extends string = string> = {
global: GlobalEntrypoints
page: PageEntrypoints
app: AppEntrypoints
page: PageEntrypoints<ModulePage>
app: AppEntrypoints<ModulePage>
}
import type { Page, Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { FallbackRouteParam } from '../static-paths/types'
......@@ -167,8 +168,8 @@ export function createAppPageEntrypoint({
interopDefault,
}: {
tree: LoaderTree
page: string
pathname: string
page: Page
pathname: Route
require: (id: string | number) => unknown
loadChunk: (id: string | number) => Promise<unknown>
interopDefault: typeof import('../../server/app-render/interop-default').interopDefault
......@@ -200,9 +201,11 @@ export function createAppPageEntrypoint({
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
// @ts-ignore -- TODO: Temporary template boundary: completed App module-key normalization; guarded construction deferred.
srcPage = srcPage.replace(/\/index$/, '') || '/'
} else if (srcPage === '/index') {
// we always normalize /index specifically
// @ts-ignore -- TODO: Temporary template boundary: existing root module-key normalization; guarded construction deferred.
srcPage = '/'
}
......
......@@ -21,7 +21,9 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
const entrypoint = createAppPageEntrypoint({
tree,
// @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier; guarded ingestion deferred.
page: 'VAR_DEFINITION_PAGE',
// @ts-ignore -- TODO: Temporary template boundary: injected normalized App URL pattern; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME',
require: __next_app_require__,
loadChunk: __next_app_load_chunk__,
......
import type { Page } from '../../shared/lib/route-types'
import {
AppRouteRouteModule,
type AppRouteRouteHandlerContext,
......@@ -117,15 +118,18 @@ export async function handler(
if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
}
let srcPage = 'VAR_DEFINITION_PAGE'
// @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier; guarded ingestion deferred.
let srcPage: Page = 'VAR_DEFINITION_PAGE'
// turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
// @ts-ignore -- TODO: Temporary template boundary: completed App module-key normalization; guarded construction deferred.
srcPage = srcPage.replace(/\/index$/, '') || '/'
} else if (srcPage === '/index') {
// we always normalize /index specifically
// @ts-ignore -- TODO: Temporary template boundary: existing root module-key normalization; guarded construction deferred.
srcPage = '/'
}
const multiZoneDraftMode = process.env
......
import type { Page } from '../../shared/lib/route-types'
import '../../server/web/globals'
import {
adapter,
......@@ -66,7 +67,8 @@ async function requestHandler(
req: NextRequestHint,
event: NextFetchEvent
): Promise<Response> {
let srcPage = 'VAR_PAGE'
// @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier; guarded ingestion deferred.
let srcPage: Page = 'VAR_PAGE'
const normalizedSrcPage = normalizeAppPath(srcPage)
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`
......
This diff is collapsed.
import type { Page } from '../../../../shared/lib/route-types'
import path from 'path'
import { stringify } from 'querystring'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
......@@ -23,7 +24,7 @@ export async function createAppRouteCode({
}: {
appDir: string
name: string
page: string
page: Page
pagePath: string
resolveAppRoute: (
pathname: string
......
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