This repository has been archived by the owner on Oct 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse5_ast_dependencies.ts
79 lines (75 loc) · 1.74 KB
/
parse5_ast_dependencies.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import {uniq} from 'lodash';
export function parse5AstDependencies(ast: any) {
const identifiers = [];
const pending = [];
let node = ast;
while (node) {
if (node.childNodes && node.childNodes.length !== 0) {
pending.push(...node.childNodes);
}
switch(node.tagName) {
case 'script':
case 'img':
for (const attr of node.attrs) {
if (attr.name === 'src') {
if (attr.value) {
identifiers.push(attr.value);
}
break;
}
}
break;
case 'link':
for (const attr of node.attrs) {
if (attr.name === 'href') {
if (attr.value) {
identifiers.push(attr.value);
}
break;
}
}
break;
default:
break;
}
node = pending.pop();
}
return {
identifiers: uniq(identifiers)
};
}
export function rewriteParse5AstDependencies(ast: any, identifiers: any) {
const pending = [];
let node = ast;
while (node) {
if (node.childNodes && node.childNodes.length !== 0) {
pending.push(...node.childNodes);
}
switch(node.tagName) {
case 'script':
case 'img':
for (const attr of node.attrs) {
if (attr.name === 'src') {
if (attr.value && attr.value in identifiers) {
attr.value = identifiers[attr.value];
}
break;
}
}
break;
case 'link':
for (const attr of node.attrs) {
if (attr.name === 'href') {
if (attr.value && attr.value in identifiers) {
attr.value = identifiers[attr.value];
}
break;
}
}
break;
default:
break;
}
node = pending.pop();
}
}