-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (47 loc) · 1.52 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
var
fs = require('fs'),
extname = require('path').extname,
parse = require('url').parse,
stylus = require('stylus');
module.exports = function(options) {
var
stylusUrlFn = stylus.url.apply(this, arguments),
sizeLimit = options.limit || 30000;
function inlineImg(url) {
var
localUrl = url,
compiler = new stylus.Compiler(localUrl);
compiler.isURL = true;
localUrl = localUrl.nodes
.map(function(node) {
return compiler.visit(node);
})
.join('');
localUrl = parse(localUrl);
// Not supported
if (extname(localUrl.href) !== '.svg')
return stylusUrlFn.apply(this, arguments);
var literal = new stylus.nodes.Literal('url("' + localUrl.href + '")')
// Absolute
if (localUrl.protocol)
return literal;
options.paths = (options.paths || []).concat(this.paths);
var found = stylus.utils.lookup(localUrl.pathname, options.paths);
if (!found)
return literal;
var fileContent = fs.readFileSync(found);
// Too large
if (sizeLimit && fileContent.length > sizeLimit)
return literal;
fileContent = fileContent.toString('utf8')
.replace(/<\?xml(.+?)\?>/, '')
.replace(/"/g, "'")
.replace(/\s+/g, ' ')
.replace(/[{}\|\\\^~\[\]`"<>#%]/g, function(match) {
return '%' + match[0].charCodeAt(0).toString(16).toUpperCase();
});
return new stylus.nodes.Literal('url("data:image/svg+xml;charset=utf8,' + fileContent + '")');
}
inlineImg.raw = true;
return inlineImg;
};