This repository was archived by the owner on Oct 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathresource-inline-visitor.ts
More file actions
56 lines (49 loc) · 1.94 KB
/
resource-inline-visitor.ts
File metadata and controls
56 lines (49 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {NodeVisitor} from '../node-visitor';
import {WorkerScope} from '../../context';
const URL_REGEXP = /:\s+url\(['"]?(.*?)['"]?\)/gmi;
export abstract class ResourceInlineVisitor extends NodeVisitor {
constructor(private scope: WorkerScope, private inlineExtensions: string[]) {
super();
}
inlineAssets(style: string) {
let urls = this.getImagesUrls(style);
urls = urls.filter((url: string, idx: number) => urls.indexOf(url) === idx);
return this.processInline(urls, style);
}
protected getImagesUrls(styles: string): string[] {
URL_REGEXP.lastIndex = 0;
let match: string[];
const result: string[] = [];
while ((match = URL_REGEXP.exec(styles)) !== null) {
const url = match[1];
if (this.supportedExtension(url)) {
result.push(url);
}
}
return result;
}
private supportedExtension(url: string) {
return this.inlineExtensions.some((ext: string) => new RegExp(`${ext}$`).test(url));
}
protected processInline(urls: string[], styles: string): Promise<string> {
const processResponse = (response: Response): Promise<string[]> => {
if (response && response.ok) {
return response.arrayBuffer()
.then((arr: ArrayBuffer) => [
btoa(String.fromCharCode.apply(null, new Uint8Array(arr))),
// Can contain whitespace: 'image/jpg; charset=utf-8'
response.headers.get('content-type').replace(/\s/g, '')
]);
} else {
return null;
}
};
return Promise.all(urls.map((url: string) => this.scope.fetch(url).catch(() => null)))
.then((responses: any[]) => <any>Promise.all(responses.map(processResponse)))
.then((images: string[][]) => {
return images.map((img: string[]) => img ? `data:${img[1]};base64,${img[0]}` : null)
.reduce((content: string, img: string, idx: number) =>
img ? content.replace(new RegExp(urls[idx], 'g'), img) : content, styles);
});
}
}