forked from postcss/postcss-url
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·358 lines (321 loc) · 9.24 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
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
358
/**
* 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 reduceFunctionCall = require("reduce-function-call")
var mkdirp = require("mkdirp")
var crypto = require("crypto")
var pathIsAbsolute = require("path-is-absolute")
/**
* 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"
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
styles.walkDecls(function(decl) {
if (decl.value && decl.value.indexOf("url(") > -1) {
processDecl(result, decl, from, to, mode, options)
}
})
}
}
)
/**
* return quote type
*
* @param {String} string quoted (or not) value
* @return {String} quote if any, or empty string
*/
function getUrlMetaData(string) {
var quote = ""
var quotes = ["\"", "'"]
var trimedString = string.trim()
quotes.forEach(function(q) {
if (
trimedString.charAt(0) === q &&
trimedString.charAt(trimedString.length - 1) === q
) {
quote = q
}
})
var urlMeta = {
before: string.slice(0, string.indexOf(quote)),
quote: quote,
value: quote
? trimedString.substr(1, trimedString.length - 2)
: trimedString,
after: string.slice(string.lastIndexOf(quote) + 1),
}
return urlMeta
}
/**
* Create an css url() from a path and a quote style
*
* @param {String} urlMeta url meta data
* @param {String} newPath url path
* @return {String} new url()
*/
function createUrl(urlMeta, newPath) {
return "url(" +
urlMeta.before +
urlMeta.quote +
(newPath || urlMeta.value) +
urlMeta.quote +
urlMeta.after +
")"
}
/**
* Processes one declaration
*
* @param {Object} decl postcss declaration
* @param {String} from source
* @param {String} to destination
* @param {String|Function} mode plugin mode
* @param {Object} options plugin options
* @return {void}
*/
function processDecl(result, decl, from, to, mode, options) {
var dirname = decl.source && decl.source.input
? path.dirname(decl.source.input.file)
: process.cwd()
decl.value = reduceFunctionCall(decl.value, "url", function(value) {
var urlMeta = getUrlMetaData(value)
if (typeof mode === "function") {
return processCustom(
result,
mode,
from,
dirname,
urlMeta,
to,
options,
decl
)
}
// ignore absolute urls, hasshes or data uris
if (urlMeta.value.indexOf("/") === 0 ||
urlMeta.value.indexOf("data:") === 0 ||
urlMeta.value.indexOf("#") === 0 ||
/^[a-z]+:\/\//.test(urlMeta.value)
) {
return createUrl(urlMeta)
}
switch (mode) {
case "rebase":
return processRebase(result, from, dirname, urlMeta, to)
case "inline":
return processInline(result, from, dirname, urlMeta, to, options, decl)
case "copy":
return processCopy(result, from, dirname, urlMeta, to, options, decl)
default:
throw new Error("Unknow mode for postcss-url: " + mode)
}
})
}
/**
* Transform url() based on a custom callback
*
* @param {Function} cb callback function
* @param {String} from from
* @param {String} dirname to dirname
* @param {String} urlMeta url meta data
* @param {String} to destination
* @param {Object} options plugin options
* @param {Object} decl postcss declaration
* @return {void}
*/
function processCustom(result, cb, from, dirname, urlMeta, to, options, decl) {
var newValue = cb(urlMeta.value, decl, from, dirname, to, options, result)
return createUrl(urlMeta, newValue)
}
/**
* Fix url() according to source (`from`) or destination (`to`)
*
* @param {String} from from
* @param {String} dirname to dirname
* @param {String} urlMeta url meta datayy
* @param {String} to destination
* @return {String} new url
*/
function processRebase(result, from, dirname, urlMeta, to) {
var newPath = urlMeta.value
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 createUrl(urlMeta, newPath)
}
/**
* Inline image in url()
*
* @param {String} from from
* @param {String} dirname to dirname
* @param {String} urlMeta url meta data
* @param {String} to destination
* @param {Object} options plugin options
* @param {Object} decl postcss declaration
* @return {String} new url
*/
function processInline(result, from, dirname, urlMeta, to, options, decl) {
var maxSize = options.maxSize === undefined ? 14 : options.maxSize
var fallback = options.fallback
var basePath = options.basePath
var fullFilePath
maxSize *= 1024
function processFallback() {
if (typeof fallback === "function") {
return processCustom(
result,
fallback,
from,
dirname,
urlMeta,
to,
options,
decl
)
}
switch (fallback) {
case "copy":
return processCopy(result, from, dirname, urlMeta, to, options, decl)
default:
return createUrl(urlMeta)
}
}
// ignore URLs with hashes/fragments, they can't be inlined
var link = url.parse(urlMeta.value)
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 createUrl(urlMeta)
}
var stats = fs.statSync(file)
if (stats.size >= maxSize) {
return processFallback()
}
var mimeType = mime.lookup(file)
if (!mimeType) {
result.warn("Unable to find asset mime-type for " + file, {node: decl})
return createUrl(urlMeta)
}
if (mimeType === "image/svg+xml") {
var svg = new SvgEncoder(file)
return createUrl(urlMeta, svg.encode())
}
// else
file = fs.readFileSync(file)
return createUrl(
urlMeta,
"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`)
*
* @param {String} from from
* @param {String} dirname to dirname
* @param {String} urlMeta url meta data
* @param {String} to destination
* @param {Object} options plugin options
* @return {String} new url
*/
function processCopy(result, from, dirname, urlMeta, to, options, decl) {
if (from === to) {
result.warn("Option `to` of postcss is required, ignoring", {node: decl})
return createUrl(urlMeta)
}
var relativeAssetsPath = (options && options.assetsPath)
? options.assetsPath
: ""
var absoluteAssetsPath
var filePathUrl = path.resolve(dirname, urlMeta.value)
var nameUrl = path.basename(filePathUrl)
// remove hash or parameters in the url.
// e.g., url('glyphicons-halflings-regular.eot?#iefix')
var fileLink = url.parse(urlMeta.value)
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 createUrl(urlMeta)
}
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(urlMeta.value)
)
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 createUrl(urlMeta, assetPath)
}