Commit 174a25ee authored by Jimmy Lai's avatar Jimmy Lai

Fix export fallback route selection

parent a4214204
...@@ -30,8 +30,8 @@ import { getDeploymentId } from '../shared/lib/deployment-id' ...@@ -30,8 +30,8 @@ import { getDeploymentId } from '../shared/lib/deployment-id'
import { setNavigationBuildId } from './navigation-build-id' import { setNavigationBuildId } from './navigation-build-id'
import { import {
addOutputExportDataSuffix, addOutputExportDataSuffix,
fetchOutputExportDataResponse,
fetchOutputExportFallbackResponse, fetchOutputExportFallbackResponse,
fetchOutputExportNotFoundDataResponse,
} from './output-export-fallback' } from './output-export-fallback'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -303,12 +303,9 @@ if (instantTestStaticFetch) { ...@@ -303,12 +303,9 @@ if (instantTestStaticFetch) {
} }
const response = const response =
(await fetchOutputExportDataResponse( (await fetchOutputExportNotFoundDataResponse(renderedUrl, {
new URL('/_not-found', renderedUrl), credentials: 'same-origin',
{ })) ??
credentials: 'same-origin',
}
)) ??
(await fetch( (await fetch(
addOutputExportDataSuffix(new URL('/_not-found', renderedUrl)), addOutputExportDataSuffix(new URL('/_not-found', renderedUrl)),
{ {
......
...@@ -3,9 +3,11 @@ import { ...@@ -3,9 +3,11 @@ import {
clearOutputExportFallbackManifestCache, clearOutputExportFallbackManifestCache,
fetchOutputExportDataResponse, fetchOutputExportDataResponse,
fetchOutputExportFallbackResponse, fetchOutputExportFallbackResponse,
fetchOutputExportNotFoundDataResponse,
getCachedOutputExportFallbackDataUrl, getCachedOutputExportFallbackDataUrl,
getCachedOutputExportFallbackRequestUrl, getCachedOutputExportFallbackRequestUrl,
getOutputExportFallbackCandidates, getOutputExportFallbackCandidates,
getOutputExportNotFoundCandidates,
stripOutputExportDataSuffix, stripOutputExportDataSuffix,
} from './output-export-fallback' } from './output-export-fallback'
...@@ -20,12 +22,12 @@ describe('output export fallback helpers', () => { ...@@ -20,12 +22,12 @@ describe('output export fallback helpers', () => {
jest.restoreAllMocks() jest.restoreAllMocks()
}) })
it('discovers fallback candidates from shallowest static prefix to root', () => { it('discovers fallback candidates from deepest static prefix to root', () => {
expect(getOutputExportFallbackCandidates('/org/acme/chat/123')).toEqual([ expect(getOutputExportFallbackCandidates('/org/acme/chat/123')).toEqual([
'/org/__fallback',
'/org/acme/__fallback',
'/org/acme/chat/__fallback',
'/org/acme/chat/123/__fallback', '/org/acme/chat/123/__fallback',
'/org/acme/chat/__fallback',
'/org/acme/__fallback',
'/org/__fallback',
'/__fallback', '/__fallback',
]) ])
}) })
...@@ -37,6 +39,15 @@ describe('output export fallback helpers', () => { ...@@ -37,6 +39,15 @@ describe('output export fallback helpers', () => {
]) ])
}) })
it('discovers not-found candidates from deepest static prefix to root', () => {
expect(getOutputExportNotFoundCandidates('/docs/missing/route')).toEqual([
'/docs/missing/route/_not-found',
'/docs/missing/_not-found',
'/docs/_not-found',
'/_not-found',
])
})
it('adds the export data suffix for flat and trailing slash routes', () => { it('adds the export data suffix for flat and trailing slash routes', () => {
expect( expect(
addOutputExportDataSuffix(new URL('https://example.com/blog/post')).href addOutputExportDataSuffix(new URL('https://example.com/blog/post')).href
...@@ -93,13 +104,27 @@ describe('output export fallback helpers', () => { ...@@ -93,13 +104,27 @@ describe('output export fallback helpers', () => {
]) ])
}) })
it('tries the direct fallback artifact before manifest lookups', async () => { it('falls through deeper prefixes before using a shallower direct fallback artifact', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false' process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
if (url.endsWith('/org/__fallback.txt')) { if (url.endsWith('/docs/guides/export/__fallback.txt')) {
return new Response('payload', { return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
}
if (url.endsWith('/docs/guides/export/__fallback.meta.json')) {
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
}
if (url.endsWith('/docs/guides/__fallback.txt')) {
return new Response('specific payload', {
status: 200, status: 200,
headers: { 'content-type': 'text/plain' }, headers: { 'content-type': 'text/plain' },
}) })
...@@ -113,13 +138,16 @@ describe('output export fallback helpers', () => { ...@@ -113,13 +138,16 @@ describe('output export fallback helpers', () => {
global.fetch = fetchMock as typeof fetch global.fetch = fetchMock as typeof fetch
const renderedUrl = new URL('https://example.com/org/acme/chat/123') const renderedUrl = new URL('https://example.com/docs/guides/export')
const result = await fetchOutputExportFallbackResponse(renderedUrl) const result = await fetchOutputExportFallbackResponse(renderedUrl)
expect(result).not.toBeNull() expect(result).not.toBeNull()
expect(result?.renderedUrl.href).toBe(renderedUrl.href) expect(result?.renderedUrl.href).toBe(renderedUrl.href)
expect(result?.fallbackUrl.pathname).toBe('/docs/guides/__fallback')
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/org/__fallback.txt', 'https://example.com/docs/guides/export/__fallback.txt',
'https://example.com/docs/guides/export/__fallback.meta.json',
'https://example.com/docs/guides/__fallback.txt',
]) ])
}) })
...@@ -129,7 +157,7 @@ describe('output export fallback helpers', () => { ...@@ -129,7 +157,7 @@ describe('output export fallback helpers', () => {
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
if (url.endsWith('/org/__fallback/index.txt')) { if (url.endsWith('/optional/__fallback/index.txt')) {
return new Response('flight', { return new Response('flight', {
status: 200, status: 200,
headers: { 'content-type': 'text/x-component' }, headers: { 'content-type': 'text/x-component' },
...@@ -144,15 +172,13 @@ describe('output export fallback helpers', () => { ...@@ -144,15 +172,13 @@ describe('output export fallback helpers', () => {
global.fetch = fetchMock as typeof fetch global.fetch = fetchMock as typeof fetch
const renderedUrl = new URL( const renderedUrl = new URL('https://example.com/optional/')
'https://example.com/org/umbrella/chat/thread-789/'
)
const result = await fetchOutputExportFallbackResponse(renderedUrl) const result = await fetchOutputExportFallbackResponse(renderedUrl)
expect(result).not.toBeNull() expect(result).not.toBeNull()
expect(result?.renderedUrl.href).toBe(renderedUrl.href) expect(result?.renderedUrl.href).toBe(renderedUrl.href)
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/org/__fallback/index.txt', 'https://example.com/optional/__fallback/index.txt',
]) ])
}) })
...@@ -210,11 +236,17 @@ describe('output export fallback helpers', () => { ...@@ -210,11 +236,17 @@ describe('output export fallback helpers', () => {
expect(result).not.toBeNull() expect(result).not.toBeNull()
expect(result?.fallbackUrl.pathname).toBe('/docs/__fallback/__route_0') expect(result?.fallbackUrl.pathname).toBe('/docs/__fallback/__route_0')
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ const requestedUrls = fetchMock.mock.calls.map(([url]) => String(url))
'https://example.com/docs/__fallback.txt', expect(requestedUrls).toContain('https://example.com/docs/__fallback.txt')
'https://example.com/docs/__fallback.meta.json', expect(requestedUrls).toContain(
'https://example.com/docs/__fallback/__route_0.txt', 'https://example.com/docs/__fallback.meta.json'
]) )
expect(requestedUrls).toContain(
'https://example.com/docs/__fallback/__route_0.txt'
)
expect(requestedUrls).not.toContain(
'https://example.com/docs/__fallback/__route_1.txt'
)
}) })
it('caches the resolved fallback data URL for later RSC fetches', async () => { it('caches the resolved fallback data URL for later RSC fetches', async () => {
...@@ -340,10 +372,50 @@ describe('output export fallback helpers', () => { ...@@ -340,10 +372,50 @@ describe('output export fallback helpers', () => {
new URL('https://example.com/docs/api/guide') new URL('https://example.com/docs/api/guide')
) )
const requestedUrls = fetchMock.mock.calls.map(([url]) => String(url))
expect(
requestedUrls.filter(
(url) => url === 'https://example.com/docs/__fallback.meta.json'
)
).toHaveLength(1)
expect(
requestedUrls.filter(
(url) => url === 'https://example.com/docs/__fallback/__route_0.txt'
)
).toHaveLength(1)
})
it('tries subpath-prefixed not-found payloads before falling back to root', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input)
if (url.endsWith('/docs/_not-found.txt')) {
return new Response('not found payload', {
status: 200,
headers: { 'content-type': 'text/plain' },
})
}
return new Response('<!doctype html><title>fallback</title>', {
status: 200,
headers: { 'content-type': 'text/html' },
})
})
global.fetch = fetchMock as typeof fetch
const response = await fetchOutputExportNotFoundDataResponse(
new URL('https://example.com/docs/missing/route')
)
expect(response).not.toBeNull()
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/__fallback.txt', 'https://example.com/docs/missing/route/_not-found.txt',
'https://example.com/docs/__fallback.meta.json', 'https://example.com/docs/missing/route/_not-found/index.txt',
'https://example.com/docs/__fallback/__route_0.txt', 'https://example.com/docs/missing/_not-found.txt',
'https://example.com/docs/missing/_not-found/index.txt',
'https://example.com/docs/_not-found.txt',
]) ])
}) })
}) })
...@@ -26,6 +26,19 @@ type OutputExportCachedResponse = { ...@@ -26,6 +26,19 @@ type OutputExportCachedResponse = {
statusText: string statusText: string
} }
function getOutputExportCandidatePrefixes(pathname: string): string[] {
const segments = pathname.split('/').filter(Boolean)
const candidates: string[] = []
for (let i = segments.length; i >= 1; i--) {
candidates.push(segments.slice(0, i).join('/'))
}
candidates.push('')
return candidates
}
function getOutputExportFallbackCacheStore(): OutputExportFallbackCacheStore { function getOutputExportFallbackCacheStore(): OutputExportFallbackCacheStore {
const globalWithCache = globalThis as typeof globalThis & { const globalWithCache = globalThis as typeof globalThis & {
__NEXT_OUTPUT_EXPORT_FALLBACK_CACHE_STORE?: OutputExportFallbackCacheStore __NEXT_OUTPUT_EXPORT_FALLBACK_CACHE_STORE?: OutputExportFallbackCacheStore
...@@ -49,17 +62,19 @@ function getOutputExportFallbackCacheStore(): OutputExportFallbackCacheStore { ...@@ -49,17 +62,19 @@ function getOutputExportFallbackCacheStore(): OutputExportFallbackCacheStore {
} }
export function getOutputExportFallbackCandidates(pathname: string): string[] { export function getOutputExportFallbackCandidates(pathname: string): string[] {
const segments = pathname.split('/').filter(Boolean) return getOutputExportCandidatePrefixes(pathname).map((prefix) =>
const candidates: string[] = [] getOutputExportFallbackPath(prefix)
)
for (let i = 1; i <= segments.length; i++) { }
const prefix = segments.slice(0, i).join('/')
candidates.push(getOutputExportFallbackPath(prefix))
}
candidates.push(getOutputExportFallbackPath('')) function getOutputExportNotFoundPath(prefix: string): string {
return prefix.length > 0 ? `/${prefix}/_not-found` : '/_not-found'
}
return candidates export function getOutputExportNotFoundCandidates(pathname: string): string[] {
return getOutputExportCandidatePrefixes(pathname).map((prefix) =>
getOutputExportNotFoundPath(prefix)
)
} }
export function addOutputExportDataSuffix(url: URL): URL { export function addOutputExportDataSuffix(url: URL): URL {
...@@ -323,6 +338,25 @@ export async function fetchOutputExportDataResponse( ...@@ -323,6 +338,25 @@ export async function fetchOutputExportDataResponse(
return result?.response ?? null return result?.response ?? null
} }
export async function fetchOutputExportNotFoundDataResponse(
renderedUrl: URL,
init?: RequestInit
): Promise<Response | null> {
for (const candidate of getOutputExportNotFoundCandidates(
renderedUrl.pathname
)) {
const candidateUrl = new URL(renderedUrl)
candidateUrl.pathname = candidate
const response = await fetchOutputExportDataResponse(candidateUrl, init)
if (response !== null) {
return response
}
}
return null
}
export async function fetchOutputExportFallbackResponse( export async function fetchOutputExportFallbackResponse(
renderedUrl: URL, renderedUrl: URL,
init?: RequestInit init?: RequestInit
......
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