2015-07-23 08:28:22 -07:00
|
|
|
var datauri = require('datauri');
|
|
|
|
|
var isLocalPath = require('is-local-path');
|
2015-09-25 13:35:27 -07:00
|
|
|
var isTemplateExpression = require('./is-template-expression');
|
2015-07-23 08:28:22 -07:00
|
|
|
var path = require('path');
|
2015-07-27 13:15:45 -07:00
|
|
|
var postcss = require('postcss');
|
2015-08-25 15:08:53 -07:00
|
|
|
var postcssUrl = require('postcss-url');
|
2015-09-21 10:16:38 -07:00
|
|
|
var R = require('ramda');
|
2015-08-25 15:08:53 -07:00
|
|
|
var url = require('url');
|
2015-07-23 08:28:22 -07:00
|
|
|
|
2015-08-25 15:08:53 -07:00
|
|
|
/**
|
|
|
|
|
* Returns url path without query string and hash if present.
|
|
|
|
|
*
|
|
|
|
|
* @param path
|
|
|
|
|
*
|
|
|
|
|
* @returns path
|
|
|
|
|
*/
|
|
|
|
|
var clean = function (path) {
|
|
|
|
|
path = url.parse(path);
|
2015-09-21 10:16:38 -07:00
|
|
|
path = R.pick(['protocol', 'host', 'pathname'], path);
|
2015-09-11 09:17:10 -07:00
|
|
|
path = url.format(path);
|
|
|
|
|
path = decodeURI(path);
|
|
|
|
|
return path;
|
2015-08-25 15:08:53 -07:00
|
|
|
};
|
|
|
|
|
/**
|
|
|
|
|
* Convert local url data type paths to datauris.
|
|
|
|
|
*
|
|
|
|
|
* @param css
|
|
|
|
|
* @param filename
|
|
|
|
|
* @returns {{css: (css|any), files: Array}}
|
|
|
|
|
*/
|
2015-10-07 11:54:47 -07:00
|
|
|
var inlineUrl = function (css, filename) {
|
2015-07-24 15:51:46 -07:00
|
|
|
var files = [];
|
|
|
|
|
var basePath = path.dirname(filename);
|
2015-07-27 13:15:45 -07:00
|
|
|
var result = postcss()
|
2015-08-25 15:08:53 -07:00
|
|
|
.use(postcssUrl({
|
|
|
|
|
url: function (urlPath) {
|
2015-09-25 13:35:27 -07:00
|
|
|
if (isLocalPath(urlPath) && !isTemplateExpression(urlPath)) {
|
2015-10-07 11:54:47 -07:00
|
|
|
try {
|
|
|
|
|
urlPath = clean(urlPath);
|
|
|
|
|
urlPath = path.resolve(basePath, urlPath);
|
|
|
|
|
files = R.append(urlPath, files);
|
|
|
|
|
urlPath = datauri(urlPath);
|
|
|
|
|
}
|
|
|
|
|
catch (error) {
|
|
|
|
|
error.filename = filename;
|
|
|
|
|
error.files = R.uniq(files);
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
2015-07-27 13:15:45 -07:00
|
|
|
}
|
2015-08-25 15:08:53 -07:00
|
|
|
return urlPath;
|
2015-07-23 08:28:22 -07:00
|
|
|
}
|
|
|
|
|
}))
|
2015-07-27 13:15:45 -07:00
|
|
|
.process(css);
|
2015-10-07 11:54:47 -07:00
|
|
|
files = R.uniq(files);
|
2015-07-24 15:51:46 -07:00
|
|
|
return {
|
2015-07-27 13:15:45 -07:00
|
|
|
css: result.css,
|
2015-10-07 11:54:47 -07:00
|
|
|
files
|
2015-07-24 15:51:46 -07:00
|
|
|
};
|
2015-07-23 08:28:22 -07:00
|
|
|
};
|
|
|
|
|
|
2015-10-07 11:54:47 -07:00
|
|
|
module.exports = inlineUrl;
|