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

Guard Page and Route construction boundaries

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent ce19c074
import { pageToRoute } from '../utils' import { pageToRoute } from '../utils'
import { collectFallbackShellRuns } from './fallback-shell-runs' import { collectFallbackShellRuns } from './fallback-shell-runs'
import type { RoutesManifest } from '..' import { createRoute } from '../../shared/lib/route-types'
import type { Route } from '../../shared/lib/route-types'
// The suites in `test/production/app-dir/adapter-dynamic-routes` cover the // 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. // shapes that a build produces, and they pin the entries that come out of them.
...@@ -17,23 +16,22 @@ import type { Route } from '../../shared/lib/route-types' ...@@ -17,23 +16,22 @@ import type { Route } from '../../shared/lib/route-types'
* A fallback shell, which the build derives from a normalized source URL pattern. * A fallback shell, which the build derives from a normalized source URL pattern.
*/ */
function shell(page: string, sourcePage: string) { function shell(page: string, sourcePage: string) {
return pageToRoute(page as Route, sourcePage as Route) return pageToRoute(createRoute(page), createRoute(sourcePage))
} }
/** /**
* Any other dynamic route, which carries no source page. * Any other dynamic route, which carries no source page.
*/ */
function plain(page: string) { function plain(page: string) {
return pageToRoute(page as Route, undefined) return pageToRoute(createRoute(page), undefined)
} }
function collect( function collect(
routes: ReturnType<typeof plain>[], routes: ReturnType<typeof plain>[],
fallbackFalsePages: string[] = [] fallbackFalsePages: string[] = []
) { ) {
const result = collectFallbackShellRuns( const result = collectFallbackShellRuns(routes, (page) =>
routes as RoutesManifest['dynamicRoutes'], fallbackFalsePages.includes(page)
(page) => fallbackFalsePages.includes(page)
) )
return { return {
......
import type { Page, Route } from '../shared/lib/route-types' import {
createPage,
pagesPageToRoute,
type Page,
type Route,
} from '../shared/lib/route-types'
import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader'
import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader'
import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader' import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader'
...@@ -241,10 +246,10 @@ export function getEdgeServerEntry(opts: { ...@@ -241,10 +246,10 @@ export function getEdgeServerEntry(opts: {
} }
const loaderParams: EdgeSSRLoaderQuery = { const loaderParams: EdgeSSRLoaderQuery = {
absolute500Path: opts.pages['/500' as Page] || '', absolute500Path: opts.pages[createPage('/500')] || '',
absoluteAppPath: opts.pages['/_app' as Page], absoluteAppPath: opts.pages[createPage('/_app')],
absoluteDocumentPath: opts.pages['/_document' as Page], absoluteDocumentPath: opts.pages[createPage('/_document')],
absoluteErrorPath: opts.pages['/_error' as Page], absoluteErrorPath: opts.pages[createPage('/_error')],
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
dev: opts.isDev, dev: opts.isDev,
isServerComponent: opts.isServerComponent, isServerComponent: opts.isServerComponent,
...@@ -308,7 +313,8 @@ export function getClientEntry(opts: { absolutePagePath: string; page: Page }) { ...@@ -308,7 +313,8 @@ export function getClientEntry(opts: { absolutePagePath: string; page: Page }) {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
// Pages-router discovery keys share the client URL namespace; raw module // Pages-router discovery keys share the client URL namespace; raw module
// definition.page instead uses normalizePagePath's file encoding. // definition.page instead uses normalizePagePath's file encoding.
page: opts.page as unknown as Route, // Both callers dispatch only Pages client entries, whose module keys equal URLs.
page: pagesPageToRoute(opts.page),
} }
const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!` const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!`
...@@ -421,16 +427,21 @@ export async function createEntrypoints( ...@@ -421,16 +427,21 @@ export async function createEntrypoints(
if (appDir && appPaths) { if (appDir && appPaths) {
const appPageFiles = new Map<Page, string>() const appPageFiles = new Map<Page, string>()
for (const pathname in appPaths) { for (const pathname in appPaths) {
const normalizedPath = normalizeAppPath(pathname as Page) // for-in erases the existing module-key type; preserve it, do not construct it.
const actualPath = appPaths[pathname as Page] const normalizedPath = normalizeAppPath(
pathname as /* TODO: Preserve Page keys across Object.keys rather than reconstructing them. */ keyof typeof appPaths
)
const actualPath =
appPaths[
pathname as /* TODO: Preserve Page keys across Object.keys rather than reconstructing them. */ keyof typeof appPaths
]
if (!appPathsPerRoute[normalizedPath]) { if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = [] appPathsPerRoute[normalizedPath] = []
} }
// TODO-APP: refactor to pass the page path from createPagesMapping instead. // TODO-APP: refactor to pass the page path from createPagesMapping instead.
const appPath = getPageFromPath(actualPath, pageExtensions).replace( const appPath = createPage(
APP_DIR_ALIAS, getPageFromPath(actualPath, pageExtensions).replace(APP_DIR_ALIAS, '')
'' )
) as Page
appPathsPerRoute[normalizedPath].push(appPath) appPathsPerRoute[normalizedPath].push(appPath)
appPageFiles.set(appPath, actualPath) appPageFiles.set(appPath, actualPath)
} }
...@@ -439,17 +450,22 @@ export async function createEntrypoints( ...@@ -439,17 +450,22 @@ export async function createEntrypoints(
const { unmatchedAppPages, incompatibleParallelRouteSlots } = const { unmatchedAppPages, incompatibleParallelRouteSlots } =
normalizeCatchAllRoutes(appPathsPerRoute, { normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching, strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}) as Page[], // TODO: Retain the discovered default-module Page keys across Object.keys.
defaultAppPaths: Object.keys(
appDefaultPaths ?? {}
) as (keyof NonNullable<typeof appDefaultPaths>)[],
}) })
// Only App Router pages can make an intercepted URL directly renderable. // Only App Router pages can make an intercepted URL directly renderable.
// Route handlers and metadata routes may share the pathname, but they // Route handlers and metadata routes may share the pathname, but they
// cannot provide the canonical page shown by an initial request. // cannot provide the canonical page shown by an initial request.
// Filtering retains the source's normalized URL keys and module-key arrays.
// TODO: Preserve the reconstructed URL-keyed record shape without this schema assertion.
const appPagePathsPerRoute = Object.fromEntries( const appPagePathsPerRoute = Object.fromEntries(
Object.entries(appPathsPerRoute).flatMap(([route, routeAppPaths]) => { Object.entries(appPathsPerRoute).flatMap(([route, routeAppPaths]) => {
const pageAppPaths = routeAppPaths.filter(isAppPageRoute) const pageAppPaths = routeAppPaths.filter(isAppPageRoute)
return pageAppPaths.length > 0 ? [[route, pageAppPaths]] : [] return pageAppPaths.length > 0 ? [[route, pageAppPaths]] : []
}) })
) as Record<Route, Page[]> ) as typeof appPathsPerRoute
const missingCanonicalInterceptionRoutes = config.experimental const missingCanonicalInterceptionRoutes = config.experimental
.strictRouteMatching .strictRouteMatching
? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute) ? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute)
...@@ -467,10 +483,9 @@ export async function createEntrypoints( ...@@ -467,10 +483,9 @@ export async function createEntrypoints(
new IncompatibleParallelRouteSlotsError( new IncompatibleParallelRouteSlotsError(
await Promise.all( await Promise.all(
incompatibleParallelRouteSlots.map(async (incompatibleRoute) => { incompatibleParallelRouteSlots.map(async (incompatibleRoute) => {
const layoutPagePath = posix.join( const layoutPagePath = createPage(
incompatibleRoute.layoutPath, posix.join(incompatibleRoute.layoutPath, 'layout')
'layout' )
) as Page
const layoutFile = await findPageFile( const layoutFile = await findPageFile(
appDir, appDir,
layoutPagePath, layoutPagePath,
...@@ -528,12 +543,14 @@ export async function createEntrypoints( ...@@ -528,12 +543,14 @@ export async function createEntrypoints(
} }
// Make sure to sort parallel routes to make the result deterministic. // Make sure to sort parallel routes to make the result deterministic.
// TODO: Preserve the existing URL-key schema across native entries/fromEntries sorting.
// Object.fromEntries erases the existing URL-key schema; sorting preserves it.
appPathsPerRoute = Object.fromEntries( appPathsPerRoute = Object.fromEntries(
Object.entries(appPathsPerRoute).map(([k, v]) => [ Object.entries(appPathsPerRoute).map(([k, v]) => [
k, k,
v.sort(compareAppPaths), v.sort(compareAppPaths),
]) ])
) as Record<Route, Page[]> ) as typeof appPathsPerRoute
} }
const getEntryHandler = const getEntryHandler =
...@@ -647,7 +664,10 @@ export async function createEntrypoints( ...@@ -647,7 +664,10 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute) as Route[], // TODO: Preserve the normalized URL keys erased by Object.keys.
allNormalizedAppPaths: Object.keys(
appPathsPerRoute
) as /* TODO: Preserve the discovered Page key type across native iteration. */ (keyof typeof appPathsPerRoute)[],
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
...@@ -733,7 +753,10 @@ export async function createEntrypoints( ...@@ -733,7 +753,10 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute) as Route[], // TODO: Preserve the normalized URL keys erased by Object.keys.
allNormalizedAppPaths: Object.keys(
appPathsPerRoute
) as /* TODO: Preserve the discovered Page key type across native iteration. */ (keyof typeof appPathsPerRoute)[],
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
...@@ -778,26 +801,37 @@ export async function createEntrypoints( ...@@ -778,26 +801,37 @@ export async function createEntrypoints(
const promises: Promise<void[]>[] = [] const promises: Promise<void[]>[] = []
// Object.keys preserves these discovery maps' module keys at runtime.
if (appPaths) { if (appPaths) {
const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP) const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP)
promises.push( promises.push(
Promise.all((Object.keys(appPaths) as Page[]).map(entryHandler)) Promise.all(
(
Object.keys(
appPaths
) as /* TODO: Preserve the discovered Page key type across native iteration. */ (keyof typeof appPaths)[]
).map(entryHandler)
)
) )
} }
if (rootPaths) { if (rootPaths) {
promises.push( promises.push(
Promise.all( Promise.all(
(Object.keys(rootPaths) as Page[]).map( (
getEntryHandler(rootPaths, PAGE_TYPES.ROOT) Object.keys(
) rootPaths
) as /* TODO: Preserve the discovered Page key type across native iteration. */ (keyof typeof rootPaths)[]
).map(getEntryHandler(rootPaths, PAGE_TYPES.ROOT))
) )
) )
} }
promises.push( promises.push(
Promise.all( Promise.all(
(Object.keys(pages) as Page[]).map( (
getEntryHandler(pages, PAGE_TYPES.PAGES) Object.keys(
) pages
) as /* TODO: Preserve the discovered Page key type across native iteration. */ (keyof typeof pages)[]
).map(getEntryHandler(pages, PAGE_TYPES.PAGES))
) )
) )
......
...@@ -18,7 +18,10 @@ export function extractSlotFromPath(pagePath: Page): SlotInfo | undefined { ...@@ -18,7 +18,10 @@ export function extractSlotFromPath(pagePath: Page): SlotInfo | undefined {
if (isParallelRouteSegment(segment)) { if (isParallelRouteSegment(segment)) {
return { return {
name: segment.slice(1), name: segment.slice(1),
parent: normalizeAppPath(segments.slice(0, i).join('/') as Page), parent: normalizeAppPath(
// @ts-ignore -- 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 slot discovery.
segments.slice(0, i).join('/')
),
} }
} }
} }
......
import type { Page } from '../shared/lib/route-types' import {
type Page,
createPage,
pagesRouteToPage,
} from '../shared/lib/route-types'
import type { TurbopackManifestLoader } from '../shared/lib/turbopack/manifest-loader' import type { TurbopackManifestLoader } from '../shared/lib/turbopack/manifest-loader'
import type { import type {
Entrypoints, Entrypoints,
...@@ -21,7 +25,7 @@ export async function rawEntrypointsToEntrypoints( ...@@ -21,7 +25,7 @@ export async function rawEntrypointsToEntrypoints(
case 'page-api': case 'page-api':
// At the native pages-router boundary, a URL pathname also identifies // At the native pages-router boundary, a URL pathname also identifies
// the page; there are no app modifiers or leaf suffixes to preserve. // the page; there are no app modifiers or leaf suffixes to preserve.
page.set(pathname as string as Page, route) page.set(pagesRouteToPage(pathname), route)
break break
case 'app-page': { case 'app-page': {
for (const p of route.pages) { for (const p of route.pages) {
...@@ -80,7 +84,7 @@ export async function handleRouteType({ ...@@ -80,7 +84,7 @@ export async function handleRouteType({
manifestLoader.deleteMiddlewareManifest(serverKey) manifestLoader.deleteMiddlewareManifest(serverKey)
} }
await manifestLoader.loadFontManifest('/_app' as Page, 'pages') await manifestLoader.loadFontManifest(createPage('/_app'), 'pages')
await manifestLoader.loadFontManifest(page, 'pages') await manifestLoader.loadFontManifest(page, 'pages')
await manifestLoader.loadSriManifest(page, 'pages') await manifestLoader.loadSriManifest(page, 'pages')
......
This diff is collapsed.
import type { Page, Route } from '../shared/lib/route-types' import {
pagesRouteToPage,
type Page,
type Route,
} from '../shared/lib/route-types'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin' import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import path from 'path' import path from 'path'
import { promises as fs, statSync } from 'fs' import { promises as fs, statSync } from 'fs'
...@@ -94,7 +98,7 @@ function readEntryJSFiles( ...@@ -94,7 +98,7 @@ function readEntryJSFiles(
g.__RSC_MANIFEST = prev g.__RSC_MANIFEST = prev
// The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page) // The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page)
// @ts-ignore -- 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. // @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] const manifestEntry = rscManifest?.[pagePath] ?? rscManifest?.[appRoute]
return manifestEntry?.entryJSFiles return manifestEntry?.entryJSFiles
} catch { } catch {
...@@ -117,7 +121,7 @@ function collectPagesRouterStats( ...@@ -117,7 +121,7 @@ function collectPagesRouterStats(
continue continue
// This list contains only Pages-router URL keys, sharing the module namespace. // This list contains only Pages-router URL keys, sharing the module namespace.
const allFiles = (buildManifest.pages[page as string as Page] ?? []).filter( const allFiles = (buildManifest.pages[pagesRouteToPage(page)] ?? []).filter(
(f) => f.endsWith('.js') (f) => f.endsWith('.js')
) )
const sharedJs = sharedFiles.filter((f) => f.endsWith('.js')) const sharedJs = sharedFiles.filter((f) => f.endsWith('.js'))
......
import type { Page, Route } from '../shared/lib/route-types' import {
createPage,
pagesPageToRoute,
type Page,
type Route,
} from '../shared/lib/route-types'
import { join } from 'path' import { join } from 'path'
import { createValidFileMatcher } from '../server/lib/find-page-file' import { createValidFileMatcher } from '../server/lib/find-page-file'
import { recursiveReadDir } from '../lib/recursive-readdir' import { recursiveReadDir } from '../lib/recursive-readdir'
...@@ -67,12 +72,12 @@ function normalizeAppRoute(pageName: Page): Route { ...@@ -67,12 +72,12 @@ function normalizeAppRoute(pageName: Page): Route {
/** Normalize a layout route (strip /layout suffix) */ /** Normalize a layout route (strip /layout suffix) */
function normalizeLayoutRoute(pageName: Page): Route { 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( return ensureLeadingSlash(
removeSuffix( removeSuffix(normalizeAppPath(normalizePathSep(pageName)), '/layout')
normalizeAppPath(normalizePathSep(pageName)), ) as Route
'/layout'
) as Route
)
} }
/** /**
...@@ -96,7 +101,7 @@ export function getPageFromPath( ...@@ -96,7 +101,7 @@ export function getPageFromPath(
page = removeSuffix(page, '/index') page = removeSuffix(page, '/index')
return (page === '' ? '/' : page) as Page return createPage(page === '' ? '/' : page)
} }
/** /**
...@@ -195,14 +200,14 @@ export function processPageRoutes( ...@@ -195,14 +200,14 @@ export function processPageRoutes(
if (route.startsWith('/api/')) { if (route.startsWith('/api/')) {
pageApiRoutes.push({ pageApiRoutes.push({
route: normalizePathSep(route) as string as Route, route: pagesPageToRoute(normalizePathSep(route)),
filePath: relativeFilePath, filePath: relativeFilePath,
}) })
} else { } else {
if (isReservedPage(route)) continue if (isReservedPage(route)) continue
pageRoutes.push({ pageRoutes.push({
route: normalizePathSep(route) as string as Route, route: pagesPageToRoute(normalizePathSep(route)),
filePath: relativeFilePath, filePath: relativeFilePath,
}) })
} }
...@@ -226,6 +231,7 @@ export function processAppRoutes( ...@@ -226,6 +231,7 @@ export function processAppRoutes(
const appRoutes: RouteInfo[] = [] const appRoutes: RouteInfo[] = []
const appRouteHandlers: RouteInfo[] = [] const appRouteHandlers: RouteInfo[] = []
// Object.entries erases the module-key role already established by mapping.
for (const [page, filePath] of Object.entries(mappedAppPages) as [ for (const [page, filePath] of Object.entries(mappedAppPages) as [
Page, Page,
string, string,
...@@ -263,6 +269,7 @@ export function processLayoutRoutes( ...@@ -263,6 +269,7 @@ export function processLayoutRoutes(
baseDir: string, baseDir: string,
isSrcDir: boolean isSrcDir: boolean
): RouteInfo[] { ): RouteInfo[] {
// Preserve the mapped module-key role through Object.entries, not new branding.
return (Object.entries(mappedAppLayouts) as [Page, string][]).map( return (Object.entries(mappedAppLayouts) as [Page, string][]).map(
([route, filePath]) => ({ ([route, filePath]) => ({
route: normalizeLayoutRoute(route), route: normalizeLayoutRoute(route),
...@@ -302,7 +309,7 @@ export async function createPagesMapping({ ...@@ -302,7 +309,7 @@ export async function createPagesMapping({
let pageKey = getPageFromPath(pagePath, pageExtensions) let pageKey = getPageFromPath(pagePath, pageExtensions)
if (isAppRoute) { if (isAppRoute) {
// Turbopack encodes '_' as '%5F' in app paths; normalize to underscores. // Turbopack encodes '_' as '%5F' in app paths; normalize to underscores.
pageKey = pageKey.replace(/%5F/g, '_') as Page pageKey = createPage(pageKey.replace(/%5F/g, '_'))
if (pageKey === UNDERSCORE_NOT_FOUND_ROUTE) { if (pageKey === UNDERSCORE_NOT_FOUND_ROUTE) {
pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
} }
...@@ -375,9 +382,9 @@ export async function createPagesMapping({ ...@@ -375,9 +382,9 @@ export async function createPagesMapping({
} }
case PAGE_TYPES.PAGES: { case PAGE_TYPES.PAGES: {
if (isDev) { if (isDev) {
delete pages['/_app' as Page] delete pages[createPage('/_app')]
delete pages['/_error' as Page] delete pages[createPage('/_error')]
delete pages['/_document' as Page] delete pages[createPage('/_document')]
} }
const root = isDev && pagesDir ? PAGES_DIR_ALIAS : 'next/dist/pages' const root = isDev && pagesDir ? PAGES_DIR_ALIAS : 'next/dist/pages'
......
import type { Page, Route } from '../../shared/lib/route-types' import { createRoute, type Route } from '../../shared/lib/route-types'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module' import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { import type {
...@@ -1373,19 +1373,23 @@ export async function buildAppStaticPaths({ ...@@ -1373,19 +1373,23 @@ export async function buildAppStaticPaths({
const replacements = createReplacements({ paramType }, paramValue) const replacements = createReplacements({ paramType }, paramValue)
pathname = pathname.replace( pathname = createRoute(
name, pathname.replace(
// We're replacing the segment name with the replacement pathname name,
// which will include the interception marker prefix if it exists. // We're replacing the segment name with the replacement pathname
replacements.pathname // which will include the interception marker prefix if it exists.
) as Route replacements.pathname
)
encodedPathname = encodedPathname.replace( )
name,
// We're replacing the segment name with the replacement encoded encodedPathname = createRoute(
// pathname which will include the encoded param value. encodedPathname.replace(
replacements.encodedPathname name,
) as Route // We're replacing the segment name with the replacement encoded
// pathname which will include the encoded param value.
replacements.encodedPathname
)
)
} }
// Resolve all route params from the loader tree if this is from an // Resolve all route params from the loader tree if this is from an
......
import type { Route } from '../../shared/lib/route-types' import { createRoute, type Route } from '../../shared/lib/route-types'
import type { GetStaticPaths } from '../../types' import type { GetStaticPaths } from '../../types'
import type { PrerenderedRoute, StaticPathsResult } from './types' import type { PrerenderedRoute, StaticPathsResult } from './types'
...@@ -99,7 +99,7 @@ export async function buildPagesStaticPaths({ ...@@ -99,7 +99,7 @@ export async function buildPagesStaticPaths({
entry = `/${defaultLocale}${entry}` entry = `/${defaultLocale}${entry}`
} }
const params = _routeMatcher(cleanedEntry as Route) const params = _routeMatcher(createRoute(cleanedEntry))
if (!params) { if (!params) {
throw new Error( throw new Error(
`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.` `The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`
...@@ -109,18 +109,20 @@ export async function buildPagesStaticPaths({ ...@@ -109,18 +109,20 @@ export async function buildPagesStaticPaths({
// If leveraging the string paths variant the entry should already be // If leveraging the string paths variant the entry should already be
// encoded so we decode the segments ensuring we only escape path // encoded so we decode the segments ensuring we only escape path
// delimiters // delimiters
const pathname = entry const pathname = createRoute(
.split('/') entry
.map((segment) => .split('/')
escapePathDelimiters(decodeURIComponent(segment), true) .map((segment) =>
) escapePathDelimiters(decodeURIComponent(segment), true)
.join('/') as Route )
.join('/')
)
if (!prerenderedRoutesByPathname.has(pathname)) { if (!prerenderedRoutesByPathname.has(pathname)) {
prerenderedRoutesByPathname.set(pathname, { prerenderedRoutesByPathname.set(pathname, {
params, params,
pathname, pathname,
encodedPathname: entry as Route, encodedPathname: createRoute(entry),
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined, fallbackRootParams: undefined,
...@@ -180,15 +182,21 @@ export async function buildPagesStaticPaths({ ...@@ -180,15 +182,21 @@ export async function buildPagesStaticPaths({
replaced = `[${replaced}]` replaced = `[${replaced}]`
} }
builtPage = builtPage.replace( builtPage = createRoute(
replaced, builtPage.replace(
encodeParam(paramValue, (value) => escapePathDelimiters(value, true)) replaced,
) as Route encodeParam(paramValue, (value) =>
escapePathDelimiters(value, true)
)
)
)
encodedBuiltPage = encodedBuiltPage.replace( encodedBuiltPage = createRoute(
replaced, encodedBuiltPage.replace(
encodeParam(paramValue, encodeURIComponent) replaced,
) as Route encodeParam(paramValue, encodeURIComponent)
)
)
}) })
if (!builtPage && !encodedBuiltPage) { if (!builtPage && !encodedBuiltPage) {
...@@ -203,7 +211,9 @@ export async function buildPagesStaticPaths({ ...@@ -203,7 +211,9 @@ export async function buildPagesStaticPaths({
const curLocale = entry.locale || defaultLocale || '' const curLocale = entry.locale || defaultLocale || ''
const pathname = normalizePathname( const pathname = normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}` as Route createRoute(
`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}`
)
) )
if (!prerenderedRoutesByPathname.has(pathname)) { if (!prerenderedRoutesByPathname.has(pathname)) {
...@@ -211,9 +221,11 @@ export async function buildPagesStaticPaths({ ...@@ -211,9 +221,11 @@ export async function buildPagesStaticPaths({
params, params,
pathname, pathname,
encodedPathname: normalizePathname( encodedPathname: normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${ createRoute(
curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage `${curLocale ? `/${curLocale}` : ''}${
}` as Route curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage
}`
)
), ),
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
......
import type { Route } from '../../shared/lib/route-types' import { createRoute, type Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled' import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled'
...@@ -43,7 +43,7 @@ export function encodeParam( ...@@ -43,7 +43,7 @@ export function encodeParam(
* @returns The normalized pathname. * @returns The normalized pathname.
*/ */
export function normalizePathname(pathname: Route): Route { export function normalizePathname(pathname: Route): Route {
return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '') as Route return createRoute(pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, ''))
} }
/** /**
......
...@@ -43,7 +43,11 @@ import type { ...@@ -43,7 +43,11 @@ import type {
WrittenEndpoint, WrittenEndpoint,
} from './types' } from './types'
import { runLoaderWorkerPool } from './loaderWorkerPool' import { runLoaderWorkerPool } from './loaderWorkerPool'
import type { Page, Route as RoutePathname } from '../../shared/lib/route-types' import {
createPage,
createRoute,
type Route as RoutePathname,
} from '../../shared/lib/route-types'
type RawBindings = typeof import('./generated-native') type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & { type RawWasmBindings = typeof import('./generated-wasm') & {
...@@ -1239,7 +1243,7 @@ function bindingToApi( ...@@ -1239,7 +1243,7 @@ function bindingToApi(
route = { route = {
type: 'app-page', type: 'app-page',
pages: nativeRoute.pages.map((page) => ({ pages: nativeRoute.pages.map((page) => ({
originalName: page.originalName as Page, originalName: createPage(page.originalName),
htmlEndpoint: new EndpointImpl(page.htmlEndpoint), htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
rscHmrEndpoint: new EndpointImpl(page.rscHmrEndpoint), rscHmrEndpoint: new EndpointImpl(page.rscHmrEndpoint),
})), })),
...@@ -1248,7 +1252,7 @@ function bindingToApi( ...@@ -1248,7 +1252,7 @@ function bindingToApi(
case 'app-route': case 'app-route':
route = { route = {
type: 'app-route', type: 'app-route',
originalName: nativeRoute.originalName as Page, originalName: createPage(nativeRoute.originalName),
hasActionManifest: nativeRoute.hasActionManifest, hasActionManifest: nativeRoute.hasActionManifest,
endpoint: new EndpointImpl(nativeRoute.endpoint), endpoint: new EndpointImpl(nativeRoute.endpoint),
} }
...@@ -1266,7 +1270,7 @@ function bindingToApi( ...@@ -1266,7 +1270,7 @@ function bindingToApi(
) )
} }
} }
routes.set(pathname as RoutePathname, route) routes.set(createRoute(pathname), route)
} }
const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({ const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({
endpoint: new EndpointImpl(middleware.endpoint), endpoint: new EndpointImpl(middleware.endpoint),
......
...@@ -198,10 +198,12 @@ export function createAppPageEntrypoint({ ...@@ -198,10 +198,12 @@ export function createAppPageEntrypoint({
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page // @ts-ignore -- TODO: Temporary template boundary: completed App module-key normalization; guarded construction deferred.
srcPage = srcPage.replace(/\/index$/, '') || '/'
} else if (srcPage === '/index') { } else if (srcPage === '/index') {
// we always normalize /index specifically // we always normalize /index specifically
srcPage = '/' as Page // @ts-ignore -- TODO: Temporary template boundary: existing root module-key normalization; guarded construction deferred.
srcPage = '/'
} }
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import { createAppPageEntrypoint } from './app-page-runtime' import { createAppPageEntrypoint } from './app-page-runtime'
import { interopDefault } from '../../server/app-render/interop-default' with { 'turbopack-transition': 'next-server-utility' } import { interopDefault } from '../../server/app-render/interop-default' with { 'turbopack-transition': 'next-server-utility' }
...@@ -22,8 +21,10 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown> ...@@ -22,8 +21,10 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
const entrypoint = createAppPageEntrypoint({ const entrypoint = createAppPageEntrypoint({
tree, tree,
page: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME' as Route, 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__, require: __next_app_require__,
loadChunk: __next_app_load_chunk__, loadChunk: __next_app_load_chunk__,
interopDefault, interopDefault,
......
import type { Page, Route } from '../../shared/lib/route-types' import type { Page } from '../../shared/lib/route-types'
import { import {
AppRouteRouteModule, AppRouteRouteModule,
type AppRouteRouteHandlerContext, type AppRouteRouteHandlerContext,
...@@ -55,8 +55,10 @@ declare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput'] ...@@ -55,8 +55,10 @@ declare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']
const routeModule = new AppRouteRouteModule({ const routeModule = new AppRouteRouteModule({
definition: { definition: {
kind: RouteKind.APP_ROUTE, kind: RouteKind.APP_ROUTE,
page: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME' as Route, page: 'VAR_DEFINITION_PAGE',
// @ts-ignore -- TODO: Temporary template boundary: injected normalized App URL pattern; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME',
filename: 'VAR_DEFINITION_FILENAME', filename: 'VAR_DEFINITION_FILENAME',
bundlePath: 'VAR_DEFINITION_BUNDLE_PATH', bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',
}, },
...@@ -118,16 +120,19 @@ export async function handler( ...@@ -118,16 +120,19 @@ export async function handler(
if (routeModule.isDev) { if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()) addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
} }
let srcPage = 'VAR_DEFINITION_PAGE' as 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 // turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page // @ts-ignore -- TODO: Temporary template boundary: completed App module-key normalization; guarded construction deferred.
srcPage = srcPage.replace(/\/index$/, '') || '/'
} else if (srcPage === '/index') { } else if (srcPage === '/index') {
// we always normalize /index specifically // we always normalize /index specifically
srcPage = '/' as Page // @ts-ignore -- TODO: Temporary template boundary: existing root module-key normalization; guarded construction deferred.
srcPage = '/'
} }
const multiZoneDraftMode = process.env const multiZoneDraftMode = process.env
.__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean
......
import type { Page } from '../../shared/lib/route-types'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { RequestMeta } from '../../server/request-meta' import type { RequestMeta } from '../../server/request-meta'
import type { EdgeHandler } from '../../server/web/adapter' import type { EdgeHandler } from '../../server/web/adapter'
...@@ -20,7 +19,8 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) ...@@ -20,7 +19,8 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier for manifests; guarded ingestion deferred.
page: 'VAR_PAGE',
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
}) })
...@@ -34,7 +34,7 @@ const edgeCacheHandlers: any = {} ...@@ -34,7 +34,7 @@ const edgeCacheHandlers: any = {}
const internalHandler: EdgeHandler = EdgeRouteModuleWrapper.wrap( const internalHandler: EdgeHandler = EdgeRouteModuleWrapper.wrap(
module.routeModule, module.routeModule,
{ {
page: 'VAR_PAGE' as Page, page: 'VAR_PAGE',
cacheHandlers: edgeCacheHandlers, cacheHandlers: edgeCacheHandlers,
incrementalCacheHandler, incrementalCacheHandler,
} }
...@@ -67,7 +67,7 @@ export async function handler( ...@@ -67,7 +67,7 @@ export async function handler(
}, },
}, },
page: { page: {
name: 'VAR_PAGE' as Page, name: 'VAR_PAGE',
}, },
body: body:
request.method !== 'GET' && request.method !== 'HEAD' request.method !== 'GET' && request.method !== 'HEAD'
......
...@@ -55,7 +55,8 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) ...@@ -55,7 +55,8 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected full App module identifier for manifests; guarded ingestion deferred.
page: 'VAR_PAGE',
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
}) })
...@@ -67,7 +68,8 @@ async function requestHandler( ...@@ -67,7 +68,8 @@ async function requestHandler(
req: NextRequestHint, req: NextRequestHint,
event: NextFetchEvent event: NextFetchEvent
): Promise<Response> { ): Promise<Response> {
let srcPage = 'VAR_PAGE' as 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 normalizedSrcPage = normalizeAppPath(srcPage)
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}` const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`
...@@ -441,7 +443,7 @@ const internalHandler: EdgeHandler = (opts) => { ...@@ -441,7 +443,7 @@ const internalHandler: EdgeHandler = (opts) => {
IncrementalCache, IncrementalCache,
handler: requestHandler, handler: requestHandler,
incrementalCacheHandler, incrementalCacheHandler,
page: 'VAR_PAGE' as Page, page: 'VAR_PAGE',
}) })
} }
...@@ -472,7 +474,7 @@ export async function handler( ...@@ -472,7 +474,7 @@ export async function handler(
}, },
}, },
page: { page: {
name: 'VAR_PAGE' as Page, name: 'VAR_PAGE',
}, },
body: body:
request.method !== 'GET' && request.method !== 'HEAD' request.method !== 'GET' && request.method !== 'HEAD'
......
...@@ -97,13 +97,14 @@ async function requestHandler( ...@@ -97,13 +97,14 @@ async function requestHandler(
req: NextRequestHint, req: NextRequestHint,
_event: NextFetchEvent _event: NextFetchEvent
): Promise<Response> { ): Promise<Response> {
let srcPage = 'VAR_DEFINITION_PATHNAME' as Route // @ts-ignore -- TODO: Temporary template boundary: injected normalized Pages URL pattern; guarded ingestion deferred.
let srcPage: Route = 'VAR_DEFINITION_PATHNAME'
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}` const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`
const baseReq = new WebNextRequest(req) const baseReq = new WebNextRequest(req)
const pageRouteModule = pageMod.routeModule as RouteModule const pageRouteModule = pageMod.routeModule as RouteModule
const prepareResult = await pageRouteModule.prepare(baseReq, null, { const prepareResult = await pageRouteModule.prepare(baseReq, null, {
// @ts-ignore -- Human review: edge Pages preparation receives the normalized pathname, not the raw definition.page used by the Node template. Preserve the existing normalization assumption. // @ts-ignore -- TODO: Human review: edge Pages preparation receives the normalized pathname, not the raw definition.page used by the Node template. Preserve the existing normalization assumption.
srcPage, srcPage,
multiZoneDraftMode: false, multiZoneDraftMode: false,
}) })
...@@ -151,7 +152,7 @@ async function requestHandler( ...@@ -151,7 +152,7 @@ async function requestHandler(
renderOpts: { renderOpts: {
params, params,
// @ts-ignore -- Human review: renderOpts.page expects the raw Page, but edge Pages rendering forwards its normalized pathname. Preserve existing behavior. // @ts-ignore -- TODO: Human review: renderOpts.page expects the raw Page, but edge Pages rendering forwards its normalized pathname. Preserve existing behavior.
page: srcPage, page: srcPage,
supportsDynamicResponse: true, supportsDynamicResponse: true,
Component: pageMod.Component, Component: pageMod.Component,
......
import type { Page, Route } from '../../shared/lib/route-types' import type { Page } from '../../shared/lib/route-types'
import type { NextApiResponse } from '../../types' import type { NextApiResponse } from '../../types'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
...@@ -34,8 +34,10 @@ export const config = hoist(userland, 'config') ...@@ -34,8 +34,10 @@ export const config = hoist(userland, 'config')
const routeModule = new PagesAPIRouteModule({ const routeModule = new PagesAPIRouteModule({
definition: { definition: {
kind: RouteKind.PAGES_API, kind: RouteKind.PAGES_API,
page: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected normalized Pages API module key; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME' as Route, page: 'VAR_DEFINITION_PAGE',
// @ts-ignore -- TODO: Temporary template boundary: injected canonical Pages API URL pattern; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production. // The following aren't used in production.
bundlePath: '', bundlePath: '',
filename: '', filename: '',
...@@ -59,13 +61,15 @@ export async function handler( ...@@ -59,13 +61,15 @@ export async function handler(
if (routeModule.isDev) { if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()) addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
} }
let srcPage = 'VAR_DEFINITION_PAGE' as Page // @ts-ignore -- TODO: Temporary template boundary: injected Pages API module key; guarded ingestion deferred.
let srcPage: Page = 'VAR_DEFINITION_PAGE'
// turbopack doesn't normalize `/index` in the page name // turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page // @ts-ignore -- TODO: Temporary template boundary: completed Pages API module-key normalization; guarded construction deferred.
srcPage = srcPage.replace(/\/index$/, '') || '/'
} }
const prepareResult = await routeModule.prepare(req, res, { srcPage }) const prepareResult = await routeModule.prepare(req, res, { srcPage })
...@@ -109,7 +113,8 @@ export async function handler( ...@@ -109,7 +113,8 @@ export async function handler(
previewProps, previewProps,
propagateError: false, propagateError: false,
dev: routeModule.isDev, dev: routeModule.isDev,
page: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected Pages API module key; guarded ingestion deferred.
page: 'VAR_DEFINITION_PAGE',
internalRevalidate: routerServerContext?.revalidate, internalRevalidate: routerServerContext?.revalidate,
......
...@@ -14,7 +14,8 @@ import handlerUserland from 'VAR_USERLAND' ...@@ -14,7 +14,8 @@ import handlerUserland from 'VAR_USERLAND'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta' import type { RequestMeta } from '../../server/request-meta'
const page = 'VAR_DEFINITION_PAGE' as Page // @ts-ignore -- TODO: Temporary template boundary: injected Pages API module key; guarded ingestion deferred.
const page: Page = 'VAR_DEFINITION_PAGE'
if (typeof handlerUserland !== 'function') { if (typeof handlerUserland !== 'function') {
throw new Error( throw new Error(
......
import type { Page, Route } from '../../shared/lib/route-types'
import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled' import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled'
import { RouteKind } from '../../server/route-kind' import { RouteKind } from '../../server/route-kind'
...@@ -48,8 +47,10 @@ export const unstable_getServerSideProps = hoist( ...@@ -48,8 +47,10 @@ export const unstable_getServerSideProps = hoist(
export const routeModule = new PagesRouteModule({ export const routeModule = new PagesRouteModule({
definition: { definition: {
kind: RouteKind.PAGES, kind: RouteKind.PAGES,
page: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected normalized Pages module key; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME' as Route, page: 'VAR_DEFINITION_PAGE',
// @ts-ignore -- TODO: Temporary template boundary: injected canonical Pages URL pattern; guarded ingestion deferred.
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production. // The following aren't used in production.
bundlePath: '', bundlePath: '',
filename: '', filename: '',
...@@ -65,7 +66,8 @@ export const routeModule = new PagesRouteModule({ ...@@ -65,7 +66,8 @@ export const routeModule = new PagesRouteModule({
}) })
export const handler = getHandler({ export const handler = getHandler({
srcPage: 'VAR_DEFINITION_PAGE' as Page, // @ts-ignore -- TODO: Temporary template boundary: injected normalized Pages module key; guarded ingestion deferred.
srcPage: 'VAR_DEFINITION_PAGE',
config, config,
userland, userland,
routeModule, routeModule,
......
...@@ -18,7 +18,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi ...@@ -18,7 +18,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi
import { getSupportedBrowsers } from '../get-supported-browsers' import { getSupportedBrowsers } from '../get-supported-browsers'
import { printBuildErrors } from '../print-build-errors' import { printBuildErrors } from '../print-build-errors'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import type { Page } from '../../shared/lib/route-types' import { createPage } from '../../shared/lib/route-types'
import type { ProjectOptions, RawEntrypoints } from '../swc/types' import type { ProjectOptions, RawEntrypoints } from '../swc/types'
import { Bundler } from '../../lib/bundler' import { Bundler } from '../../lib/bundler'
import { getStrictRouteMatchingDefaultWarning } from '../../server/lib/router-utils/strict-route-matching-config' import { getStrictRouteMatchingDefaultWarning } from '../../server/lib/router-utils/strict-route-matching-config'
...@@ -267,14 +267,14 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{ ...@@ -267,14 +267,14 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
// Only load pages router manifests if not app-only // Only load pages router manifests if not app-only
...(!appDirOnly ...(!appDirOnly
? [ ? [
manifestLoader.loadBuildManifest('_app' as Page), manifestLoader.loadBuildManifest(createPage('_app')),
manifestLoader.loadPagesManifest('_app' as Page), manifestLoader.loadPagesManifest(createPage('_app')),
manifestLoader.loadFontManifest('_app' as Page), manifestLoader.loadFontManifest(createPage('_app')),
manifestLoader.loadPagesManifest('_document' as Page), manifestLoader.loadPagesManifest(createPage('_document')),
manifestLoader.loadClientBuildManifest('_error' as Page), manifestLoader.loadClientBuildManifest(createPage('_error')),
manifestLoader.loadBuildManifest('_error' as Page), manifestLoader.loadBuildManifest(createPage('_error')),
manifestLoader.loadPagesManifest('_error' as Page), manifestLoader.loadPagesManifest(createPage('_error')),
manifestLoader.loadFontManifest('_error' as Page), manifestLoader.loadFontManifest(createPage('_error')),
] ]
: []), : []),
entrypoints.value.instrumentation && entrypoints.value.instrumentation &&
......
import type { Page, Route } from '../shared/lib/route-types' import {
createPage,
createRoute,
type Page,
type Route,
} from '../shared/lib/route-types'
import type { import type {
NextConfigComplete, NextConfigComplete,
NextConfigRuntime, NextConfigRuntime,
...@@ -104,7 +109,7 @@ import { mapNftFileEntries, type NftJson, resolveNftOutputPath } from './nft' ...@@ -104,7 +109,7 @@ import { mapNftFileEntries, type NftJson, resolveNftOutputPath } from './nft'
*/ */
function getTreeViewDisplayPath(pagePath: Route): string { function getTreeViewDisplayPath(pagePath: Route): string {
const prerenderPathname = getStaticMetadataPrerenderPathname( const prerenderPathname = getStaticMetadataPrerenderPathname(
(pagePath.startsWith('/') ? pagePath : `/${pagePath}`) as Route pagePath.startsWith('/') ? pagePath : createRoute(`/${pagePath}`)
) )
return prerenderPathname ?? pagePath return prerenderPathname ?? pagePath
} }
...@@ -113,10 +118,10 @@ function buildStaticMetadataStaticPaths(page: Route): { ...@@ -113,10 +118,10 @@ function buildStaticMetadataStaticPaths(page: Route): {
fallbackMode: FallbackMode | undefined fallbackMode: FallbackMode | undefined
prerenderedRoutes: PrerenderedRoute[] prerenderedRoutes: PrerenderedRoute[]
} { } {
// @ts-ignore -- Human review: this is already a Route from static collection; raw Page normalization may strip a real URL leaf. Preserve the existing second normalization. // @ts-ignore -- TODO: Human review: this is already a Route from static collection; raw Page normalization may strip a real URL leaf. Preserve the existing second normalization.
let pathname = normalizeAppPath(page) let pathname = normalizeAppPath(page)
if (pathname.endsWith('/route')) { if (pathname.endsWith('/route')) {
pathname = pathname.slice(0, -'/route'.length) as Route pathname = createRoute(pathname.slice(0, -'/route'.length))
} }
const prerenderPathname = getStaticMetadataPrerenderPathname(pathname) const prerenderPathname = getStaticMetadataPrerenderPathname(pathname)
...@@ -337,7 +342,7 @@ export async function printTreeView( ...@@ -337,7 +342,7 @@ export async function printTreeView(
// Check if we have a custom app. // Check if we have a custom app.
const hasCustomApp = !!( const hasCustomApp = !!(
pagesDir && pagesDir &&
(await findPageFile(pagesDir, '/_app' as Page, pageExtensions, false)) (await findPageFile(pagesDir, createPage('/_app'), pageExtensions, false))
) )
// Collect all the symbols we use so we can print the icons out. // Collect all the symbols we use so we can print the icons out.
...@@ -539,10 +544,10 @@ export async function printTreeView( ...@@ -539,10 +544,10 @@ export async function printTreeView(
: 0 : 0
const routeSymbol = const routeSymbol =
(isSummary ? summarySymbol : undefined) ?? (isSummary ? summarySymbol : undefined) ??
// @ts-ignore -- Human review: a summary display label intentionally probes the Route-keyed map, relying on a miss and parent pageInfo fallback. Do not brand this non-URL text. // @ts-ignore -- TODO: Human review: a summary display label intentionally probes the Route-keyed map, relying on a miss and parent pageInfo fallback. Do not brand this non-URL text.
getTreeViewSymbol(route, pageInfos.get(route) ?? pageInfo) getTreeViewSymbol(route, pageInfos.get(route) ?? pageInfo)
const innerSymbol = index === displayedRoutes - 1 ? '└' : '├' const innerSymbol = index === displayedRoutes - 1 ? '└' : '├'
// @ts-ignore -- Human review: summary display text is not a Route; this lookup deliberately yields no per-route cache metadata. Preserve the display behavior. // @ts-ignore -- TODO: Human review: summary display text is not a Route; this lookup deliberately yields no per-route cache metadata. Preserve the display behavior.
const initialCacheControl = pageInfos.get(route)?.initialCacheControl const initialCacheControl = pageInfos.get(route)?.initialCacheControl
usedSymbols.add(routeSymbol) usedSymbols.add(routeSymbol)
...@@ -576,17 +581,18 @@ export async function printTreeView( ...@@ -576,17 +581,18 @@ export async function printTreeView(
messages.push(['', '', '', '']) messages.push(['', '', '', ''])
} }
pageInfos.set('/404' as Route, { pageInfos.set(createRoute('/404'), {
...(pageInfos.get('/404' as Route) || pageInfos.get('/_error' as Route))!, ...(pageInfos.get(createRoute('/404')) ||
pageInfos.get(createRoute('/_error')))!,
isStatic: useStaticPages404, isStatic: useStaticPages404,
}) })
// If there's no app /_notFound page present, then the 404 is still using the pages/404 // If there's no app /_notFound page present, then the 404 is still using the pages/404
if ( if (
!lists.pages.includes('/404' as Route) && !lists.pages.includes(createRoute('/404')) &&
!lists.app?.includes(UNDERSCORE_NOT_FOUND_ROUTE as Route) !lists.app?.includes(createRoute(UNDERSCORE_NOT_FOUND_ROUTE))
) { ) {
lists.pages = [...lists.pages, '/404' as Route] lists.pages = [...lists.pages, createRoute('/404')]
} }
// Print the tree view for the pages directory. // Print the tree view for the pages directory.
...@@ -596,7 +602,7 @@ export async function printTreeView( ...@@ -596,7 +602,7 @@ export async function printTreeView(
}) })
if ( if (
middlewareManifest.middleware?.['/' as Route]?.files.length > 0 || middlewareManifest.middleware?.[createRoute('/')]?.files.length > 0 ||
// 'nodejs' runtime middleware or proxy is set to // 'nodejs' runtime middleware or proxy is set to
// functions-config-manifest instead of middleware-manifest. // functions-config-manifest instead of middleware-manifest.
functionsConfigManifest.functions?.['/_middleware'] functionsConfigManifest.functions?.['/_middleware']
...@@ -680,7 +686,9 @@ export function printPrerenderMatchers( ...@@ -680,7 +686,9 @@ export function printPrerenderMatchers(
for (const sourceRoute of [...sourceRoutes].sort()) { for (const sourceRoute of [...sourceRoutes].sort()) {
const matchers = ( const matchers = (
Object.entries(prerenderManifest.dynamicRoutes) as [ Object.entries(
prerenderManifest.dynamicRoutes
) as /* TODO: Preserve Route entry keys through native iteration. */ [
Route, Route,
DynamicPrerenderManifestRoute, DynamicPrerenderManifestRoute,
][] ][]
...@@ -705,7 +713,9 @@ export function printPrerenderMatchers( ...@@ -705,7 +713,9 @@ export function printPrerenderMatchers(
) )
const prerenders = ( const prerenders = (
Object.entries(prerenderManifest.routes) as [ Object.entries(
prerenderManifest.routes
) as /* TODO: Preserve Route entry keys through native iteration. */ [
Route, Route,
PrerenderManifestRoute, PrerenderManifestRoute,
][] ][]
...@@ -965,7 +975,7 @@ export async function isPageStatic({ ...@@ -965,7 +975,7 @@ export async function isPageStatic({
Document: mod.Document, Document: mod.Document,
App: mod.App, App: mod.App,
routeModule: mod.routeModule, routeModule: mod.routeModule,
// @ts-ignore -- Human review: the edge component record stores the normalized Route in a Page loader-result field, unlike the non-edge raw module lookup. Preserve existing metadata. // @ts-ignore -- TODO: Human review: the edge component record stores the normalized Route in a Page loader-result field, unlike the non-edge raw module lookup. Preserve existing metadata.
page, page,
ComponentMod: mod, ComponentMod: mod,
pageConfig: mod.config || {}, pageConfig: mod.config || {},
...@@ -978,7 +988,7 @@ export async function isPageStatic({ ...@@ -978,7 +988,7 @@ export async function isPageStatic({
} else { } else {
componentsResult = await loadComponents({ componentsResult = await loadComponents({
distDir, distDir,
// @ts-ignore -- Human review: an absent raw App Page falls back to a normalized Route in the module loader. Pages namespaces can coincide, but App routes lose groups/leaf suffixes. Preserve the existing lookup. // @ts-ignore -- TODO: Human review: an absent raw App Page falls back to a normalized Route in the module loader. Pages namespaces can coincide, but App routes lose groups/leaf suffixes. Preserve the existing lookup.
page: originalAppPath || page, page: originalAppPath || page,
isAppPath: pageType === 'app', isAppPath: pageType === 'app',
isDev: false, isDev: false,
...@@ -1049,10 +1059,10 @@ export async function isPageStatic({ ...@@ -1049,10 +1059,10 @@ export async function isPageStatic({
// build the static paths. The edge runtime doesn't support static // build the static paths. The edge runtime doesn't support static
// paths. // paths.
if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) { if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) {
// @ts-ignore -- Human review: page is already a Route from appPathRoutes; raw Page normalization is applied again. Preserve the existing static metadata lookup assumption. // @ts-ignore -- TODO: Human review: page is already a Route from appPathRoutes; raw Page normalization is applied again. Preserve the existing static metadata lookup assumption.
let pathname = normalizeAppPath(page) let pathname = normalizeAppPath(page)
if (pathname.endsWith('/route')) { if (pathname.endsWith('/route')) {
pathname = pathname.slice(0, -'/route'.length) as Route pathname = createRoute(pathname.slice(0, -'/route'.length))
} }
if ( if (
...@@ -1598,7 +1608,7 @@ export async function copyTracedFiles( ...@@ -1598,7 +1608,7 @@ export async function copyTracedFiles(
} }
const route = normalizePagePath(page) const route = normalizePagePath(page)
// @ts-ignore -- Human review: file-encoded Page is tested against URL-keyed staticPages; /index encoding may differ. Preserve standalone trace selection. // @ts-ignore -- TODO: Human review: file-encoded Page is tested against URL-keyed staticPages; /index encoding may differ. Preserve standalone trace selection.
if (staticPages.has(route)) { if (staticPages.has(route)) {
continue continue
} }
......
import type { Page, Route } from '../../../../shared/lib/route-types' import {
createPage,
type Page,
type Route,
} from '../../../../shared/lib/route-types'
import type webpack from 'next/dist/compiled/webpack/webpack' import type webpack from 'next/dist/compiled/webpack/webpack'
import { import {
UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_GLOBAL_ERROR_ROUTE,
...@@ -1057,7 +1061,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1057,7 +1061,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const getStaticSiblingSegments = (segmentPath: string): string[] => { const getStaticSiblingSegments = (segmentPath: string): string[] => {
// Normalize the current path to URL space // Normalize the current path to URL space
// Add a trailing /page so normalizeAppPath strips it properly // Add a trailing /page so normalizeAppPath strips it properly
const currentUrlPath = normalizeAppPath((segmentPath + '/page') as Page) const currentUrlPath = normalizeAppPath(createPage(segmentPath + '/page'))
const currentUrlSegments = currentUrlPath.split('/').filter(Boolean) const currentUrlSegments = currentUrlPath.split('/').filter(Boolean)
// If the path is empty (root level), there are no siblings // If the path is empty (root level), there are no siblings
...@@ -1084,7 +1088,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1084,7 +1088,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
for (const appPath of allNormalizedAppPaths) { for (const appPath of allNormalizedAppPaths) {
// Normalize each path to URL space (strip route groups, parallel routes, and /page suffix) // Normalize each path to URL space (strip route groups, parallel routes, and /page suffix)
// @ts-ignore -- Human review: these keys are already Routes from appPathsPerRoute; normalizing again as raw Pages may strip a real URL /page or /route segment. Preserve sibling computation. // @ts-ignore -- TODO: Human review: these keys are already Routes from appPathsPerRoute; normalizing again as raw Pages may strip a real URL /page or /route segment. Preserve sibling computation.
const urlPath = normalizeAppPath(appPath) const urlPath = normalizeAppPath(appPath)
const urlSegments = urlPath.split('/').filter(Boolean) const urlSegments = urlPath.split('/').filter(Boolean)
......
import type { Page } from '../../../shared/lib/route-types' import { createPage, type Page } from '../../../shared/lib/route-types'
import type webpack from 'webpack' 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'
...@@ -32,13 +32,13 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade ...@@ -32,13 +32,13 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
buildInfo.route = { buildInfo.route = {
page: page || ('/' as Page), page: page || createPage('/'),
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
middlewareConfig, middlewareConfig,
} }
buildInfo.nextEdgeApiFunction = { buildInfo.nextEdgeApiFunction = {
page: page || ('/' as Page), page: page || createPage('/'),
} }
buildInfo.rootDir = rootDir buildInfo.rootDir = rootDir
......
import type { Page, Route } from '../../../../shared/lib/route-types' import {
createPage,
pagesPageToRoute,
type Page,
} from '../../../../shared/lib/route-types'
import type webpack from 'webpack' import type webpack from 'webpack'
import type { SizeLimit } from '../../../../types' import type { SizeLimit } from '../../../../types'
import type { PagesRouteModuleOptions } from '../../../../server/route-modules/pages/module' import type { PagesRouteModuleOptions } from '../../../../server/route-modules/pages/module'
...@@ -55,7 +59,7 @@ function getRouteModuleOptions(page: Page) { ...@@ -55,7 +59,7 @@ function getRouteModuleOptions(page: Page) {
page: normalizePagePath(page), page: normalizePagePath(page),
// Pages-router discovery keys also identify URL patterns. The raw module // Pages-router discovery keys also identify URL patterns. The raw module
// page above has its separate file encoding from normalizePagePath. // page above has its separate file encoding from normalizePagePath.
pathname: page as unknown as Route, pathname: pagesPageToRoute(page),
// The following aren't used in production. // The following aren't used in production.
bundlePath: '', bundlePath: '',
filename: '', filename: '',
...@@ -215,10 +219,10 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -215,10 +219,10 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
{ {
pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)), pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)),
errorRouteModuleOptions: JSON.stringify( errorRouteModuleOptions: JSON.stringify(
getRouteModuleOptions('/_error' as Page) getRouteModuleOptions(createPage('/_error'))
), ),
user500RouteModuleOptions: JSON.stringify( user500RouteModuleOptions: JSON.stringify(
getRouteModuleOptions('/500' as Page) getRouteModuleOptions(createPage('/500'))
), ),
...(cacheHandlersSetup ?? {}), ...(cacheHandlersSetup ?? {}),
}, },
......
import type { Page, Route } from '../../../shared/lib/route-types' import { createRoute, type Page } from '../../../shared/lib/route-types'
import type { import type {
ProxyConfig, ProxyConfig,
ProxyMatcher, ProxyMatcher,
...@@ -54,10 +54,14 @@ export default async function middlewareLoader(this: any) { ...@@ -54,10 +54,14 @@ export default async function middlewareLoader(this: any) {
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeMiddleware = { buildInfo.nextEdgeMiddleware = {
matchers, matchers,
page: (page.replace( page: createRoute(
new RegExp(`/(${MIDDLEWARE_LOCATION_REGEXP}|${PROXY_LOCATION_REGEXP})$`), page.replace(
'' new RegExp(
) || '/') as Route, `/(${MIDDLEWARE_LOCATION_REGEXP}|${PROXY_LOCATION_REGEXP})$`
),
''
) || '/'
),
} }
buildInfo.rootDir = rootDir buildInfo.rootDir = rootDir
buildInfo.route = { buildInfo.route = {
......
import type { Page } from '../../../shared/lib/route-types'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import * as path from 'node:path' import * as path from 'node:path'
import * as fs from 'node:fs/promises' import * as fs from 'node:fs/promises'
...@@ -154,10 +153,10 @@ function getParamsFromLayoutFilePath({ ...@@ -154,10 +153,10 @@ function getParamsFromLayoutFilePath({
layoutFilePath: string layoutFilePath: string
}): string[] { }): string[] {
const rootLayoutPath = normalizeAppPath( const rootLayoutPath = normalizeAppPath(
// Construct the app identifier prefix from the discovered layout directory. // @ts-ignore TODO: Human review: this is a layout directory prefix, not a module Page; normalizeAppPath may strip a real trailing page/route directory. Preserve root-parameter discovery.
ensureLeadingSlash( ensureLeadingSlash(
normalizePathSep(path.dirname(path.relative(appDir, layoutFilePath))) normalizePathSep(path.dirname(path.relative(appDir, layoutFilePath)))
) as Page )
) )
const segments = rootLayoutPath.split('/') const segments = rootLayoutPath.split('/')
const paramNames: string[] = [] const paramNames: string[] = []
......
import type { Page } from '../../../../shared/lib/route-types' import { createPage, type Page } from '../../../../shared/lib/route-types'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { ProxyConfig } from '../../../analysis/get-page-static-info' import type { ProxyConfig } from '../../../analysis/get-page-static-info'
...@@ -114,8 +114,8 @@ export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string { ...@@ -114,8 +114,8 @@ export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string {
absolutePagePath: options.absolutePagePath, absolutePagePath: options.absolutePagePath,
// These are the path references to the internal components that may be // These are the path references to the internal components that may be
// overridden by userland components. // overridden by userland components.
absoluteAppPath: options.pages['/_app' as Page], absoluteAppPath: options.pages[createPage('/_app')],
absoluteDocumentPath: options.pages['/_document' as Page], absoluteDocumentPath: options.pages[createPage('/_document')],
middlewareConfigBase64: encodeToBase64(options.middlewareConfig), middlewareConfigBase64: encodeToBase64(options.middlewareConfig),
} }
......
...@@ -67,7 +67,10 @@ export function generateClientManifest( ...@@ -67,7 +67,10 @@ export function generateClientManifest(
) )
sortedPageKeys.forEach((page) => { sortedPageKeys.forEach((page) => {
const dependencies = assetMap.pages[page as string as Page] const dependencies =
assetMap.pages[
page as string as /* TODO: Model the Pages-only URL/module relationship without erasing Route. */ Page
]
if (page === '/_app') return if (page === '/_app') return
// Filter out dependencies in the _app entry, because those will have already // Filter out dependencies in the _app entry, because those will have already
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import type { Page } from '../../../shared/lib/route-types' import { createPage } from '../../../shared/lib/route-types'
import path from 'path' import path from 'path'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
...@@ -605,7 +605,7 @@ export class ClientReferenceManifestPlugin { ...@@ -605,7 +605,7 @@ export class ClientReferenceManifestPlugin {
// Only app/page and app/route entrypoints reach this loop. Removing // Only app/page and app/route entrypoints reach this loop. Removing
// the bundle namespace recovers their raw App module identifier. // the bundle namespace recovers their raw App module identifier.
const pageBundlePath = normalizePagePath( const pageBundlePath = normalizePagePath(
pagePath.slice('app'.length) as Page createPage(pagePath.slice('app'.length))
) )
compilation.emitAsset( compilation.emitAsset(
'server/app' + pageBundlePath + '_' + CLIENT_REFERENCE_MANIFEST + '.js', 'server/app' + pageBundlePath + '_' + CLIENT_REFERENCE_MANIFEST + '.js',
......
...@@ -230,6 +230,7 @@ function getCreateAssets(params: { ...@@ -230,6 +230,7 @@ function getCreateAssets(params: {
continue continue
} }
// TODO: Preserve the metadata discriminator's Page/Route correlation in these views.
// Entry metadata is exclusive: the app SSR tag proves a raw app Page, // Entry metadata is exclusive: the app SSR tag proves a raw app Page,
// while proxy entries carry a Route scope prefix. // while proxy entries carry a Route scope prefix.
const matcherSource = metadata.edgeSSR?.isAppDir const matcherSource = metadata.edgeSSR?.isAppDir
...@@ -272,6 +273,7 @@ function getCreateAssets(params: { ...@@ -272,6 +273,7 @@ function getCreateAssets(params: {
...(metadata.regions && { regions: metadata.regions }), ...(metadata.regions && { regions: metadata.regions }),
} }
// TODO: Preserve the key/payload correlation without asserting each manifest branch.
// The metadata tag determines the namespace of both key and payload. // The metadata tag determines the namespace of both key and payload.
if (isEdgeFunction) { if (isEdgeFunction) {
middlewareManifest.functions[page as Page] = middlewareManifest.functions[page as Page] =
...@@ -283,8 +285,10 @@ function getCreateAssets(params: { ...@@ -283,8 +285,10 @@ function getCreateAssets(params: {
} }
middlewareManifest.sortedMiddleware = getSortedRoutes( middlewareManifest.sortedMiddleware = getSortedRoutes(
Object.keys(middlewareManifest.middleware) as Route[] Object.keys(
) as Route[] middlewareManifest.middleware
) as /* TODO: Preserve Route keys across iteration and sorting. */ Route[]
) as /* TODO: Preserve Route keys across iteration and sorting. */ Route[]
compilation.emitAsset( compilation.emitAsset(
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
......
...@@ -443,7 +443,7 @@ export class NextTypesPlugin { ...@@ -443,7 +443,7 @@ export class NextTypesPlugin {
) )
) )
// @ts-ignore -- Human review: App normalization yields a Route, but the Pages branch decodes a Page-file identifier and treats it as a URL pattern. Preserve existing typed-route generation. // @ts-ignore -- TODO: Human review: App normalization yields a Route, but the Pages branch decodes a Page-file identifier and treats it as a URL pattern. Preserve existing typed-route generation.
const { isDynamic, routeType } = formatRouteToRouteType(route) const { isDynamic, routeType } = formatRouteToRouteType(route)
pluginState.routeTypes[this.isEdgeServer ? 'edge' : 'node'][ pluginState.routeTypes[this.isEdgeServer ? 'edge' : 'node'][
......
...@@ -15,7 +15,14 @@ ...@@ -15,7 +15,14 @@
* only the top N routes (totals always reflect all routes). * only the top N routes (totals always reflect all routes).
*/ */
import type { Page, Route } from '../../shared/lib/route-types' import {
createPage,
createPages,
createRoutes,
pagesRouteToPage,
type Page,
type Route,
} from '../../shared/lib/route-types'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import loadConfig from '../../server/config' import loadConfig from '../../server/config'
...@@ -191,16 +198,12 @@ type RouteEntry = ...@@ -191,16 +198,12 @@ type RouteEntry =
* `_app` / `_document` / `_error` aren't really routes, and `404` / `500` * `_app` / `_document` / `_error` aren't really routes, and `404` / `500`
* are HTML-only error pages. * are HTML-only error pages.
*/ */
const SKIP_PAGES_ENTRIES = new Set<Route>([ const SKIP_PAGES_ENTRIES = new Set<Route>(
'/_app', createRoutes(['/_app', '/_document', '/_error', '/404', '/500'])
'/_document', )
'/_error',
'/404',
'/500',
] as Route[])
/** App Router infrastructure entries we never report as routes. */ /** App Router infrastructure entries we never report as routes. */
const SKIP_APP_ENTRIES = new Set<Page>(['/_global-error/page'] as Page[]) const SKIP_APP_ENTRIES = new Set<Page>(createPages(['/_global-error/page']))
function readJsonFile<T>(filePath: string): T | null { function readJsonFile<T>(filePath: string): T | null {
try { try {
...@@ -251,27 +254,29 @@ function discoverPagesRoutes( ...@@ -251,27 +254,29 @@ function discoverPagesRoutes(
if (!manifest) return [] if (!manifest) return []
const routes: RouteEntry[] = [] const routes: RouteEntry[] = []
for (const [route, entry] of Object.entries(manifest)) { // Object.entries erases the key role declared by the native Pages manifest.
if (SKIP_PAGES_ENTRIES.has(route as Route)) continue // Restore that existing role; this is not raw pathname construction.
for (const [route, entry] of Object.entries(manifest) as [Route, string][]) {
if (SKIP_PAGES_ENTRIES.has(route)) continue
const isApi = route.startsWith('/api/') const isApi = route.startsWith('/api/')
const edge = edgeFunctions[route] const edge = edgeFunctions[route]
if (edge) { if (edge) {
// Edge runtime — bundle files come from middleware-manifest, not nft. // Edge runtime — bundle files come from middleware-manifest, not nft.
routes.push({ routes.push({
type: isApi ? 'pages-api' : 'pages', type: isApi ? 'pages-api' : 'pages',
route: route as Route, route: route,
runtime: { kind: 'edge', files: edge.files }, runtime: { kind: 'edge', files: edge.files },
}) })
} else if (entry.endsWith('.js')) { } else if (entry.endsWith('.js')) {
routes.push({ routes.push({
type: isApi ? 'pages-api' : 'pages', type: isApi ? 'pages-api' : 'pages',
route: route as Route, route: route,
runtime: { kind: 'node', serverEntry: entry }, runtime: { kind: 'node', serverEntry: entry },
}) })
} else if (entry.endsWith('.html')) { } else if (entry.endsWith('.html')) {
// Statically pre-rendered page — no server JS bundle, but still ships // Statically pre-rendered page — no server JS bundle, but still ships
// client JS via build-manifest.json. // client JS via build-manifest.json.
routes.push({ type: 'pages-static', route: route as Route }) routes.push({ type: 'pages-static', route: route })
} }
} }
return routes return routes
...@@ -293,10 +298,14 @@ function discoverAppRoutes( ...@@ -293,10 +298,14 @@ function discoverAppRoutes(
) )
const routes: RouteEntry[] = [] const routes: RouteEntry[] = []
for (const [internalKey, entry] of Object.entries(appPathsManifest)) { // Restore the native App manifest's existing key role after Object.entries.
if (SKIP_APP_ENTRIES.has(internalKey as Page)) continue for (const [internalKey, entry] of Object.entries(appPathsManifest) as [
Page,
string,
][]) {
if (SKIP_APP_ENTRIES.has(internalKey)) continue
const type = internalKey.endsWith('/route') ? 'app-route' : 'app-page' const type = internalKey.endsWith('/route') ? 'app-route' : 'app-page'
const route = appPathRoutesManifest?.[internalKey as Page] ?? internalKey const route = appPathRoutesManifest?.[internalKey] ?? internalKey
const edge = edgeFunctions[internalKey] const edge = edgeFunctions[internalKey]
if (edge) { if (edge) {
// Edge runtime — turbopack writes a placeholder entry value (e.g. // Edge runtime — turbopack writes a placeholder entry value (e.g.
...@@ -635,9 +644,9 @@ function collectPagesClientFiles( ...@@ -635,9 +644,9 @@ function collectPagesClientFiles(
}>(path.join(distDir, 'build-manifest.json')) }>(path.join(distDir, 'build-manifest.json'))
if (!bm) return if (!bm) return
const chunks = [ const chunks = [
...(bm.pages?.['/_app' as Page] ?? []), ...(bm.pages?.[createPage('/_app')] ?? []),
// Pages-only URL and module keys share this namespace. // Pages-only URL and module keys share this namespace.
...(bm.pages?.[route as string as Page] ?? []), ...(bm.pages?.[pagesRouteToPage(route)] ?? []),
...(bm.polyfillFiles ?? []), ...(bm.polyfillFiles ?? []),
] ]
for (const chunk of chunks) { for (const chunk of chunks) {
......
import type { ClientBuildManifest } from '../build/webpack/plugins/build-manifest-plugin-utils'
import type { createRouteKeys, createRoutes } from '../shared/lib/route-types'
/**
* Ingest the framework-emitted client manifest through its legacy ambient
* string-indexed declaration. Webpack's build-manifest-plugin and Turbopack's
* manifest-loader supply URL keys, sortedPages and rewrite/filter metadata.
* This is a producer trust boundary, not validation of that native schema.
*
* Reuse the primitive key/member guards without introducing a build-schema
* dependency into the shared brand layer. Keep file payload types, array shape,
* metadata and the original object; no fields are inspected or copied.
*/
export function ingestClientBuildManifest<
Value extends Record<string, string[]>,
>(
value: Value &
Parameters<typeof createRouteKeys<Value>>[0] & {
sortedPages?: Parameters<typeof createRoutes<Value['sortedPages']>>[0]
}
): ClientBuildManifest &
ReturnType<typeof createRouteKeys<Omit<Value, 'sortedPages'>>> & {
sortedPages: ReturnType<typeof createRoutes<Value['sortedPages']>>
} {
return value as unknown as ClientBuildManifest &
ReturnType<typeof createRouteKeys<Omit<Value, 'sortedPages'>>> & {
sortedPages: ReturnType<typeof createRoutes<Value['sortedPages']>>
}
}
import type { Route } from '../../shared/lib/route-types' import { createRoute, type Route } from '../../shared/lib/route-types'
import type { RootRouteTree } from './segment-cache/cache' import type { RootRouteTree } from './segment-cache/cache'
import type { import type {
FlightRouterState, FlightRouterState,
...@@ -285,7 +285,7 @@ export function navigateToKnownRoute( ...@@ -285,7 +285,7 @@ export function navigateToKnownRoute(
PrefetchHint.SubtreeHasInstantFalse)) === PrefetchHint.SubtreeHasInstantFalse)) ===
0 0
) { ) {
const error = createLinkPrefetchPartialError(url.pathname as Route) const error = createLinkPrefetchPartialError(createRoute(url.pathname))
const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined
if (ownerStack === undefined) { if (ownerStack === undefined) {
console.error( console.error(
...@@ -543,7 +543,7 @@ async function navigateToUnknownRoute( ...@@ -543,7 +543,7 @@ async function navigateToUnknownRoute(
// retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch). // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).
discoverKnownRoute( discoverKnownRoute(
now, now,
url.pathname as Route, createRoute(url.pathname),
url.search as NormalizedSearch, url.search as NormalizedSearch,
nextUrl, nextUrl,
null, // No pending entry null, // No pending entry
......
import type { Route } from '../../shared/lib/route-types' import { createRoute } from '../../shared/lib/route-types'
import type { RouteTree } from './segment-cache/cache' import type { RouteTree } from './segment-cache/cache'
import React, { import React, {
useEffect, useEffect,
...@@ -456,7 +456,7 @@ function Router({ ...@@ -456,7 +456,7 @@ function Router({
tree, tree,
// Internal devtools consume the native URL pathname; public hook/context // Internal devtools consume the native URL pathname; public hook/context
// and NavigationPromises string types remain unchanged. // and NavigationPromises string types remain unchanged.
pathname as Route, createRoute(pathname),
searchParams, searchParams,
pathParams pathParams
) )
......
...@@ -617,7 +617,7 @@ export default function OuterLayoutRouter({ ...@@ -617,7 +617,7 @@ export default function OuterLayoutRouter({
const { SegmentBoundaryTriggerNode, SegmentViewStateNode } = const { SegmentBoundaryTriggerNode, SegmentViewStateNode } =
require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node') require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')
// @ts-ignore Human review: canonical navigation URL can contain search text and is not a raw Page; preserve the existing devtools prefix normalization. // @ts-ignore TODO: Human review: canonical navigation URL can contain search text and is not a raw Page; preserve the existing devtools prefix normalization.
const pagePrefix = normalizeAppPath(url) const pagePrefix = normalizeAppPath(url)
segmentViewStateNode = ( segmentViewStateNode = (
<SegmentViewStateNode key={pagePrefix} page={pagePrefix} /> <SegmentViewStateNode key={pagePrefix} page={pagePrefix} />
......
import type { Route } from '../../shared/lib/route-types' import { createRoute, type Route } from '../../shared/lib/route-types'
import type { FlightRouterState } from '../../shared/lib/app-router-types' import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { CacheNode } from '../../shared/lib/app-router-types' import type { CacheNode } from '../../shared/lib/app-router-types'
import type { ScrollRef } from '../../shared/lib/app-router-types' import type { ScrollRef } from '../../shared/lib/app-router-types'
...@@ -1664,7 +1664,7 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1664,7 +1664,7 @@ function dispatchRetryDueToTreeMismatch(
const now = Date.now() const now = Date.now()
discoverKnownRoute( discoverKnownRoute(
now, now,
retryUrl.pathname as Route, createRoute(retryUrl.pathname),
retryUrl.search as NormalizedSearch, retryUrl.search as NormalizedSearch,
retryNextUrl, retryNextUrl,
null, null,
......
import type { Page, Route } from '../../../shared/lib/route-types' import {
createRoute,
createRouteOrNull,
type Page,
type Route,
} from '../../../shared/lib/route-types'
import type { import type {
FlightRouterState, FlightRouterState,
Segment, Segment,
...@@ -66,14 +71,16 @@ export const segmentToSourcePagePathname = (segment: Segment): string => { ...@@ -66,14 +71,16 @@ export const segmentToSourcePagePathname = (segment: Segment): string => {
} }
function normalizeSegments(segments: string[]): Route { function normalizeSegments(segments: string[]): Route {
return (segments.reduce((acc, segment) => { return createRoute(
segment = removeLeadingSlash(segment) segments.reduce((acc, segment) => {
if (segment === '' || isGroupSegment(segment)) { segment = removeLeadingSlash(segment)
return acc if (segment === '' || isGroupSegment(segment)) {
} return acc
}
return `${acc}/${segment}` return `${acc}/${segment}`
}, '') || '/') as Route }, '') || '/'
)
} }
export function extractPathFromFlightRouterState( export function extractPathFromFlightRouterState(
...@@ -161,7 +168,7 @@ export function extractSourcePageFromFlightRouterState( ...@@ -161,7 +168,7 @@ export function extractSourcePageFromFlightRouterState(
const sourcePageSegments = const sourcePageSegments =
extractSourcePageSegmentsFromFlightRouterState(flightRouterState) extractSourcePageSegmentsFromFlightRouterState(flightRouterState)
// @ts-ignore Human review: source-module reconstruction omits parallel slot keys, so it may not retain the full raw Page identity. Preserve the existing diagnostic value. // @ts-ignore TODO: Human review: source-module reconstruction omits parallel slot keys, so it may not retain the full raw Page identity. Preserve the existing diagnostic value.
return sourcePageSegments ? `/${sourcePageSegments.join('/')}` : undefined return sourcePageSegments ? `/${sourcePageSegments.join('/')}` : undefined
} }
...@@ -226,7 +233,7 @@ export function computeChangedPath( ...@@ -226,7 +233,7 @@ export function computeChangedPath(
const changedPath = computeChangedPathImpl(treeA, treeB) const changedPath = computeChangedPathImpl(treeA, treeB)
if (changedPath == null || changedPath === '/') { if (changedPath == null || changedPath === '/') {
return changedPath as Route | null return createRouteOrNull(changedPath)
} }
// lightweight normalization to remove route groups // lightweight normalization to remove route groups
......
import type { Route } from '../../../shared/lib/route-types' import {
createRoute,
ingestBrowserLocation,
} from '../../../shared/lib/route-types'
import type { InitialRSCPayload } from '../../../shared/lib/app-router-types' import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'
import { createHrefFromUrl } from './create-href-from-url' import { createHrefFromUrl } from './create-href-from-url'
...@@ -112,7 +115,7 @@ export function createInitialRouterState({ ...@@ -112,7 +115,7 @@ export function createInitialRouterState({
// Learn the route pattern so we can predict it for future navigations. // Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute( discoverKnownRoute(
Date.now(), Date.now(),
location.pathname as Route, createRoute(location.pathname),
location.search as NormalizedSearch, location.search as NormalizedSearch,
null, // nextUrl — initial render is never an interception null, // nextUrl — initial render is never an interception
null, // No pending entry null, // No pending entry
...@@ -260,9 +263,10 @@ export function createInitialRouterState({ ...@@ -260,9 +263,10 @@ export function createInitialRouterState({
// the || operator is intentional, the pathname can be an empty string // the || operator is intentional, the pathname can be an empty string
// Tree extraction drops its empty fragment sentinel here; the remaining // Tree extraction drops its empty fragment sentinel here; the remaining
// alternative is the native browser Location pathname. // alternative is the native browser Location pathname.
nextUrl: ((extractPathFromFlightRouterState(initialTree) || nextUrl:
location?.pathname) ?? (extractPathFromFlightRouterState(initialTree) ||
null) as Route | null, ingestBrowserLocation(location)?.pathname) ??
null,
previousNextUrl: null, previousNextUrl: null,
debugInfo: null, debugInfo: null,
} }
......
import type { Route } from '../../../../shared/lib/route-types' import { createRoute, type Route } from '../../../../shared/lib/route-types'
import type { import type {
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
...@@ -44,10 +44,10 @@ export function restoreReducer( ...@@ -44,10 +44,10 @@ export function restoreReducer(
const currentUrl = new URL(state.canonicalUrl, location.origin) const currentUrl = new URL(state.canonicalUrl, location.origin)
const restoredUrl = action.url const restoredUrl = action.url
// @ts-ignore Human review: nullish fallback retains the extractor's empty fragment sentinel as Next-Url. Preserve this unlike initial-state || handling. // @ts-ignore TODO: Human review: nullish fallback retains the extractor's empty fragment sentinel as Next-Url. Preserve this unlike initial-state || handling.
const restoredNextUrl: Route = const restoredNextUrl: Route =
extractPathFromFlightRouterState(treeToRestore) ?? extractPathFromFlightRouterState(treeToRestore) ??
(restoredUrl.pathname as Route) createRoute(restoredUrl.pathname)
const now = Date.now() const now = Date.now()
// TODO: Store the dynamic stale time on the top-level state so it's known // TODO: Store the dynamic stale time on the top-level state so it's known
......
import type { Route } from '../../../../shared/lib/route-types' import { createRoute } from '../../../../shared/lib/route-types'
import type { import type {
ActionFlightResponse, ActionFlightResponse,
ActionResult, ActionResult,
...@@ -502,7 +502,7 @@ export function serverActionReducer( ...@@ -502,7 +502,7 @@ export function serverActionReducer(
// Learn the route pattern so we can predict it for future navigations. // Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute( discoverKnownRoute(
now, now,
redirectUrl.pathname as Route, createRoute(redirectUrl.pathname),
redirectUrl.search as NormalizedSearch, redirectUrl.search as NormalizedSearch,
nextUrl, nextUrl,
null, // No pending entry null, // No pending entry
......
import type { Route } from '../../../shared/lib/route-types' import { createRoute, type Route } from '../../../shared/lib/route-types'
// TypeScript trick to simulate opaque types, like in Flow. // TypeScript trick to simulate opaque types, like in Flow.
type Opaque<K, T> = T & { __brand: K } type Opaque<K, T> = T & { __brand: K }
...@@ -26,7 +26,9 @@ export function createCacheKey( ...@@ -26,7 +26,9 @@ export function createCacheKey(
): RouteCacheKey { ): RouteCacheKey {
const originalUrl = new URL(originalHref) const originalUrl = new URL(originalHref)
const cacheKey = { const cacheKey = {
pathname: originalUrl.pathname as NormalizedPathname, // Native parsing establishes the Route; this assertion adds only the
// existing cache-specific opacity, not a second routing identity.
pathname: createRoute(originalUrl.pathname) as NormalizedPathname,
search: originalUrl.search as NormalizedSearch, search: originalUrl.search as NormalizedSearch,
nextUrl: nextUrl as NormalizedNextUrl | null, nextUrl: nextUrl as NormalizedNextUrl | null,
} as RouteCacheKey } as RouteCacheKey
......
import type { Route } from '../../../shared/lib/route-types' import { createRoute } from '../../../shared/lib/route-types'
import { import {
getSerializedRuntimeErrorState, getSerializedRuntimeErrorState,
subscribeToRuntimeErrorState, subscribeToRuntimeErrorState,
...@@ -22,7 +22,7 @@ export function createRuntimeErrorStateReporter( ...@@ -22,7 +22,7 @@ export function createRuntimeErrorStateReporter(
const report = (errorState: SerializedRuntimeErrorState, force = false) => { const report = (errorState: SerializedRuntimeErrorState, force = false) => {
// Native location parsing supplies the reporter's URL pathname. // Native location parsing supplies the reporter's URL pathname.
const pathname = window.location.pathname as Route const pathname = createRoute(window.location.pathname)
const serializedState = JSON.stringify({ pathname, errorState }) const serializedState = JSON.stringify({ pathname, errorState })
if (!force && serializedState === lastSerializedState) { if (!force && serializedState === lastSerializedState) {
return return
......
...@@ -26,6 +26,7 @@ import type { NextWebVitalsMetric, NEXT_DATA } from '../shared/lib/utils' ...@@ -26,6 +26,7 @@ import type { NextWebVitalsMetric, NEXT_DATA } from '../shared/lib/utils'
import { Portal } from './portal' import { Portal } from './portal'
import initHeadManager from './head-manager' import initHeadManager from './head-manager'
import PageLoader from './page-loader' import PageLoader from './page-loader'
import { ingestNextData } from './next-data'
import type { StyleSheetTuple } from './page-loader' import type { StyleSheetTuple } from './page-loader'
import { RouteAnnouncer } from './route-announcer' import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router' import { createRouter, makePublicRouterInstance } from './router'
...@@ -203,8 +204,8 @@ export async function initialize(opts: { devClient?: any } = {}): Promise<{ ...@@ -203,8 +204,8 @@ export async function initialize(opts: { devClient?: any } = {}): Promise<{
devClient = opts.devClient devClient = opts.devClient
} }
initialData = JSON.parse( initialData = ingestNextData<NEXT_DATA>(
document.getElementById('__NEXT_DATA__')!.textContent! JSON.parse(document.getElementById('__NEXT_DATA__')!.textContent!)
) )
window.__NEXT_DATA__ = initialData window.__NEXT_DATA__ = initialData
...@@ -275,7 +276,7 @@ export async function initialize(opts: { devClient?: any } = {}): Promise<{ ...@@ -275,7 +276,7 @@ export async function initialize(opts: { devClient?: any } = {}): Promise<{
const register: RegisterFn = ([r, f]) => const register: RegisterFn = ([r, f]) =>
// The generated public registration queue carries serialized Pages URLs. // The generated public registration queue carries serialized Pages URLs.
pageLoader.routeLoader.onEntrypoint(r as Route, f) pageLoader.routeLoader.onEntrypoint(r, f)
if (window.__NEXT_P) { if (window.__NEXT_P) {
// Defer page registration for another tick. This will increase the overall // Defer page registration for another tick. This will increase the overall
// latency in hydrating the page, but reduce the total blocking time. // latency in hydrating the page, but reduce the total blocking time.
...@@ -381,7 +382,7 @@ function renderError(renderErrorProps: RenderErrorProps): Promise<any> { ...@@ -381,7 +382,7 @@ function renderError(renderErrorProps: RenderErrorProps): Promise<any> {
) )
return pageLoader return pageLoader
.loadPage('/_error' as Route) .loadPage('/_error')
.then(({ page: ErrorComponent, styleSheets }) => { .then(({ page: ErrorComponent, styleSheets }) => {
return lastAppProps?.Component === ErrorComponent return lastAppProps?.Component === ErrorComponent
? import('../pages/_error') ? import('../pages/_error')
...@@ -837,9 +838,7 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) { ...@@ -837,9 +838,7 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) {
let initialErr = initialData.err let initialErr = initialData.err
try { try {
const appEntrypoint = await pageLoader.routeLoader.whenEntrypoint( const appEntrypoint = await pageLoader.routeLoader.whenEntrypoint('/_app')
'/_app' as Route
)
if ('error' in appEntrypoint) { if ('error' in appEntrypoint) {
throw appEntrypoint.error throw appEntrypoint.error
} }
......
import type { NEXT_DATA } from '../shared/lib/utils'
import type { createRoute, Route } from '../shared/lib/route-types'
/**
* Ingest the Pages hydration data emitted by server/render and serialized by
* pages/_document. Its page field is the renderer's URL pattern, not an App
* module identifier. The public NEXT_DATA and Window declarations stay strings.
*
* This trusts that specific producer schema; it does not validate JSON, read
* fields or change the original object. Untyped JSON must supply NEXT_DATA as its
* schema. Guard known page-field brands and retain all other fields/modifiers.
*/
export function ingestNextData<Value extends NEXT_DATA>(
value: Value &
NoInfer<{ page: Parameters<typeof createRoute<Value['page']>>[0] }>
): { [Key in keyof Value]: Key extends 'page' ? Route : Value[Key] } {
return value as unknown as {
[Key in keyof Value]: Key extends 'page' ? Route : Value[Key]
}
}
import type { Route } from '../shared/lib/route-types' import { createRoute } from '../shared/lib/route-types'
import '../lib/require-instrumentation-client' import '../lib/require-instrumentation-client'
import { hydrate, router } from './' import { hydrate, router } from './'
import initOnDemandEntries from './dev/on-demand-entries-client' import initOnDemandEntries from './dev/on-demand-entries-client'
...@@ -91,7 +91,7 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -91,7 +91,7 @@ export function pageBootstrap(assetPrefix: string) {
// The public router getter stays string-compatible; private router // The public router getter stays string-compatible; private router
// state already carries the normalized pathname. // state already carries the normalized pathname.
if (!router.clc && pages.includes(router.pathname as Route)) { if (!router.clc && pages.includes(createRoute(router.pathname))) {
console.log('Refreshing page data due to server-side change') console.log('Refreshing page data due to server-side change')
dispatcher.buildingIndicatorShow() dispatcher.buildingIndicatorShow()
const clearIndicator = dispatcher.buildingIndicatorHide const clearIndicator = dispatcher.buildingIndicatorHide
......
import type { Route } from '../shared/lib/route-types' import {
type Route,
createRoute,
createRoutes,
createRouteSet,
} from '../shared/lib/route-types'
import type { ComponentType } from 'react' import type { ComponentType } from 'react'
import type { RouteLoader } from './route-loader' import type { RouteLoader } from './route-loader'
import type { ProxyMatcher } from '../build/analysis/get-page-static-info' import type { ProxyMatcher } from '../build/analysis/get-page-static-info'
...@@ -55,10 +60,10 @@ export default class PageLoader { ...@@ -55,10 +60,10 @@ export default class PageLoader {
this.promisedSsgManifest = new Promise((resolve) => { this.promisedSsgManifest = new Promise((resolve) => {
if (window.__SSG_MANIFEST) { if (window.__SSG_MANIFEST) {
// Framework manifest data enters the private Route-keyed cache here. // Framework manifest data enters the private Route-keyed cache here.
resolve(window.__SSG_MANIFEST as Set<Route>) resolve(createRouteSet(window.__SSG_MANIFEST))
} else { } else {
window.__SSG_MANIFEST_CB = () => { window.__SSG_MANIFEST_CB = () => {
resolve(window.__SSG_MANIFEST! as Set<Route>) resolve(createRouteSet(window.__SSG_MANIFEST!))
} }
} }
}) })
...@@ -78,9 +83,11 @@ export default class PageLoader { ...@@ -78,9 +83,11 @@ export default class PageLoader {
{ credentials: 'same-origin' } { credentials: 'same-origin' }
) )
.then((res) => res.json()) .then((res) => res.json())
.then((manifest: { pages: Route[] }) => { // The dev manifest endpoint emits this raw JSON shape. This is a
// producer trust boundary, not validation of its array or members.
.then((manifest: { pages: string[] }) => {
window.__DEV_PAGES_MANIFEST = manifest window.__DEV_PAGES_MANIFEST = manifest
return manifest.pages return createRoutes(manifest.pages)
}) })
.catch((err) => { .catch((err) => {
console.log(`Failed to fetch devPagesManifest:`, err) console.log(`Failed to fetch devPagesManifest:`, err)
...@@ -195,7 +202,7 @@ export default class PageLoader { ...@@ -195,7 +202,7 @@ export default class PageLoader {
route: string route: string
): Promise<boolean> { ): Promise<boolean> {
return this.promisedSsgManifest.then((manifest) => return this.promisedSsgManifest.then((manifest) =>
manifest.has(route as Route) manifest.has(createRoute(route))
) )
} }
......
import type { Route } from '../shared/lib/route-types' import { createRoute } from '../shared/lib/route-types'
import type { NextRouter, Url } from '../shared/lib/router/router' import type { NextRouter, Url } from '../shared/lib/router/router'
import { searchParamsToUrlQuery } from '../shared/lib/router/utils/querystring' import { searchParamsToUrlQuery } from '../shared/lib/router/utils/querystring'
...@@ -73,7 +73,7 @@ export function resolveHref( ...@@ -73,7 +73,7 @@ export function resolveHref(
// Public router types stay string-compatible; this getter exposes its // Public router types stay string-compatible; this getter exposes its
// internal normalized URL pattern, not asPath with search/hash. // internal normalized URL pattern, not asPath with search/hash.
const routeRegex = getRouteRegex(router.pathname as Route) const routeRegex = getRouteRegex(createRoute(router.pathname))
const match = getRouteMatcher(routeRegex)(router.asPath) const match = getRouteMatcher(routeRegex)(router.asPath)
// For dynamic routes, if asPath doesn't match the pathname regex, it is a rewritten path. // For dynamic routes, if asPath doesn't match the pathname regex, it is a rewritten path.
...@@ -114,8 +114,8 @@ export function resolveHref( ...@@ -114,8 +114,8 @@ export function resolveHref(
// This is the native URL parsing boundary; public href/router inputs // This is the native URL parsing boundary; public href/router inputs
// remain ordinary strings and may include search/hash/full URLs. // remain ordinary strings and may include search/hash/full URLs.
const { result, params } = interpolateAs( const { result, params } = interpolateAs(
finalUrl.pathname as Route, createRoute(finalUrl.pathname),
finalUrl.pathname as Route, createRoute(finalUrl.pathname),
query query
) )
......
This diff is collapsed.
import { createRoute } from '../shared/lib/route-types'
import type { DynamicParamTypesShort } from '../shared/lib/app-router-types' import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'
import { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment' import { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment'
import { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding' import { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'
...@@ -53,11 +54,14 @@ export function getRenderedPathname( ...@@ -53,11 +54,14 @@ export function getRenderedPathname(
// the response will include a header that gives the rewritten pathname. // the response will include a header that gives the rewritten pathname.
const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER) const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)
if (rewrittenPath !== null) { if (rewrittenPath !== null) {
return rewrittenPath as NormalizedPathname // Trust the existing rewritten-path transport from the parsed destination.
// The constructor declares Route; the assertion adds only cache opacity.
return createRoute(rewrittenPath) as NormalizedPathname
} }
const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname
return ( // Preserve the cache-specific tag after declaring the native/decoded Route.
return createRoute(
hasBasePath(pathname) ? removeBasePath(pathname) : pathname hasBasePath(pathname) ? removeBasePath(pathname) : pathname
) as NormalizedPathname ) as NormalizedPathname
} }
...@@ -70,7 +74,8 @@ export function getRenderedPathname( ...@@ -70,7 +74,8 @@ export function getRenderedPathname(
*/ */
export function getPathnameFromRequestURL(url: URL): NormalizedPathname { export function getPathnameFromRequestURL(url: URL): NormalizedPathname {
const pathname = url.pathname const pathname = url.pathname
return ( // Preserve the cache-specific tag after declaring the native/decoded Route.
return createRoute(
hasBasePath(pathname) ? removeBasePath(pathname) : pathname hasBasePath(pathname) ? removeBasePath(pathname) : pathname
) as NormalizedPathname ) as NormalizedPathname
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -429,6 +429,7 @@ export function normalizeWorkerPageName(pageName: Page) { ...@@ -429,6 +429,7 @@ export function normalizeWorkerPageName(pageName: Page) {
* name. * name.
*/ */
function denormalizeWorkerPageName(bundlePath: string): Route { function denormalizeWorkerPageName(bundlePath: string): Route {
// TODO: Guard the action bundle-path decoder's Page boundary without changing prefix handling.
return normalizeAppPath(removePathPrefix(bundlePath, 'app') as Page) return normalizeAppPath(removePathPrefix(bundlePath, 'app') as Page)
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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