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

Expose resolved invocation targets in next-routing (#91242)

### What?

This PR extends `@next/routing` so `resolveRoutes()` returns the
concrete route resolution data callers need after rewrites and dynamic
matches:

- rename `matchedPathname` to `resolvedPathname`
- add `resolvedQuery`
- add `invocationTarget` for the concrete pathname/query that should be
invoked
- export the new query/invocation target types from the package
entrypoint

It also removes the leftover `query` alias so the result shape
consistently uses `resolvedQuery`.

### Why?

`matchedPathname` only described part of the result, and it was
ambiguous for dynamic routes because the resolved route template and the
concrete invocation target are not always the same thing.

For example, a dynamic route can resolve to `/blog/[slug]` while the
actual invocation target is `/blog/post-1`, and rewrites can merge query
params that callers need to preserve. Exposing these values directly
makes the package easier to consume from adapters without each caller
reconstructing them manually.

### How?

- thread resolved query construction through the route resolution paths
- build `invocationTarget` alongside `resolvedPathname` wherever
rewrites, static matches, and dynamic matches resolve successfully
- preserve merged rewrite query params in `resolvedQuery`
- update the public types, README example, and existing tests to use
`resolvedPathname`
- add coverage for resolved query + invocation target behavior on
rewrite and dynamic route matches

Verified with:
- `pnpm --filter @next/routing test -- --runInBand`
- `pnpm --filter @next/routing build`
parent efcfe05a
......@@ -444,8 +444,22 @@ const result = await resolveRoutes({
return {}
},
})
if (result.resolvedPathname) {
console.log('Resolved pathname:', result.resolvedPathname)
console.log('Resolved query:', result.resolvedQuery)
console.log('Invocation target:', result.invocationTarget)
}
```
`resolveRoutes()` returns:
- `resolvedPathname`: The route pathname selected by Next.js routing. For dynamic routes, this is the matched route template such as `/blog/[slug]`.
- `resolvedQuery`: The final query after rewrites or middleware have added or replaced search params.
- `invocationTarget`: The concrete pathname and query to invoke for the matched route.
For example, if `/blog/post-1?draft=1` matches `/blog/[slug]?slug=post-1`, `resolvedPathname` is `/blog/[slug]` while `invocationTarget.pathname` is `/blog/post-1`.
## Implementing PPR in an Adapter
For partially prerendered app routes, `onBuildComplete` gives you the data needed to seed and resume PPR:
......
......@@ -39,8 +39,10 @@ const result = await resolveRoutes({
},
})
if (result.matchedPathname) {
console.log('Matched:', result.matchedPathname)
if (result.resolvedPathname) {
console.log('Resolved pathname:', result.resolvedPathname)
console.log('Resolved query:', result.resolvedQuery)
console.log('Invocation target:', result.invocationTarget)
}
```
......
......@@ -54,7 +54,7 @@ describe('Regex Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/my-post')
expect(result.resolvedPathname).toBe('/posts/my-post')
})
it('should replace multiple numbered captures $1, $2, $3', async () => {
......@@ -78,7 +78,7 @@ describe('Regex Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/archive/2024/01/post-title')
expect(result.resolvedPathname).toBe('/archive/2024/01/post-title')
})
it('should replace named captures in destination', async () => {
......@@ -102,7 +102,7 @@ describe('Regex Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/u/alice/p/123')
expect(result.resolvedPathname).toBe('/u/alice/p/123')
})
it('should mix numbered and named captures', async () => {
......@@ -126,7 +126,7 @@ describe('Regex Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal/v1/user/john')
expect(result.resolvedPathname).toBe('/internal/v1/user/john')
})
it('should use captures in query parameters', async () => {
......@@ -150,7 +150,7 @@ describe('Regex Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/products')
expect(result.resolvedPathname).toBe('/api/products')
})
it('should replace captures in external rewrite', async () => {
......@@ -240,7 +240,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/12345/profile')
expect(result.resolvedPathname).toBe('/users/12345/profile')
})
it('should use cookie value in destination', async () => {
......@@ -275,7 +275,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/sessions/abc123xyz/dashboard')
expect(result.resolvedPathname).toBe('/sessions/abc123xyz/dashboard')
})
it('should use query parameter value in destination', async () => {
......@@ -305,7 +305,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/results/nextjs')
expect(result.resolvedPathname).toBe('/results/nextjs')
})
it('should combine regex captures and has captures', async () => {
......@@ -340,7 +340,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/tenants/acme/users/123')
expect(result.resolvedPathname).toBe('/tenants/acme/users/123')
})
it('should combine named regex captures and has captures', async () => {
......@@ -375,7 +375,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/v2/products/electronics')
expect(result.resolvedPathname).toBe('/api/v2/products/electronics')
})
it('should use multiple has captures in destination', async () => {
......@@ -415,7 +415,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/regions/us-west/tenants/acme/data')
expect(result.resolvedPathname).toBe('/regions/us-west/tenants/acme/data')
})
it('should use has captures with regex pattern match', async () => {
......@@ -451,7 +451,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/localized/en-US/page')
expect(result.resolvedPathname).toBe('/localized/en-US/page')
})
it('should use has captures in query string', async () => {
......@@ -486,7 +486,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal/dashboard')
expect(result.resolvedPathname).toBe('/internal/dashboard')
})
it('should use has captures in external rewrite', async () => {
......@@ -601,7 +601,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/123')
expect(result.resolvedPathname).toBe('/users/123')
expect(result.resolvedHeaders?.get('Location')).toBe('/profiles/123')
expect(result.resolvedHeaders?.get('x-user-id')).toBe('123')
expect(result.resolvedHeaders?.get('x-language')).toBe('es')
......@@ -650,7 +650,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/posts')
expect(result.resolvedPathname).toBe('/api/posts')
expect(result.resolvedHeaders?.get('x-resource')).toBe('posts')
expect(result.resolvedHeaders?.get('x-language')).toBe('fr')
expect(result.resolvedHeaders?.get('x-combined')).toBe('posts-fr')
......@@ -689,7 +689,7 @@ describe('Has Condition Captures in Destination', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/fr/profile/john')
expect(result.resolvedPathname).toBe('/fr/profile/john')
expect(result.routeMatches).toEqual({
'1': 'john',
})
......@@ -736,7 +736,7 @@ describe('Complex Capture Scenarios', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe(
expect(result.resolvedPathname).toBe(
'/orgs/myorg/users/john/projects/backend/issues/42'
)
})
......@@ -762,7 +762,7 @@ describe('Complex Capture Scenarios', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/a/test/b/test/c/test')
expect(result.resolvedPathname).toBe('/a/test/b/test/c/test')
})
it('should handle capture with special characters', async () => {
......@@ -786,7 +786,7 @@ describe('Complex Capture Scenarios', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/storage/my-file.test.js')
expect(result.resolvedPathname).toBe('/storage/my-file.test.js')
})
it('should not replace undefined captures', async () => {
......@@ -810,7 +810,7 @@ describe('Complex Capture Scenarios', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/result/$1/$2')
expect(result.resolvedPathname).toBe('/result/$1/$2')
})
it('should handle captures across chained rewrites', async () => {
......@@ -838,6 +838,6 @@ describe('Complex Capture Scenarios', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal/user-service/alice')
expect(result.resolvedPathname).toBe('/internal/user-service/alice')
})
})
......@@ -66,7 +66,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/admin-dashboard')
expect(result.resolvedPathname).toBe('/admin-dashboard')
})
it('should match route with cookie condition', async () => {
......@@ -102,7 +102,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/dark-theme-page')
expect(result.resolvedPathname).toBe('/dark-theme-page')
})
it('should match route with query condition', async () => {
......@@ -133,7 +133,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/preview-page')
expect(result.resolvedPathname).toBe('/preview-page')
})
it('should match route with host condition', async () => {
......@@ -163,7 +163,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/subdomain-home')
expect(result.resolvedPathname).toBe('/subdomain-home')
})
it('should match when has condition checks key existence only', async () => {
......@@ -199,7 +199,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/feature-enabled')
expect(result.resolvedPathname).toBe('/feature-enabled')
})
it('should match with regex pattern in has condition', async () => {
......@@ -235,7 +235,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/mobile')
expect(result.resolvedPathname).toBe('/mobile')
})
it('should require ALL has conditions to match', async () => {
......@@ -277,7 +277,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/admin-beta-feature')
expect(result.resolvedPathname).toBe('/admin-beta-feature')
})
it('should NOT match when one has condition fails', async () => {
......@@ -320,7 +320,7 @@ describe('Has conditions', () => {
const result = await resolveRoutes(params)
// Should not match the route, so stays at /feature
expect(result.matchedPathname).toBe('/feature')
expect(result.resolvedPathname).toBe('/feature')
})
})
......@@ -357,7 +357,7 @@ describe('Missing conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/no-debug-page')
expect(result.resolvedPathname).toBe('/no-debug-page')
})
it('should NOT match when missing condition is present', async () => {
......@@ -393,7 +393,7 @@ describe('Missing conditions', () => {
const result = await resolveRoutes(params)
// Route should not match, stays at /page
expect(result.matchedPathname).toBe('/page')
expect(result.resolvedPathname).toBe('/page')
})
it('should match when missing cookie is not present', async () => {
......@@ -428,7 +428,7 @@ describe('Missing conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/no-tracking')
expect(result.resolvedPathname).toBe('/no-tracking')
})
it('should match when missing query is not present', async () => {
......@@ -458,7 +458,7 @@ describe('Missing conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/no-preview')
expect(result.resolvedPathname).toBe('/no-preview')
})
it('should require ALL missing conditions to be absent', async () => {
......@@ -498,7 +498,7 @@ describe('Missing conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/standard-page')
expect(result.resolvedPathname).toBe('/standard-page')
})
})
......@@ -543,7 +543,7 @@ describe('Combined has and missing conditions', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/member-content')
expect(result.resolvedPathname).toBe('/member-content')
})
it('should NOT match when has is satisfied but missing is present', async () => {
......@@ -587,7 +587,7 @@ describe('Combined has and missing conditions', () => {
const result = await resolveRoutes(params)
// Should not match, stays at /content
expect(result.matchedPathname).toBe('/content')
expect(result.resolvedPathname).toBe('/content')
})
it('should NOT match when has fails even if missing is satisfied', async () => {
......@@ -631,7 +631,7 @@ describe('Combined has and missing conditions', () => {
const result = await resolveRoutes(params)
// Should not match, stays at /content
expect(result.matchedPathname).toBe('/content')
expect(result.resolvedPathname).toBe('/content')
})
})
......@@ -657,7 +657,7 @@ describe('Dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/123')
expect(result.resolvedPathname).toBe('/posts/123')
expect(result.routeMatches).toEqual({
'1': '123',
})
......@@ -684,7 +684,7 @@ describe('Dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/alice/posts/456')
expect(result.resolvedPathname).toBe('/users/alice/posts/456')
expect(result.routeMatches).toEqual({
'1': 'alice',
'2': '456',
......@@ -726,7 +726,7 @@ describe('Dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/profile/john')
expect(result.resolvedPathname).toBe('/profile/john')
expect(result.routeMatches).toEqual({
'1': 'john',
})
......
......@@ -59,7 +59,7 @@ describe('Dynamic Routes After afterFiles Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/my-post')
expect(result.resolvedPathname).toBe('/posts/my-post')
expect(result.routeMatches).toEqual({
'1': 'my-post',
slug: 'my-post',
......@@ -96,7 +96,7 @@ describe('Dynamic Routes After afterFiles Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/article')
expect(result.resolvedPathname).toBe('/posts/article')
expect(result.routeMatches).toEqual({
'1': 'article',
slug: 'article',
......@@ -137,7 +137,7 @@ describe('Dynamic Routes After afterFiles Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/test')
expect(result.resolvedPathname).toBe('/users/test')
expect(result.routeMatches).toEqual({
'1': 'test',
username: 'test',
......@@ -178,7 +178,7 @@ describe('Dynamic Routes After afterFiles Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/post')
expect(result.resolvedPathname).toBe('/posts/post')
expect(result.routeMatches).toEqual({
'1': 'post',
slug: 'post',
......@@ -222,7 +222,7 @@ describe('Dynamic Routes After afterFiles Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/profile')
expect(result.resolvedPathname).toBe('/users/profile')
expect(result.routeMatches).toEqual({
'1': 'profile',
page: 'profile',
......@@ -257,7 +257,7 @@ describe('Dynamic Routes After fallback Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/catch-all/page')
expect(result.resolvedPathname).toBe('/catch-all/page')
expect(result.routeMatches).toEqual({
'1': 'page',
path: 'page',
......@@ -294,7 +294,7 @@ describe('Dynamic Routes After fallback Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/error/404')
expect(result.resolvedPathname).toBe('/error/404')
expect(result.routeMatches).toEqual({
'1': '404',
code: '404',
......@@ -331,7 +331,7 @@ describe('Dynamic Routes After fallback Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/fallback/404')
expect(result.resolvedPathname).toBe('/fallback/404')
expect(result.routeMatches).toEqual({
'1': '404',
type: '404',
......@@ -368,7 +368,7 @@ describe('Dynamic Routes After fallback Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/error/500')
expect(result.resolvedPathname).toBe('/error/500')
expect(result.routeMatches).toEqual({
'1': '500',
code: '500',
......@@ -405,7 +405,7 @@ describe('Dynamic Routes After fallback Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/users/123')
expect(result.resolvedPathname).toBe('/users/123')
expect(result.routeMatches).toEqual({
'1': '123',
id: '123',
......@@ -446,7 +446,7 @@ describe('Mixed afterFiles and fallback with Dynamic Routes', () => {
const result = await resolveRoutes(params)
// Should match in afterFiles -> dynamic routes, not reach fallback
expect(result.matchedPathname).toBe('/posts/article')
expect(result.resolvedPathname).toBe('/posts/article')
expect(result.routeMatches).toEqual({
'1': 'article',
slug: 'article',
......@@ -485,7 +485,7 @@ describe('Mixed afterFiles and fallback with Dynamic Routes', () => {
const result = await resolveRoutes(params)
// Should go through: test -> intermediate (no match) -> fallback -> posts/fallback (dynamic match)
expect(result.matchedPathname).toBe('/posts/fallback')
expect(result.resolvedPathname).toBe('/posts/fallback')
expect(result.routeMatches).toEqual({
'1': 'fallback',
slug: 'fallback',
......
......@@ -166,7 +166,7 @@ describe('resolveRoutes with i18n', () => {
// Path locale takes priority, so no redirect
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/fr/about')
expect(result.resolvedPathname).toBe('/fr/about')
})
it('should handle locale prefix with trailing slash', async () => {
......@@ -179,7 +179,7 @@ describe('resolveRoutes with i18n', () => {
})
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/fr/about/')
expect(result.resolvedPathname).toBe('/fr/about/')
})
})
......@@ -326,7 +326,7 @@ describe('resolveRoutes with i18n', () => {
// Should not redirect for api routes
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/api/ping')
expect(result.resolvedPathname).toBe('/api/ping')
})
it('should skip locale handling for nested api routes', async () => {
......@@ -352,7 +352,7 @@ describe('resolveRoutes with i18n', () => {
// Should not redirect for api routes, even with locale cookies/headers
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/api/users/[id]')
expect(result.resolvedPathname).toBe('/api/users/[id]')
expect(result.routeMatches).toEqual({
'1': '123',
id: '123',
......
......@@ -56,7 +56,7 @@ describe('normalizeNextData - beforeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe(
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/api/blog/post.json'
)
})
......@@ -84,7 +84,7 @@ describe('normalizeNextData - beforeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe(
expect(result.resolvedPathname).toBe(
'/base/_next/data/BUILD_ID/api/page.json'
)
})
......@@ -109,7 +109,9 @@ describe('normalizeNextData - pathname checking', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts/hello.json')
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/posts/hello.json'
)
})
it('should work with rewrites then pathname check', async () => {
......@@ -135,7 +137,7 @@ describe('normalizeNextData - pathname checking', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/posts.json')
})
})
......@@ -163,7 +165,7 @@ describe('normalizeNextData - afterFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/404.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/404.json')
})
it('should handle complex flow: normalize -> beforeFiles -> denormalize -> normalize -> afterFiles -> denormalize', async () => {
......@@ -194,7 +196,7 @@ describe('normalizeNextData - afterFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe(
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/internal/users.json'
)
})
......@@ -224,7 +226,7 @@ describe('normalizeNextData - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts/123.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/posts/123.json')
expect(result.routeMatches).toEqual({
'1': '123',
id: '123',
......@@ -261,7 +263,9 @@ describe('normalizeNextData - dynamic routes', () => {
const result = await resolveRoutes(params)
// Should match with denormalized pathname
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/users/alice.json')
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/users/alice.json'
)
expect(result.routeMatches).toEqual({
'1': 'alice',
username: 'alice',
......@@ -296,7 +300,7 @@ describe('normalizeNextData - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe(
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/posts/post-1.json'
)
expect(result.routeMatches).toEqual({
......@@ -330,7 +334,7 @@ describe('normalizeNextData - fallback routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/404.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/404.json')
})
})
......@@ -358,7 +362,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/post')
expect(result.resolvedPathname).toBe('/posts/post')
})
it('should not normalize when normalizeNextData is undefined', async () => {
......@@ -384,7 +388,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/page')
expect(result.resolvedPathname).toBe('/api/page')
})
it('should not normalize URLs that are not data URLs', async () => {
......@@ -405,7 +409,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/regular/path')
expect(result.resolvedPathname).toBe('/regular/path')
})
it('should not apply normalization to non-data URLs even with rewrites', async () => {
......@@ -431,7 +435,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/post')
expect(result.resolvedPathname).toBe('/posts/post')
})
it('should not normalize if rewrite creates a data URL pattern from non-data URL', async () => {
......@@ -459,7 +463,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should NOT normalize because original URL was not a data URL
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/some/path.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/some/path.json')
})
it('should not normalize in afterFiles if original URL was not a data URL', async () => {
......@@ -493,7 +497,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match because afterFiles rewrite should work on the unrewritten data URL path
expect(result.matchedPathname).toBe('/processed.json')
expect(result.resolvedPathname).toBe('/processed.json')
})
it('should not normalize data URLs with different buildId', async () => {
......@@ -514,7 +518,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/DIFFERENT_ID/page.json')
expect(result.resolvedPathname).toBe('/_next/data/DIFFERENT_ID/page.json')
})
it('should handle data URL without .json extension', async () => {
......@@ -535,7 +539,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/page.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/page.json')
})
it('should resolve to _next/data pathname when both exist and URL is a data URL', async () => {
......@@ -558,7 +562,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the denormalized path
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/posts.json')
})
it('should resolve to normalized pathname when both exist and URL is NOT a data URL', async () => {
......@@ -581,7 +585,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the normalized path
expect(result.matchedPathname).toBe('/posts')
expect(result.resolvedPathname).toBe('/posts')
})
it('should resolve to _next/data pathname after rewrite when both exist and original URL is data URL', async () => {
......@@ -609,7 +613,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the denormalized path
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/posts.json')
})
it('should resolve to normalized pathname after rewrite when both exist and original URL is NOT data URL', async () => {
......@@ -637,7 +641,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the normalized path
expect(result.matchedPathname).toBe('/posts')
expect(result.resolvedPathname).toBe('/posts')
})
it('should resolve to _next/data pathname after afterFiles rewrite when original URL is data URL', async () => {
......@@ -665,7 +669,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the denormalized path
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/404.json')
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/404.json')
})
it('should resolve to normalized pathname after afterFiles rewrite when original URL is NOT data URL', async () => {
......@@ -693,7 +697,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the normalized path
expect(result.matchedPathname).toBe('/404')
expect(result.resolvedPathname).toBe('/404')
})
it('should resolve to _next/data pathname with dynamic routes when both exist and original URL is data URL', async () => {
......@@ -725,7 +729,9 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the denormalized path with the first dynamic route
expect(result.matchedPathname).toBe('/_next/data/BUILD_ID/posts/hello.json')
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/posts/hello.json'
)
expect(result.routeMatches).toEqual({
'1': 'hello',
slug: 'hello',
......@@ -761,7 +767,7 @@ describe('normalizeNextData - without normalization', () => {
const result = await resolveRoutes(params)
// Should match the normalized path with the second dynamic route
expect(result.matchedPathname).toBe('/posts/hello')
expect(result.resolvedPathname).toBe('/posts/hello')
expect(result.routeMatches).toEqual({
'1': 'hello',
slug: 'hello',
......
......@@ -60,7 +60,7 @@ describe('Redirects with Location header', () => {
expect(result.redirect).toBeDefined()
expect(result.redirect?.status).toBe(301)
expect(result.redirect?.url.pathname).toBe('/new')
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
expect(result.externalRewrite).toBeUndefined()
})
......@@ -292,9 +292,9 @@ describe('Redirects with Refresh header', () => {
const result = await resolveRoutes(params)
// Should return redirect, not matchedPathname
// Should return redirect, not resolvedPathname
expect(result.redirect).toBeDefined()
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
})
......@@ -440,7 +440,7 @@ describe('Redirect edge cases', () => {
// Should not redirect, should rewrite instead
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/target')
expect(result.resolvedPathname).toBe('/target')
})
it('should NOT redirect when status is 3xx but no Location/Refresh header', async () => {
......@@ -470,7 +470,7 @@ describe('Redirect edge cases', () => {
// Should not redirect without Location or Refresh header
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/target')
expect(result.resolvedPathname).toBe('/target')
})
it('should stop processing routes after redirect', async () => {
......@@ -503,7 +503,7 @@ describe('Redirect edge cases', () => {
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/redirected')
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should handle case-insensitive Location header check', async () => {
......
......@@ -56,7 +56,7 @@ describe('resolveRoutes - beforeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/new-path')
expect(result.resolvedPathname).toBe('/new-path')
expect(result.resolvedHeaders).toBeDefined()
})
......@@ -138,7 +138,7 @@ describe('resolveRoutes - beforeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/third')
expect(result.resolvedPathname).toBe('/third')
})
})
......@@ -172,7 +172,7 @@ describe('resolveRoutes - invokeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.middlewareResponded).toBe(true)
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should handle middleware redirect', async () => {
......@@ -206,7 +206,7 @@ describe('resolveRoutes - invokeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/rewritten')
expect(result.resolvedPathname).toBe('/rewritten')
})
it('should handle middleware external rewrite', async () => {
......@@ -258,7 +258,7 @@ describe('resolveRoutes - invokeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal')
expect(result.resolvedPathname).toBe('/internal')
expect(result.resolvedHeaders?.get('x-custom-header')).toBeNull()
})
......@@ -284,7 +284,7 @@ describe('resolveRoutes - invokeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/test')
expect(result.resolvedPathname).toBe('/test')
expect(result.resolvedHeaders?.get('x-response-header')).toBe(
'response-value'
)
......@@ -304,7 +304,7 @@ describe('resolveRoutes - invokeMiddleware', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/test')
expect(result.resolvedPathname).toBe('/test')
expect(result.resolvedHeaders?.get('authorization')).toBeNull()
expect(result.resolvedHeaders?.get('x-request-id')).toBeNull()
})
......@@ -332,7 +332,7 @@ describe('resolveRoutes - beforeFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal-api/users')
expect(result.resolvedPathname).toBe('/internal-api/users')
})
it('should handle redirect in beforeFiles', async () => {
......@@ -419,7 +419,7 @@ describe('resolveRoutes - beforeFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/final')
expect(result.resolvedPathname).toBe('/final')
})
})
......@@ -445,7 +445,7 @@ describe('resolveRoutes - afterFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/404')
expect(result.resolvedPathname).toBe('/404')
})
it('should handle redirect in afterFiles', async () => {
......@@ -522,7 +522,7 @@ describe('resolveRoutes - afterFiles', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/middle')
expect(result.resolvedPathname).toBe('/middle')
})
})
......@@ -548,7 +548,7 @@ describe('resolveRoutes - fallback', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/default')
expect(result.resolvedPathname).toBe('/default')
})
it('should handle redirect in fallback', async () => {
......@@ -631,7 +631,7 @@ describe('resolveRoutes - fallback', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/fallback-final')
expect(result.resolvedPathname).toBe('/fallback-final')
})
})
......@@ -660,7 +660,7 @@ describe('resolveRoutes - routes without destination', () => {
const result = await resolveRoutes(params)
expect(result.resolvedHeaders?.get('x-custom-header')).toBe('value')
expect(result.matchedPathname).toBe('/headers-only')
expect(result.resolvedPathname).toBe('/headers-only')
})
it('should process routes with status only', async () => {
......@@ -685,7 +685,7 @@ describe('resolveRoutes - routes without destination', () => {
const result = await resolveRoutes(params)
expect(result.status).toBe(418)
expect(result.matchedPathname).toBe('/status-only')
expect(result.resolvedPathname).toBe('/status-only')
})
it('should process multiple routes without destination in sequence', async () => {
......@@ -721,7 +721,7 @@ describe('resolveRoutes - routes without destination', () => {
expect(result.resolvedHeaders?.get('x-header-1')).toBe('1')
expect(result.resolvedHeaders?.get('x-header-2')).toBe('2')
expect(result.status).toBe(200)
expect(result.matchedPathname).toBe('/multi')
expect(result.resolvedPathname).toBe('/multi')
})
})
......@@ -749,7 +749,7 @@ describe('resolveRoutes - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/dynamic/[slug]')
expect(result.resolvedPathname).toBe('/dynamic/[slug]')
expect(result.routeMatches).toEqual({
'1': 'page',
nxtPslug: 'page',
......@@ -777,7 +777,7 @@ describe('resolveRoutes - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts/[year]/[slug]')
expect(result.resolvedPathname).toBe('/posts/[year]/[slug]')
expect(result.routeMatches).toEqual({
'1': '2024',
'2': 'my-article',
......@@ -807,7 +807,7 @@ describe('resolveRoutes - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/docs/[...path]')
expect(result.resolvedPathname).toBe('/docs/[...path]')
expect(result.routeMatches).toEqual({
'1': 'getting-started/installation',
path: 'getting-started/installation',
......@@ -835,7 +835,7 @@ describe('resolveRoutes - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should apply onMatch headers for dynamic routes', async () => {
......@@ -866,7 +866,120 @@ describe('resolveRoutes - dynamic routes', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/[resource]')
expect(result.resolvedPathname).toBe('/api/[resource]')
expect(result.resolvedHeaders?.get('x-matched')).toBe('true')
})
it('should apply onMatch headers using merged destination query for dynamic routes', async () => {
const params = createBaseParams({
url: new URL('https://example.com/blog/post-1?draft=1'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex: '^/blog/(?<slug>[^/]+?)$',
destination: '/blog/[slug]?slug=$slug',
},
],
onMatch: [
{
sourceRegex: '^/blog/post-1$',
has: [
{
type: 'query',
key: 'slug',
value: 'post-1',
},
],
headers: {
'x-slug-match': 'true',
},
},
],
fallback: [],
},
pathnames: ['/blog/[slug]'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/blog/[slug]')
expect(result.resolvedHeaders?.get('x-slug-match')).toBe('true')
expect(result.resolvedQuery).toEqual({
draft: '1',
slug: 'post-1',
})
})
it('should expose resolved query and invocation target for rewrite matches', async () => {
const params = createBaseParams({
url: new URL('https://example.com/rewrite-source?existing=1'),
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/rewrite-source$',
destination: '/rewrite-target?added=2',
},
],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
pathnames: ['/rewrite-target'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/rewrite-target')
expect(result.resolvedQuery).toEqual({
existing: '1',
added: '2',
})
expect(result.invocationTarget).toEqual({
pathname: '/rewrite-target',
query: {
existing: '1',
added: '2',
},
})
})
it('should expose concrete invocation target for dynamic route matches', async () => {
const params = createBaseParams({
url: new URL('https://example.com/blog/post-1?draft=1'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex: '^/blog/(?<slug>[^/]+?)$',
destination: '/blog/[slug]?slug=$slug',
},
],
onMatch: [],
fallback: [],
},
pathnames: ['/blog/[slug]'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/blog/[slug]')
expect(result.resolvedQuery).toEqual({
draft: '1',
slug: 'post-1',
})
expect(result.invocationTarget).toEqual({
pathname: '/blog/post-1',
query: {
draft: '1',
slug: 'post-1',
},
})
})
})
......@@ -54,7 +54,7 @@ describe('Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/posts')
expect(result.resolvedPathname).toBe('/posts')
expect(result.externalRewrite).toBeUndefined()
})
......@@ -79,7 +79,7 @@ describe('Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/search')
expect(result.resolvedPathname).toBe('/api/search')
})
it('should preserve original query params during internal rewrite', async () => {
......@@ -103,7 +103,7 @@ describe('Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/internal/page')
expect(result.resolvedPathname).toBe('/internal/page')
})
it('should handle regex captures in internal rewrite', async () => {
......@@ -127,7 +127,7 @@ describe('Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/profile/john')
expect(result.resolvedPathname).toBe('/profile/john')
})
it('should handle named captures in internal rewrite', async () => {
......@@ -151,7 +151,7 @@ describe('Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/product')
expect(result.resolvedPathname).toBe('/api/product')
})
})
......@@ -178,7 +178,7 @@ describe('External Rewrites', () => {
expect(result.externalRewrite).toBeDefined()
expect(result.externalRewrite?.toString()).toBe('http://external.com/api')
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should handle external rewrite with https', async () => {
......@@ -381,7 +381,7 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/d')
expect(result.resolvedPathname).toBe('/d')
})
it('should chain rewrites across different phases', async () => {
......@@ -415,7 +415,7 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/final')
expect(result.resolvedPathname).toBe('/final')
})
it('should complete chaining then check pathname match', async () => {
......@@ -444,7 +444,7 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
// Should chain through all routes, then match pathname
expect(result.matchedPathname).toBe('/path3')
expect(result.resolvedPathname).toBe('/path3')
})
it('should chain with regex captures preserved', async () => {
......@@ -472,7 +472,7 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/user-content')
expect(result.resolvedPathname).toBe('/api/user-content')
})
it('should stop chaining on external rewrite', async () => {
......@@ -504,7 +504,7 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.externalRewrite?.toString()).toBe('https://external.com/api')
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should stop chaining on redirect', async () => {
......@@ -542,7 +542,7 @@ describe('Chained Internal Rewrites', () => {
expect(result.redirect).toBeDefined()
expect(result.redirect?.status).toBe(301)
expect(result.redirect?.url.pathname).toBe('/final-destination')
expect(result.matchedPathname).toBeUndefined()
expect(result.resolvedPathname).toBeUndefined()
})
it('should handle complex chaining scenario', async () => {
......@@ -571,6 +571,6 @@ describe('Chained Internal Rewrites', () => {
const result = await resolveRoutes(params)
expect(result.matchedPathname).toBe('/api/posts')
expect(result.resolvedPathname).toBe('/api/posts')
})
})
......@@ -6,6 +6,9 @@ export type {
MiddlewareResult,
ResolveRoutesParams,
ResolveRoutesResult,
ResolveRoutesQuery,
ResolveRoutesQueryValue,
RouteInvocationTarget,
} from './types'
export type { I18nConfig, I18nDomain } from './i18n'
export {
......
import type { Route, ResolveRoutesParams, ResolveRoutesResult } from './types'
import type {
Route,
ResolveRoutesParams,
ResolveRoutesQuery,
ResolveRoutesResult,
} from './types'
import { checkHasConditions, checkMissingConditions } from './matchers'
import {
replaceDestination,
......@@ -168,6 +173,58 @@ function matchesPathname(
return undefined
}
function toResolvedQuery(url: URL): ResolveRoutesQuery {
const query: ResolveRoutesQuery = {}
for (const [key, value] of url.searchParams.entries()) {
const existing = query[key]
if (existing === undefined) {
query[key] = value
continue
}
query[key] = Array.isArray(existing)
? [...existing, value]
: [existing, value]
}
return query
}
function mergeDestinationQueryIntoUrl(url: URL, destination: string): URL {
const mergedUrl = new URL(url.toString())
const destinationSearch = destination.split('?')[1]
if (!destinationSearch) {
return mergedUrl
}
const destinationParams = new URLSearchParams(destinationSearch)
for (const [key, value] of destinationParams.entries()) {
mergedUrl.searchParams.set(key, value)
}
return mergedUrl
}
function withResolvedInvocationTarget({
result,
url,
resolvedPathname,
invocationPathname,
}: {
result: ResolveRoutesResult
url: URL
resolvedPathname: string
invocationPathname: string
}): ResolveRoutesResult {
const resolvedQuery = toResolvedQuery(url)
return {
...result,
resolvedPathname,
resolvedQuery,
invocationTarget: {
pathname: invocationPathname,
query: resolvedQuery,
},
}
}
/**
* Matches dynamic routes and extracts route parameters
*/
......@@ -265,30 +322,41 @@ function checkDynamicRoutes(
)
if (hasResult.matched && missingMatched) {
// Check if the destination pathname (template path) is in the provided pathnames list
// For dynamic routes, the destination contains the template path like /dynamic/[slug]
const pathnameToCheck = route.destination
const replacedDestination = route.destination
? replaceDestination(
route.destination,
match.regexMatches || null,
hasResult.captures
).split('?')[0]
)
: undefined
// Check if the destination pathname (template path) is in the provided pathnames list
// For dynamic routes, the destination contains the template path like /dynamic/[slug]
const pathnameToCheck = replacedDestination
? replacedDestination.split('?')[0]
: checkUrl.pathname
const matchedPath = matchesPathname(pathnameToCheck, pathnames)
if (matchedPath) {
const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(checkUrl, replacedDestination)
: checkUrl
const finalHeaders = applyOnMatchHeaders(
onMatchRoutes,
checkUrl,
resolvedUrl,
requestHeaders,
responseHeaders
)
return {
matched: true,
const result = withResolvedInvocationTarget({
result: {
matchedPathname: matchedPath,
routeMatches: match.params,
resolvedHeaders: finalHeaders,
},
url: resolvedUrl,
resolvedPathname: matchedPath,
invocationPathname: checkUrl.pathname,
})
return {
matched: true,
result,
resetUrl: checkUrl, // Return the denormalized URL to reset to
}
}
......@@ -580,18 +648,32 @@ export async function resolveRoutes(
)
if (hasResult.matched && missingMatched) {
const replacedDestination = route.destination
? replaceDestination(
route.destination,
match.regexMatches || null,
hasResult.captures
)
: undefined
const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination)
: currentUrl
const finalHeaders = applyOnMatchHeaders(
routes.onMatch,
currentUrl,
resolvedUrl,
currentRequestHeaders,
currentResponseHeaders
)
return {
matchedPathname: matchedPath,
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
}
return withResolvedInvocationTarget({
result: {
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: resolvedUrl,
resolvedPathname: matchedPath,
invocationPathname: currentUrl.pathname,
})
}
}
}
......@@ -603,11 +685,15 @@ export async function resolveRoutes(
currentRequestHeaders,
currentResponseHeaders
)
return {
matchedPathname: matchedPath,
resolvedHeaders: finalHeaders,
status: currentStatus,
}
return withResolvedInvocationTarget({
result: {
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: currentUrl,
resolvedPathname: matchedPath,
invocationPathname: currentUrl.pathname,
})
}
// Normalize again before processing afterFiles if this was originally a data URL
......@@ -712,11 +798,15 @@ export async function resolveRoutes(
currentRequestHeaders,
currentResponseHeaders
)
return {
matchedPathname: matchedPath,
resolvedHeaders: finalHeaders,
status: currentStatus,
}
return withResolvedInvocationTarget({
result: {
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: pathnameCheckUrl,
resolvedPathname: matchedPath,
invocationPathname: pathnameCheckUrl.pathname,
})
}
}
}
......@@ -740,29 +830,39 @@ export async function resolveRoutes(
)
if (hasResult.matched && missingMatched) {
// Check if the destination pathname (template path) is in the provided pathnames list
// For dynamic routes, the destination contains the template path like /dynamic/[slug]
const pathnameToCheck = route.destination
const replacedDestination = route.destination
? replaceDestination(
route.destination,
match.regexMatches || null,
hasResult.captures
).split('?')[0]
)
: undefined
// Check if the destination pathname (template path) is in the provided pathnames list
// For dynamic routes, the destination contains the template path like /dynamic/[slug]
const pathnameToCheck = replacedDestination
? replacedDestination.split('?')[0]
: currentUrl.pathname
matchedPath = matchesPathname(pathnameToCheck, pathnames)
if (matchedPath) {
const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination)
: currentUrl
const finalHeaders = applyOnMatchHeaders(
routes.onMatch,
currentUrl,
resolvedUrl,
currentRequestHeaders,
currentResponseHeaders
)
return {
matchedPathname: matchedPath,
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
}
return withResolvedInvocationTarget({
result: {
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: resolvedUrl,
resolvedPathname: matchedPath,
invocationPathname: currentUrl.pathname,
})
}
}
}
......@@ -865,11 +965,15 @@ export async function resolveRoutes(
currentRequestHeaders,
currentResponseHeaders
)
return {
matchedPathname: matchedPath,
resolvedHeaders: finalHeaders,
status: currentStatus,
}
return withResolvedInvocationTarget({
result: {
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: pathnameCheckUrl,
resolvedPathname: matchedPath,
invocationPathname: pathnameCheckUrl.pathname,
})
}
}
}
......
......@@ -69,6 +69,20 @@ export type ResolveRoutesParams = {
invokeMiddleware: (ctx: MiddlewareContext) => Promise<MiddlewareResult>
}
export type ResolveRoutesQueryValue = string | string[]
export type ResolveRoutesQuery = Record<string, ResolveRoutesQueryValue>
export type RouteInvocationTarget = {
/**
* Concrete pathname that should be invoked after routing resolution.
*/
pathname: string
/**
* Concrete query that should be invoked after routing resolution.
*/
query: ResolveRoutesQuery
}
export type ResolveRoutesResult = {
middlewareResponded?: boolean
externalRewrite?: URL
......@@ -76,7 +90,19 @@ export type ResolveRoutesResult = {
url: URL
status: number
}
matchedPathname?: string
/**
* Resolved pathname selected by route matching. For dynamic routes this is
* the matched template pathname.
*/
resolvedPathname?: string
/**
* Merged query produced by rewrite/middleware routing.
*/
resolvedQuery?: ResolveRoutesQuery
/**
* Concrete invocation target to use when invoking the resolved route/module.
*/
invocationTarget?: RouteInvocationTarget
resolvedHeaders?: Headers
status?: number
routeMatches?: Record<string, string>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment