/
index.js
65 lines (60 loc) · 1.75 KB
/
index.js
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
var htmlparser = require('htmlparser2');
var _ = require('lodash');
var url = require('url');
var absolution = module.exports = function(input, base, options) {
if (!options) {
options = absolution.defaults;
} else {
_.defaults(options, absolution.defaults);
}
var selfClosingMap = {};
_.each(options.selfClosing, function(tag) {
selfClosingMap[tag] = true;
});
var result = '';
var parser = new htmlparser.Parser({
onopentag: function(name, attribs) {
_.each(options.urlAttributes, function(attr) {
if (_.has(attribs, attr) && attribs[attr].trim()) {
attribs[attr] = url.resolve(base, attribs[attr]);
if (options.decorator) {
attribs[attr] = options.decorator(attribs[attr]);
}
}
});
result += '<' + name;
_.each(attribs, function(value, a) {
result += ' ' + a;
if (value.length) {
// Values are ALREADY escaped, calling escapeHtml here
// results in double escapes
result += '="' + value + '"';
}
});
if (_.has(selfClosingMap, name)) {
result += " />";
} else {
result += ">";
}
},
ontext: function(text) {
// It is NOT actually raw text, entities are already escaped.
// If we call escapeHtml here we wind up double-escaping.
result += text;
},
onclosetag: function(name) {
if (_.has(selfClosingMap, name)) {
// Already output />
return;
}
result += "</" + name + ">";
}
});
parser.write(input);
parser.end();
return result;
};
absolution.defaults = {
urlAttributes: [ 'href', 'src', 'action' ],
selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ]
};