vinext 0.0.42 → 0.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/entries/app-rsc-entry.js +29 -7
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/routing/app-router.js +23 -3
- package/dist/routing/app-router.js.map +1 -1
- package/dist/server/app-browser-entry.js +96 -27
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-route-handler-policy.js +5 -3
- package/dist/server/app-route-handler-policy.js.map +1 -1
- package/dist/server/app-route-handler-response.js +2 -0
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/shims/navigation.d.ts +1 -1
- package/dist/shims/navigation.js +15 -5
- package/dist/shims/navigation.js.map +1 -1
- package/package.json +1 -1
|
@@ -28,6 +28,13 @@ function invalidateAppRouteCache() {
|
|
|
28
28
|
cachedAppDir = null;
|
|
29
29
|
cachedPageExtensionsKey = null;
|
|
30
30
|
}
|
|
31
|
+
function hasParallelSlotDirectory(dir) {
|
|
32
|
+
try {
|
|
33
|
+
return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && entry.name.startsWith("@"));
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
31
38
|
/**
|
|
32
39
|
* Scan the app/ directory and return a list of routes.
|
|
33
40
|
*/
|
|
@@ -45,6 +52,17 @@ async function appRouter(appDir, pageExtensions, matcher) {
|
|
|
45
52
|
const route = fileToAppRoute(file, appDir, "route", matcher);
|
|
46
53
|
if (route) routes.push(route);
|
|
47
54
|
}
|
|
55
|
+
const routePatterns = new Set(routes.map((route) => route.pattern));
|
|
56
|
+
for await (const file of scanWithExtensions("**/layout", appDir, matcher.extensions, excludeDir)) {
|
|
57
|
+
const dir = path.dirname(file);
|
|
58
|
+
const routeDir = dir === "." ? appDir : path.join(appDir, dir);
|
|
59
|
+
if (!hasParallelSlotDirectory(routeDir)) continue;
|
|
60
|
+
if (discoverParallelSlots(routeDir, appDir, matcher).length === 0) continue;
|
|
61
|
+
const route = directoryToAppRoute(dir, appDir, matcher, null, null);
|
|
62
|
+
if (!route || routePatterns.has(route.pattern)) continue;
|
|
63
|
+
routes.push(route);
|
|
64
|
+
routePatterns.add(route.pattern);
|
|
65
|
+
}
|
|
48
66
|
const slotSubRoutes = discoverSlotSubRoutes(routes, appDir, matcher);
|
|
49
67
|
routes.push(...slotSubRoutes);
|
|
50
68
|
validateRoutePatterns(routes.map((route) => route.pattern));
|
|
@@ -194,7 +212,9 @@ function findSlotSubPages(slotDir, matcher) {
|
|
|
194
212
|
* Convert a file path relative to app/ into an AppRoute.
|
|
195
213
|
*/
|
|
196
214
|
function fileToAppRoute(file, appDir, type, matcher) {
|
|
197
|
-
|
|
215
|
+
return directoryToAppRoute(path.dirname(file), appDir, matcher, type === "page" ? path.join(appDir, file) : null, type === "route" ? path.join(appDir, file) : null);
|
|
216
|
+
}
|
|
217
|
+
function directoryToAppRoute(dir, appDir, matcher, pagePath, routePath) {
|
|
198
218
|
const segments = dir === "." ? [] : dir.split(path.sep);
|
|
199
219
|
const params = [];
|
|
200
220
|
let isDynamic = false;
|
|
@@ -219,8 +239,8 @@ function fileToAppRoute(file, appDir, type, matcher) {
|
|
|
219
239
|
const parallelSlots = discoverInheritedParallelSlots(segments, appDir, routeDir, matcher);
|
|
220
240
|
return {
|
|
221
241
|
pattern: pattern === "/" ? "/" : pattern,
|
|
222
|
-
pagePath
|
|
223
|
-
routePath
|
|
242
|
+
pagePath,
|
|
243
|
+
routePath,
|
|
224
244
|
layouts,
|
|
225
245
|
templates,
|
|
226
246
|
parallelSlots,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-router.js","names":[],"sources":["../../src/routing/app-router.ts"],"sourcesContent":["/**\n * App Router file-system routing.\n *\n * Scans the app/ directory following Next.js App Router conventions:\n * - app/page.tsx -> /\n * - app/about/page.tsx -> /about\n * - app/blog/[slug]/page.tsx -> /blog/:slug\n * - app/[...catchAll]/page.tsx -> /:catchAll+\n * - app/route.ts -> / (API route)\n * - app/(group)/page.tsx -> / (route groups are transparent)\n * - Layouts: app/layout.tsx wraps all children\n * - Loading: app/loading.tsx -> Suspense fallback\n * - Error: app/error.tsx -> ErrorBoundary\n * - Not Found: app/not-found.tsx\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport type InterceptingRoute = {\n /** The interception convention: \".\" | \"..\" | \"../..\" | \"...\" */\n convention: string;\n /** The URL pattern this intercepts (e.g. \"/photos/:id\") */\n targetPattern: string;\n /** Absolute path to the intercepting page component */\n pagePath: string;\n /** Parameter names for dynamic segments */\n params: string[];\n};\n\nexport type ParallelSlot = {\n /** Stable slot identity (name + owning directory), used for route serialization keys. */\n key: string;\n /** Slot name (e.g. \"team\" from @team) */\n name: string;\n /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */\n ownerDir: string;\n /** Absolute path to the slot's page component */\n pagePath: string | null;\n /** Absolute path to the slot's default.tsx fallback */\n defaultPath: string | null;\n /** Absolute path to the slot's layout component (wraps slot content) */\n layoutPath: string | null;\n /** Absolute path to the slot's loading component */\n loadingPath: string | null;\n /** Absolute path to the slot's error component */\n errorPath: string | null;\n /** Intercepting routes within this slot */\n interceptingRoutes: InterceptingRoute[];\n /**\n * The layout index (0-based, in route.layouts[]) that this slot belongs to.\n * Slots are passed as props to the layout at their directory level, not\n * necessarily the innermost layout. -1 means \"innermost\" (legacy default).\n */\n layoutIndex: number;\n /**\n * Filesystem segments from the slot's root directory to its active page.\n * Used at render time to compute segments for useSelectedLayoutSegment(slotName).\n * For a page at the slot root (@team/page.tsx), this is [].\n * For a sub-page (@team/members/page.tsx), this is [\"members\"].\n * null when the slot has no active page (showing default.tsx fallback).\n */\n routeSegments: string[] | null;\n};\n\nexport type AppRoute = {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/blog/:slug\" */\n pattern: string;\n /** Absolute file path to the page component */\n pagePath: string | null;\n /** Absolute file path to the route handler (route.ts) */\n routePath: string | null;\n /** Ordered list of layout files from root to leaf */\n layouts: string[];\n /** Ordered list of all discovered template files from root to leaf (not necessarily aligned 1:1 with layouts) */\n templates: string[];\n /** Parallel route slots (from @slot directories at the route's directory level) */\n parallelSlots: ParallelSlot[];\n /** Loading component path */\n loadingPath: string | null;\n /** Error component path (leaf directory only) */\n errorPath: string | null;\n /**\n * Per-layout error boundary paths, aligned with the layouts array.\n * Each entry is the error.tsx at the same directory level as the\n * corresponding layout (or null if that level has no error.tsx).\n * Used to interleave ErrorBoundary components with layouts so that\n * ancestor error boundaries catch errors from descendant segments.\n */\n layoutErrorPaths: (string | null)[];\n /** Not-found component path (nearest, walking up from page dir) */\n notFoundPath: string | null;\n /**\n * Not-found component paths per layout level (aligned with layouts array).\n * Each entry is the not-found.tsx at that layout's directory, or null.\n * Used to create per-layout NotFoundBoundary so that notFound() thrown from\n * a layout is caught by the parent layout's boundary (matching Next.js behavior).\n */\n notFoundPaths: (string | null)[];\n /** Forbidden component path (403) */\n forbiddenPath: string | null;\n /** Unauthorized component path (401) */\n unauthorizedPath: string | null;\n /**\n * Filesystem segments from app/ root to the route's directory.\n * Includes route groups and dynamic segments (as template strings like \"[id]\").\n * Used at render time to compute the child segments for useSelectedLayoutSegments().\n */\n routeSegments: string[];\n /** Tree position (directory depth from app/ root) for each template. */\n templateTreePositions?: number[];\n /**\n * Tree position (directory depth from app/ root) for each layout.\n * Used to slice routeSegments and determine which segments are below each layout.\n * For example, root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Unlike the old layoutSegmentDepths, this counts ALL directory levels including\n * route groups and parallel slots.\n */\n layoutTreePositions: number[];\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n};\n\n// Cache for app routes\nlet cachedRoutes: AppRoute[] | null = null;\nlet cachedAppDir: string | null = null;\nlet cachedPageExtensionsKey: string | null = null;\n\nexport function invalidateAppRouteCache(): void {\n cachedRoutes = null;\n cachedAppDir = null;\n cachedPageExtensionsKey = null;\n}\n\n/**\n * Scan the app/ directory and return a list of routes.\n */\nexport async function appRouter(\n appDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<AppRoute[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const pageExtensionsKey = JSON.stringify(matcher.extensions);\n if (cachedRoutes && cachedAppDir === appDir && cachedPageExtensionsKey === pageExtensionsKey) {\n return cachedRoutes;\n }\n\n // Find all page.tsx and route.ts files, excluding @slot directories\n // (slot pages are not standalone routes — they're rendered as props of their parent layout)\n // and _private folders (Next.js convention for colocated non-route files).\n const routes: AppRoute[] = [];\n\n const excludeDir = (name: string) => name.startsWith(\"@\") || name.startsWith(\"_\");\n\n // Process page files in a single pass\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\"**/page\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"page\", matcher);\n if (route) routes.push(route);\n }\n\n // Process route handler files (API routes) in a single pass\n for await (const file of scanWithExtensions(\"**/route\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"route\", matcher);\n if (route) routes.push(route);\n }\n\n // Discover sub-routes created by nested pages within parallel slots.\n // In Next.js, pages nested inside @slot directories create additional URL routes.\n // For example, @audience/demographics/page.tsx at app/parallel-routes/ creates\n // a route at /parallel-routes/demographics.\n const slotSubRoutes = discoverSlotSubRoutes(routes, appDir, matcher);\n routes.push(...slotSubRoutes);\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n const interceptTargetPatterns = [\n ...new Set(\n routes.flatMap((route) =>\n route.parallelSlots.flatMap((slot) =>\n slot.interceptingRoutes.map((intercept) => intercept.targetPattern),\n ),\n ),\n ),\n ];\n validateRoutePatterns(interceptTargetPatterns);\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n cachedRoutes = routes;\n cachedAppDir = appDir;\n cachedPageExtensionsKey = pageExtensionsKey;\n return routes;\n}\n\n/**\n * Discover sub-routes created by nested pages within parallel slots.\n *\n * In Next.js, pages nested inside @slot directories create additional URL routes.\n * For example, given:\n * app/parallel-routes/@audience/demographics/page.tsx\n * This creates a route at /parallel-routes/demographics where:\n * - children slot → parent's default.tsx\n * - @audience slot → @audience/demographics/page.tsx (matched)\n * - other slots → their default.tsx (fallback)\n */\nfunction discoverSlotSubRoutes(\n routes: AppRoute[],\n _appDir: string,\n matcher: ValidFileMatcher,\n): AppRoute[] {\n const syntheticRoutes: AppRoute[] = [];\n\n // O(1) lookup for existing routes by pattern — avoids O(n) routes.find() per sub-path per parent.\n // Updated as new synthetic routes are pushed so that later parents can see earlier synthetic entries.\n const routesByPattern = new Map<string, AppRoute>(routes.map((r) => [r.pattern, r]));\n\n const applySlotSubPages = (\n route: AppRoute,\n slotPages: Map<string, string>,\n rawSegments: string[],\n ): void => {\n route.parallelSlots = route.parallelSlots.map((slot) => {\n const subPage = slotPages.get(slot.key);\n if (subPage !== undefined) {\n return { ...slot, pagePath: subPage, routeSegments: rawSegments };\n }\n return slot;\n });\n };\n\n for (const parentRoute of routes) {\n if (parentRoute.parallelSlots.length === 0) continue;\n if (!parentRoute.pagePath) continue;\n\n const parentPageDir = path.dirname(parentRoute.pagePath);\n\n // Collect sub-paths from all slots.\n // Map: normalized visible sub-path -> slot pages, raw filesystem segments (for routeSegments),\n // and the pre-computed convertedSubRoute (to avoid a redundant re-conversion in the merge loop).\n const subPathMap = new Map<\n string,\n {\n // Raw filesystem segments (with route groups, @slots, etc.) used for routeSegments so\n // that useSelectedLayoutSegments() sees the correct segment list at runtime.\n rawSegments: string[];\n // Pre-computed URL parts, params, isDynamic from convertSegmentsToRouteParts.\n converted: { urlSegments: string[]; params: string[]; isDynamic: boolean };\n slotPages: Map<string, string>;\n }\n >();\n\n for (const slot of parentRoute.parallelSlots) {\n // Only scan sub-pages from slots owned by this route directory.\n // Inherited slots with the same name live in different owner dirs.\n if (path.dirname(slot.ownerDir) !== parentPageDir) {\n continue;\n }\n const slotDir = slot.ownerDir;\n if (!fs.existsSync(slotDir)) continue;\n\n const subPages = findSlotSubPages(slotDir, matcher);\n for (const { relativePath, pagePath } of subPages) {\n const subSegments = relativePath.split(path.sep);\n const convertedSubRoute = convertSegmentsToRouteParts(subSegments);\n if (!convertedSubRoute) continue;\n\n const { urlSegments } = convertedSubRoute;\n const normalizedSubPath = urlSegments.join(\"/\");\n let subPathEntry = subPathMap.get(normalizedSubPath);\n\n if (!subPathEntry) {\n subPathEntry = {\n rawSegments: subSegments,\n converted: convertedSubRoute,\n slotPages: new Map(),\n };\n subPathMap.set(normalizedSubPath, subPathEntry);\n }\n\n const existingSlotPage = subPathEntry.slotPages.get(slot.key);\n if (existingSlotPage) {\n const pattern = joinRoutePattern(parentRoute.pattern, normalizedSubPath);\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n\n subPathEntry.slotPages.set(slot.key, pagePath);\n }\n }\n\n if (subPathMap.size === 0) continue;\n\n // Find the default.tsx for the children slot at the parent directory\n const childrenDefault = findFile(parentPageDir, \"default\", matcher);\n if (!childrenDefault) continue;\n\n for (const { rawSegments, converted: convertedSubRoute, slotPages } of subPathMap.values()) {\n const {\n urlSegments: urlParts,\n params: subParams,\n isDynamic: subIsDynamic,\n } = convertedSubRoute;\n\n const subUrlPath = urlParts.join(\"/\");\n const pattern = joinRoutePattern(parentRoute.pattern, subUrlPath);\n\n const existingRoute = routesByPattern.get(pattern);\n if (existingRoute) {\n if (existingRoute.routePath && !existingRoute.pagePath) {\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n applySlotSubPages(existingRoute, slotPages, rawSegments);\n continue;\n }\n\n // Build parallel slots for this sub-route: matching slots get the sub-page,\n // non-matching slots get null pagePath (rendering falls back to defaultPath)\n const subSlots: ParallelSlot[] = parentRoute.parallelSlots.map((slot) => {\n const subPage = slotPages.get(slot.key);\n return {\n ...slot,\n pagePath: subPage || null,\n routeSegments: subPage ? rawSegments : null,\n };\n });\n\n const newRoute: AppRoute = {\n pattern,\n pagePath: childrenDefault, // children slot uses parent's default.tsx as page\n routePath: null,\n layouts: parentRoute.layouts,\n templates: parentRoute.templates,\n parallelSlots: subSlots,\n loadingPath: parentRoute.loadingPath,\n errorPath: parentRoute.errorPath,\n layoutErrorPaths: parentRoute.layoutErrorPaths,\n notFoundPath: parentRoute.notFoundPath,\n notFoundPaths: parentRoute.notFoundPaths,\n forbiddenPath: parentRoute.forbiddenPath,\n unauthorizedPath: parentRoute.unauthorizedPath,\n routeSegments: [...parentRoute.routeSegments, ...rawSegments],\n templateTreePositions: parentRoute.templateTreePositions,\n layoutTreePositions: parentRoute.layoutTreePositions,\n isDynamic: parentRoute.isDynamic || subIsDynamic,\n params: [...parentRoute.params, ...subParams],\n patternParts: [...parentRoute.patternParts, ...urlParts],\n };\n syntheticRoutes.push(newRoute);\n routesByPattern.set(pattern, newRoute);\n }\n }\n\n return syntheticRoutes;\n}\n\n/**\n * Find all page files in subdirectories of a parallel slot directory.\n * Returns relative paths (from the slot dir) and absolute page paths.\n * Skips the root page.tsx (already handled as the slot's main page)\n * and intercepting route directories.\n */\nfunction findSlotSubPages(\n slotDir: string,\n matcher: ValidFileMatcher,\n): Array<{ relativePath: string; pagePath: string }> {\n const results: Array<{ relativePath: string; pagePath: string }> = [];\n\n function scan(dir: string): void {\n if (!fs.existsSync(dir)) return;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip intercepting route directories\n if (matchInterceptConvention(entry.name)) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n const subDir = path.join(dir, entry.name);\n const page = findFile(subDir, \"page\", matcher);\n if (page) {\n const relativePath = path.relative(slotDir, subDir);\n results.push({ relativePath, pagePath: page });\n }\n // Continue scanning deeper for nested sub-pages\n scan(subDir);\n }\n }\n\n scan(slotDir);\n return results;\n}\n\n/**\n * Convert a file path relative to app/ into an AppRoute.\n */\nfunction fileToAppRoute(\n file: string,\n appDir: string,\n type: \"page\" | \"route\",\n matcher: ValidFileMatcher,\n): AppRoute | null {\n // Remove the filename (page.tsx or route.ts)\n const dir = path.dirname(file);\n const segments = dir === \".\" ? [] : dir.split(path.sep);\n\n const params: string[] = [];\n let isDynamic = false;\n\n const convertedRoute = convertSegmentsToRouteParts(segments);\n if (!convertedRoute) return null;\n\n const { urlSegments, params: routeParams, isDynamic: routeIsDynamic } = convertedRoute;\n params.push(...routeParams);\n isDynamic = routeIsDynamic;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n // Discover layouts and templates from root to leaf\n const layouts = discoverLayouts(segments, appDir, matcher);\n const templates = discoverTemplates(segments, appDir, matcher);\n const templateTreePositions = computeLayoutTreePositions(appDir, templates);\n\n // Compute the tree position (directory depth) for each layout.\n const layoutTreePositions = computeLayoutTreePositions(appDir, layouts);\n\n // Discover per-layout error boundaries (aligned with layouts array).\n // In Next.js, each segment independently wraps its children with an ErrorBoundary.\n // This array enables interleaving error boundaries with layouts in the rendering.\n const layoutErrorPaths = discoverLayoutAlignedErrors(segments, appDir, matcher);\n\n // Discover loading, error in the route's directory\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n const loadingPath = findFile(routeDir, \"loading\", matcher);\n const errorPath = findFile(routeDir, \"error\", matcher);\n\n // Discover not-found/forbidden/unauthorized: walk from route directory up to root (nearest wins).\n const notFoundPath = discoverBoundaryFile(segments, appDir, \"not-found\", matcher);\n const forbiddenPath = discoverBoundaryFile(segments, appDir, \"forbidden\", matcher);\n const unauthorizedPath = discoverBoundaryFile(segments, appDir, \"unauthorized\", matcher);\n\n // Discover per-layout not-found files (one per layout directory).\n // These are used for per-layout NotFoundBoundary to match Next.js behavior where\n // notFound() thrown from a layout is caught by the parent layout's boundary.\n const notFoundPaths = discoverBoundaryFilePerLayout(layouts, \"not-found\", matcher);\n\n // Discover parallel slots (@team, @analytics, etc.).\n // Slots at the route's own directory use page.tsx; slots at ancestor directories\n // (inherited from parent layouts) use default.tsx as fallback.\n const parallelSlots = discoverInheritedParallelSlots(segments, appDir, routeDir, matcher);\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n pagePath: type === \"page\" ? path.join(appDir, file) : null,\n routePath: type === \"route\" ? path.join(appDir, file) : null,\n layouts,\n templates,\n parallelSlots,\n loadingPath,\n errorPath,\n layoutErrorPaths,\n notFoundPath,\n notFoundPaths,\n forbiddenPath,\n unauthorizedPath,\n routeSegments: segments,\n templateTreePositions,\n layoutTreePositions,\n isDynamic,\n params,\n patternParts: urlSegments,\n };\n}\n\n/**\n * Compute the tree position (directory depth from app root) for each layout.\n * Root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Counts ALL directory levels including route groups and parallel slots.\n */\nfunction computeLayoutTreePositions(appDir: string, layouts: string[]): number[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n if (layoutDir === appDir) return 0;\n const relative = path.relative(appDir, layoutDir);\n return relative.split(path.sep).length;\n });\n}\n\n/**\n * Discover all layout files from root to the given directory.\n * Each level of the directory tree may have a layout.tsx.\n */\nfunction discoverLayouts(segments: string[], appDir: string, matcher: ValidFileMatcher): string[] {\n const layouts: string[] = [];\n\n // Check root layout\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) layouts.push(rootLayout);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) layouts.push(layout);\n }\n\n return layouts;\n}\n\n/**\n * Discover all template files from root to the given directory.\n * Each level of the directory tree may have a template.tsx.\n * Templates are like layouts but re-mount on navigation.\n */\nfunction discoverTemplates(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): string[] {\n const templates: string[] = [];\n\n // Check root template\n const rootTemplate = findFile(appDir, \"template\", matcher);\n if (rootTemplate) templates.push(rootTemplate);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const template = findFile(currentDir, \"template\", matcher);\n if (template) templates.push(template);\n }\n\n return templates;\n}\n\n/**\n * Discover error.tsx files aligned with the layouts array.\n * Walks the same directory levels as discoverLayouts and, for each level\n * that contributes a layout entry, checks whether error.tsx also exists.\n * Returns an array of the same length as discoverLayouts() would return,\n * with the error path (or null) at each corresponding layout level.\n *\n * This enables interleaving ErrorBoundary components with layouts in the\n * rendering tree, matching Next.js behavior where each segment independently\n * wraps its children with an error boundary.\n */\nfunction discoverLayoutAlignedErrors(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n const errors: (string | null)[] = [];\n\n // Root level (only if root has a layout — matching discoverLayouts logic)\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) {\n errors.push(findFile(appDir, \"error\", matcher));\n }\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) {\n errors.push(findFile(currentDir, \"error\", matcher));\n }\n }\n\n return errors;\n}\n\n/**\n * Discover the nearest boundary file (not-found, forbidden, unauthorized)\n * by walking from the route's directory up to the app root.\n * Returns the first (closest) file found, or null.\n */\nfunction discoverBoundaryFile(\n segments: string[],\n appDir: string,\n fileName: string,\n matcher: ValidFileMatcher,\n): string | null {\n // Build all directory paths from leaf to root\n const dirs: string[] = [];\n let dir = appDir;\n dirs.push(dir);\n for (const segment of segments) {\n dir = path.join(dir, segment);\n dirs.push(dir);\n }\n\n // Walk from leaf (last) to root (first)\n for (let i = dirs.length - 1; i >= 0; i--) {\n const f = findFile(dirs[i], fileName, matcher);\n if (f) return f;\n }\n return null;\n}\n\n/**\n * Discover boundary files (not-found, forbidden, unauthorized) at each layout directory.\n * Returns an array aligned with the layouts array, where each entry is the boundary\n * file at that layout's directory, or null if none exists there.\n *\n * This is used for per-layout error boundaries. In Next.js, each layout level\n * has its own boundary that wraps the layout's children. When notFound() is thrown\n * from a layout, it propagates up to the parent layout's boundary.\n */\nfunction discoverBoundaryFilePerLayout(\n layouts: string[],\n fileName: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n return findFile(layoutDir, fileName, matcher);\n });\n}\n\n/**\n * Discover parallel slots inherited from ancestor directories.\n *\n * In Next.js, parallel slots belong to the layout that defines them. When a\n * child route is rendered, its parent layout's slots must still be present.\n * If the child doesn't have matching content in a slot, the slot's default.tsx\n * is rendered instead.\n *\n * Walk from appDir through each segment to the route's directory. At each level\n * that has @slot dirs, collect them. Slots at the route's own directory level\n * use page.tsx; slots at ancestor levels use default.tsx only.\n */\nfunction discoverInheritedParallelSlots(\n segments: string[],\n appDir: string,\n routeDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n const slotMap = new Map<string, ParallelSlot>();\n\n // Walk from appDir through each segment, tracking layout indices.\n // layoutIndex tracks which position in the route's layouts[] array corresponds\n // to a given directory. Only directories with a layout.tsx file increment.\n let currentDir = appDir;\n const dirsToCheck: { dir: string; layoutIdx: number }[] = [];\n let layoutIdx = findFile(appDir, \"layout\", matcher) ? 0 : -1;\n dirsToCheck.push({ dir: appDir, layoutIdx: Math.max(layoutIdx, 0) });\n\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n if (findFile(currentDir, \"layout\", matcher)) {\n layoutIdx++;\n }\n dirsToCheck.push({ dir: currentDir, layoutIdx: Math.max(layoutIdx, 0) });\n }\n\n for (const { dir, layoutIdx: lvlLayoutIdx } of dirsToCheck) {\n const isOwnDir = dir === routeDir;\n const slotsAtLevel = discoverParallelSlots(dir, appDir, matcher);\n\n for (const slot of slotsAtLevel) {\n if (isOwnDir) {\n // At the route's own directory: use page.tsx (normal behavior)\n slot.layoutIndex = lvlLayoutIdx;\n slotMap.set(slot.key, slot);\n } else {\n // At an ancestor directory: use default.tsx as the page, not page.tsx\n // (the slot's page.tsx is for the parent route, not this child route)\n const inheritedSlot: ParallelSlot = {\n ...slot,\n pagePath: null, // Don't use ancestor's page.tsx\n layoutIndex: lvlLayoutIdx,\n routeSegments: null,\n // defaultPath, loadingPath, errorPath, interceptingRoutes remain\n };\n slotMap.set(slot.key, inheritedSlot);\n }\n }\n }\n\n return Array.from(slotMap.values());\n}\n\n/**\n * Discover parallel route slots (@team, @analytics, etc.) in a directory.\n * Returns a ParallelSlot for each @-prefixed subdirectory that has a page or default component.\n */\nfunction discoverParallelSlots(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n if (!fs.existsSync(dir)) return [];\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const slots: ParallelSlot[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"@\")) continue;\n\n const slotName = entry.name.slice(1); // \"@team\" -> \"team\"\n const slotDir = path.join(dir, entry.name);\n\n const pagePath = findFile(slotDir, \"page\", matcher);\n const defaultPath = findFile(slotDir, \"default\", matcher);\n const interceptingRoutes = discoverInterceptingRoutes(slotDir, dir, appDir, matcher);\n\n // Only include slots that have at least a page, default, or intercepting route\n if (!pagePath && !defaultPath && interceptingRoutes.length === 0) continue;\n\n slots.push({\n key: `${slotName}@${path.relative(appDir, slotDir).replace(/\\\\/g, \"/\")}`,\n name: slotName,\n ownerDir: slotDir,\n pagePath,\n defaultPath,\n layoutPath: findFile(slotDir, \"layout\", matcher),\n loadingPath: findFile(slotDir, \"loading\", matcher),\n errorPath: findFile(slotDir, \"error\", matcher),\n interceptingRoutes,\n layoutIndex: -1, // Will be set by discoverInheritedParallelSlots\n routeSegments: pagePath ? [] : null,\n });\n }\n\n return slots;\n}\n\n/**\n * The interception convention prefix patterns.\n * (.) — same level, (..) — one level up, (..)(..)\" — two levels up, (...) — root\n */\nconst INTERCEPT_PATTERNS = [\n { prefix: \"(...)\", convention: \"...\" },\n { prefix: \"(..)(..)\", convention: \"../..\" },\n { prefix: \"(..)\", convention: \"..\" },\n { prefix: \"(.)\", convention: \".\" },\n] as const;\n\n/**\n * Discover intercepting routes inside a parallel slot directory.\n *\n * Intercepting routes use conventions like (.)photo, (..)feed, (...), etc.\n * They intercept navigation to another route and render within the slot instead.\n *\n * @param slotDir - The parallel slot directory (e.g. app/feed/@modal)\n * @param routeDir - The directory of the route that owns this slot (e.g. app/feed)\n * @param appDir - The root app directory\n */\nfunction discoverInterceptingRoutes(\n slotDir: string,\n routeDir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): InterceptingRoute[] {\n if (!fs.existsSync(slotDir)) return [];\n\n const results: InterceptingRoute[] = [];\n\n // Recursively scan for page files inside intercepting directories\n scanForInterceptingPages(slotDir, routeDir, appDir, results, matcher);\n\n return results;\n}\n\n/**\n * Recursively scan a directory tree for page.tsx files that are inside\n * intercepting route directories.\n */\nfunction scanForInterceptingPages(\n currentDir: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n if (!fs.existsSync(currentDir)) return;\n\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n // Check if this directory name starts with an interception convention\n const interceptMatch = matchInterceptConvention(entry.name);\n\n if (interceptMatch) {\n // This directory is the start of an intercepting route\n // e.g. \"(.)photos\" means intercept same-level \"photos\" route\n const restOfName = entry.name.slice(interceptMatch.prefix.length);\n const interceptDir = path.join(currentDir, entry.name);\n\n // Find page files within this intercepting directory tree\n collectInterceptingPages(\n interceptDir,\n interceptDir,\n interceptMatch.convention,\n restOfName,\n routeDir,\n appDir,\n results,\n matcher,\n );\n } else {\n // Regular subdirectory — keep scanning for intercepting dirs\n scanForInterceptingPages(\n path.join(currentDir, entry.name),\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n }\n}\n\n/**\n * Match a directory name against interception convention prefixes.\n */\nfunction matchInterceptConvention(name: string): { prefix: string; convention: string } | null {\n for (const pattern of INTERCEPT_PATTERNS) {\n if (name.startsWith(pattern.prefix)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Collect page.tsx files inside an intercepting route directory tree\n * and compute their target URL patterns.\n */\nfunction collectInterceptingPages(\n currentDir: string,\n interceptRoot: string,\n convention: string,\n interceptSegment: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n // Check for page.tsx in current directory\n const page = findFile(currentDir, \"page\", matcher);\n if (page) {\n const targetPattern = computeInterceptTarget(\n convention,\n interceptSegment,\n currentDir,\n interceptRoot,\n routeDir,\n appDir,\n );\n if (targetPattern) {\n results.push({\n convention,\n targetPattern: targetPattern.pattern,\n pagePath: page,\n params: targetPattern.params,\n });\n }\n }\n\n // Recurse into subdirectories for nested intercepting routes\n if (!fs.existsSync(currentDir)) return;\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n collectInterceptingPages(\n path.join(currentDir, entry.name),\n interceptRoot,\n convention,\n interceptSegment,\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n}\n\n/**\n * Check whether a path segment is invisible in the URL (route groups, parallel slots, \".\").\n *\n * Used by computeInterceptTarget, convertSegmentsToRouteParts, and\n * hasRemainingVisibleSegments — keep this the single source of truth.\n */\nfunction isInvisibleSegment(segment: string): boolean {\n if (segment === \".\") return true;\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) return true;\n if (segment.startsWith(\"@\")) return true;\n return false;\n}\n\n/**\n * Compute the target URL pattern for an intercepting route.\n *\n * Interception conventions (..), (..)(..)\" climb by *visible route segments*\n * (not filesystem directories). Route groups like (marketing) and parallel\n * slots like @modal are invisible and must be skipped when counting levels.\n *\n * - (.) same level: resolve relative to routeDir\n * - (..) one level up: climb 1 visible segment\n * - (..)(..) two levels up: climb 2 visible segments\n * - (...) root: resolve from appDir\n */\nfunction computeInterceptTarget(\n convention: string,\n interceptSegment: string,\n currentDir: string,\n interceptRoot: string,\n routeDir: string,\n appDir: string,\n): { pattern: string; params: string[] } | null {\n // Determine the base segments for target resolution.\n // We work on route segments (not filesystem paths) so that route groups\n // and parallel slots are properly skipped when climbing.\n const routeSegments = path.relative(appDir, routeDir).split(path.sep).filter(Boolean);\n\n let baseParts: string[];\n switch (convention) {\n case \".\":\n baseParts = routeSegments;\n break;\n case \"..\":\n case \"../..\": {\n const levelsToClimb = convention === \"..\" ? 1 : 2;\n let climbed = 0;\n let cutIndex = routeSegments.length;\n while (cutIndex > 0 && climbed < levelsToClimb) {\n cutIndex--;\n if (!isInvisibleSegment(routeSegments[cutIndex])) {\n climbed++;\n }\n }\n baseParts = routeSegments.slice(0, cutIndex);\n break;\n }\n case \"...\":\n baseParts = [];\n break;\n default:\n return null;\n }\n\n // Add the intercept segment and any nested path segments\n const nestedParts = path.relative(interceptRoot, currentDir).split(path.sep).filter(Boolean);\n const allSegments = [...baseParts, interceptSegment, ...nestedParts];\n\n const convertedTarget = convertSegmentsToRouteParts(allSegments);\n if (!convertedTarget) return null;\n\n const { urlSegments, params } = convertedTarget;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n return { pattern: pattern === \"/\" ? \"/\" : pattern, params };\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks configured pageExtensions.\n */\nfunction findFile(dir: string, name: string, matcher: ValidFileMatcher): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/**\n * Convert filesystem path segments to URL route parts, skipping invisible segments\n * (route groups, @slots, \".\") and converting dynamic segment syntax to Express-style\n * patterns (e.g. \"[id]\" → \":id\", \"[...slug]\" → \":slug+\").\n */\nfunction convertSegmentsToRouteParts(\n segments: string[],\n): { urlSegments: string[]; params: string[]; isDynamic: boolean } | null {\n const urlSegments: string[] = [];\n const params: string[] = [];\n let isDynamic = false;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n if (isInvisibleSegment(segment)) continue;\n\n // Catch-all segments are only valid in terminal URL position.\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n return { urlSegments, params, isDynamic };\n}\n\nfunction hasRemainingVisibleSegments(segments: string[], startIndex: number): boolean {\n for (let i = startIndex; i < segments.length; i++) {\n if (!isInvisibleSegment(segments[i])) return true;\n }\n return false;\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst appTrieCache = new WeakMap<AppRoute[], TrieNode<AppRoute>>();\n\nfunction getOrBuildAppTrie(routes: AppRoute[]): TrieNode<AppRoute> {\n let trie = appTrieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n appTrieCache.set(routes, trie);\n }\n return trie;\n}\n\nfunction joinRoutePattern(basePattern: string, subPath: string): string {\n if (!subPath) return basePattern;\n return basePattern === \"/\" ? `/${subPath}` : `${basePattern}/${subPath}`;\n}\n\n/**\n * Match a URL against App Router routes.\n */\nexport function matchAppRoute(\n url: string,\n routes: AppRoute[],\n): { route: AppRoute; params: Record<string, string | string[]> } | null {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildAppTrie(routes);\n return trieMatch(trie, urlParts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuIA,IAAI,eAAkC;AACtC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,gBAAe;AACf,gBAAe;AACf,2BAA0B;;;;;AAM5B,eAAsB,UACpB,QACA,gBACA,SACqB;AACrB,aAAY,uBAAuB,eAAe;CAClD,MAAM,oBAAoB,KAAK,UAAU,QAAQ,WAAW;AAC5D,KAAI,gBAAgB,iBAAiB,UAAU,4BAA4B,kBACzE,QAAO;CAMT,MAAM,SAAqB,EAAE;CAE7B,MAAM,cAAc,SAAiB,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI;AAIjF,YAAW,MAAM,QAAQ,mBAAmB,WAAW,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC9F,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ,QAAQ;AAC3D,MAAI,MAAO,QAAO,KAAK,MAAM;;AAI/B,YAAW,MAAM,QAAQ,mBAAmB,YAAY,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC/F,MAAM,QAAQ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,OAAO;AAC7B,eAAa,IAAI,QAAQ,KAAK;;AAEhC,QAAO;;AAGT,SAAS,iBAAiB,aAAqB,SAAyB;AACtE,KAAI,CAAC,QAAS,QAAO;AACrB,QAAO,gBAAgB,MAAM,IAAI,YAAY,GAAG,YAAY,GAAG;;;;;AAMjE,SAAgB,cACd,KACA,QACuE;CACvE,MAAM,WAAW,IAAI,MAAM,IAAI,CAAC;CAChC,IAAI,gBAAgB,aAAa,MAAM,MAAM,SAAS,QAAQ,OAAO,GAAG;AACxE,iBAAgB,+BAA+B,cAAc;CAG7D,MAAM,WAAW,cAAc,MAAM,IAAI,CAAC,OAAO,QAAQ;AAEzD,QAAO,UADM,kBAAkB,OAAO,EACf,SAAS"}
|
|
1
|
+
{"version":3,"file":"app-router.js","names":[],"sources":["../../src/routing/app-router.ts"],"sourcesContent":["/**\n * App Router file-system routing.\n *\n * Scans the app/ directory following Next.js App Router conventions:\n * - app/page.tsx -> /\n * - app/about/page.tsx -> /about\n * - app/blog/[slug]/page.tsx -> /blog/:slug\n * - app/[...catchAll]/page.tsx -> /:catchAll+\n * - app/route.ts -> / (API route)\n * - app/(group)/page.tsx -> / (route groups are transparent)\n * - Layouts: app/layout.tsx wraps all children\n * - Loading: app/loading.tsx -> Suspense fallback\n * - Error: app/error.tsx -> ErrorBoundary\n * - Not Found: app/not-found.tsx\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport type InterceptingRoute = {\n /** The interception convention: \".\" | \"..\" | \"../..\" | \"...\" */\n convention: string;\n /** The URL pattern this intercepts (e.g. \"/photos/:id\") */\n targetPattern: string;\n /** Absolute path to the intercepting page component */\n pagePath: string;\n /** Parameter names for dynamic segments */\n params: string[];\n};\n\nexport type ParallelSlot = {\n /** Stable slot identity (name + owning directory), used for route serialization keys. */\n key: string;\n /** Slot name (e.g. \"team\" from @team) */\n name: string;\n /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */\n ownerDir: string;\n /** Absolute path to the slot's page component */\n pagePath: string | null;\n /** Absolute path to the slot's default.tsx fallback */\n defaultPath: string | null;\n /** Absolute path to the slot's layout component (wraps slot content) */\n layoutPath: string | null;\n /** Absolute path to the slot's loading component */\n loadingPath: string | null;\n /** Absolute path to the slot's error component */\n errorPath: string | null;\n /** Intercepting routes within this slot */\n interceptingRoutes: InterceptingRoute[];\n /**\n * The layout index (0-based, in route.layouts[]) that this slot belongs to.\n * Slots are passed as props to the layout at their directory level, not\n * necessarily the innermost layout. -1 means \"innermost\" (legacy default).\n */\n layoutIndex: number;\n /**\n * Filesystem segments from the slot's root directory to its active page.\n * Used at render time to compute segments for useSelectedLayoutSegment(slotName).\n * For a page at the slot root (@team/page.tsx), this is [].\n * For a sub-page (@team/members/page.tsx), this is [\"members\"].\n * null when the slot has no active page (showing default.tsx fallback).\n */\n routeSegments: string[] | null;\n};\n\nexport type AppRoute = {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/blog/:slug\" */\n pattern: string;\n /** Absolute file path to the page component */\n pagePath: string | null;\n /** Absolute file path to the route handler (route.ts) */\n routePath: string | null;\n /** Ordered list of layout files from root to leaf */\n layouts: string[];\n /** Ordered list of all discovered template files from root to leaf (not necessarily aligned 1:1 with layouts) */\n templates: string[];\n /** Parallel route slots (from @slot directories at the route's directory level) */\n parallelSlots: ParallelSlot[];\n /** Loading component path */\n loadingPath: string | null;\n /** Error component path (leaf directory only) */\n errorPath: string | null;\n /**\n * Per-layout error boundary paths, aligned with the layouts array.\n * Each entry is the error.tsx at the same directory level as the\n * corresponding layout (or null if that level has no error.tsx).\n * Used to interleave ErrorBoundary components with layouts so that\n * ancestor error boundaries catch errors from descendant segments.\n */\n layoutErrorPaths: (string | null)[];\n /** Not-found component path (nearest, walking up from page dir) */\n notFoundPath: string | null;\n /**\n * Not-found component paths per layout level (aligned with layouts array).\n * Each entry is the not-found.tsx at that layout's directory, or null.\n * Used to create per-layout NotFoundBoundary so that notFound() thrown from\n * a layout is caught by the parent layout's boundary (matching Next.js behavior).\n */\n notFoundPaths: (string | null)[];\n /** Forbidden component path (403) */\n forbiddenPath: string | null;\n /** Unauthorized component path (401) */\n unauthorizedPath: string | null;\n /**\n * Filesystem segments from app/ root to the route's directory.\n * Includes route groups and dynamic segments (as template strings like \"[id]\").\n * Used at render time to compute the child segments for useSelectedLayoutSegments().\n */\n routeSegments: string[];\n /** Tree position (directory depth from app/ root) for each template. */\n templateTreePositions?: number[];\n /**\n * Tree position (directory depth from app/ root) for each layout.\n * Used to slice routeSegments and determine which segments are below each layout.\n * For example, root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Unlike the old layoutSegmentDepths, this counts ALL directory levels including\n * route groups and parallel slots.\n */\n layoutTreePositions: number[];\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n};\n\n// Cache for app routes\nlet cachedRoutes: AppRoute[] | null = null;\nlet cachedAppDir: string | null = null;\nlet cachedPageExtensionsKey: string | null = null;\n\nexport function invalidateAppRouteCache(): void {\n cachedRoutes = null;\n cachedAppDir = null;\n cachedPageExtensionsKey = null;\n}\n\nfunction hasParallelSlotDirectory(dir: string): boolean {\n try {\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .some((entry) => entry.isDirectory() && entry.name.startsWith(\"@\"));\n } catch {\n return false;\n }\n}\n\n/**\n * Scan the app/ directory and return a list of routes.\n */\nexport async function appRouter(\n appDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<AppRoute[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const pageExtensionsKey = JSON.stringify(matcher.extensions);\n if (cachedRoutes && cachedAppDir === appDir && cachedPageExtensionsKey === pageExtensionsKey) {\n return cachedRoutes;\n }\n\n // Find all page.tsx and route.ts files, excluding @slot directories\n // (slot pages are not standalone routes — they're rendered as props of their parent layout)\n // and _private folders (Next.js convention for colocated non-route files).\n const routes: AppRoute[] = [];\n\n const excludeDir = (name: string) => name.startsWith(\"@\") || name.startsWith(\"_\");\n\n // Process page files in a single pass\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\"**/page\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"page\", matcher);\n if (route) routes.push(route);\n }\n\n // Process route handler files (API routes) in a single pass\n for await (const file of scanWithExtensions(\"**/route\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"route\", matcher);\n if (route) routes.push(route);\n }\n\n // Layouts with parallel slot pages are valid route entries even when the\n // segment has no children page. Next.js uses this for modal/feed patterns\n // like app/user/[id]/layout + @feed/page + @modal/default.\n const routePatterns = new Set(routes.map((route) => route.pattern));\n for await (const file of scanWithExtensions(\n \"**/layout\",\n appDir,\n matcher.extensions,\n excludeDir,\n )) {\n const dir = path.dirname(file);\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n if (!hasParallelSlotDirectory(routeDir)) continue;\n if (discoverParallelSlots(routeDir, appDir, matcher).length === 0) continue;\n\n const route = directoryToAppRoute(dir, appDir, matcher, null, null);\n if (!route || routePatterns.has(route.pattern)) continue;\n\n routes.push(route);\n routePatterns.add(route.pattern);\n }\n\n // Discover sub-routes created by nested pages within parallel slots.\n // In Next.js, pages nested inside @slot directories create additional URL routes.\n // For example, @audience/demographics/page.tsx at app/parallel-routes/ creates\n // a route at /parallel-routes/demographics.\n const slotSubRoutes = discoverSlotSubRoutes(routes, appDir, matcher);\n routes.push(...slotSubRoutes);\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n const interceptTargetPatterns = [\n ...new Set(\n routes.flatMap((route) =>\n route.parallelSlots.flatMap((slot) =>\n slot.interceptingRoutes.map((intercept) => intercept.targetPattern),\n ),\n ),\n ),\n ];\n validateRoutePatterns(interceptTargetPatterns);\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n cachedRoutes = routes;\n cachedAppDir = appDir;\n cachedPageExtensionsKey = pageExtensionsKey;\n return routes;\n}\n\n/**\n * Discover sub-routes created by nested pages within parallel slots.\n *\n * In Next.js, pages nested inside @slot directories create additional URL routes.\n * For example, given:\n * app/parallel-routes/@audience/demographics/page.tsx\n * This creates a route at /parallel-routes/demographics where:\n * - children slot → parent's default.tsx\n * - @audience slot → @audience/demographics/page.tsx (matched)\n * - other slots → their default.tsx (fallback)\n */\nfunction discoverSlotSubRoutes(\n routes: AppRoute[],\n _appDir: string,\n matcher: ValidFileMatcher,\n): AppRoute[] {\n const syntheticRoutes: AppRoute[] = [];\n\n // O(1) lookup for existing routes by pattern — avoids O(n) routes.find() per sub-path per parent.\n // Updated as new synthetic routes are pushed so that later parents can see earlier synthetic entries.\n const routesByPattern = new Map<string, AppRoute>(routes.map((r) => [r.pattern, r]));\n\n const applySlotSubPages = (\n route: AppRoute,\n slotPages: Map<string, string>,\n rawSegments: string[],\n ): void => {\n route.parallelSlots = route.parallelSlots.map((slot) => {\n const subPage = slotPages.get(slot.key);\n if (subPage !== undefined) {\n return { ...slot, pagePath: subPage, routeSegments: rawSegments };\n }\n return slot;\n });\n };\n\n for (const parentRoute of routes) {\n if (parentRoute.parallelSlots.length === 0) continue;\n if (!parentRoute.pagePath) continue;\n\n const parentPageDir = path.dirname(parentRoute.pagePath);\n\n // Collect sub-paths from all slots.\n // Map: normalized visible sub-path -> slot pages, raw filesystem segments (for routeSegments),\n // and the pre-computed convertedSubRoute (to avoid a redundant re-conversion in the merge loop).\n const subPathMap = new Map<\n string,\n {\n // Raw filesystem segments (with route groups, @slots, etc.) used for routeSegments so\n // that useSelectedLayoutSegments() sees the correct segment list at runtime.\n rawSegments: string[];\n // Pre-computed URL parts, params, isDynamic from convertSegmentsToRouteParts.\n converted: { urlSegments: string[]; params: string[]; isDynamic: boolean };\n slotPages: Map<string, string>;\n }\n >();\n\n for (const slot of parentRoute.parallelSlots) {\n // Only scan sub-pages from slots owned by this route directory.\n // Inherited slots with the same name live in different owner dirs.\n if (path.dirname(slot.ownerDir) !== parentPageDir) {\n continue;\n }\n const slotDir = slot.ownerDir;\n if (!fs.existsSync(slotDir)) continue;\n\n const subPages = findSlotSubPages(slotDir, matcher);\n for (const { relativePath, pagePath } of subPages) {\n const subSegments = relativePath.split(path.sep);\n const convertedSubRoute = convertSegmentsToRouteParts(subSegments);\n if (!convertedSubRoute) continue;\n\n const { urlSegments } = convertedSubRoute;\n const normalizedSubPath = urlSegments.join(\"/\");\n let subPathEntry = subPathMap.get(normalizedSubPath);\n\n if (!subPathEntry) {\n subPathEntry = {\n rawSegments: subSegments,\n converted: convertedSubRoute,\n slotPages: new Map(),\n };\n subPathMap.set(normalizedSubPath, subPathEntry);\n }\n\n const existingSlotPage = subPathEntry.slotPages.get(slot.key);\n if (existingSlotPage) {\n const pattern = joinRoutePattern(parentRoute.pattern, normalizedSubPath);\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n\n subPathEntry.slotPages.set(slot.key, pagePath);\n }\n }\n\n if (subPathMap.size === 0) continue;\n\n // Find the default.tsx for the children slot at the parent directory\n const childrenDefault = findFile(parentPageDir, \"default\", matcher);\n if (!childrenDefault) continue;\n\n for (const { rawSegments, converted: convertedSubRoute, slotPages } of subPathMap.values()) {\n const {\n urlSegments: urlParts,\n params: subParams,\n isDynamic: subIsDynamic,\n } = convertedSubRoute;\n\n const subUrlPath = urlParts.join(\"/\");\n const pattern = joinRoutePattern(parentRoute.pattern, subUrlPath);\n\n const existingRoute = routesByPattern.get(pattern);\n if (existingRoute) {\n if (existingRoute.routePath && !existingRoute.pagePath) {\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n applySlotSubPages(existingRoute, slotPages, rawSegments);\n continue;\n }\n\n // Build parallel slots for this sub-route: matching slots get the sub-page,\n // non-matching slots get null pagePath (rendering falls back to defaultPath)\n const subSlots: ParallelSlot[] = parentRoute.parallelSlots.map((slot) => {\n const subPage = slotPages.get(slot.key);\n return {\n ...slot,\n pagePath: subPage || null,\n routeSegments: subPage ? rawSegments : null,\n };\n });\n\n const newRoute: AppRoute = {\n pattern,\n pagePath: childrenDefault, // children slot uses parent's default.tsx as page\n routePath: null,\n layouts: parentRoute.layouts,\n templates: parentRoute.templates,\n parallelSlots: subSlots,\n loadingPath: parentRoute.loadingPath,\n errorPath: parentRoute.errorPath,\n layoutErrorPaths: parentRoute.layoutErrorPaths,\n notFoundPath: parentRoute.notFoundPath,\n notFoundPaths: parentRoute.notFoundPaths,\n forbiddenPath: parentRoute.forbiddenPath,\n unauthorizedPath: parentRoute.unauthorizedPath,\n routeSegments: [...parentRoute.routeSegments, ...rawSegments],\n templateTreePositions: parentRoute.templateTreePositions,\n layoutTreePositions: parentRoute.layoutTreePositions,\n isDynamic: parentRoute.isDynamic || subIsDynamic,\n params: [...parentRoute.params, ...subParams],\n patternParts: [...parentRoute.patternParts, ...urlParts],\n };\n syntheticRoutes.push(newRoute);\n routesByPattern.set(pattern, newRoute);\n }\n }\n\n return syntheticRoutes;\n}\n\n/**\n * Find all page files in subdirectories of a parallel slot directory.\n * Returns relative paths (from the slot dir) and absolute page paths.\n * Skips the root page.tsx (already handled as the slot's main page)\n * and intercepting route directories.\n */\nfunction findSlotSubPages(\n slotDir: string,\n matcher: ValidFileMatcher,\n): Array<{ relativePath: string; pagePath: string }> {\n const results: Array<{ relativePath: string; pagePath: string }> = [];\n\n function scan(dir: string): void {\n if (!fs.existsSync(dir)) return;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip intercepting route directories\n if (matchInterceptConvention(entry.name)) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n const subDir = path.join(dir, entry.name);\n const page = findFile(subDir, \"page\", matcher);\n if (page) {\n const relativePath = path.relative(slotDir, subDir);\n results.push({ relativePath, pagePath: page });\n }\n // Continue scanning deeper for nested sub-pages\n scan(subDir);\n }\n }\n\n scan(slotDir);\n return results;\n}\n\n/**\n * Convert a file path relative to app/ into an AppRoute.\n */\nfunction fileToAppRoute(\n file: string,\n appDir: string,\n type: \"page\" | \"route\",\n matcher: ValidFileMatcher,\n): AppRoute | null {\n // Remove the filename (page.tsx or route.ts)\n const dir = path.dirname(file);\n return directoryToAppRoute(\n dir,\n appDir,\n matcher,\n type === \"page\" ? path.join(appDir, file) : null,\n type === \"route\" ? path.join(appDir, file) : null,\n );\n}\n\nfunction directoryToAppRoute(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n pagePath: string | null,\n routePath: string | null,\n): AppRoute | null {\n const segments = dir === \".\" ? [] : dir.split(path.sep);\n\n const params: string[] = [];\n let isDynamic = false;\n\n const convertedRoute = convertSegmentsToRouteParts(segments);\n if (!convertedRoute) return null;\n\n const { urlSegments, params: routeParams, isDynamic: routeIsDynamic } = convertedRoute;\n params.push(...routeParams);\n isDynamic = routeIsDynamic;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n // Discover layouts and templates from root to leaf\n const layouts = discoverLayouts(segments, appDir, matcher);\n const templates = discoverTemplates(segments, appDir, matcher);\n const templateTreePositions = computeLayoutTreePositions(appDir, templates);\n\n // Compute the tree position (directory depth) for each layout.\n const layoutTreePositions = computeLayoutTreePositions(appDir, layouts);\n\n // Discover per-layout error boundaries (aligned with layouts array).\n // In Next.js, each segment independently wraps its children with an ErrorBoundary.\n // This array enables interleaving error boundaries with layouts in the rendering.\n const layoutErrorPaths = discoverLayoutAlignedErrors(segments, appDir, matcher);\n\n // Discover loading, error in the route's directory\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n const loadingPath = findFile(routeDir, \"loading\", matcher);\n const errorPath = findFile(routeDir, \"error\", matcher);\n\n // Discover not-found/forbidden/unauthorized: walk from route directory up to root (nearest wins).\n const notFoundPath = discoverBoundaryFile(segments, appDir, \"not-found\", matcher);\n const forbiddenPath = discoverBoundaryFile(segments, appDir, \"forbidden\", matcher);\n const unauthorizedPath = discoverBoundaryFile(segments, appDir, \"unauthorized\", matcher);\n\n // Discover per-layout not-found files (one per layout directory).\n // These are used for per-layout NotFoundBoundary to match Next.js behavior where\n // notFound() thrown from a layout is caught by the parent layout's boundary.\n const notFoundPaths = discoverBoundaryFilePerLayout(layouts, \"not-found\", matcher);\n\n // Discover parallel slots (@team, @analytics, etc.).\n // Slots at the route's own directory use page.tsx; slots at ancestor directories\n // (inherited from parent layouts) use default.tsx as fallback.\n const parallelSlots = discoverInheritedParallelSlots(segments, appDir, routeDir, matcher);\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n pagePath,\n routePath,\n layouts,\n templates,\n parallelSlots,\n loadingPath,\n errorPath,\n layoutErrorPaths,\n notFoundPath,\n notFoundPaths,\n forbiddenPath,\n unauthorizedPath,\n routeSegments: segments,\n templateTreePositions,\n layoutTreePositions,\n isDynamic,\n params,\n patternParts: urlSegments,\n };\n}\n\n/**\n * Compute the tree position (directory depth from app root) for each layout.\n * Root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Counts ALL directory levels including route groups and parallel slots.\n */\nfunction computeLayoutTreePositions(appDir: string, layouts: string[]): number[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n if (layoutDir === appDir) return 0;\n const relative = path.relative(appDir, layoutDir);\n return relative.split(path.sep).length;\n });\n}\n\n/**\n * Discover all layout files from root to the given directory.\n * Each level of the directory tree may have a layout.tsx.\n */\nfunction discoverLayouts(segments: string[], appDir: string, matcher: ValidFileMatcher): string[] {\n const layouts: string[] = [];\n\n // Check root layout\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) layouts.push(rootLayout);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) layouts.push(layout);\n }\n\n return layouts;\n}\n\n/**\n * Discover all template files from root to the given directory.\n * Each level of the directory tree may have a template.tsx.\n * Templates are like layouts but re-mount on navigation.\n */\nfunction discoverTemplates(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): string[] {\n const templates: string[] = [];\n\n // Check root template\n const rootTemplate = findFile(appDir, \"template\", matcher);\n if (rootTemplate) templates.push(rootTemplate);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const template = findFile(currentDir, \"template\", matcher);\n if (template) templates.push(template);\n }\n\n return templates;\n}\n\n/**\n * Discover error.tsx files aligned with the layouts array.\n * Walks the same directory levels as discoverLayouts and, for each level\n * that contributes a layout entry, checks whether error.tsx also exists.\n * Returns an array of the same length as discoverLayouts() would return,\n * with the error path (or null) at each corresponding layout level.\n *\n * This enables interleaving ErrorBoundary components with layouts in the\n * rendering tree, matching Next.js behavior where each segment independently\n * wraps its children with an error boundary.\n */\nfunction discoverLayoutAlignedErrors(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n const errors: (string | null)[] = [];\n\n // Root level (only if root has a layout — matching discoverLayouts logic)\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) {\n errors.push(findFile(appDir, \"error\", matcher));\n }\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) {\n errors.push(findFile(currentDir, \"error\", matcher));\n }\n }\n\n return errors;\n}\n\n/**\n * Discover the nearest boundary file (not-found, forbidden, unauthorized)\n * by walking from the route's directory up to the app root.\n * Returns the first (closest) file found, or null.\n */\nfunction discoverBoundaryFile(\n segments: string[],\n appDir: string,\n fileName: string,\n matcher: ValidFileMatcher,\n): string | null {\n // Build all directory paths from leaf to root\n const dirs: string[] = [];\n let dir = appDir;\n dirs.push(dir);\n for (const segment of segments) {\n dir = path.join(dir, segment);\n dirs.push(dir);\n }\n\n // Walk from leaf (last) to root (first)\n for (let i = dirs.length - 1; i >= 0; i--) {\n const f = findFile(dirs[i], fileName, matcher);\n if (f) return f;\n }\n return null;\n}\n\n/**\n * Discover boundary files (not-found, forbidden, unauthorized) at each layout directory.\n * Returns an array aligned with the layouts array, where each entry is the boundary\n * file at that layout's directory, or null if none exists there.\n *\n * This is used for per-layout error boundaries. In Next.js, each layout level\n * has its own boundary that wraps the layout's children. When notFound() is thrown\n * from a layout, it propagates up to the parent layout's boundary.\n */\nfunction discoverBoundaryFilePerLayout(\n layouts: string[],\n fileName: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n return findFile(layoutDir, fileName, matcher);\n });\n}\n\n/**\n * Discover parallel slots inherited from ancestor directories.\n *\n * In Next.js, parallel slots belong to the layout that defines them. When a\n * child route is rendered, its parent layout's slots must still be present.\n * If the child doesn't have matching content in a slot, the slot's default.tsx\n * is rendered instead.\n *\n * Walk from appDir through each segment to the route's directory. At each level\n * that has @slot dirs, collect them. Slots at the route's own directory level\n * use page.tsx; slots at ancestor levels use default.tsx only.\n */\nfunction discoverInheritedParallelSlots(\n segments: string[],\n appDir: string,\n routeDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n const slotMap = new Map<string, ParallelSlot>();\n\n // Walk from appDir through each segment, tracking layout indices.\n // layoutIndex tracks which position in the route's layouts[] array corresponds\n // to a given directory. Only directories with a layout.tsx file increment.\n let currentDir = appDir;\n const dirsToCheck: { dir: string; layoutIdx: number }[] = [];\n let layoutIdx = findFile(appDir, \"layout\", matcher) ? 0 : -1;\n dirsToCheck.push({ dir: appDir, layoutIdx: Math.max(layoutIdx, 0) });\n\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n if (findFile(currentDir, \"layout\", matcher)) {\n layoutIdx++;\n }\n dirsToCheck.push({ dir: currentDir, layoutIdx: Math.max(layoutIdx, 0) });\n }\n\n for (const { dir, layoutIdx: lvlLayoutIdx } of dirsToCheck) {\n const isOwnDir = dir === routeDir;\n const slotsAtLevel = discoverParallelSlots(dir, appDir, matcher);\n\n for (const slot of slotsAtLevel) {\n if (isOwnDir) {\n // At the route's own directory: use page.tsx (normal behavior)\n slot.layoutIndex = lvlLayoutIdx;\n slotMap.set(slot.key, slot);\n } else {\n // At an ancestor directory: use default.tsx as the page, not page.tsx\n // (the slot's page.tsx is for the parent route, not this child route)\n const inheritedSlot: ParallelSlot = {\n ...slot,\n pagePath: null, // Don't use ancestor's page.tsx\n layoutIndex: lvlLayoutIdx,\n routeSegments: null,\n // defaultPath, loadingPath, errorPath, interceptingRoutes remain\n };\n slotMap.set(slot.key, inheritedSlot);\n }\n }\n }\n\n return Array.from(slotMap.values());\n}\n\n/**\n * Discover parallel route slots (@team, @analytics, etc.) in a directory.\n * Returns a ParallelSlot for each @-prefixed subdirectory that has a page or default component.\n */\nfunction discoverParallelSlots(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n if (!fs.existsSync(dir)) return [];\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const slots: ParallelSlot[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"@\")) continue;\n\n const slotName = entry.name.slice(1); // \"@team\" -> \"team\"\n const slotDir = path.join(dir, entry.name);\n\n const pagePath = findFile(slotDir, \"page\", matcher);\n const defaultPath = findFile(slotDir, \"default\", matcher);\n const interceptingRoutes = discoverInterceptingRoutes(slotDir, dir, appDir, matcher);\n\n // Only include slots that have at least a page, default, or intercepting route\n if (!pagePath && !defaultPath && interceptingRoutes.length === 0) continue;\n\n slots.push({\n key: `${slotName}@${path.relative(appDir, slotDir).replace(/\\\\/g, \"/\")}`,\n name: slotName,\n ownerDir: slotDir,\n pagePath,\n defaultPath,\n layoutPath: findFile(slotDir, \"layout\", matcher),\n loadingPath: findFile(slotDir, \"loading\", matcher),\n errorPath: findFile(slotDir, \"error\", matcher),\n interceptingRoutes,\n layoutIndex: -1, // Will be set by discoverInheritedParallelSlots\n routeSegments: pagePath ? [] : null,\n });\n }\n\n return slots;\n}\n\n/**\n * The interception convention prefix patterns.\n * (.) — same level, (..) — one level up, (..)(..)\" — two levels up, (...) — root\n */\nconst INTERCEPT_PATTERNS = [\n { prefix: \"(...)\", convention: \"...\" },\n { prefix: \"(..)(..)\", convention: \"../..\" },\n { prefix: \"(..)\", convention: \"..\" },\n { prefix: \"(.)\", convention: \".\" },\n] as const;\n\n/**\n * Discover intercepting routes inside a parallel slot directory.\n *\n * Intercepting routes use conventions like (.)photo, (..)feed, (...), etc.\n * They intercept navigation to another route and render within the slot instead.\n *\n * @param slotDir - The parallel slot directory (e.g. app/feed/@modal)\n * @param routeDir - The directory of the route that owns this slot (e.g. app/feed)\n * @param appDir - The root app directory\n */\nfunction discoverInterceptingRoutes(\n slotDir: string,\n routeDir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): InterceptingRoute[] {\n if (!fs.existsSync(slotDir)) return [];\n\n const results: InterceptingRoute[] = [];\n\n // Recursively scan for page files inside intercepting directories\n scanForInterceptingPages(slotDir, routeDir, appDir, results, matcher);\n\n return results;\n}\n\n/**\n * Recursively scan a directory tree for page.tsx files that are inside\n * intercepting route directories.\n */\nfunction scanForInterceptingPages(\n currentDir: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n if (!fs.existsSync(currentDir)) return;\n\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n // Check if this directory name starts with an interception convention\n const interceptMatch = matchInterceptConvention(entry.name);\n\n if (interceptMatch) {\n // This directory is the start of an intercepting route\n // e.g. \"(.)photos\" means intercept same-level \"photos\" route\n const restOfName = entry.name.slice(interceptMatch.prefix.length);\n const interceptDir = path.join(currentDir, entry.name);\n\n // Find page files within this intercepting directory tree\n collectInterceptingPages(\n interceptDir,\n interceptDir,\n interceptMatch.convention,\n restOfName,\n routeDir,\n appDir,\n results,\n matcher,\n );\n } else {\n // Regular subdirectory — keep scanning for intercepting dirs\n scanForInterceptingPages(\n path.join(currentDir, entry.name),\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n }\n}\n\n/**\n * Match a directory name against interception convention prefixes.\n */\nfunction matchInterceptConvention(name: string): { prefix: string; convention: string } | null {\n for (const pattern of INTERCEPT_PATTERNS) {\n if (name.startsWith(pattern.prefix)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Collect page.tsx files inside an intercepting route directory tree\n * and compute their target URL patterns.\n */\nfunction collectInterceptingPages(\n currentDir: string,\n interceptRoot: string,\n convention: string,\n interceptSegment: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n // Check for page.tsx in current directory\n const page = findFile(currentDir, \"page\", matcher);\n if (page) {\n const targetPattern = computeInterceptTarget(\n convention,\n interceptSegment,\n currentDir,\n interceptRoot,\n routeDir,\n appDir,\n );\n if (targetPattern) {\n results.push({\n convention,\n targetPattern: targetPattern.pattern,\n pagePath: page,\n params: targetPattern.params,\n });\n }\n }\n\n // Recurse into subdirectories for nested intercepting routes\n if (!fs.existsSync(currentDir)) return;\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n collectInterceptingPages(\n path.join(currentDir, entry.name),\n interceptRoot,\n convention,\n interceptSegment,\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n}\n\n/**\n * Check whether a path segment is invisible in the URL (route groups, parallel slots, \".\").\n *\n * Used by computeInterceptTarget, convertSegmentsToRouteParts, and\n * hasRemainingVisibleSegments — keep this the single source of truth.\n */\nfunction isInvisibleSegment(segment: string): boolean {\n if (segment === \".\") return true;\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) return true;\n if (segment.startsWith(\"@\")) return true;\n return false;\n}\n\n/**\n * Compute the target URL pattern for an intercepting route.\n *\n * Interception conventions (..), (..)(..)\" climb by *visible route segments*\n * (not filesystem directories). Route groups like (marketing) and parallel\n * slots like @modal are invisible and must be skipped when counting levels.\n *\n * - (.) same level: resolve relative to routeDir\n * - (..) one level up: climb 1 visible segment\n * - (..)(..) two levels up: climb 2 visible segments\n * - (...) root: resolve from appDir\n */\nfunction computeInterceptTarget(\n convention: string,\n interceptSegment: string,\n currentDir: string,\n interceptRoot: string,\n routeDir: string,\n appDir: string,\n): { pattern: string; params: string[] } | null {\n // Determine the base segments for target resolution.\n // We work on route segments (not filesystem paths) so that route groups\n // and parallel slots are properly skipped when climbing.\n const routeSegments = path.relative(appDir, routeDir).split(path.sep).filter(Boolean);\n\n let baseParts: string[];\n switch (convention) {\n case \".\":\n baseParts = routeSegments;\n break;\n case \"..\":\n case \"../..\": {\n const levelsToClimb = convention === \"..\" ? 1 : 2;\n let climbed = 0;\n let cutIndex = routeSegments.length;\n while (cutIndex > 0 && climbed < levelsToClimb) {\n cutIndex--;\n if (!isInvisibleSegment(routeSegments[cutIndex])) {\n climbed++;\n }\n }\n baseParts = routeSegments.slice(0, cutIndex);\n break;\n }\n case \"...\":\n baseParts = [];\n break;\n default:\n return null;\n }\n\n // Add the intercept segment and any nested path segments\n const nestedParts = path.relative(interceptRoot, currentDir).split(path.sep).filter(Boolean);\n const allSegments = [...baseParts, interceptSegment, ...nestedParts];\n\n const convertedTarget = convertSegmentsToRouteParts(allSegments);\n if (!convertedTarget) return null;\n\n const { urlSegments, params } = convertedTarget;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n return { pattern: pattern === \"/\" ? \"/\" : pattern, params };\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks configured pageExtensions.\n */\nfunction findFile(dir: string, name: string, matcher: ValidFileMatcher): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/**\n * Convert filesystem path segments to URL route parts, skipping invisible segments\n * (route groups, @slots, \".\") and converting dynamic segment syntax to Express-style\n * patterns (e.g. \"[id]\" → \":id\", \"[...slug]\" → \":slug+\").\n */\nfunction convertSegmentsToRouteParts(\n segments: string[],\n): { urlSegments: string[]; params: string[]; isDynamic: boolean } | null {\n const urlSegments: string[] = [];\n const params: string[] = [];\n let isDynamic = false;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n if (isInvisibleSegment(segment)) continue;\n\n // Catch-all segments are only valid in terminal URL position.\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n return { urlSegments, params, isDynamic };\n}\n\nfunction hasRemainingVisibleSegments(segments: string[], startIndex: number): boolean {\n for (let i = startIndex; i < segments.length; i++) {\n if (!isInvisibleSegment(segments[i])) return true;\n }\n return false;\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst appTrieCache = new WeakMap<AppRoute[], TrieNode<AppRoute>>();\n\nfunction getOrBuildAppTrie(routes: AppRoute[]): TrieNode<AppRoute> {\n let trie = appTrieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n appTrieCache.set(routes, trie);\n }\n return trie;\n}\n\nfunction joinRoutePattern(basePattern: string, subPath: string): string {\n if (!subPath) return basePattern;\n return basePattern === \"/\" ? `/${subPath}` : `${basePattern}/${subPath}`;\n}\n\n/**\n * Match a URL against App Router routes.\n */\nexport function matchAppRoute(\n url: string,\n routes: AppRoute[],\n): { route: AppRoute; params: Record<string, string | string[]> } | null {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildAppTrie(routes);\n return trieMatch(trie, urlParts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuIA,IAAI,eAAkC;AACtC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,gBAAe;AACf,gBAAe;AACf,2BAA0B;;AAG5B,SAAS,yBAAyB,KAAsB;AACtD,KAAI;AACF,SAAO,GACJ,YAAY,KAAK,EAAE,eAAe,MAAM,CAAC,CACzC,MAAM,UAAU,MAAM,aAAa,IAAI,MAAM,KAAK,WAAW,IAAI,CAAC;SAC/D;AACN,SAAO;;;;;;AAOX,eAAsB,UACpB,QACA,gBACA,SACqB;AACrB,aAAY,uBAAuB,eAAe;CAClD,MAAM,oBAAoB,KAAK,UAAU,QAAQ,WAAW;AAC5D,KAAI,gBAAgB,iBAAiB,UAAU,4BAA4B,kBACzE,QAAO;CAMT,MAAM,SAAqB,EAAE;CAE7B,MAAM,cAAc,SAAiB,KAAK,WAAW,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M,IAAI,CAAC,OAAO,QAAQ;AAEzD,QAAO,UADM,kBAAkB,OAAO,EACf,SAAS"}
|
|
@@ -7,7 +7,7 @@ import "../client/instrumentation-client.js";
|
|
|
7
7
|
import { chunksToReadableStream, createProgressiveRscStream, getVinextBrowserGlobal } from "./app-browser-stream.js";
|
|
8
8
|
import { createHistoryStateWithPreviousNextUrl, createPendingNavigationCommit, readHistoryStatePreviousNextUrl, resolveAndClassifyNavigationCommit, resolveInterceptionContextFromPreviousNextUrl, resolvePendingNavigationCommitDisposition, resolveServerActionRequestState, routerReducer } from "./app-browser-state.js";
|
|
9
9
|
import { devOnCaughtError } from "./app-browser-error.js";
|
|
10
|
-
import { createElement, startTransition, use, useLayoutEffect,
|
|
10
|
+
import { createElement, startTransition, use, useLayoutEffect, useRef, useState } from "react";
|
|
11
11
|
import { hydrateRoot } from "react-dom/client";
|
|
12
12
|
import { createFromFetch, createFromReadableStream, createTemporaryReferenceSet, encodeReply, setServerCallback } from "@vitejs/plugin-rsc/browser";
|
|
13
13
|
//#region src/server/app-browser-entry.ts
|
|
@@ -21,21 +21,56 @@ let nextNavigationRenderId = 0;
|
|
|
21
21
|
let activeNavigationId = 0;
|
|
22
22
|
const pendingNavigationCommits = /* @__PURE__ */ new Map();
|
|
23
23
|
const pendingNavigationPrePaintEffects = /* @__PURE__ */ new Map();
|
|
24
|
-
|
|
24
|
+
function isRouterStatePromise(value) {
|
|
25
|
+
return value instanceof Promise;
|
|
26
|
+
}
|
|
27
|
+
let setBrowserRouterState = null;
|
|
25
28
|
let browserRouterStateRef = null;
|
|
29
|
+
let activePendingBrowserRouterState = null;
|
|
26
30
|
let latestClientParams = {};
|
|
27
31
|
const visitedResponseCache = /* @__PURE__ */ new Map();
|
|
28
32
|
function isServerActionResult(value) {
|
|
29
33
|
return !!value && typeof value === "object" && "root" in value;
|
|
30
34
|
}
|
|
31
|
-
function
|
|
32
|
-
if (!
|
|
33
|
-
return
|
|
35
|
+
function getBrowserRouterStateSetter() {
|
|
36
|
+
if (!setBrowserRouterState) throw new Error("[vinext] Browser router state setter is not initialized");
|
|
37
|
+
return setBrowserRouterState;
|
|
34
38
|
}
|
|
35
39
|
function getBrowserRouterState() {
|
|
36
40
|
if (!browserRouterStateRef) throw new Error("[vinext] Browser router state is not initialized");
|
|
37
41
|
return browserRouterStateRef.current;
|
|
38
42
|
}
|
|
43
|
+
function beginPendingBrowserRouterState() {
|
|
44
|
+
const setter = getBrowserRouterStateSetter();
|
|
45
|
+
if (activePendingBrowserRouterState && !activePendingBrowserRouterState.settled) {
|
|
46
|
+
activePendingBrowserRouterState.settled = true;
|
|
47
|
+
activePendingBrowserRouterState.resolve(getBrowserRouterState());
|
|
48
|
+
}
|
|
49
|
+
let resolve;
|
|
50
|
+
const promise = new Promise((resolvePromise) => {
|
|
51
|
+
resolve = resolvePromise;
|
|
52
|
+
});
|
|
53
|
+
const pending = {
|
|
54
|
+
promise,
|
|
55
|
+
resolve,
|
|
56
|
+
settled: false
|
|
57
|
+
};
|
|
58
|
+
activePendingBrowserRouterState = pending;
|
|
59
|
+
setter(promise);
|
|
60
|
+
return pending;
|
|
61
|
+
}
|
|
62
|
+
function settlePendingBrowserRouterState(pending) {
|
|
63
|
+
if (!pending || pending.settled) return;
|
|
64
|
+
pending.settled = true;
|
|
65
|
+
pending.resolve(getBrowserRouterState());
|
|
66
|
+
if (activePendingBrowserRouterState === pending) activePendingBrowserRouterState = null;
|
|
67
|
+
}
|
|
68
|
+
function resolvePendingBrowserRouterState(pending, action) {
|
|
69
|
+
if (!pending || pending.settled) return;
|
|
70
|
+
pending.settled = true;
|
|
71
|
+
pending.resolve(routerReducer(getBrowserRouterState(), action));
|
|
72
|
+
if (activePendingBrowserRouterState === pending) activePendingBrowserRouterState = null;
|
|
73
|
+
}
|
|
39
74
|
function applyClientParams(params) {
|
|
40
75
|
latestClientParams = params;
|
|
41
76
|
setClientParams(params);
|
|
@@ -213,7 +248,7 @@ async function commitSameUrlNavigatePayload(nextElements, returnValue) {
|
|
|
213
248
|
window.location.assign(window.location.href);
|
|
214
249
|
return;
|
|
215
250
|
}
|
|
216
|
-
if (disposition === "dispatch") dispatchBrowserTree(pending.action.elements, navigationSnapshot, pending.action.renderId, "navigate", pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, false);
|
|
251
|
+
if (disposition === "dispatch") dispatchBrowserTree(pending.action.elements, navigationSnapshot, pending.action.renderId, "navigate", pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, null, false);
|
|
217
252
|
if (returnValue) {
|
|
218
253
|
if (!returnValue.ok) throw returnValue.data;
|
|
219
254
|
return returnValue.data;
|
|
@@ -222,7 +257,7 @@ async function commitSameUrlNavigatePayload(nextElements, returnValue) {
|
|
|
222
257
|
function BrowserRoot({ initialElements, initialNavigationSnapshot }) {
|
|
223
258
|
const resolvedElements = use(initialElements);
|
|
224
259
|
const initialMetadata = readAppElementsMetadata(resolvedElements);
|
|
225
|
-
const [
|
|
260
|
+
const [treeStateValue, setTreeStateValue] = useState({
|
|
226
261
|
elements: resolvedElements,
|
|
227
262
|
interceptionContext: initialMetadata.interceptionContext,
|
|
228
263
|
layoutFlags: initialMetadata.layoutFlags,
|
|
@@ -232,17 +267,18 @@ function BrowserRoot({ initialElements, initialNavigationSnapshot }) {
|
|
|
232
267
|
rootLayoutTreePath: initialMetadata.rootLayoutTreePath,
|
|
233
268
|
routeId: initialMetadata.routeId
|
|
234
269
|
});
|
|
270
|
+
const treeState = isRouterStatePromise(treeStateValue) ? use(treeStateValue) : treeStateValue;
|
|
235
271
|
const stateRef = useRef(treeState);
|
|
236
272
|
stateRef.current = treeState;
|
|
237
273
|
useLayoutEffect(() => {
|
|
238
|
-
|
|
274
|
+
setBrowserRouterState = setTreeStateValue;
|
|
239
275
|
browserRouterStateRef = stateRef;
|
|
240
276
|
return () => {
|
|
241
|
-
if (
|
|
277
|
+
if (setBrowserRouterState === setTreeStateValue) setBrowserRouterState = null;
|
|
242
278
|
if (browserRouterStateRef === stateRef) browserRouterStateRef = null;
|
|
243
279
|
setMountedSlotsHeader(null);
|
|
244
280
|
};
|
|
245
|
-
}, [
|
|
281
|
+
}, [setTreeStateValue]);
|
|
246
282
|
useLayoutEffect(() => {
|
|
247
283
|
setMountedSlotsHeader(getMountedSlotIdsHeader(stateRef.current.elements));
|
|
248
284
|
}, [treeState.elements]);
|
|
@@ -255,9 +291,9 @@ function BrowserRoot({ initialElements, initialNavigationSnapshot }) {
|
|
|
255
291
|
if (!ClientNavigationRenderContext) return committedTree;
|
|
256
292
|
return createElement(ClientNavigationRenderContext.Provider, { value: treeState.navigationSnapshot }, committedTree);
|
|
257
293
|
}
|
|
258
|
-
function dispatchBrowserTree(elements, navigationSnapshot, renderId, actionType, interceptionContext, layoutFlags, previousNextUrl, routeId, rootLayoutTreePath, useTransitionMode) {
|
|
259
|
-
const
|
|
260
|
-
const
|
|
294
|
+
function dispatchBrowserTree(elements, navigationSnapshot, renderId, actionType, interceptionContext, layoutFlags, previousNextUrl, routeId, rootLayoutTreePath, pendingRouterState, useTransitionMode) {
|
|
295
|
+
const setter = getBrowserRouterStateSetter();
|
|
296
|
+
const action = {
|
|
261
297
|
elements,
|
|
262
298
|
interceptionContext,
|
|
263
299
|
layoutFlags,
|
|
@@ -267,11 +303,18 @@ function dispatchBrowserTree(elements, navigationSnapshot, renderId, actionType,
|
|
|
267
303
|
rootLayoutTreePath,
|
|
268
304
|
routeId,
|
|
269
305
|
type: actionType
|
|
270
|
-
}
|
|
306
|
+
};
|
|
307
|
+
const applyAction = () => {
|
|
308
|
+
if (pendingRouterState) {
|
|
309
|
+
resolvePendingBrowserRouterState(pendingRouterState, action);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
setter(routerReducer(getBrowserRouterState(), action));
|
|
313
|
+
};
|
|
271
314
|
if (useTransitionMode) startTransition(applyAction);
|
|
272
315
|
else applyAction();
|
|
273
316
|
}
|
|
274
|
-
async function renderNavigationPayload(payload, navigationSnapshot, targetHref, navId, historyUpdateMode, params, previousNextUrl, useTransition = true, actionType = "navigate") {
|
|
317
|
+
async function renderNavigationPayload(payload, navigationSnapshot, targetHref, navId, historyUpdateMode, params, previousNextUrl, pendingRouterState, useTransition = true, actionType = "navigate") {
|
|
275
318
|
const renderId = ++nextNavigationRenderId;
|
|
276
319
|
const committed = new Promise((resolve) => {
|
|
277
320
|
pendingNavigationCommits.set(renderId, resolve);
|
|
@@ -294,12 +337,14 @@ async function renderNavigationPayload(payload, navigationSnapshot, targetHref,
|
|
|
294
337
|
startedNavigationId: navId
|
|
295
338
|
});
|
|
296
339
|
if (disposition === "skip") {
|
|
340
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
297
341
|
const resolve = pendingNavigationCommits.get(renderId);
|
|
298
342
|
pendingNavigationCommits.delete(renderId);
|
|
299
343
|
resolve?.();
|
|
300
344
|
return;
|
|
301
345
|
}
|
|
302
346
|
if (disposition === "hard-navigate") {
|
|
347
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
303
348
|
pendingNavigationCommits.delete(renderId);
|
|
304
349
|
window.location.assign(targetHref);
|
|
305
350
|
return;
|
|
@@ -307,12 +352,13 @@ async function renderNavigationPayload(payload, navigationSnapshot, targetHref,
|
|
|
307
352
|
queuePrePaintNavigationEffect(renderId, createNavigationCommitEffect(targetHref, historyUpdateMode, navId, params, pending.previousNextUrl));
|
|
308
353
|
activateNavigationSnapshot();
|
|
309
354
|
snapshotActivated = true;
|
|
310
|
-
dispatchBrowserTree(pending.action.elements, navigationSnapshot, renderId, actionType, pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, useTransition);
|
|
355
|
+
dispatchBrowserTree(pending.action.elements, navigationSnapshot, renderId, actionType, pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, pendingRouterState, useTransition);
|
|
311
356
|
} catch (error) {
|
|
312
357
|
pendingNavigationPrePaintEffects.delete(renderId);
|
|
313
358
|
const resolve = pendingNavigationCommits.get(renderId);
|
|
314
359
|
pendingNavigationCommits.delete(renderId);
|
|
315
360
|
if (snapshotActivated) commitClientNavigationState(navId);
|
|
361
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
316
362
|
resolve?.();
|
|
317
363
|
throw error;
|
|
318
364
|
}
|
|
@@ -404,15 +450,17 @@ async function main() {
|
|
|
404
450
|
initialNavigationSnapshot
|
|
405
451
|
}), import.meta.env.DEV ? { onCaughtError: devOnCaughtError } : void 0);
|
|
406
452
|
window.__VINEXT_HYDRATED_AT = performance.now();
|
|
407
|
-
window.__VINEXT_RSC_NAVIGATE__ = async function navigateRsc(href, redirectDepth = 0, navigationKind = "navigate", historyUpdateMode, previousNextUrlOverride) {
|
|
453
|
+
window.__VINEXT_RSC_NAVIGATE__ = async function navigateRsc(href, redirectDepth = 0, navigationKind = "navigate", historyUpdateMode, previousNextUrlOverride, programmaticTransition = false) {
|
|
408
454
|
if (redirectDepth > 10) {
|
|
409
455
|
console.error("[vinext] Too many RSC redirects — aborting navigation to prevent infinite loop.");
|
|
410
456
|
window.location.href = href;
|
|
411
457
|
return;
|
|
412
458
|
}
|
|
413
459
|
let _snapshotPending = false;
|
|
460
|
+
let pendingRouterState = null;
|
|
414
461
|
const navId = ++activeNavigationId;
|
|
415
462
|
try {
|
|
463
|
+
if (programmaticTransition) pendingRouterState = beginPendingBrowserRouterState();
|
|
416
464
|
const url = new URL(href, window.location.origin);
|
|
417
465
|
const rscUrl = toRscUrl(url.pathname + url.search);
|
|
418
466
|
const requestState = getRequestState(navigationKind, previousNextUrlOverride);
|
|
@@ -426,14 +474,20 @@ async function main() {
|
|
|
426
474
|
const mountedSlotsHeader = getMountedSlotIdsHeader(elementsAtNavStart);
|
|
427
475
|
const cachedRoute = getVisitedResponse(rscUrl, requestInterceptionContext, mountedSlotsHeader, navigationKind);
|
|
428
476
|
if (cachedRoute) {
|
|
429
|
-
if (navId !== activeNavigationId)
|
|
477
|
+
if (navId !== activeNavigationId) {
|
|
478
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
430
481
|
const cachedParams = cachedRoute.params;
|
|
431
482
|
const cachedNavigationSnapshot = createClientNavigationRenderSnapshot(href, cachedParams);
|
|
432
483
|
const cachedPayload = normalizeAppElementsPromise(createFromFetch(Promise.resolve(restoreRscResponse(cachedRoute.response))));
|
|
433
|
-
if (navId !== activeNavigationId)
|
|
484
|
+
if (navId !== activeNavigationId) {
|
|
485
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
434
488
|
_snapshotPending = true;
|
|
435
489
|
try {
|
|
436
|
-
await renderNavigationPayload(cachedPayload, cachedNavigationSnapshot, href, navId, historyUpdateMode, cachedParams, requestPreviousNextUrl, isSameRoute, toActionType(navigationKind));
|
|
490
|
+
await renderNavigationPayload(cachedPayload, cachedNavigationSnapshot, href, navId, historyUpdateMode, cachedParams, requestPreviousNextUrl, pendingRouterState, isSameRoute, toActionType(navigationKind));
|
|
437
491
|
} finally {
|
|
438
492
|
_snapshotPending = false;
|
|
439
493
|
}
|
|
@@ -456,7 +510,10 @@ async function main() {
|
|
|
456
510
|
credentials: "include"
|
|
457
511
|
});
|
|
458
512
|
}
|
|
459
|
-
if (navId !== activeNavigationId)
|
|
513
|
+
if (navId !== activeNavigationId) {
|
|
514
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
460
517
|
const finalUrl = new URL(navResponseUrl ?? navResponse.url, window.location.origin);
|
|
461
518
|
const requestedUrl = new URL(rscUrl, window.location.origin);
|
|
462
519
|
if (finalUrl.pathname !== requestedUrl.pathname) {
|
|
@@ -464,10 +521,12 @@ async function main() {
|
|
|
464
521
|
replaceHistoryStateWithoutNotify(createHistoryStateWithPreviousNextUrl(null, requestPreviousNextUrl), "", destinationPath);
|
|
465
522
|
const navigate = window.__VINEXT_RSC_NAVIGATE__;
|
|
466
523
|
if (!navigate) {
|
|
524
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
467
525
|
window.location.href = destinationPath;
|
|
468
526
|
return;
|
|
469
527
|
}
|
|
470
|
-
|
|
528
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
529
|
+
return navigate(destinationPath, redirectDepth + 1, navigationKind, void 0, requestPreviousNextUrl, false);
|
|
471
530
|
}
|
|
472
531
|
let navParams = {};
|
|
473
532
|
const paramsHeader = navResponse.headers.get("X-Vinext-Params");
|
|
@@ -476,16 +535,25 @@ async function main() {
|
|
|
476
535
|
} catch {}
|
|
477
536
|
const navigationSnapshot = createClientNavigationRenderSnapshot(href, navParams);
|
|
478
537
|
const responseSnapshot = await snapshotRscResponse(navResponse);
|
|
479
|
-
if (navId !== activeNavigationId)
|
|
538
|
+
if (navId !== activeNavigationId) {
|
|
539
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
480
542
|
const rscPayload = normalizeAppElementsPromise(createFromFetch(Promise.resolve(restoreRscResponse(responseSnapshot))));
|
|
481
|
-
if (navId !== activeNavigationId)
|
|
543
|
+
if (navId !== activeNavigationId) {
|
|
544
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
482
547
|
_snapshotPending = true;
|
|
483
548
|
try {
|
|
484
|
-
await renderNavigationPayload(rscPayload, navigationSnapshot, href, navId, historyUpdateMode, navParams, requestPreviousNextUrl, isSameRoute, toActionType(navigationKind));
|
|
549
|
+
await renderNavigationPayload(rscPayload, navigationSnapshot, href, navId, historyUpdateMode, navParams, requestPreviousNextUrl, pendingRouterState, isSameRoute, toActionType(navigationKind));
|
|
485
550
|
} finally {
|
|
486
551
|
_snapshotPending = false;
|
|
487
552
|
}
|
|
488
|
-
if (navId !== activeNavigationId)
|
|
553
|
+
if (navId !== activeNavigationId) {
|
|
554
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
489
557
|
storeVisitedResponseSnapshot(rscUrl, resolveVisitedResponseInterceptionContext(requestInterceptionContext, readAppElementsMetadata(await rscPayload).interceptionContext), responseSnapshot, navParams);
|
|
490
558
|
return;
|
|
491
559
|
} catch (error) {
|
|
@@ -493,6 +561,7 @@ async function main() {
|
|
|
493
561
|
_snapshotPending = false;
|
|
494
562
|
commitClientNavigationState(navId);
|
|
495
563
|
}
|
|
564
|
+
settlePendingBrowserRouterState(pendingRouterState);
|
|
496
565
|
if (navId === activeNavigationId) clearPendingPathname(navId);
|
|
497
566
|
if (navId !== activeNavigationId) return;
|
|
498
567
|
console.error("[vinext] RSC navigation error:", error);
|
|
@@ -520,7 +589,7 @@ async function main() {
|
|
|
520
589
|
renderId: ++nextNavigationRenderId,
|
|
521
590
|
type: "replace"
|
|
522
591
|
});
|
|
523
|
-
dispatchBrowserTree(pending.action.elements, navigationSnapshot, pending.action.renderId, "replace", pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, false);
|
|
592
|
+
dispatchBrowserTree(pending.action.elements, navigationSnapshot, pending.action.renderId, "replace", pending.interceptionContext, pending.action.layoutFlags, pending.previousNextUrl, pending.routeId, pending.rootLayoutTreePath, null, false);
|
|
524
593
|
} catch (error) {
|
|
525
594
|
console.error("[vinext] RSC HMR error:", error);
|
|
526
595
|
}
|