2021-12-21 16:13:45 +01:00
|
|
|
import { parse, HTMLElement } from 'next/dist/compiled/node-html-parser'
|
2020-07-28 12:19:28 +02:00
|
|
|
import { OPTIMIZED_FONT_PROVIDERS } from './constants'
|
|
|
|
|
2021-01-13 16:54:31 +01:00
|
|
|
// const MIDDLEWARE_TIME_BUDGET = parseInt(process.env.__POST_PROCESS_MIDDLEWARE_TIME_BUDGET || '', 10) || 10
|
2020-07-28 12:19:28 +02:00
|
|
|
|
|
|
|
type postProcessOptions = {
|
2020-12-21 20:26:00 +01:00
|
|
|
optimizeFonts: boolean
|
2020-07-28 12:19:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type renderOptions = {
|
|
|
|
getFontDefinition?: (url: string) => string
|
|
|
|
}
|
|
|
|
interface PostProcessMiddleware {
|
2021-04-26 20:30:21 +02:00
|
|
|
inspect: (originalDom: HTMLElement, options: renderOptions) => any
|
|
|
|
mutate: (markup: string, data: any, options: renderOptions) => Promise<string>
|
2020-07-28 12:19:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type middlewareSignature = {
|
|
|
|
name: string
|
|
|
|
middleware: PostProcessMiddleware
|
|
|
|
condition: ((options: postProcessOptions) => boolean) | null
|
|
|
|
}
|
|
|
|
|
|
|
|
const middlewareRegistry: Array<middlewareSignature> = []
|
|
|
|
|
|
|
|
function registerPostProcessor(
|
|
|
|
name: string,
|
|
|
|
middleware: PostProcessMiddleware,
|
|
|
|
condition?: (options: postProcessOptions) => boolean
|
|
|
|
) {
|
|
|
|
middlewareRegistry.push({ name, middleware, condition: condition || null })
|
|
|
|
}
|
|
|
|
|
|
|
|
async function processHTML(
|
|
|
|
html: string,
|
|
|
|
data: renderOptions,
|
|
|
|
options: postProcessOptions
|
|
|
|
): Promise<string> {
|
|
|
|
// Don't parse unless there's at least one processor middleware
|
|
|
|
if (!middlewareRegistry[0]) {
|
|
|
|
return html
|
|
|
|
}
|
|
|
|
const root: HTMLElement = parse(html)
|
|
|
|
let document = html
|
2021-09-15 18:43:13 +02:00
|
|
|
|
2020-07-28 12:19:28 +02:00
|
|
|
// Calls the middleware, with some instrumentation and logging
|
2021-01-13 16:54:31 +01:00
|
|
|
async function callMiddleWare(middleware: PostProcessMiddleware) {
|
|
|
|
// let timer = Date.now()
|
2021-04-26 20:30:21 +02:00
|
|
|
const inspectData = middleware.inspect(root, data)
|
|
|
|
document = await middleware.mutate(document, inspectData, data)
|
2021-01-13 16:54:31 +01:00
|
|
|
// timer = Date.now() - timer
|
|
|
|
// if (timer > MIDDLEWARE_TIME_BUDGET) {
|
|
|
|
// TODO: Identify a correct upper limit for the postprocess step
|
|
|
|
// and add a warning to disable the optimization
|
|
|
|
// }
|
2020-07-28 12:19:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let i = 0; i < middlewareRegistry.length; i++) {
|
|
|
|
let middleware = middlewareRegistry[i]
|
|
|
|
if (!middleware.condition || middleware.condition(options)) {
|
2021-01-13 16:54:31 +01:00
|
|
|
await callMiddleWare(middlewareRegistry[i].middleware)
|
2020-07-28 12:19:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return document
|
|
|
|
}
|
|
|
|
|
|
|
|
class FontOptimizerMiddleware implements PostProcessMiddleware {
|
2021-04-26 20:30:21 +02:00
|
|
|
inspect(originalDom: HTMLElement, options: renderOptions) {
|
2020-07-28 12:19:28 +02:00
|
|
|
if (!options.getFontDefinition) {
|
|
|
|
return
|
|
|
|
}
|
2021-04-26 20:30:21 +02:00
|
|
|
const fontDefinitions: (string | undefined)[][] = []
|
2020-07-28 12:19:28 +02:00
|
|
|
// collecting all the requested font definitions
|
|
|
|
originalDom
|
|
|
|
.querySelectorAll('link')
|
|
|
|
.filter(
|
|
|
|
(tag: HTMLElement) =>
|
|
|
|
tag.getAttribute('rel') === 'stylesheet' &&
|
|
|
|
tag.hasAttribute('data-href') &&
|
2021-06-02 11:43:03 +02:00
|
|
|
OPTIMIZED_FONT_PROVIDERS.some(({ url }) => {
|
2020-08-10 11:14:53 +02:00
|
|
|
const dataHref = tag.getAttribute('data-href')
|
|
|
|
return dataHref ? dataHref.startsWith(url) : false
|
|
|
|
})
|
2020-07-28 12:19:28 +02:00
|
|
|
)
|
|
|
|
.forEach((element: HTMLElement) => {
|
|
|
|
const url = element.getAttribute('data-href')
|
2021-01-26 19:32:39 +01:00
|
|
|
const nonce = element.getAttribute('nonce')
|
|
|
|
|
2020-08-10 11:14:53 +02:00
|
|
|
if (url) {
|
2021-04-26 20:30:21 +02:00
|
|
|
fontDefinitions.push([url, nonce])
|
2020-08-10 11:14:53 +02:00
|
|
|
}
|
2020-07-28 12:19:28 +02:00
|
|
|
})
|
2021-04-26 20:30:21 +02:00
|
|
|
|
|
|
|
return fontDefinitions
|
2020-07-28 12:19:28 +02:00
|
|
|
}
|
|
|
|
mutate = async (
|
|
|
|
markup: string,
|
2021-04-26 20:30:21 +02:00
|
|
|
fontDefinitions: string[][],
|
2020-07-28 12:19:28 +02:00
|
|
|
options: renderOptions
|
|
|
|
) => {
|
|
|
|
let result = markup
|
2021-06-02 11:43:03 +02:00
|
|
|
let preconnectUrls = new Set<string>()
|
|
|
|
|
2020-07-28 12:19:28 +02:00
|
|
|
if (!options.getFontDefinition) {
|
|
|
|
return markup
|
|
|
|
}
|
2021-04-26 20:30:21 +02:00
|
|
|
|
|
|
|
fontDefinitions.forEach((fontDef) => {
|
|
|
|
const [url, nonce] = fontDef
|
2020-12-31 00:41:33 +01:00
|
|
|
const fallBackLinkTag = `<link rel="stylesheet" href="${url}"/>`
|
|
|
|
if (
|
|
|
|
result.indexOf(`<style data-href="${url}">`) > -1 ||
|
|
|
|
result.indexOf(fallBackLinkTag) > -1
|
|
|
|
) {
|
2020-07-28 12:19:28 +02:00
|
|
|
// The font is already optimized and probably the response is cached
|
2021-04-26 20:30:21 +02:00
|
|
|
return
|
2020-07-28 12:19:28 +02:00
|
|
|
}
|
2021-04-26 20:30:21 +02:00
|
|
|
const fontContent = options.getFontDefinition
|
|
|
|
? options.getFontDefinition(url as string)
|
|
|
|
: null
|
2020-12-04 10:52:54 +01:00
|
|
|
if (!fontContent) {
|
|
|
|
/**
|
|
|
|
* In case of unreachable font definitions, fallback to default link tag.
|
|
|
|
*/
|
2020-12-31 00:41:33 +01:00
|
|
|
result = result.replace('</head>', `${fallBackLinkTag}</head>`)
|
2020-12-04 10:52:54 +01:00
|
|
|
} else {
|
2021-01-26 19:32:39 +01:00
|
|
|
const nonceStr = nonce ? ` nonce="${nonce}"` : ''
|
2020-12-04 10:52:54 +01:00
|
|
|
result = result.replace(
|
|
|
|
'</head>',
|
2021-01-26 19:32:39 +01:00
|
|
|
`<style data-href="${url}"${nonceStr}>${fontContent}</style></head>`
|
2020-12-04 10:52:54 +01:00
|
|
|
)
|
2021-06-02 11:43:03 +02:00
|
|
|
|
2021-09-15 18:43:13 +02:00
|
|
|
// Remove inert font tag
|
|
|
|
const escapedUrl = url
|
|
|
|
.replace(/&/g, '&')
|
|
|
|
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
|
|
const fontRegex = new RegExp(
|
|
|
|
`<link[^>]*data-href="${escapedUrl}"[^>]*/>`
|
|
|
|
)
|
|
|
|
result = result.replace(fontRegex, '')
|
|
|
|
|
2021-06-02 11:43:03 +02:00
|
|
|
const provider = OPTIMIZED_FONT_PROVIDERS.find((p) =>
|
|
|
|
url.startsWith(p.url)
|
|
|
|
)
|
|
|
|
|
|
|
|
if (provider) {
|
|
|
|
preconnectUrls.add(provider.preconnect)
|
|
|
|
}
|
2020-12-04 10:52:54 +01:00
|
|
|
}
|
2021-04-26 20:30:21 +02:00
|
|
|
})
|
|
|
|
|
2021-06-02 11:43:03 +02:00
|
|
|
let preconnectTag = ''
|
|
|
|
preconnectUrls.forEach((url) => {
|
|
|
|
preconnectTag += `<link rel="preconnect" href="${url}" crossorigin />`
|
|
|
|
})
|
|
|
|
|
|
|
|
result = result.replace(
|
|
|
|
'<meta name="next-font-preconnect"/>',
|
|
|
|
preconnectTag
|
|
|
|
)
|
|
|
|
|
2020-07-28 12:19:28 +02:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialization
|
2020-12-21 20:26:00 +01:00
|
|
|
registerPostProcessor(
|
|
|
|
'Inline-Fonts',
|
|
|
|
new FontOptimizerMiddleware(),
|
|
|
|
// Using process.env because passing Experimental flag through loader is not possible.
|
|
|
|
// @ts-ignore
|
|
|
|
(options) => options.optimizeFonts || process.env.__NEXT_OPTIMIZE_FONTS
|
|
|
|
)
|
2020-07-28 12:19:28 +02:00
|
|
|
|
|
|
|
export default processHTML
|