Skip to content

Commit

Permalink
Fix turbopack route resolver (#46206
Browse files Browse the repository at this point in the history
This ensures we correctly handle the new route matchers with turbopack.
Also updates the custom-routes test suite to allow it to run against
turbopack although relies on changes in
vercel/turborepo#3894 for the tests to run
correctly.
  • Loading branch information
ijjk authored Feb 21, 2023
1 parent 04c6c8c commit 185a892
Show file tree
Hide file tree
Showing 2 changed files with 175 additions and 3 deletions.
45 changes: 43 additions & 2 deletions packages/next/src/server/lib/route-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextConfig } from '../config'
import type { Route } from '../router'
import { RouteDefinition } from '../future/route-definitions/route-definition'
import { RouteKind } from '../future/route-kind'
import { DefaultRouteMatcherManager } from '../future/route-matcher-managers/default-route-matcher-manager'
import { RouteMatch } from '../future/route-matches/route-match'
import type { PageChecker, Route } from '../router'

type RouteResult =
| {
Expand All @@ -13,6 +17,37 @@ type RouteResult =
type: 'none'
}

class DevRouteMatcherManager extends DefaultRouteMatcherManager {
private hasPage: PageChecker

constructor(hasPage: PageChecker) {
super()
this.hasPage = hasPage
}

async match(
pathname: string
): Promise<RouteMatch<RouteDefinition<RouteKind>> | null> {
if (await this.hasPage(pathname)) {
return {
definition: {
kind: RouteKind.PAGES,
page: '',
pathname,
filename: '',
bundlePath: '',
},
params: {},
}
}
return null
}

async test(pathname: string) {
return (await this.match(pathname)) !== null
}
}

export async function makeResolver(dir: string, nextConfig: NextConfig) {
const url = require('url') as typeof import('url')
const { default: Router } = require('../router') as typeof import('../router')
Expand All @@ -37,6 +72,12 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {

const routeResults = new WeakMap<any, string>()
const routes = devServer.generateRoutes.bind(devServer)()

routes.matchers = new DevRouteMatcherManager(
// @ts-expect-error internal method
devServer.hasPage.bind(devServer)
)

const router = new Router({
...routes,
catchAllRoute: {
Expand Down Expand Up @@ -98,7 +139,7 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {
type: 'rewrite',
url: resolvedUrl,
statusCode: 200,
headers: {},
headers: res.originalResponse.getHeaders(),
}

res.body(JSON.stringify(routeResult)).send()
Expand Down
Loading

0 comments on commit 185a892

Please sign in to comment.