Commit c0fc33f6 authored by Jimmy Lai's avatar Jimmy Lai

Fix output export fallback prefetching

parent dedd4acb
/**
* @jest-environment node
*/
import type { NavigationFlightResponse } from '../../../shared/lib/app-router-types'
import { setNavigationBuildId } from '../../navigation-build-id'
import { fetchServerResponse } from './fetch-server-response'
const mockCreateFromReadableStream = jest.fn()
const mockFetchOutputExportFallbackResponse = jest.fn()
const mockGetCachedOutputExportFallbackRequestUrl = jest.fn()
jest.mock('react-server-dom-webpack/client', () => ({
createFromFetch: jest.fn(),
createFromReadableStream: (...args: Array<unknown>) =>
mockCreateFromReadableStream(...args),
}))
jest.mock('../../output-export-fallback', () => ({
fetchOutputExportFallbackResponse: (...args: Array<unknown>) =>
mockFetchOutputExportFallbackResponse(...args),
getCachedOutputExportFallbackRequestUrl: (...args: Array<unknown>) =>
mockGetCachedOutputExportFallbackRequestUrl(...args),
}))
function withResponseUrl(response: Response, url: string): Response {
Object.defineProperty(response, 'url', { value: url })
Object.defineProperty(response, 'redirected', { value: false })
return response
}
describe('fetchServerResponse output export fallback', () => {
const originalNodeEnv = process.env.NODE_ENV
const originalOutput = process.env.__NEXT_CONFIG_OUTPUT
const originalFetch = global.fetch
const originalLocation = global.location
beforeEach(() => {
process.env.NODE_ENV = 'production'
process.env.__NEXT_CONFIG_OUTPUT = 'export'
global.location = new URL('https://example.com/') as Location
setNavigationBuildId('build-id')
mockCreateFromReadableStream.mockReset()
mockFetchOutputExportFallbackResponse.mockReset()
mockGetCachedOutputExportFallbackRequestUrl.mockReset()
mockGetCachedOutputExportFallbackRequestUrl.mockReturnValue(null)
})
afterEach(() => {
process.env.NODE_ENV = originalNodeEnv
process.env.__NEXT_CONFIG_OUTPUT = originalOutput
global.fetch = originalFetch
global.location = originalLocation
jest.restoreAllMocks()
})
it('reuses the discovered fallback response instead of fetching it again', async () => {
const origin = global.location.origin
const initialMiss = withResponseUrl(
new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
}),
`${origin}/another/third.txt`
)
const fallbackResponse = withResponseUrl(
new Response('fallback payload', {
status: 200,
headers: { 'content-type': 'text/plain' },
}),
`${origin}/another/__fallback/index.txt`
)
global.fetch = jest
.fn<typeof fetch>()
.mockResolvedValueOnce(initialMiss)
.mockImplementation(async () => {
throw new Error('unexpected extra fetch')
})
mockFetchOutputExportFallbackResponse.mockResolvedValue({
response: fallbackResponse,
renderedUrl: new URL('/another/third', origin),
fallbackUrl: new URL('/another/__fallback', origin),
})
mockCreateFromReadableStream.mockResolvedValue({
b: 'build-id',
f: [
[
'children',
'another',
'children',
['slug', '%%drp:slug:abc123%%', 'd', null],
[
'',
{
children: [
'another',
{
children: [['slug', '%%drp:slug:abc123%%', 'd', null], {}],
},
],
},
],
null,
null,
false,
],
],
S: false,
q: '',
i: false,
h: null,
} satisfies NavigationFlightResponse)
const result = await fetchServerResponse(
new URL('/another/third', origin),
{
flightRouterState: ['', {}, null, null],
nextUrl: null,
}
)
expect(typeof result).not.toBe('string')
if (typeof result !== 'string') {
expect(result.canonicalUrl.href).toBe(`${origin}/another/third`)
}
expect(global.fetch).toHaveBeenCalledTimes(1)
expect(mockFetchOutputExportFallbackResponse).toHaveBeenCalledTimes(1)
})
})
...@@ -38,7 +38,10 @@ import { ...@@ -38,7 +38,10 @@ import {
} from '../../flight-data-helpers' } from '../../flight-data-helpers'
import { setCacheBustingSearchParam } from './set-cache-busting-search-param' import { setCacheBustingSearchParam } from './set-cache-busting-search-param'
import { urlToUrlWithoutFlightMarker } from '../../route-params' import { urlToUrlWithoutFlightMarker } from '../../route-params'
import { fetchOutputExportFallbackResponse } from '../../output-export-fallback' import {
fetchOutputExportFallbackResponse,
getCachedOutputExportFallbackRequestUrl,
} from '../../output-export-fallback'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
import { getDeploymentId } from '../../../shared/lib/deployment-id' import { getDeploymentId } from '../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../navigation-build-id' import { getNavigationBuildId } from '../../navigation-build-id'
...@@ -168,6 +171,7 @@ export async function fetchServerResponse( ...@@ -168,6 +171,7 @@ export async function fetchServerResponse(
const originalUrl = url const originalUrl = url
try { try {
let usedCachedOutputExportFallback = false
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') { if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
// In "output: export" mode, we can't rely on headers to distinguish // In "output: export" mode, we can't rely on headers to distinguish
...@@ -179,6 +183,10 @@ export async function fetchServerResponse( ...@@ -179,6 +183,10 @@ export async function fetchServerResponse(
} else { } else {
url.pathname += '.txt' url.pathname += '.txt'
} }
if (getCachedOutputExportFallbackRequestUrl(url) !== null) {
usedCachedOutputExportFallback = true
}
} }
} }
...@@ -236,17 +244,19 @@ export async function fetchServerResponse( ...@@ -236,17 +244,19 @@ export async function fetchServerResponse(
if (fallbackResult !== null) { if (fallbackResult !== null) {
usedOutputExportFallback = true usedOutputExportFallback = true
const fallbackFetch = await createFetch<NavigationFlightResponse>( const { response: processed, cacheData } = await processFetch(
new URL(fallbackResult.response.url), fallbackResult.response
headers,
'auto',
false
) )
res = { res = {
...fallbackFetch, ok: processed.ok,
redirected: false, redirected: false,
headers: processed.headers,
body: processed.body,
status: processed.status,
url: originalUrl.href, url: originalUrl.href,
flightResponsePromise: null,
cacheData: Promise.resolve(cacheData),
} }
responseUrl = originalUrl responseUrl = originalUrl
canonicalUrl = originalUrl canonicalUrl = originalUrl
...@@ -314,7 +324,7 @@ export async function fetchServerResponse( ...@@ -314,7 +324,7 @@ export async function fetchServerResponse(
} }
const normalizedFlightData = normalizeFlightData( const normalizedFlightData = normalizeFlightData(
usedOutputExportFallback usedOutputExportFallback || usedCachedOutputExportFallback
? fillInFallbackFlightData( ? fillInFallbackFlightData(
flightResponse.f, flightResponse.f,
originalUrl.pathname, originalUrl.pathname,
...@@ -584,6 +594,12 @@ export async function createFetch<T>( ...@@ -584,6 +594,12 @@ export async function createFetch<T>(
// search param to it. This should not leak outside of this function, so we // search param to it. This should not leak outside of this function, so we
// track them separately. // track them separately.
let fetchUrl = new URL(url) let fetchUrl = new URL(url)
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
const fallbackRequestUrl = getCachedOutputExportFallbackRequestUrl(fetchUrl)
if (fallbackRequestUrl !== null) {
fetchUrl = fallbackRequestUrl
}
}
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
let processed = fetch(fetchUrl, fetchOptions).then(processFetch) let processed = fetch(fetchUrl, fetchOptions).then(processFetch)
let fetchPromise = processed.then(({ response }) => response) let fetchPromise = processed.then(({ response }) => response)
......
...@@ -587,6 +587,7 @@ export function matchKnownRoute( ...@@ -587,6 +587,7 @@ export function matchKnownRoute(
metadata: reifiedMetadata, metadata: reifiedMetadata,
couldBeIntercepted: pattern.couldBeIntercepted, couldBeIntercepted: pattern.couldBeIntercepted,
supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching, supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,
hasInlinedSegments: pattern.hasInlinedSegments,
hasDynamicRewrite: false, hasDynamicRewrite: false,
renderedSearch: search, renderedSearch: search,
ref: null, ref: null,
......
...@@ -709,6 +709,11 @@ function pingRootRouteTree( ...@@ -709,6 +709,11 @@ function pingRootRouteTree(
// Do not prefetch segment data until we've entered the segment phase. // Do not prefetch segment data until we've entered the segment phase.
return PrefetchTaskExitStatus.Done return PrefetchTaskExitStatus.Done
} }
if (route.hasInlinedSegments) {
// Segment data was already written into the cache during route
// fulfillment. Skip the per-segment fetch phase.
return PrefetchTaskExitStatus.Done
}
// Recursively fill in the segment tree. // Recursively fill in the segment tree.
if (!hasNetworkBandwidth(task)) { if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth. // Stop prefetching segments until there's more bandwidth.
......
import { import {
addOutputExportDataSuffix, addOutputExportDataSuffix,
clearOutputExportFallbackManifestCache,
fetchOutputExportDataResponse, fetchOutputExportDataResponse,
fetchOutputExportFallbackResponse, fetchOutputExportFallbackResponse,
getCachedOutputExportFallbackDataUrl,
getCachedOutputExportFallbackRequestUrl,
getOutputExportFallbackCandidates, getOutputExportFallbackCandidates,
stripOutputExportDataSuffix, stripOutputExportDataSuffix,
} from './output-export-fallback' } from './output-export-fallback'
...@@ -11,6 +14,7 @@ describe('output export fallback helpers', () => { ...@@ -11,6 +14,7 @@ describe('output export fallback helpers', () => {
afterEach(() => { afterEach(() => {
global.fetch = originalFetch global.fetch = originalFetch
clearOutputExportFallbackManifestCache()
jest.restoreAllMocks() jest.restoreAllMocks()
}) })
...@@ -175,4 +179,125 @@ describe('output export fallback helpers', () => { ...@@ -175,4 +179,125 @@ describe('output export fallback helpers', () => {
'https://example.com/docs/__fallback/__route_0.txt', 'https://example.com/docs/__fallback/__route_0.txt',
]) ])
}) })
it('caches the resolved fallback data URL for later RSC fetches', async () => {
const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input)
if (url.endsWith('/docs/__fallback.meta.json')) {
return new Response(
JSON.stringify({
version: 1,
routes: [
{
route: '/docs/[section]/[page]',
fallbackPath: '/docs/__fallback/__route_0',
},
],
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
}
)
}
if (url.endsWith('/docs/__fallback/__route_0.txt')) {
return new Response('payload', {
status: 200,
headers: { 'content-type': 'text/plain' },
})
}
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
})
global.fetch = fetchMock as typeof fetch
const renderedUrl = new URL('https://example.com/docs/api/reference')
await fetchOutputExportFallbackResponse(renderedUrl)
expect(
getCachedOutputExportFallbackDataUrl(
new URL('https://example.com/docs/api/reference.txt')
)?.href
).toBe('https://example.com/docs/__fallback/__route_0.txt')
expect(
getCachedOutputExportFallbackDataUrl(
new URL('https://example.com/docs/api/reference/index.txt')
)?.href
).toBe('https://example.com/docs/__fallback/__route_0.txt')
expect(
getCachedOutputExportFallbackRequestUrl(
new URL('https://example.com/docs/api/reference/__next._head.txt')
)?.href
).toBe('https://example.com/docs/__fallback/__route_0/__next._head.txt')
expect(
getCachedOutputExportFallbackRequestUrl(
new URL(
'https://example.com/docs/api/reference/__next.docs.$d$section.$d$page.txt'
)
)?.href
).toBe(
'https://example.com/docs/__fallback/__route_0/__next.docs.$d$section.$d$page.txt'
)
})
it('caches fallback metadata lookups across sibling routes', async () => {
const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input)
if (url.endsWith('/docs/__fallback.meta.json')) {
return new Response(
JSON.stringify({
version: 1,
routes: [
{
route: '/docs/[section]/[page]',
fallbackPath: '/docs/__fallback/__route_0',
},
{
route: '/docs/[...slug]',
fallbackPath: '/docs/__fallback/__route_1',
},
],
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
}
)
}
if (url.endsWith('/docs/__fallback/__route_0.txt')) {
return new Response('payload', {
status: 200,
headers: { 'content-type': 'text/plain' },
})
}
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
})
global.fetch = fetchMock as typeof fetch
await fetchOutputExportFallbackResponse(
new URL('https://example.com/docs/api/reference')
)
await fetchOutputExportFallbackResponse(
new URL('https://example.com/docs/api/guide')
)
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/__fallback.meta.json',
'https://example.com/docs/__fallback/__route_0.txt',
'https://example.com/docs/__fallback/__route_0.txt',
])
})
}) })
...@@ -7,6 +7,44 @@ import { RSC_CONTENT_TYPE_HEADER } from './components/app-router-headers' ...@@ -7,6 +7,44 @@ import { RSC_CONTENT_TYPE_HEADER } from './components/app-router-headers'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
type OutputExportFallbackManifest = {
version: 1
routes: OutputExportFallbackManifestEntry[]
}
const outputExportFallbackManifestCache = new Map<
string,
Promise<OutputExportFallbackManifest | null>
>()
function getOutputExportFallbackDataUrlCache(): Map<string, string> {
const globalWithCache = globalThis as typeof globalThis & {
__NEXT_OUTPUT_EXPORT_FALLBACK_DATA_URL_CACHE?: Map<string, string>
}
const existing = globalWithCache.__NEXT_OUTPUT_EXPORT_FALLBACK_DATA_URL_CACHE
if (existing !== undefined) {
return existing
}
const cache = new Map<string, string>()
globalWithCache.__NEXT_OUTPUT_EXPORT_FALLBACK_DATA_URL_CACHE = cache
return cache
}
function getOutputExportFallbackBasePathCache(): Map<string, string> {
const globalWithCache = globalThis as typeof globalThis & {
__NEXT_OUTPUT_EXPORT_FALLBACK_BASE_PATH_CACHE?: Map<string, string>
}
const existing = globalWithCache.__NEXT_OUTPUT_EXPORT_FALLBACK_BASE_PATH_CACHE
if (existing !== undefined) {
return existing
}
const cache = new Map<string, string>()
globalWithCache.__NEXT_OUTPUT_EXPORT_FALLBACK_BASE_PATH_CACHE = cache
return cache
}
export function getOutputExportFallbackCandidates(pathname: string): string[] { export function getOutputExportFallbackCandidates(pathname: string): string[] {
const segments = pathname.split('/').filter(Boolean) const segments = pathname.split('/').filter(Boolean)
const candidates: string[] = [] const candidates: string[] = []
...@@ -31,6 +69,20 @@ export function addOutputExportDataSuffix(url: URL): URL { ...@@ -31,6 +69,20 @@ export function addOutputExportDataSuffix(url: URL): URL {
return nextUrl return nextUrl
} }
export function isOutputExportFlightContentType(contentType: string): boolean {
return (
contentType.startsWith(RSC_CONTENT_TYPE_HEADER) ||
contentType.startsWith('text/plain') ||
contentType.startsWith('application/octet-stream')
)
}
export function clearOutputExportFallbackManifestCache(): void {
outputExportFallbackManifestCache.clear()
getOutputExportFallbackDataUrlCache().clear()
getOutputExportFallbackBasePathCache().clear()
}
export function stripOutputExportDataSuffix(url: URL): URL { export function stripOutputExportDataSuffix(url: URL): URL {
const nextUrl = new URL(url) const nextUrl = new URL(url)
if (nextUrl.pathname.endsWith('/index.txt')) { if (nextUrl.pathname.endsWith('/index.txt')) {
...@@ -58,27 +110,37 @@ function matchOutputExportFallbackManifestEntry( ...@@ -58,27 +110,37 @@ function matchOutputExportFallbackManifestEntry(
async function fetchOutputExportFallbackManifest( async function fetchOutputExportFallbackManifest(
fallbackUrl: URL, fallbackUrl: URL,
init?: RequestInit init?: RequestInit
): Promise<{ ): Promise<OutputExportFallbackManifest | null> {
version: 1 const metadataUrl = getOutputExportFallbackMetadataUrl(fallbackUrl)
routes: OutputExportFallbackManifestEntry[] const cacheKey = metadataUrl.href
} | null> { const cached = outputExportFallbackManifestCache.get(cacheKey)
const metadataResponse = await fetch( if (cached !== undefined) {
getOutputExportFallbackMetadataUrl(fallbackUrl), return cached
init
)
if (!metadataResponse.ok) {
return null
} }
const contentType = metadataResponse.headers.get('content-type') || '' const manifestPromise = fetch(metadataUrl, init)
if ( .then(async (metadataResponse) => {
!contentType.startsWith('application/json') && if (!metadataResponse.ok) {
!contentType.startsWith('text/json') return null
) { }
return null
} const contentType = metadataResponse.headers.get('content-type') || ''
if (
!contentType.startsWith('application/json') &&
!contentType.startsWith('text/json')
) {
return null
}
return metadataResponse.json() return metadataResponse.json()
})
.catch((error) => {
outputExportFallbackManifestCache.delete(cacheKey)
throw error
})
outputExportFallbackManifestCache.set(cacheKey, manifestPromise)
return manifestPromise
} }
function getOutputExportDataCandidates(url: URL): URL[] { function getOutputExportDataCandidates(url: URL): URL[] {
...@@ -95,26 +157,85 @@ function getOutputExportDataCandidates(url: URL): URL[] { ...@@ -95,26 +157,85 @@ function getOutputExportDataCandidates(url: URL): URL[] {
return [direct, trailingSlash] return [direct, trailingSlash]
} }
export async function fetchOutputExportDataResponse( function normalizeOutputExportRouteDirectory(pathname: string): string {
if (pathname === '/') {
return ''
}
return pathname.endsWith('/') ? pathname.slice(0, -1) : pathname
}
function cacheOutputExportFallbackDataUrl(
renderedUrl: URL,
fallbackUrl: URL,
resolvedDataUrl: URL
) {
const dataUrlCache = getOutputExportFallbackDataUrlCache()
for (const candidateUrl of getOutputExportDataCandidates(renderedUrl)) {
dataUrlCache.set(candidateUrl.href, resolvedDataUrl.href)
}
getOutputExportFallbackBasePathCache().set(
normalizeOutputExportRouteDirectory(renderedUrl.pathname),
normalizeOutputExportRouteDirectory(fallbackUrl.pathname)
)
}
export function getCachedOutputExportFallbackDataUrl(url: URL): URL | null {
const cached = getOutputExportFallbackDataUrlCache().get(url.href)
return cached !== undefined ? new URL(cached) : null
}
export function getCachedOutputExportFallbackRequestUrl(url: URL): URL | null {
const cachedDataUrl = getCachedOutputExportFallbackDataUrl(url)
if (cachedDataUrl !== null) {
return cachedDataUrl
}
const filename = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)
if (!filename.startsWith('__next.')) {
return null
}
const routeDirectory = normalizeOutputExportRouteDirectory(
url.pathname.slice(0, url.pathname.lastIndexOf('/')) || '/'
)
const fallbackBasePath =
getOutputExportFallbackBasePathCache().get(routeDirectory)
if (fallbackBasePath === undefined) {
return null
}
const nextUrl = new URL(url)
nextUrl.pathname = `${fallbackBasePath}/${filename}`
return nextUrl
}
async function fetchOutputExportDataResult(
renderedUrl: URL, renderedUrl: URL,
init?: RequestInit init?: RequestInit
): Promise<Response | null> { ): Promise<{ response: Response; dataUrl: URL } | null> {
for (const dataUrl of getOutputExportDataCandidates(renderedUrl)) { for (const dataUrl of getOutputExportDataCandidates(renderedUrl)) {
const response = await fetch(dataUrl, init) const response = await fetch(dataUrl, init)
const contentType = response.headers.get('content-type') || '' const contentType = response.headers.get('content-type') || ''
const isFlightResponse = if (
contentType.startsWith(RSC_CONTENT_TYPE_HEADER) || response.ok &&
contentType.startsWith('text/plain') || response.body &&
contentType.startsWith('application/octet-stream') isOutputExportFlightContentType(contentType)
) {
if (response.ok && response.body && isFlightResponse) { return { response, dataUrl }
return response
} }
} }
return null return null
} }
export async function fetchOutputExportDataResponse(
renderedUrl: URL,
init?: RequestInit
): Promise<Response | null> {
const result = await fetchOutputExportDataResult(renderedUrl, init)
return result?.response ?? null
}
export async function fetchOutputExportFallbackResponse( export async function fetchOutputExportFallbackResponse(
renderedUrl: URL, renderedUrl: URL,
init?: RequestInit init?: RequestInit
...@@ -140,13 +261,18 @@ export async function fetchOutputExportFallbackResponse( ...@@ -140,13 +261,18 @@ export async function fetchOutputExportFallbackResponse(
const branchFallbackUrl = new URL(renderedUrl) const branchFallbackUrl = new URL(renderedUrl)
branchFallbackUrl.pathname = entry.fallbackPath branchFallbackUrl.pathname = entry.fallbackPath
const response = await fetchOutputExportDataResponse( const result = await fetchOutputExportDataResult(
branchFallbackUrl, branchFallbackUrl,
init init
) )
if (response) { if (result) {
cacheOutputExportFallbackDataUrl(
renderedUrl,
branchFallbackUrl,
result.dataUrl
)
return { return {
response, response: result.response,
renderedUrl, renderedUrl,
fallbackUrl: branchFallbackUrl, fallbackUrl: branchFallbackUrl,
} }
...@@ -154,9 +280,18 @@ export async function fetchOutputExportFallbackResponse( ...@@ -154,9 +280,18 @@ export async function fetchOutputExportFallbackResponse(
} }
} }
const response = await fetchOutputExportDataResponse(candidateUrl, init) const result = await fetchOutputExportDataResult(candidateUrl, init)
if (response) { if (result) {
return { response, renderedUrl, fallbackUrl: candidateUrl } cacheOutputExportFallbackDataUrl(
renderedUrl,
candidateUrl,
result.dataUrl
)
return {
response: result.response,
renderedUrl,
fallbackUrl: candidateUrl,
}
} }
} }
......
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({ href, children, prefetch }) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch} data-accordion-link={href}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { Suspense } from 'react'
import IsolatedSlugClient from './slug-client'
export default function Page() {
return (
<main>
<Suspense fallback={<h1>Loading isolated slug...</h1>}>
<IsolatedSlugClient />
</Suspense>
</main>
)
}
'use client'
import { useParams } from 'next/navigation'
export default function IsolatedSlugClient() {
const params = useParams()
return <h1>{params.slug}</h1>
}
import { LinkAccordion } from '../components/link-accordion'
export default function Isolated() {
return (
<main>
<h1>Isolated</h1>
<ul>
<li>
<LinkAccordion href="/isolated/third" prefetch={true}>
prefetched isolated third page
</LinkAccordion>
</li>
</ul>
</main>
)
}
...@@ -2,6 +2,8 @@ import { join } from 'path' ...@@ -2,6 +2,8 @@ import { join } from 'path'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import fs from 'fs-extra' import fs from 'fs-extra'
import { buildAndStartOutputExportServer } from './utils' import { buildAndStartOutputExportServer } from './utils'
...@@ -115,6 +117,62 @@ if (skipped) { ...@@ -115,6 +117,62 @@ if (skipped) {
} }
}) })
it('prefetches fallback payloads for unknown-param links before navigation', async () => {
let act!: ReturnType<typeof createRouterAct>
const browser = await webdriver(port, '/isolated/', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
try {
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Isolated')
})
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/isolated/third"]'
)
await toggle.click()
})
clearRequests()
await browser
.elementByCss('a[data-accordion-link="/isolated/third"]')
.click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('third')
})
const clickRequests = getRequests()
expect(
clickRequests.some((requestPath) =>
requestPath.startsWith('/isolated/__fallback.meta.json')
)
).toBe(false)
expect(
clickRequests.some((requestPath) =>
requestPath.startsWith('/isolated/__fallback/index.txt')
)
).toBe(false)
expect(
clickRequests.some((requestPath) =>
requestPath.startsWith('/isolated/third/index.txt')
)
).toBe(false)
expect(
clickRequests.some((requestPath) =>
requestPath.startsWith('/isolated/third/__next.')
)
).toBe(false)
} finally {
await browser.close()
}
})
it('renders the app not-found page when no fallback route matches', async () => { it('renders the app not-found page when no fallback route matches', async () => {
const browser = await webdriver(port, '/missing/route/') const browser = await webdriver(port, '/missing/route/')
......
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