-
Notifications
You must be signed in to change notification settings - Fork 4
/
url.js
230 lines (194 loc) · 5.85 KB
/
url.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*jshint laxcomma: true */
/*!
* Stylus - plugin - url
* Copyright(c) 2010 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var stylus = require('stylus')
, Compiler = stylus.Compiler
, nodes = stylus.nodes
, parse = require('url').parse
, path = require('path')
, basename = path.basename
, dirname = path.dirname
, extname = path.extname
, utils = stylus.utils
, fs = require('fs');
/**
* Mime table.
*/
var mimes = {
'.gif': 'image/gif'
, '.png': 'image/png'
, '.jpg': 'image/jpeg'
, '.jpeg': 'image/jpeg'
, '.svg': 'image/svg+xml'
};
/**
* Return a url() function with the given `options`.
*
* Options:
*
* - `limit` bytesize limit defaulting to 30Kb
* - `paths` image resolution path(s), merged with general lookup paths
*
* Examples:
*
* stylus(str)
* .set('filename', __dirname + '/css/test.styl')
* .define('url', stylus.url({ paths: [__dirname + '/public'] }))
* .render(function(err, css){ ... })
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function(options) {
options = options || {};
var _paths = options.paths || [],
imageCount = 0;
function url(url) {
// Inject the merge filter. This executes after the AST as been finalized and will
// merge any duplicate data URI instances.
if (!this.imagesSeen) {
this.imagesSeen = {};
this.root.nodes.push(new nodes.Call('merge-urls', new nodes.Arguments()));
}
// Compile the url
var compiler = new Compiler(url);
compiler.isURL = true;
var url = url.nodes.map(function(node) {
return compiler.visit(node);
}).join('');
// Parse literal
var url = parse(url)
, mime = mimes[extname(url.pathname)];
// Not supported MIME or absolute URL
if (!mime || url.protocol) {
return literalNode(url.href);
}
var imageInfo = this.imagesSeen[url.href] = (this.imagesSeen[url.href] || {count: 0, id: imageCount++});
imageInfo.count++;
if (imageInfo.literal) {
return imageInfo.literal.clone();
}
// Lookup
var lookup = imageInfo.resolutions = lookupPath(url, _paths.concat(this.paths), options);
if (!lookup.length) {
// No resolutions defined
return imageInfo.literal = literalNode(lookup.href);
} else if (lookup.length === 1) {
// Only one output
return imageInfo.literal = outputPath.call(this, lookup[0], url.href, options);
} else {
// Multiple outputs here, add a placeholder that we can replace on output
return imageInfo.literal = literalNode('stylusImages://' + imageInfo.id, url.href);
}
}
url.raw = true;
return url;
};
function literalNode(href, id) {
var ret = new nodes.Literal('url("' + href + '")');
if (id !== undefined) {
ret.url = id;
ret.clone = function() {
var ret = nodes.Literal.prototype.clone.call(this);
ret.url = this.url;
return ret;
};
}
return ret;
}
function lookupPath(url, paths, options) {
var resolutions = options.resolutions || [0],
dir = dirname(url.pathname),
ext = extname(url.pathname),
base = basename(url.pathname, ext);
if (options.res) {
resolutions = [options.res];
}
// Zero is a special case for the base file and 1x
if (resolutions.indexOf(0) === -1) {
resolutions = resolutions.slice();
resolutions.unshift(0);
}
resolutions = resolutions.map(function(resolution) {
var href = url.href,
highResFileName = base + (resolution ? '@' + resolution + 'x' : '') + ext,
highResPath = dir + '/' + highResFileName,
found = utils.lookup(highResPath, paths);
if (found) {
// Reset our literal path for the file too large case
var urlDir = dirname(href) + '/';
if (urlDir === './') {
urlDir = '';
}
href = urlDir + highResFileName;
}
// Remap relative paths
if (options.externalPrefix && !/^\//.test(href)) {
href = options.externalPrefix + href;
}
return {
resolution: parseFloat(resolution),
found: found,
href: href
};
});
// Sort so we always have the lowest value providing the default
resolutions = resolutions.sort(function(a, b) {
return a.resolution - b.resolution;
});
// If an explicit resolution was requested return only that
if (options.res) {
resolutions = [selectResolution(options.res, resolutions)];
}
return resolutions;
}
function selectResolution(resolution, lookup) {
return lookup.reduceRight(function(prev, current) {
if ((Math.abs(prev.resolution - resolution) > Math.abs(current.resolution - resolution))
|| !prev.found) {
return current;
} else {
return prev;
}
});
}
function outputPath(resolution, id, options) {
if (!resolution.found) {
return literalNode(resolution.href);
}
var buf = fs.readFileSync(resolution.found),
sizeLimit = options.limit || 30000;
// To large
if (buf.length > sizeLimit) {
// If copy files flag is true and not an absolute url
if (options.copyFiles && !/^\//.test(resolution.href)) {
var relativeDir = dirname(resolution.href),
outputDir = options.outdir || dirname(this.filename),
components = relativeDir.split('/');
for (var i = 0; i < components.length; i++) {
try {
outputDir += '/' + components[i];
fs.mkdirSync(outputDir, parseInt('0777', 8));
} catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
}
fs.writeFileSync(outputDir + '/' + basename(resolution.href), buf);
}
return literalNode(resolution.href);
}
// Encode
return literalNode('data:' + mimes[extname(resolution.href)] + ';base64,' + buf.toString('base64'), id);
}
module.exports.lookup = lookupPath;
module.exports.selectResolution = selectResolution;
module.exports.output = outputPath;