Fixed url parser regex not working for Google Fonts subset API

This commit is contained in:
Stephen Tse 2025-04-02 23:52:20 -07:00
parent f334e78ed6
commit 0abcd609cb

View File

@ -107,6 +107,13 @@ export interface GoogleFontFile {
extension: string extension: string
} }
const fontMimeMap: Record<string, string> = {
"truetype": "ttf",
"woff": "woff",
"woff2": "woff2",
"opentype": "otf",
}
export async function processGoogleFonts( export async function processGoogleFonts(
stylesheet: string, stylesheet: string,
baseUrl: string, baseUrl: string,
@ -114,14 +121,15 @@ export async function processGoogleFonts(
processedStylesheet: string processedStylesheet: string
fontFiles: GoogleFontFile[] fontFiles: GoogleFontFile[]
}> { }> {
const fontSourceRegex = /url\((https:\/\/fonts.gstatic.com\/s\/[^)]+\.(woff2|ttf))\)/g const fontSourceRegex = /url\((https:\/\/fonts.gstatic.com\/.+(?:\/|(?:kit=))(.+?)[.&].+?)\)\sformat\('(\w+?)'\);/g
const fontFiles: GoogleFontFile[] = [] const fontFiles: GoogleFontFile[] = []
let processedStylesheet = stylesheet let processedStylesheet = stylesheet
let match let match
while ((match = fontSourceRegex.exec(stylesheet)) !== null) { while ((match = fontSourceRegex.exec(stylesheet)) !== null) {
const url = match[1] const url = match[1]
const [filename, extension] = url.split("/").pop()!.split(".") const filename = match[2]
const extension = fontMimeMap[match[3].toLowerCase()]
const staticUrl = `https://${baseUrl}/static/fonts/${filename}.${extension}` const staticUrl = `https://${baseUrl}/static/fonts/${filename}.${extension}`
processedStylesheet = processedStylesheet.replace(url, staticUrl) processedStylesheet = processedStylesheet.replace(url, staticUrl)