index.js
8.88 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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
* Module dependencies.
*/
var fs = require("fs")
var path = require("path")
var postcss = require("postcss")
var mime = require("mime")
var url = require("url")
var SvgEncoder = require("directory-encoder/lib/svg-uri-encoder.js")
var mkdirp = require("mkdirp")
var crypto = require("crypto")
var pathIsAbsolute = require("path-is-absolute")
var minimatch = require("minimatch")
/**
* @typedef UrlRegExp
* @name UrlRegExp
* @desc A regex for match url with parentheses:
* (before url)(the url)(after url).
* (the url) will be replace with new url, and before and after will remain
* @type RegExp
*/
/**
* @type {UrlRegExp[]}
*/
var UrlsPatterns = [
/(url\(\s*['"]?)([^"')]+)(["']?\s*\))/g,
/(AlphaImageLoader\(\s*src=['"]?)([^"')]+)(["'])/g,
]
/**
* Fix url() according to source (`from`) or destination (`to`)
*
* @param {Object} options plugin options
* @return {void}
*/
module.exports = postcss.plugin(
"postcss-url",
function fixUrl(options) {
options = options || {}
var mode = options.url !== undefined ? options.url : "rebase"
var isCustom = typeof mode === "function"
var callback = isCustom ? getCustomProcessor(mode) : getUrlProcessor(mode)
return function(styles, result) {
var from = result.opts.from
? path.dirname(result.opts.from)
: "."
var to = result.opts.to
? path.dirname(result.opts.to)
: from
var cb = getDeclProcessor(result, from, to, callback, options, isCustom)
styles.walkDecls(cb)
}
}
)
/**
* @callback PostcssUrl~UrlProcessor
* @param {String} from from
* @param {String} dirname to dirname
* @param {String} oldUrl url
* @param {String} to destination
* @param {Object} options plugin options
* @param {Object} decl postcss declaration
* @return {String|undefined} new url or undefined if url is old
*/
/**
* @param {String} mode
* @returns {PostcssUrl~UrlProcessor}
*/
function getUrlProcessor(mode) {
switch (mode) {
case "rebase":
return processRebase
case "inline":
return processInline
case "copy":
return processCopy
default:
throw new Error("Unknown mode for postcss-url: " + mode)
}
}
/**
* Returns wether the given filename matches the given pattern
* Allways returns true if the given pattern is empty
*
* @param {String} filename the processed filename
* @param {String|RegExp|Function} pattern A minimatch string,
* regular expression or function to test the filename
*
* @return {Boolean}
*/
function matchesFilter(filename, pattern) {
if (typeof pattern === "string") {
pattern = minimatch.filter(pattern)
}
if (pattern instanceof RegExp) {
return pattern.test(filename)
}
if (pattern instanceof Function) {
return pattern(filename)
}
return true
}
/**
* @callback PostcssUrl~DeclProcessor
* @param {Object} decl declaration
*/
/**
* @param {Object} result
* @param {String} from from
* @param {String} to destination
* @param {PostcssUrl~UrlProcessor} callback
* @param {Object} options
* @param {Boolean} [isCustom]
* @returns {PostcssUrl~DeclProcessor}
*/
function getDeclProcessor(result, from, to, cb, options, isCustom) {
var valueCallback = function(decl, oldUrl) {
var dirname = decl.source && decl.source.input && decl.source.input.file
? path.dirname(decl.source.input.file)
: process.cwd()
var newUrl
if (isCustom || !isUrlShouldBeIgnored(oldUrl)) {
newUrl = cb(result, from, dirname, oldUrl, to, options, decl)
}
return newUrl || oldUrl
}
return function(decl) {
UrlsPatterns.some(function(pattern) {
if (pattern.test(decl.value)) {
decl.value = decl.value
.replace(pattern, function(_, beforeUrl, oldUrl, afterUrl) {
return beforeUrl + valueCallback(decl, oldUrl) + afterUrl
})
return true
}
})
}
}
/**
* Check if url is absolute, hash or data-uri
* @param {String} url
* @returns {boolean}
*/
function isUrlShouldBeIgnored(url) {
return url[0] === "/" ||
url[0] === "#" ||
url.indexOf("data:") === 0 ||
/^[a-z]+:\/\//.test(url)
}
/**
* Transform url() based on a custom callback
*
* @param {Function} cb callback function
* @return {PostcssUrl~UrlProcessor}
*/
function getCustomProcessor(cb) {
return function(result, from, dirname, oldUrl, to, options, decl) {
return cb(oldUrl, decl, from, dirname, to, options, result)
}
}
/**
* Fix url() according to source (`from`) or destination (`to`)
*
* @type {PostcssUrl~UrlProcessor}
*/
function processRebase(result, from, dirname, oldUrl, to) {
var newPath = oldUrl
if (dirname !== from) {
newPath = path.relative(from, dirname + path.sep + newPath)
}
newPath = path.resolve(from, newPath)
newPath = path.relative(to, newPath)
if (path.sep === "\\") {
newPath = newPath.replace(/\\/g, "\/")
}
return newPath
}
/**
* Inline image in url()
*
* @type {PostcssUrl~UrlProcessor}
*/
function processInline(result, from, dirname, oldUrl, to, options, decl) {
var maxSize = options.maxSize === undefined ? 14 : options.maxSize
var fallback = options.fallback
var basePath = options.basePath
var filter = options.filter
var fullFilePath
maxSize *= 1024
function processFallback() {
if (typeof fallback === "function") {
return getCustomProcessor(fallback)
(result, from, dirname, oldUrl, to, options, decl)
}
switch (fallback) {
case "copy":
return processCopy(result, from, dirname, oldUrl, to, options, decl)
default:
return
}
}
// ignore URLs with hashes/fragments, they can't be inlined
var link = url.parse(oldUrl)
if (link.hash) {
return processFallback()
}
if (basePath) {
fullFilePath = path.join(basePath, link.pathname)
}
else {
fullFilePath = dirname !== from
? dirname + path.sep + link.pathname
: link.pathname
}
var file = path.resolve(from, fullFilePath)
if (!fs.existsSync(file)) {
result.warn("Can't read file '" + file + "', ignoring", { node: decl })
return
}
var stats = fs.statSync(file)
if (stats.size >= maxSize) {
return processFallback()
}
if (!matchesFilter(file, filter)) {
return processFallback()
}
var mimeType = mime.lookup(file)
if (!mimeType) {
result.warn("Unable to find asset mime-type for " + file, { node: decl })
return
}
if (mimeType === "image/svg+xml") {
var svg = new SvgEncoder(file)
return svg.encode()
}
// else
file = fs.readFileSync(file)
return "data:" + mimeType + ";base64," + file.toString("base64")
}
/**
* Copy images from readed from url() to an specific assets destination
* (`assetsPath`) and fix url() according to that path.
* You can rename the assets by a hash or keep the real filename.
*
* Option assetsPath is require and is relative to the css destination (`to`)
*
* @type {PostcssUrl~UrlProcessor}
*/
function processCopy(result, from, dirname, oldUrl, to, options, decl) {
if (from === to) {
result.warn("Option `to` of postcss is required, ignoring", { node: decl })
return
}
var relativeAssetsPath = (options && options.assetsPath)
? options.assetsPath
: ""
var absoluteAssetsPath
var filePathUrl = path.resolve(dirname, oldUrl)
var nameUrl = path.basename(filePathUrl)
// remove hash or parameters in the url.
// e.g., url('glyphicons-halflings-regular.eot?#iefix')
var fileLink = url.parse(oldUrl)
var filePath = path.resolve(dirname, fileLink.pathname)
var name = path.basename(filePath)
var useHash = options.useHash || false
// check if the file exist in the source
try {
var contents = fs.readFileSync(filePath)
}
catch (err) {
result.warn("Can't read file '" + filePath + "', ignoring", { node: decl })
return
}
if (useHash) {
absoluteAssetsPath = path.resolve(to, relativeAssetsPath)
// create the destination directory if it not exist
mkdirp.sync(absoluteAssetsPath)
name = crypto.createHash("sha1")
.update(contents)
.digest("hex")
.substr(0, 16)
name += path.extname(filePath)
nameUrl = name + (fileLink.search || "") + (fileLink.hash || "")
}
else {
if (!pathIsAbsolute.posix(from)) {
from = path.resolve(from)
}
relativeAssetsPath = path.join(
relativeAssetsPath,
dirname.replace(new RegExp(from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ "[\/]\?"), ""),
path.dirname(oldUrl)
)
absoluteAssetsPath = path.resolve(to, relativeAssetsPath)
// create the destination directory if it not exist
mkdirp.sync(absoluteAssetsPath)
}
absoluteAssetsPath = path.join(absoluteAssetsPath, name)
// if the file don't exist in the destination, create it.
try {
fs.accessSync(absoluteAssetsPath)
}
catch (err) {
fs.writeFileSync(absoluteAssetsPath, contents)
}
var assetPath = path.join(relativeAssetsPath, nameUrl)
if (path.sep === "\\") {
assetPath = assetPath.replace(/\\/g, "\/")
}
return assetPath
}