Unverified Commit f1b88b4c authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: content-hash PageLoaderAsset (#81450)

Closes PACK-5035

- [x] Content hash chunks such as `static/chunks/pages/404.js` with  `static/chunks/19a8e82e8f.js` instead
- [x] Including the actual path in `_buildManifest.js`
- [x] Update tests to check the path specified in the manifest
parent e54a837e
......@@ -866,11 +866,22 @@ impl PageEndpoint {
let project = this.pages_project.project();
let node_root = project.client_root().owned().await?;
let client_relative_path = self.client_relative_path();
// In development mode, don't include a content hash and put the chunk at e.g.
// `static/chunks/pages/page2.js`, so that the dev runtime can request it at a known path.
// https://github.com/vercel/next.js/blob/84873e00874e096e6c4951dcf070e8219ed414e5/packages/next/src/client/route-loader.ts#L256-L271
let use_fixed_path = this
.pages_project
.project()
.next_mode()
.await?
.is_development();
let page_loader = PageLoaderAsset::new(
node_root,
this.pathname.clone(),
client_relative_path,
client_chunks,
project.client_chunking_context(),
use_fixed_path,
);
Ok(Vc::upcast(page_loader))
}
......@@ -1306,6 +1317,30 @@ impl PageEndpoint {
))
}
#[turbo_tasks::function]
async fn client_build_manifest(
self: Vc<Self>,
page_loader: ResolvedVc<Box<dyn OutputAsset>>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
let this = self.await?;
let node_root = this.pages_project.project().node_root().await?;
let client_relative_path = this.pages_project.project().client_relative_path().await?;
let page_loader_path = client_relative_path
.get_relative_path_to(&*page_loader.path().await?)
.context("failed to resolve client-relative path to page loader")?;
let client_build_manifest = fxindexmap!(this.pathname.clone() => vec![page_loader_path]);
let manifest_path_prefix = get_asset_prefix_from_pathname(&this.pathname);
Ok(Vc::upcast(VirtualOutputAsset::new_with_references(
node_root.join(&format!(
"server/pages{manifest_path_prefix}/client-build-manifest.json",
))?,
AssetContent::file(
File::from(serde_json::to_string_pretty(&client_build_manifest)?).into(),
),
Vc::cell(vec![page_loader]),
)))
}
#[turbo_tasks::function]
async fn output(self: Vc<Self>) -> Result<Vc<PageEndpointOutput>> {
let this = self.await?;
......@@ -1319,8 +1354,13 @@ impl PageEndpoint {
client_assets.extend(client_chunks.await?.iter().map(|asset| **asset));
let build_manifest = self.build_manifest(client_chunks).to_resolved().await?;
let page_loader = self.page_loader(client_chunks);
let client_build_manifest = self
.client_build_manifest(page_loader)
.to_resolved()
.await?;
client_assets.push(page_loader);
server_assets.push(build_manifest);
server_assets.push(client_build_manifest);
self.ssr_chunk()
}
PageEndpointType::Data => self.ssr_data_chunk(),
......
......@@ -8,8 +8,9 @@ use turbo_tasks_fs::{
};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{ChunkData, ChunksData},
chunk::{ChunkData, ChunkingContext, ChunksData},
context::AssetContext,
ident::AssetIdent,
module::Module,
output::{OutputAsset, OutputAssets},
proxied_asset::ProxiedAsset,
......@@ -73,6 +74,8 @@ pub struct PageLoaderAsset {
pub pathname: RcStr,
pub rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
pub page_chunks: ResolvedVc<OutputAssets>,
pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
pub use_fixed_path: bool,
}
#[turbo_tasks::value_impl]
......@@ -83,12 +86,16 @@ impl PageLoaderAsset {
pathname: RcStr,
rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
page_chunks: ResolvedVc<OutputAssets>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
use_fixed_path: bool,
) -> Vc<Self> {
Self {
server_root,
pathname,
rebase_prefix_path,
page_chunks,
chunking_context,
use_fixed_path,
}
.cell()
}
......@@ -134,21 +141,35 @@ impl PageLoaderAsset {
}
}
impl PageLoaderAsset {
async fn ident_for_path(&self) -> Result<Vc<AssetIdent>> {
let rebase_prefix_path = self.rebase_prefix_path.await?;
let root = rebase_prefix_path.as_ref().unwrap_or(&self.server_root);
Ok(AssetIdent::from_path(root.join(&format!(
"static/chunks/pages{}",
get_asset_path_from_pathname(&self.pathname, ".js")
))?)
.with_modifier(rcstr!("page loader asset")))
}
}
#[turbo_tasks::value_impl]
impl OutputAsset for PageLoaderAsset {
#[turbo_tasks::function]
async fn path(&self) -> Result<Vc<FileSystemPath>> {
let root = self
.rebase_prefix_path
.owned()
.await?
.map_or(self.server_root.clone(), |path| path);
Ok(root
.join(&format!(
"static/chunks/pages{}",
get_asset_path_from_pathname(&self.pathname, ".js")
))?
.cell())
async fn path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
let this = self.await?;
let ident = this.ident_for_path().await?;
if this.use_fixed_path {
// In development mode, don't include a content hash and put the chunk at e.g.
// `static/chunks/pages/page2.js`, so that the dev runtime can request it at a known
// path.
// https://github.com/vercel/next.js/blob/84873e00874e096e6c4951dcf070e8219ed414e5/packages/next/src/client/route-loader.ts#L256-L271
Ok(ident.path())
} else {
Ok(this
.chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
}
}
#[turbo_tasks::function]
......
......@@ -69,6 +69,7 @@ export async function handleRouteType({
case 'page': {
const serverKey = getEntryKey('pages', 'server', page)
await manifestLoader.loadClientBuildManifest(page)
await manifestLoader.loadBuildManifest(page)
await manifestLoader.loadPagesManifest(page)
......
......@@ -180,6 +180,7 @@ export async function turbopackBuild(): Promise<{
manifestLoader.loadPagesManifest('_app'),
manifestLoader.loadFontManifest('_app'),
manifestLoader.loadPagesManifest('_document'),
manifestLoader.loadClientBuildManifest('_error'),
manifestLoader.loadBuildManifest('_error'),
manifestLoader.loadPagesManifest('_error'),
manifestLoader.loadFontManifest('_error'),
......
......@@ -226,6 +226,7 @@ export async function handleRouteType({
const type = writtenEndpoint?.type
await manifestLoader.loadClientBuildManifest(page)
await manifestLoader.loadBuildManifest(page)
await manifestLoader.loadPagesManifest(page)
if (type === 'edge') {
......@@ -942,6 +943,7 @@ export async function handlePagesErrorRoute({
)
processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)
}
await manifestLoader.loadClientBuildManifest('_error')
await manifestLoader.loadBuildManifest('_error')
await manifestLoader.loadPagesManifest('_error')
await manifestLoader.loadFontManifest('_error')
......
......@@ -47,6 +47,7 @@ export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'
export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'
export const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =
'_clientMiddlewareManifest.json'
export const TURBOPACK_CLIENT_BUILD_MANIFEST = 'client-build-manifest.json'
export const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
export const SERVER_DIRECTORY = 'server'
......
......@@ -26,6 +26,7 @@ import {
NEXT_FONT_MANIFEST,
PAGES_MANIFEST,
SERVER_REFERENCE_MANIFEST,
TURBOPACK_CLIENT_BUILD_MANIFEST,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
WEBPACK_STATS,
} from '../constants'
......@@ -74,6 +75,7 @@ type ManifestName =
| `${typeof SERVER_REFERENCE_MANIFEST}.json`
| `${typeof NEXT_FONT_MANIFEST}.json`
| typeof REACT_LOADABLE_MANIFEST
| typeof TURBOPACK_CLIENT_BUILD_MANIFEST
const getManifestPath = (
page: string,
......@@ -135,6 +137,7 @@ export class TurbopackManifestLoader {
private appBuildManifests: Map<EntryKey, AppBuildManifest> = new Map()
private appPathsManifests: Map<EntryKey, PagesManifest> = new Map()
private buildManifests: Map<EntryKey, BuildManifest> = new Map()
private clientBuildManifests: Map<EntryKey, ClientBuildManifest> = new Map()
private fontManifests: Map<EntryKey, NextFontManifest> = new Map()
private middlewareManifests: Map<EntryKey, TurbopackMiddlewareManifest> =
new Map()
......@@ -164,6 +167,7 @@ export class TurbopackManifestLoader {
this.appBuildManifests.delete(key)
this.appPathsManifests.delete(key)
this.buildManifests.delete(key)
this.clientBuildManifests.delete(key)
this.fontManifests.delete(key)
this.middlewareManifests.delete(key)
this.pagesManifests.delete(key)
......@@ -326,6 +330,21 @@ export class TurbopackManifestLoader {
)
}
async loadClientBuildManifest(
pageName: string,
type: 'app' | 'pages' = 'pages'
): Promise<void> {
this.clientBuildManifests.set(
getEntryKey(type, 'server', pageName),
await readPartialManifest(
this.distDir,
TURBOPACK_CLIENT_BUILD_MANIFEST,
pageName,
type
)
)
}
async loadWebpackStats(
pageName: string,
type: 'app' | 'pages' = 'pages'
......@@ -422,6 +441,21 @@ export class TurbopackManifestLoader {
return manifest
}
private mergeClientBuildManifests(
rewrites: CustomRoutes['rewrites'],
manifests: Iterable<ClientBuildManifest>,
sortedPageKeys: string[]
): ClientBuildManifest {
const manifest = {
__rewrites: normalizeRewritesForBuildManifest(rewrites) as any,
sortedPages: sortedPageKeys,
}
for (const m of manifests) {
Object.assign(manifest, m)
}
return sortObjectByKey(manifest)
}
private async writeBuildManifest(
entrypoints: Entrypoints,
devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,
......@@ -479,25 +513,15 @@ export class TurbopackManifestLoader {
}
const sortedPageKeys = getSortedRoutes(pagesKeys)
const clientBuildManifest: ClientBuildManifest = {
__rewrites: normalizeRewritesForBuildManifest(rewrites) as any,
...Object.fromEntries(
sortedPageKeys.map((pathname) => {
let filePath
if (pathname === '/') {
filePath = '/index.js'
} else if (pathname.endsWith('/index')) {
filePath = `${pathname}/index.js`
} else {
filePath = `${pathname}.js`
}
return [pathname, [`static/chunks/pages${filePath}`]]
})
),
sortedPages: sortedPageKeys,
}
const clientBuildManifest = this.mergeClientBuildManifests(
rewrites,
this.clientBuildManifests.values(),
sortedPageKeys
)
const clientBuildManifestJs = `self.__BUILD_MANIFEST = ${JSON.stringify(
clientBuildManifest
clientBuildManifest,
null,
2
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
await writeFileAtomic(
join(this.distDir, 'static', this.buildId, '_buildManifest.js'),
......
......@@ -7,6 +7,7 @@ import {
assertNoRedbox,
check,
fetchViaHTTP,
getClientBuildManifestLoaderChunkUrlPath,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
......@@ -124,75 +125,91 @@ describe('basePath', () => {
)
expect(routesManifest.basePath).toBe(basePath)
})
}
it('should prefetch pages correctly when manually called', async () => {
const browser = await webdriver(next.url, `${basePath}/other-page`)
await browser.eval('window.next.router.prefetch("/gssp")')
it('should prefetch pages correctly when manually called', async () => {
const browser = await webdriver(next.url, `${basePath}/other-page`)
await browser.eval('window.next.router.prefetch("/gssp")')
await check(
async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
let chunk = getClientBuildManifestLoaderChunkUrlPath(
next.testDir,
'/gssp'
)
for (const link of links) {
const href = await link.getAttribute('href')
if (href.includes('gssp')) {
return true
await check(
async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
for (const link of links) {
const href = await link.getAttribute('href')
if (href.includes(chunk)) {
return true
}
}
}
const scripts = await browser.elementsByCss('script')
const scripts = await browser.elementsByCss('script')
for (const script of scripts) {
const src = await script.getAttribute('src')
if (src.includes('gssp')) {
return true
for (const script of scripts) {
const src = await script.getAttribute('src')
if (src.includes(chunk)) {
return true
}
}
}
return false
},
{
test(result) {
return result === true
return false
},
}
)
})
it('should prefetch pages correctly in viewport with <Link>', async () => {
const browser = await webdriver(next.url, `${basePath}/hello`)
await browser.eval('window.next.router.prefetch("/gssp")')
await check(async () => {
const hrefs = await browser.eval(`Object.keys(window.next.router.sdc)`)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname.replace(/\/_next\/data\/[^/]+/, '')
),
[
`${basePath}/gsp.json`,
`${basePath}/index.json`,
// `${basePath}/index/index.json`,
]
{
test(result) {
return result === true
},
}
)
})
const prefetches = await browser.eval(
`[].slice.call(document.querySelectorAll("link[rel=prefetch]")).map((e) => new URL(e.href).pathname)`
)
expect(prefetches).toContainEqual(
expect.stringMatching(/\/gsp-?([^./]+)?\.js/)
)
expect(prefetches).toContainEqual(
expect.stringMatching(/\/gssp-?([^./]+)?\.js/)
)
expect(prefetches).toContainEqual(
expect.stringMatching(/\/other-page-?([^./]+)?\.js/)
)
return 'yes'
}, 'yes')
})
it('should prefetch pages correctly in viewport with <Link>', async () => {
const browser = await webdriver(next.url, `${basePath}/hello`)
await browser.eval('window.next.router.prefetch("/gssp")')
await check(async () => {
const hrefs = await browser.eval(
`Object.keys(window.next.router.sdc)`
)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname.replace(/\/_next\/data\/[^/]+/, '')
),
[
`${basePath}/gsp.json`,
`${basePath}/index.json`,
// `${basePath}/index/index.json`,
]
)
let chunkGsp = getClientBuildManifestLoaderChunkUrlPath(
next.testDir,
'/gsp'
)
let chunkGssp = getClientBuildManifestLoaderChunkUrlPath(
next.testDir,
'/gssp'
)
let chunkOtherPage = getClientBuildManifestLoaderChunkUrlPath(
next.testDir,
'/other-page'
)
const prefetches = await browser.eval(
`[].slice.call(document.querySelectorAll("link[rel=prefetch]")).map((e) => new URL(e.href).pathname)`
)
expect(prefetches).toContainEqual(expect.stringContaining(chunkGsp))
expect(prefetches).toContainEqual(expect.stringContaining(chunkGssp))
expect(prefetches).toContainEqual(
expect.stringContaining(chunkOtherPage)
)
return 'yes'
}, 'yes')
})
}
}
it('should serve public file with basePath correctly', async () => {
......
......@@ -9,6 +9,7 @@ import {
nextBuild,
nextStart,
retry,
getClientBuildManifestLoaderChunkUrlPath,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { check } from 'next-test-utils'
......@@ -45,9 +46,10 @@ const clientNavigation = (context, isProd = false) => {
if (isProd) {
it('should hard navigate to URL on failing to load missing bundle', async () => {
let chunk = getClientBuildManifestLoaderChunkUrlPath(appDir, '/missing')
const browser = await webdriver(context.appPort, '/to-missing-link', {
beforePageLoad(page) {
page.route('**/pages/missing**', (route) => {
page.route('**/' + chunk, (route) => {
route.abort('internetdisconnected')
})
},
......
......@@ -2,7 +2,14 @@
import { join } from 'path'
import webdriver from 'next-webdriver'
import { nextBuild, nextStart, findPort, killApp, check } from 'next-test-utils'
import {
nextBuild,
nextStart,
findPort,
killApp,
check,
getClientBuildManifestLoaderChunkUrlPath,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
let app
......@@ -18,10 +25,12 @@ describe('Failing to load _error', () => {
const appPort = await findPort()
app = await nextStart(appDir, appPort)
let chunk = getClientBuildManifestLoaderChunkUrlPath(appDir, '/_error')
const browser = await webdriver(appPort, '/', {
beforePageLoad(page) {
// Make _error route fail to load
page.route('**/_error*.js', (route) => {
page.route('**/' + chunk, (route) => {
route.abort('blockedbyclient')
})
},
......
......@@ -10,6 +10,7 @@ import {
nextStart,
nextBuild,
waitFor,
getClientBuildManifestLoaderChunkUrlPath,
} from 'next-test-utils'
let app
......@@ -42,6 +43,8 @@ const noError = async (pathname) => {
const didPrefetch = async (pathname) => {
const browser = await webdriver(appPort, pathname)
let chunk = getClientBuildManifestLoaderChunkUrlPath(appDir, '/')
await retry(async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
......@@ -49,9 +52,8 @@ const didPrefetch = async (pathname) => {
links.map((link) => link.getAttribute('href'))
)
// expect one of the href contain string "index"
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('index')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
......
......@@ -3,7 +3,14 @@
import { join } from 'path'
import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import { check, findPort, killApp, nextBuild, nextStart } from 'next-test-utils'
import {
check,
findPort,
killApp,
nextBuild,
nextStart,
getClientBuildManifestLoaderChunkUrlPath,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
......@@ -60,9 +67,11 @@ describe('Middleware Production Prefetch', () => {
const attrs = await Promise.all(
scripts.map((script) => script.getAttribute('src'))
)
// Check if the filename follows the format `static/chunks/pages/[pagename]-[hash].js`
// and specifically targets files containing '/ssg-page-' in their path.
return attrs.find((src) => src.includes('/ssg-page')) ? 'yes' : 'nope'
let chunk = getClientBuildManifestLoaderChunkUrlPath(
context.appDir,
'/ssg-page'
)
return attrs.find((src) => src.includes(chunk)) ? 'yes' : 'nope'
}, 'yes')
})
......
......@@ -8,6 +8,7 @@ import {
nextBuild,
nextStart,
waitFor,
getClientBuildManifestLoaderChunkUrlPath,
} from 'next-test-utils'
import http from 'http'
import httpProxy from 'http-proxy'
......@@ -108,8 +109,12 @@ describe('Prefetching Links in viewport', () => {
const hrefs = await Promise.all(
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/first'
)
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('first')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
} finally {
......@@ -126,8 +131,10 @@ describe('Prefetching Links in viewport', () => {
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
)}`
)
const links = await browser.elementsByCss('link[rel=prefetch]')
expect(links).toHaveLength(1)
await retry(async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
expect(links).toHaveLength(1)
})
} finally {
if (browser) await browser.close()
}
......@@ -161,8 +168,12 @@ describe('Prefetching Links in viewport', () => {
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/ssg/dynamic/[slug]'
)
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('%5Bslug%5D')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
const hrefs = await browser.eval(
......@@ -187,10 +198,19 @@ describe('Prefetching Links in viewport', () => {
let foundFirst = false
let foundAnother = false
let chunkFirst = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/first'
)
let chunkAnother = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
for (const link of links) {
const href = await link.getAttribute('href')
if (href.includes('another')) foundAnother = true
if (href.includes('first')) foundFirst = true
if (href.includes(chunkAnother)) foundAnother = true
if (href.includes(chunkFirst)) foundFirst = true
}
expect(foundFirst).toBe(true)
expect(foundAnother).toBe(true)
......@@ -211,8 +231,12 @@ describe('Prefetching Links in viewport', () => {
const hrefs = await Promise.all(
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('another')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
} finally {
......@@ -232,8 +256,12 @@ describe('Prefetching Links in viewport', () => {
const hrefs = await Promise.all(
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('another')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
......@@ -246,8 +274,12 @@ describe('Prefetching Links in viewport', () => {
const srcProps = await Promise.all(
scripts.map((script) => script.getAttribute('src'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
expect(srcProps).toEqual(
expect.arrayContaining([expect.stringContaining('another')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
} finally {
......@@ -260,6 +292,10 @@ describe('Prefetching Links in viewport', () => {
try {
browser = await webdriver(appPort, '/prefetch-disabled')
let chunkAnother = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
await retry(async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
......@@ -267,7 +303,9 @@ describe('Prefetching Links in viewport', () => {
links.map((link) => link.getAttribute('href'))
)
expect(hrefs).toEqual(
expect.not.arrayContaining([expect.stringContaining('another')])
expect.not.arrayContaining([
expect.stringContaining(chunkAnother),
])
)
})
......@@ -279,7 +317,7 @@ describe('Prefetching Links in viewport', () => {
let scriptFound = false
for (const aScript of scripts) {
const href = await aScript.getAttribute('src')
if (href.includes('another')) {
if (href.includes(chunkAnother)) {
scriptFound = true
break
}
......@@ -301,6 +339,10 @@ describe('Prefetching Links in viewport', () => {
try {
browser = await webdriver(appPort, '/prefetch-disabled-ssg')
let chunkBasic = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/ssg/basic'
)
async function hasSsgScript() {
const scripts = await browser.elementsByCss(
// Mouse hover is a high-priority fetch
......@@ -309,7 +351,7 @@ describe('Prefetching Links in viewport', () => {
let scriptFound = false
for (const aScript of scripts) {
const href = await aScript.getAttribute('src')
if (href.includes('basic')) {
if (href.includes(chunkBasic)) {
scriptFound = true
break
}
......@@ -350,8 +392,12 @@ describe('Prefetching Links in viewport', () => {
const srcProps = await Promise.all(
scripts.map((script) => script.getAttribute('src'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
expect(srcProps).toEqual(
expect.arrayContaining([expect.stringContaining('another')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
} finally {
......@@ -383,8 +429,12 @@ describe('Prefetching Links in viewport', () => {
const hrefs = await Promise.all(
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/another'
)
expect(hrefs).toEqual(
expect.not.arrayContaining([expect.stringContaining('another')])
expect.not.arrayContaining([expect.stringContaining(chunk)])
)
})
})
......@@ -437,8 +487,12 @@ describe('Prefetching Links in viewport', () => {
// Ensure no duplicates
expect(hrefs).toEqual([...new Set(hrefs)])
let chunk = getClientBuildManifestLoaderChunkUrlPath(
appDir,
'/dynamic/[hello]'
)
// Verify encoding
expect(hrefs.some((e) => e.includes(`%5Bhello%5D`))).toBe(true)
expect(hrefs.some((e) => e.includes(chunk))).toBe(true)
})
it('should not re-prefetch for an already prefetched page', async () => {
......@@ -451,8 +505,9 @@ describe('Prefetching Links in viewport', () => {
const hrefs = await Promise.all(
links.map((link) => link.getAttribute('href'))
)
let chunk = getClientBuildManifestLoaderChunkUrlPath(appDir, '/first')
expect(hrefs).toEqual(
expect.arrayContaining([expect.stringContaining('first')])
expect.arrayContaining([expect.stringContaining(chunk)])
)
})
......
......@@ -33,11 +33,9 @@ describe('Production browser sourcemaps', () => {
})
it('includes sourcemaps for all browser files', async () => {
const staticDir = join(appDir, '.next', 'static')
const staticDir = join(appDir, '.next', 'static', 'chunks')
const browserFiles = await recursiveReadDir(staticDir)
const jsFiles = browserFiles.filter(
(file) => file.endsWith('.js') && file.includes('/pages/')
)
const jsFiles = browserFiles.filter((file) => file.endsWith('.js'))
expect(jsFiles).not.toBeEmpty()
for (const file of jsFiles) {
......
......@@ -1283,6 +1283,35 @@ export function readNextBuildServerPageFile(appDir: string, page: string) {
return readFileSync(path.join(appDir, '.next', 'server', pageFile), 'utf8')
}
export function getClientBuildManifest(dir: string) {
let buildId = readFileSync(path.join(dir, '.next/BUILD_ID'), 'utf8')
let code = readFileSync(
path.join(dir, '.next/static', buildId, '_buildManifest.js'),
'utf8'
)
// eslint-disable-next-line no-eval
let manifest = (0, eval)(`var self = global;${code};self.__BUILD_MANIFEST`)
return manifest
}
export function getClientBuildManifestLoaderChunkUrlPath(
dir: string,
page: string
) {
let manifest = getClientBuildManifest(dir)
let chunk: string[] | undefined = manifest[page]
if (chunk == null) {
throw new Error(`Couldn't find page "${page}" in _buildManifest.js`)
}
if (chunk.length !== 1) {
throw new Error(
`Expected a single chunk, but found ${chunk.length} for "${page}" in _buildManifest.js`
)
}
// Remove leading './' so that this can be used in a `url.contains(chunk)` check.
return encodeURI(chunk[0].replace(/^\.\//, ''))
}
function runSuite(
suiteName: string,
context: { env: 'prod' | 'dev'; appDir: string } & Partial<{
......
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