scramjet/src/shared/rewriters/css.ts
Percs 47b59945a9 bug fixes
Co-authored-by: Avad3 <Avad3@users.noreply.github.com>
2024-07-13 19:42:12 -05:00

35 lines
977 B
TypeScript

// This CSS rewriter uses code from Meteor
// You can find the original source code at https://github.com/MeteorProxy/Meteor
import { encodeUrl } from "./url";
export function rewriteCss(css: string, origin?: URL) {
const regex =
/(@import\s+(?!url\())?\s*url\(\s*(['"]?)([^'")]+)\2\s*\)|@import\s+(['"])([^'"]+)\4/g
return css.replace(
regex,
(
match,
importStatement,
urlQuote,
urlContent,
importQuote,
importContent
) => {
const url = urlContent || importContent
const encodedUrl = encodeUrl(url.trim(), origin)
if (importStatement) {
return `@import url(${urlQuote}${encodedUrl}${urlQuote})`
}
if (importQuote) {
return `@import ${importQuote}${encodedUrl}${importQuote}`
}
return `url(${urlQuote}${encodedUrl}${urlQuote})`
}
)
}