Unverified Commit 7b614701 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Segment Cache] Add act-inspired internal router testing helper (#74668)

Adds an internal test utility for e2e testing of requests initiated by
the Next.js Router, such as prefetches and navigations. Calls the given
async function then intercepts any router requests that are initiated as
a result. It will then wait for all the requests to complete before
exiting. Inspired by the React `act` API.

I generally dislike early testing abstractions, but getting all the
details right for intercepting the requests with Playwright ended up
being non-trivial enough that I relented and extracted it to a separate
module, in the `e2e/app-dir/segment-cache` folder. I'll hold off moving
it to somewhere even more generic until it's proven to be useful.

Example:

```js
// Asserts that rendering a link results in a prefetch response that
// contains some expected substring
await act(async () => {
  await revealLink()
}, {
  includes: 'subset of linked page content'
})
```

A few goals here:

- As much as possible, avoid coupling to internal implementation
details. For example, it will check for the presence of the "rsc" header
to determine if a request was initiated by the router, but that's about
it.
- No timers, no race conditions. It works by intercepting the requests
at the Playwright network layer. There should be no long pauses when
running the tests, and if an assertion fails, it should fail quickly.
- Account for Next.js's internal bandwidth throttling. The router does
not initiate more than a fixed number of requests at a time, so every
time a request is fulfilled, it has the potential to unblock more
prefetches. So we must wait a task to check for additional requests.
This is similar to what React's `act` implementation does to account for
asynchronous rendering tasks.
parent e7b58935
...@@ -84,6 +84,7 @@ ...@@ -84,6 +84,7 @@
"@emotion/cache": "11.11.0", "@emotion/cache": "11.11.0",
"@emotion/react": "11.11.1", "@emotion/react": "11.11.1",
"@fullhuman/postcss-purgecss": "1.3.0", "@fullhuman/postcss-purgecss": "1.3.0",
"@jest/expect-utils": "29.7.0",
"@mdx-js/loader": "2.2.1", "@mdx-js/loader": "2.2.1",
"@mdx-js/react": "2.2.1", "@mdx-js/react": "2.2.1",
"@next/bundle-analyzer": "workspace:*", "@next/bundle-analyzer": "workspace:*",
...@@ -177,6 +178,7 @@ ...@@ -177,6 +178,7 @@
"is-animated": "2.0.2", "is-animated": "2.0.2",
"isomorphic-unfetch": "3.0.0", "isomorphic-unfetch": "3.0.0",
"jest": "29.7.0", "jest": "29.7.0",
"jest-diff": "29.7.0",
"jest-environment-jsdom": "29.7.0", "jest-environment-jsdom": "29.7.0",
"jest-extended": "4.0.2", "jest-extended": "4.0.2",
"jest-junit": "16.0.0", "jest-junit": "16.0.0",
......
...@@ -75,6 +75,9 @@ importers: ...@@ -75,6 +75,9 @@ importers:
'@fullhuman/postcss-purgecss': '@fullhuman/postcss-purgecss':
specifier: 1.3.0 specifier: 1.3.0
version: 1.3.0 version: 1.3.0
'@jest/expect-utils':
specifier: 29.7.0
version: 29.7.0
'@mdx-js/loader': '@mdx-js/loader':
specifier: 2.2.1 specifier: 2.2.1
version: 2.2.1(webpack@5.96.1(@swc/core@1.9.3(@swc/helpers@0.5.15))) version: 2.2.1(webpack@5.96.1(@swc/core@1.9.3(@swc/helpers@0.5.15)))
...@@ -354,6 +357,9 @@ importers: ...@@ -354,6 +357,9 @@ importers:
jest: jest:
specifier: 29.7.0 specifier: 29.7.0
version: 29.7.0(@types/node@20.17.6)(babel-plugin-macros@3.1.0) version: 29.7.0(@types/node@20.17.6)(babel-plugin-macros@3.1.0)
jest-diff:
specifier: 29.7.0
version: 29.7.0
jest-environment-jsdom: jest-environment-jsdom:
specifier: 29.7.0 specifier: 29.7.0
version: 29.7.0 version: 29.7.0
...@@ -14783,7 +14789,7 @@ packages: ...@@ -14783,7 +14789,7 @@ packages:
superagent@3.8.3: superagent@3.8.3:
resolution: {integrity: sha512-GLQtLMCoEIK4eDv6OGtkOoSMt3D+oq0y3dsxMuYuDvaNUvuT8eFBuLmfR0iYYzHC1e8hpzC6ZsxbuP6DIalMFA==} resolution: {integrity: sha512-GLQtLMCoEIK4eDv6OGtkOoSMt3D+oq0y3dsxMuYuDvaNUvuT8eFBuLmfR0iYYzHC1e8hpzC6ZsxbuP6DIalMFA==}
engines: {node: '>= 4.0'} engines: {node: '>= 4.0'}
deprecated: Please upgrade to v9.0.0+ as we have fixed a public vulnerability with formidable dependency. Note that v9.0.0+ requires Node.js v14.18.0+. See https://github.com/ladjs/superagent/pull/1800 for insight. This project is supported and maintained by the team at Forward Email @ https://forwardemail.net deprecated: Please upgrade to v7.0.2+ of superagent. We have fixed numerous issues with streams, form-data, attach(), filesystem errors not bubbling up (ENOENT on attach()), and all tests are now passing. See the releases tab for more information at <https://github.com/visionmedia/superagent/releases>.
superstruct@1.0.3: superstruct@1.0.3:
resolution: {integrity: sha512-8iTn3oSS8nRGn+C2pgXSKPI3jmpm6FExNazNpjvqS6ZUJQCej3PUXEKM8NjHBOs54ExM+LPW/FBRhymrdcCiSg==} resolution: {integrity: sha512-8iTn3oSS8nRGn+C2pgXSKPI3jmpm6FExNazNpjvqS6ZUJQCej3PUXEKM8NjHBOs54ExM+LPW/FBRhymrdcCiSg==}
import Link from 'next/link' import { LinkAccordion } from '../../components/link-accordion'
export default function FullyStaticStart() { export default function FullyStaticStart() {
return ( return (
...@@ -10,7 +10,7 @@ export default function FullyStaticStart() { ...@@ -10,7 +10,7 @@ export default function FullyStaticStart() {
</p> </p>
<ul> <ul>
<li> <li>
<Link href="/fully-static/target-page">Target</Link> <LinkAccordion href="/fully-static/target-page">Target</LinkAccordion>
</li> </li>
</ul> </ul>
</> </>
......
import Link from 'next/link' import { LinkAccordion } from '../../../components/link-accordion'
export default function FeedPage() { export default function FeedPage() {
return <Link href="/interception/photo">Go to photo</Link> return <LinkAccordion href="/interception/photo">Go to photo</LinkAccordion>
} }
import Link from 'next/link' import { LinkAccordion } from '../../components/link-accordion'
// TODO: Once the appropriate API exists/is implemented, configure the param to // TODO: Once the appropriate API exists/is implemented, configure the param to
// be statically generated on demand but not at build time (`dynamicParams = // be statically generated on demand but not at build time (`dynamicParams =
...@@ -14,7 +14,9 @@ export default function LazilyGeneratedParamsStartPage() { ...@@ -14,7 +14,9 @@ export default function LazilyGeneratedParamsStartPage() {
</p> </p>
<ul> <ul>
<li> <li>
<Link href="/lazily-generated-params/some-param-value">Target</Link> <LinkAccordion href="/lazily-generated-params/some-param-value">
Target
</LinkAccordion>
</li> </li>
</ul> </ul>
</> </>
......
import Link from 'next/link' import { LinkAccordion } from '../components/link-accordion'
export default function Page() { export default function Page() {
return <Link href="/test">Go to test page</Link> return <LinkAccordion href="/test">Go to test page</LinkAccordion>
} }
import Link from 'next/link' import { LinkAccordion } from '../../components/link-accordion'
export default function FullyStaticStart() { export default function FullyStaticStart() {
return ( return (
...@@ -9,7 +9,9 @@ export default function FullyStaticStart() { ...@@ -9,7 +9,9 @@ export default function FullyStaticStart() {
</p> </p>
<ul> <ul>
<li> <li>
<Link href="/partially-static/target-page">Target</Link> <LinkAccordion href="/partially-static/target-page">
Target
</LinkAccordion>
</li> </li>
</ul> </ul>
</> </>
......
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({ href, children }) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache (incremental opt in)', () => { describe('segment cache (incremental opt in)', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -22,12 +23,23 @@ describe('segment cache (incremental opt in)', () => { ...@@ -22,12 +23,23 @@ describe('segment cache (incremental opt in)', () => {
const prefetches = new Map() const prefetches = new Map()
const duplicatePrefetches = new Map() const duplicatePrefetches = new Map()
const interceptor = createRequestInterceptor() let act
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) { async beforePageLoad(page: Playwright.Page) {
page.route('**/*', async (route: Playwright.Route) => { act = createRouterAct(page)
const prefetchInfo = await interceptor.checkPrefetch(route) await page.route('**/*', async (route: Playwright.Route) => {
if (prefetchInfo) { const request = route.request()
const isPrefetch =
request.headerValue('rsc') !== null &&
request.headerValue('next-router-prefetch') !== null
if (isPrefetch) {
const request = route.request()
const headers = await request.allHeaders()
const prefetchInfo = {
href: new URL(request.url()).pathname,
segment: headers['Next-Router-Segment-Prefetch'.toLowerCase()],
base: headers['Next-Router-State-Tree'.toLowerCase()] ?? null,
}
const key = JSON.stringify(prefetchInfo) const key = JSON.stringify(prefetchInfo)
if (prefetches.has(key)) { if (prefetches.has(key)) {
duplicatePrefetches.set(key, prefetchInfo) duplicatePrefetches.set(key, prefetchInfo)
...@@ -35,10 +47,11 @@ describe('segment cache (incremental opt in)', () => { ...@@ -35,10 +47,11 @@ describe('segment cache (incremental opt in)', () => {
prefetches.set(key, prefetchInfo) prefetches.set(key, prefetchInfo)
} }
} }
await interceptor.interceptRoute(page, route) route.continue()
}) })
}, },
}) })
// Each link on the test page has a checkbox that controls its visibility. // Each link on the test page has a checkbox that controls its visibility.
// It starts off as hidden. // It starts off as hidden.
const checkbox = await browser.elementByCss( const checkbox = await browser.elementByCss(
...@@ -48,7 +61,7 @@ describe('segment cache (incremental opt in)', () => { ...@@ -48,7 +61,7 @@ describe('segment cache (incremental opt in)', () => {
expect(await checkbox.isChecked()).toBe(false) expect(await checkbox.isChecked()).toBe(false)
// Click the checkbox to reveal the link and trigger a prefetch // Click the checkbox to reveal the link and trigger a prefetch
await interceptor.waitForPrefetches(async () => { await act(async () => {
await checkbox.click() await checkbox.click()
await browser.elementByCss(`a[href="${linkHref}"]`) await browser.elementByCss(`a[href="${linkHref}"]`)
}) })
...@@ -67,6 +80,7 @@ describe('segment cache (incremental opt in)', () => { ...@@ -67,6 +80,7 @@ describe('segment cache (incremental opt in)', () => {
expect(new URL(await browser.url()).pathname).toBe(linkHref) expect(new URL(await browser.url()).pathname).toBe(linkHref)
// Finally, assert there were no duplicate prefetches // Finally, assert there were no duplicate prefetches
expect(prefetches.size).not.toBe(0)
expect(duplicatePrefetches.size).toBe(0) expect(duplicatePrefetches.size).toBe(0)
} }
...@@ -79,117 +93,3 @@ describe('segment cache (incremental opt in)', () => { ...@@ -79,117 +93,3 @@ describe('segment cache (incremental opt in)', () => {
testPrefetchDeduping('/ppr-disabled-with-loading-boundary')) testPrefetchDeduping('/ppr-disabled-with-loading-boundary'))
}) })
}) })
function createRequestInterceptor() {
// Test utility for intercepting internal RSC requests so we can control the
// timing of when they resolve. We want to avoid relying on internals and
// implementation details as much as possible, so the only thing this does
// for now is let you block and release requests from happening based on
// their type (prefetch requests, navigation requests).
let prefetchesPromise: PromiseWithResolvers<void> = null
let lastPrefetchRequest: Playwright.Request | null = null
async function checkPrefetch(route: Playwright.Route): Promise<{
href: string
segment: string | null
base: string | null
} | null> {
const request = route.request()
const requestHeaders = await request.allHeaders()
if (
requestHeaders['RSC'.toLowerCase()] &&
requestHeaders['Next-Router-Prefetch'.toLowerCase()]
) {
return {
href: new URL(request.url()).pathname,
segment: requestHeaders['Next-Router-Segment-Prefetch'.toLowerCase()],
base: requestHeaders['Next-Router-State-Tree'.toLowerCase()] ?? null,
}
}
return null
}
return {
checkPrefetch,
/**
* Waits for the next for the next prefetch request, then keeps waiting
* until the prefetch queue is empty (to account for network throttling).
*
* If no prefetches are initiated, this will timeout.
*/
async waitForPrefetches<T>(
scope: () => Promise<T> | T = (): undefined => {}
): Promise<T> {
if (prefetchesPromise === null) {
let resolve
let reject
const promise: Promise<void> = new Promise((res, rej) => {
resolve = res
reject = rej
})
prefetchesPromise = {
resolve,
reject,
promise,
}
}
const result = await scope()
if (prefetchesPromise !== null) {
await prefetchesPromise.promise
}
return result
},
async interceptRoute(page: Playwright.Page, route: Playwright.Route) {
const request = route.request()
const requestHeaders = await request.allHeaders()
if (requestHeaders['RSC'.toLowerCase()]) {
// This is an RSC request. Check if it's a prefetch or a navigation.
if (requestHeaders['Next-Router-Prefetch'.toLowerCase()]) {
// This is a prefetch request.
if (prefetchesPromise !== null) {
// Wait for the prefetch response to finish, then wait an additional
// async task for additional prefetches to be initiated.
lastPrefetchRequest = request
const waitForMorePrefetches = async () => {
const inBrowserResponse = await request.response()
await inBrowserResponse.finished()
await page.evaluate(
() =>
// If the prefetch queue is network throttled, the next
// request should be issued within a microtask of the previous
// one finishing.
new Promise<void>((res) => requestIdleCallback(() => res()))
)
if (request === lastPrefetchRequest) {
// No further prefetches were initiated. Assume the prefetch
// queue is now empty.
prefetchesPromise.resolve()
prefetchesPromise = null
lastPrefetchRequest = null
}
}
const response = await page.request.fetch(route.request())
const responseText = await response.text()
await route.fulfill({
body: responseText,
headers: response.headers(),
})
waitForMorePrefetches().then(
() => {},
() => {}
)
return
}
} else {
// This is a navigation request.
}
}
await route.continue()
},
}
}
export default async function Page() { import { Suspense } from 'react'
// Render a large string such that a prefetch of this segment is roughly 1MB
// over the network type Params = { step: string }
return <div id="memory-pressure-step-page">{'a'.repeat(1024 * 1024)}</div>
async function Content({ params }: { params: Promise<Params> }) {
const { step } = await params
return (
<div id="memory-pressure-step-page">
<h1>{`Page ${step}.`}</h1>
{/* Render a large string such that a prefetch of this segment is roughly
1MB over the network */}
<p>{'a'.repeat(1024 * 1024)}</p>
</div>
)
}
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<Suspense fallback="Loading...">
<Content params={params} />
</Suspense>
)
} }
export async function generateStaticParams() { export async function generateStaticParams(): Promise<Array<Params>> {
// Generate some number of steps. This should be just enough to trigger the // Generate some number of steps. This should be just enough to trigger the
// default LRU limit used by the client prefetch cache. // default LRU limit used by the client prefetch cache.
// TODO: Once we add a config option to set the prefetch limit, we can set a // TODO: Once we add a config option to set the prefetch limit, we can set a
// smaller number, to speed up testing iteration (and CI). // smaller number, to speed up testing iteration (and CI).
const result = [] const result: Array<Params> = []
for (let i = 0; i < 60; i++) { for (let i = 0; i < 60; i++) {
result.push({ step: i.toString() }) result.push({ step: i.toString() })
} }
......
...@@ -3,6 +3,10 @@ import Link from 'next/link' ...@@ -3,6 +3,10 @@ import Link from 'next/link'
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
function Tab0() {
return 'Intentionally empty'
}
function Tab1() { function Tab1() {
return <Link href="/memory-pressure/0">Link 0</Link> return <Link href="/memory-pressure/0">Link 0</Link>
} }
...@@ -17,12 +21,28 @@ function Tab2() { ...@@ -17,12 +21,28 @@ function Tab2() {
export default function MemoryPressure() { export default function MemoryPressure() {
const router = useRouter() const router = useRouter()
const [selectedTab, setSelectedTab] = useState('1') const [selectedTab, setSelectedTab] = useState('0')
const handlePageChange = (event: React.ChangeEvent<HTMLInputElement>) => { const handlePageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedTab(event.target.value) setSelectedTab(event.target.value)
} }
let tab
switch (selectedTab) {
case '0':
tab = <Tab0 />
break
case '1':
tab = <Tab1 />
break
case '2':
tab = <Tab2 />
break
default:
tab = null
break
}
return ( return (
<form> <form>
<h1>Memory pressure</h1> <h1>Memory pressure</h1>
...@@ -55,6 +75,18 @@ export default function MemoryPressure() { ...@@ -55,6 +75,18 @@ export default function MemoryPressure() {
Navigate to link 0 Navigate to link 0
</button> </button>
</div> </div>
<div>
<label>
<input
type="radio"
value="0"
checked={selectedTab === '0'}
onChange={handlePageChange}
name="tabSelection"
/>
Tab 0
</label>
</div>
<div> <div>
<label> <label>
<input <input
...@@ -64,7 +96,7 @@ export default function MemoryPressure() { ...@@ -64,7 +96,7 @@ export default function MemoryPressure() {
onChange={handlePageChange} onChange={handlePageChange}
name="tabSelection" name="tabSelection"
/> />
Page 1 Tab 1
</label> </label>
</div> </div>
<div> <div>
...@@ -76,10 +108,10 @@ export default function MemoryPressure() { ...@@ -76,10 +108,10 @@ export default function MemoryPressure() {
onChange={handlePageChange} onChange={handlePageChange}
name="tabSelection" name="tabSelection"
/> />
Page 2 Tab 2
</label> </label>
</div> </div>
<div>{selectedTab === '1' ? <Tab1 /> : <Tab2 />}</div> <div>{tab}</div>
</form> </form>
) )
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache memory pressure', () => { describe('segment cache memory pressure', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -12,18 +13,12 @@ describe('segment cache memory pressure', () => { ...@@ -12,18 +13,12 @@ describe('segment cache memory pressure', () => {
} }
it('evicts least recently used prefetch data once cache size exceeds limit', async () => { it('evicts least recently used prefetch data once cache size exceeds limit', async () => {
const interceptor = createRequestInterceptor() let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/memory-pressure', {
// Loading the page triggers a prefetch of the first link. beforePageLoad(page: Playwright.Page) {
const browser = await interceptor.waitForPrefetches(() => act = createRouterAct(page)
next.browser('/memory-pressure', { },
beforePageLoad(page: Playwright.Page) { })
page.route('**/*', async (route: Playwright.Route) => {
await interceptor.interceptRoute(page, route)
})
},
})
)
const switchToTab1 = await browser.elementByCss( const switchToTab1 = await browser.elementByCss(
'input[type="radio"][value="1"]' 'input[type="radio"][value="1"]'
...@@ -32,149 +27,32 @@ describe('segment cache memory pressure', () => { ...@@ -32,149 +27,32 @@ describe('segment cache memory pressure', () => {
'input[type="radio"][value="2"]' 'input[type="radio"][value="2"]'
) )
// Switch to tab 1 to kick off a prefetch for a link to Page 0.
await act(
async () => {
await switchToTab1.click()
},
{ includes: 'Page 0.' }
)
// Switching to tab 2 causes the cache to overflow, evicting the prefetch // Switching to tab 2 causes the cache to overflow, evicting the prefetch
// for the link on tab 1. // for the Page 0 link.
await interceptor.waitForPrefetches(async () => { await act(
await switchToTab2.click() async () => {
}) await switchToTab2.click()
},
{ includes: 'Page 1.' }
)
// Switching back to tab 1 initiates a new prefetch for the first link. // Switching back to tab 1 initiates a new prefetch for Page 0. If
// Otherwise, this will timeout. // there are no requests, that means the prefetch was not evicted correctly.
await interceptor.waitForPrefetches(async () => { await act(
await switchToTab1.click() async () => {
}) await switchToTab1.click()
},
{
includes: 'Page 0.',
}
)
}) })
}) })
function createRequestInterceptor() {
// Test utility for intercepting internal RSC requests so we can control the
// timing of when they resolve. We want to avoid relying on internals and
// implementation details as much as possible, so the only thing this does
// for now is let you block and release requests from happening based on
// their type (prefetch requests, navigation requests).
let pendingPrefetches: Set<Playwright.Route> | null = null
let pendingNavigations: Set<Playwright.Route> | null = null
let prefetchesPromise: PromiseWithResolvers<void> = null
let lastPrefetchRequest: Playwright.Request | null = null
return {
lockNavigations() {
if (pendingNavigations !== null) {
throw new Error('Navigations are already locked')
}
pendingNavigations = new Set()
return {
async release() {
if (pendingNavigations === null) {
throw new Error('This lock was already released')
}
const routes = pendingNavigations
pendingNavigations = null
for (const route of routes) {
route.continue()
}
},
}
},
lockPrefetches() {
if (pendingPrefetches !== null) {
throw new Error('Prefetches are already locked')
}
pendingPrefetches = new Set()
return {
release() {
if (pendingPrefetches === null) {
throw new Error('This lock was already released')
}
const routes = pendingPrefetches
pendingPrefetches = null
for (const route of routes) {
route.continue()
}
},
}
},
/**
* Waits for the next for the next prefetch request, then keeps waiting
* until the prefetch queue is empty (to account for network throttling).
*
* If no prefetches are initiated, this will timeout.
*/
async waitForPrefetches<T>(
scope: () => Promise<T> | T = (): undefined => {}
): Promise<T> {
if (prefetchesPromise === null) {
let resolve
let reject
const promise: Promise<void> = new Promise((res, rej) => {
resolve = res
reject = rej
})
prefetchesPromise = {
resolve,
reject,
promise,
}
}
const result = await scope()
if (prefetchesPromise !== null) {
await prefetchesPromise.promise
}
return result
},
async interceptRoute(page: Playwright.Page, route: Playwright.Route) {
const request = route.request()
const requestHeaders = await request.allHeaders()
if (requestHeaders['RSC'.toLowerCase()]) {
// This is an RSC request. Check if it's a prefetch or a navigation.
if (requestHeaders['Next-Router-Prefetch'.toLowerCase()]) {
// This is a prefetch request.
if (prefetchesPromise !== null) {
// Wait for the prefetch response to finish, then wait an additional
// async task for additional prefetches to be initiated.
lastPrefetchRequest = request
const waitForMorePrefetches = async () => {
const response = await request.response()
await response.finished()
await page.evaluate(
() =>
// If the prefetch queue is network throttled, the next
// request should be issued within a microtask of the previous
// one finishing.
new Promise<void>((res) => requestIdleCallback(() => res()))
)
if (request === lastPrefetchRequest) {
// No further prefetches were initiated. Assume the prefetch
// queue is now empty.
prefetchesPromise.resolve()
prefetchesPromise = null
lastPrefetchRequest = null
}
}
waitForMorePrefetches().then(
() => {},
() => {}
)
}
if (pendingPrefetches !== null) {
pendingPrefetches.add(route)
return
}
} else {
// This is a navigation request.
if (pendingNavigations !== null) {
pendingNavigations.add(route)
return
}
}
}
await route.continue()
},
}
}
This diff is collapsed.
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