Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
titaniumnetwork-dev
GitHub Repository: titaniumnetwork-dev/Ultraviolet
Path: blob/main/src/rewrite/css.js
304 views
1
import EventEmitter from "events";
2
3
class CSS extends EventEmitter {
4
constructor(ctx) {
5
super();
6
this.ctx = ctx;
7
this.meta = ctx.meta;
8
}
9
rewrite(str, options) {
10
return this.recast(str, options, "rewrite");
11
}
12
source(str, options) {
13
return this.recast(str, options, "source");
14
}
15
recast(str, options, type) {
16
// regex from vk6 (https://github.com/ading2210)
17
const urlRegex = /url\(['"]?(.+?)['"]?\)/gm;
18
const Atruleregex =
19
/@import\s+(url\s*?\(.{0,9999}?\)|['"].{0,9999}?['"]|.{0,9999}?)($|\s|;)/gm;
20
str = new String(str).toString();
21
str = str.replace(urlRegex, (match, url) => {
22
const encodedUrl =
23
type === "rewrite" ? this.ctx.rewriteUrl(url) : this.ctx.sourceUrl(url);
24
25
return match.replace(url, encodedUrl);
26
});
27
str = str.replace(Atruleregex, (match, importStatement) => {
28
return match.replace(
29
importStatement,
30
importStatement.replace(
31
/^(url\(['"]?|['"]|)(.+?)(['"]|['"]?\)|)$/gm,
32
(match, firstQuote, url, endQuote) => {
33
if (firstQuote.startsWith("url")) {
34
return match;
35
}
36
const encodedUrl =
37
type === "rewrite"
38
? this.ctx.rewriteUrl(url)
39
: this.ctx.sourceUrl(url);
40
41
return `${firstQuote}${encodedUrl}${endQuote}`;
42
}
43
)
44
);
45
});
46
47
return str;
48
}
49
}
50
51
export default CSS;
52
53