Unverified Commit 5e2a834d authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Share in-flight Google font requests

Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 0950e8ae
...@@ -148,4 +148,74 @@ describe('next/font/google loader', () => { ...@@ -148,4 +148,74 @@ describe('next/font/google loader', () => {
} }
) )
}) })
it('shares in-flight CSS and font file requests', async () => {
const googleFontsUrl =
'https://fonts.googleapis.com/css2?family=Inter:ital,wght@1,600&display=optional'
const fontFileUrl =
'https://fonts.gstatic.com/s/inter/v1/concurrent-test.woff2'
const fontFaceDeclarations = `/* latin */
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 600;
src: url(${fontFileUrl}) format('woff2');
}`
let releaseFetch!: () => void
const fetchGate = new Promise<void>((resolve) => {
releaseFetch = resolve
})
mockFetchResource.mockImplementation(async (url: string) => {
await fetchGate
return Buffer.from(
url === fontFileUrl ? 'font-file' : fontFaceDeclarations
)
})
const emitFontFile = jest.fn().mockReturnValue('/font.woff2')
const loaderArgs = {
functionName: 'Inter',
data: [
{
weight: '600',
style: 'italic',
display: 'optional',
adjustFontFallback: false,
subsets: [],
},
],
emitFontFile,
resolve: jest.fn(),
loaderContext: {} as any,
isDev: false,
variableName: 'myFont',
}
const serverLoad = nextFontGoogleFontLoader({
...loaderArgs,
isServer: true,
})
const clientLoad = nextFontGoogleFontLoader({
...loaderArgs,
isServer: false,
})
// Both compilers overlap while the CSS request is pending.
expect(mockFetchResource).toHaveBeenCalledTimes(1)
releaseFetch()
const [serverResult, clientResult] = await Promise.all([
serverLoad,
clientLoad,
])
expect(mockFetchResource.mock.calls.map(([url]) => url)).toEqual([
googleFontsUrl,
fontFileUrl,
])
expect(emitFontFile).toHaveBeenCalledTimes(2)
expect(serverResult.css).toBe(clientResult.css)
expect(serverResult.css).toContain('url(/font.woff2)')
})
}) })
...@@ -10,8 +10,8 @@ import { getFallbackFontOverrideMetrics } from './get-fallback-font-override-met ...@@ -10,8 +10,8 @@ import { getFallbackFontOverrideMetrics } from './get-fallback-font-override-met
import { fetchCSSFromGoogleFonts } from './fetch-css-from-google-fonts' import { fetchCSSFromGoogleFonts } from './fetch-css-from-google-fonts'
import { fetchFontFile } from './fetch-font-file' import { fetchFontFile } from './fetch-font-file'
const cssCache = new Map<string, string | null>() const cssCache = new Map<string, Promise<string | null>>()
const fontCache = new Map<string, Buffer | null>() const fontCache = new Map<string, Promise<Buffer | null>>()
// regexp is based on https://github.com/sindresorhus/escape-string-regexp // regexp is based on https://github.com/sindresorhus/escape-string-regexp
const reHasRegExp = /[|\\{}()[\]^$+*?.-]/ const reHasRegExp = /[|\\{}()[\]^$+*?.-]/
...@@ -77,17 +77,19 @@ const nextFontGoogleFontLoader: FontLoader = async ({ ...@@ -77,17 +77,19 @@ const nextFontGoogleFontLoader: FontLoader = async ({
* Otherwise both the client and server compiler would fetch the CSS. * Otherwise both the client and server compiler would fetch the CSS.
* The reason we need to return the actual CSS from both the server and client is because a hash is generated based on the CSS content. * The reason we need to return the actual CSS from both the server and client is because a hash is generated based on the CSS content.
*/ */
const hasCachedCSS = cssCache.has(url) const cachedCSS = cssCache.get(url)
// Fetch CSS from Google Fonts or get it from the cache // Fetch CSS from Google Fonts or get it from the cache
let fontFaceDeclarations = hasCachedCSS const cssPromise =
? cssCache.get(url) cachedCSS ??
: await fetchCSSFromGoogleFonts(url, fontFamily, isDev).catch((err) => { fetchCSSFromGoogleFonts(url, fontFamily, isDev).catch((err) => {
console.error(err) console.error(err)
return null return null
}) })
if (!hasCachedCSS) { if (!cachedCSS) {
cssCache.set(url, fontFaceDeclarations ?? null) cssCache.set(url, cssPromise)
} else { }
let fontFaceDeclarations = await cssPromise
if (cachedCSS) {
cssCache.delete(url) cssCache.delete(url)
} }
if (fontFaceDeclarations == null) { if (fontFaceDeclarations == null) {
...@@ -106,17 +108,19 @@ const nextFontGoogleFontLoader: FontLoader = async ({ ...@@ -106,17 +108,19 @@ const nextFontGoogleFontLoader: FontLoader = async ({
// Download the font files extracted from the CSS // Download the font files extracted from the CSS
const downloadedFiles = await Promise.all( const downloadedFiles = await Promise.all(
fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => { fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => {
const hasCachedFont = fontCache.has(googleFontFileUrl) const cachedFont = fontCache.get(googleFontFileUrl)
// Download the font file or get it from cache // Download the font file or get it from cache
const fontFileBuffer = hasCachedFont const fontPromise =
? fontCache.get(googleFontFileUrl) cachedFont ??
: await fetchFontFile(googleFontFileUrl, isDev).catch((err) => { fetchFontFile(googleFontFileUrl, isDev).catch((err) => {
console.error(err) console.error(err)
return null return null
}) })
if (!hasCachedFont) { if (!cachedFont) {
fontCache.set(googleFontFileUrl, fontFileBuffer ?? null) fontCache.set(googleFontFileUrl, fontPromise)
} else { }
const fontFileBuffer = await fontPromise
if (cachedFont) {
fontCache.delete(googleFontFileUrl) fontCache.delete(googleFontFileUrl)
} }
if (fontFileBuffer == null) { if (fontFileBuffer == null) {
......
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