-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
263 lines (235 loc) · 7.51 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
import postcss from 'postcss';
import path from 'path';
import valueParser from 'postcss-value-parser';
import url from 'url';
import crypto from 'crypto';
import micromatch from 'micromatch';
import copy from './lib/copy';
import { defineCSSDestPath, findBasePath } from './lib/tools-path';
const tags = ['path', 'name', 'hash', 'ext', 'query', 'qparams', 'qhash'];
/**
* Helper function to ignore files
*
* @param {string} filename
* @param {string} extra
* @param {Object} opts plugin options
* @return {boolean}
*/
function ignore(fileMeta, opts) {
if (typeof opts.ignore === 'function') {
return opts.ignore(fileMeta, opts);
}
if (typeof opts.ignore === 'string' || Array.isArray(opts.ignore)) {
return micromatch.any(fileMeta.sourceValue, opts.ignore);
}
return false;
}
/**
* Helper function that reads the file ang get some helpful information
* to the copy process.
*
* @param {string} dirname path of the read file css
* @param {string} sourceInputFile path to the source input file css
* @param {string} value url
* @param {Object} opts plugin options
* @return {Promise} resolve => fileMeta | reject => error message
*/
function getFileMeta(dirname, sourceInputFile, value, opts) {
const parsedUrl = url.parse(value, true);
const filename = decodeURI(parsedUrl.pathname);
const pathname = path.resolve(dirname, filename);
const params = parsedUrl.search || '';
const hash = parsedUrl.hash || '';
// path between the basePath and the filename
const basePath = findBasePath(opts.basePath, pathname);
if (!basePath) {
throw Error(`"basePath" not found in ${pathname}`);
}
const ext = path.extname(pathname);
const fileMeta = {
sourceInputFile,
sourceValue: value,
filename,
// the absolute path without the #hash param and ?query
absolutePath: pathname,
fullName: path.basename(pathname),
path: path.relative(basePath, path.dirname(pathname)),
// name without extension
name: path.basename(pathname, ext),
// extension without the '.'
ext: ext.slice(1),
query: params + hash,
qparams: params.length > 0 ? params.slice(1) : '',
qhash: hash.length > 0 ? hash.slice(1) : '',
basePath
};
return fileMeta;
}
/**
* process to copy an asset based on the css file, destination
* and the url value
*
* @param {Object} result
* @param {Object} decl postcss declaration
* @param {Object} node postcss-value-parser
* @param {Object} opts plugin options
* @return {Promise}
*/
function processUrl(result, decl, node, opts) {
// ignore from the css file by `!`
if (node.value.indexOf('!') === 0) {
node.value = node.value.slice(1);
return Promise.resolve();
}
if (
node.value.indexOf('/') === 0 ||
node.value.indexOf('data:') === 0 ||
node.value.indexOf('#') === 0 ||
/^[a-z]+:\/\//.test(node.value)
) {
return Promise.resolve();
}
/**
* dirname of the read file css
* @type {String}
*/
const dirname = path.dirname(decl.source.input.file);
let fileMeta = getFileMeta(
dirname,
decl.source.input.file,
node.value,
opts
);
// ignore from the fileMeta config
if (ignore(fileMeta, opts)) {
return Promise.resolve();
}
return copy(
fileMeta.absolutePath,
() => fileMeta.resultAbsolutePath,
(contents, isModified) => {
fileMeta.contents = contents;
return Promise.resolve(
isModified ? opts.transform(fileMeta) : fileMeta
)
.then(fileMetaTransformed => {
fileMetaTransformed.hash = opts.hashFunction(
fileMetaTransformed.contents
);
let tpl = opts.template;
if (typeof tpl === 'function') {
tpl = tpl(fileMetaTransformed);
} else {
tags.forEach(tag => {
tpl = tpl.replace(
'[' + tag + ']',
fileMetaTransformed[tag] || opts[tag] || ''
);
});
}
const resultUrl = url.parse(tpl);
fileMetaTransformed.resultAbsolutePath = decodeURI(
path.resolve(
opts.dest,
resultUrl.pathname
)
);
fileMetaTransformed.extra = (resultUrl.search || '') +
(resultUrl.hash || '');
return fileMetaTransformed;
})
.then(fileMetaTransformed => fileMetaTransformed.contents);
}
).then(() => {
const destPath = defineCSSDestPath(
dirname,
fileMeta.basePath,
result,
opts
);
node.value = path
.relative(destPath, fileMeta.resultAbsolutePath)
.split('\\')
.join('/') + fileMeta.extra;
});
}
/**
* Processes each declaration using postcss-value-parser
*
* @param {Object} result
* @param {Object} decl postcss declaration
* @param {Object} opts plugin options
* @return {Promise}
*/
function processDecl(result, decl, opts) {
const promises = [];
decl.value = valueParser(decl.value).walk(node => {
if (
node.type !== 'function' ||
node.value !== 'url' ||
node.nodes.length === 0
) {
return;
}
const promise = Promise.resolve()
.then(() => processUrl(result, decl, node.nodes[0], opts))
.catch(err => {
decl.warn(result, err.message);
});
promises.push(promise);
});
return Promise.all(promises).then(() => decl);
}
/**
* Initialize the postcss-copy plugin
* @param {Object} plugin options
* @return {plugin}
*/
function init(userOpts = {}) {
const opts = Object.assign(
{
template: '[hash].[ext][query]',
preservePath: false,
hashFunction(contents) {
return crypto
.createHash('sha1')
.update(contents)
.digest('hex')
.substr(0, 16);
},
transform(fileMeta) {
return fileMeta;
},
ignore: []
},
userOpts
);
return (style, result) => {
if (opts.basePath) {
if (typeof opts.basePath === 'string') {
opts.basePath = [path.resolve(opts.basePath)];
} else {
opts.basePath = opts.basePath.map(elem => path.resolve(elem));
}
} else {
opts.basePath = [process.cwd()];
}
if (opts.dest) {
opts.dest = path.resolve(opts.dest);
} else {
throw new Error('Option `dest` is required in postcss-copy');
}
const promises = [];
style.walkDecls(decl => {
if (decl.value && decl.value.indexOf('url(') > -1) {
promises.push(processDecl(result, decl, opts));
}
});
return Promise.all(promises).then(decls =>
decls.forEach(decl => {
decl.value = String(decl.value);
})
);
};
}
export default postcss.plugin('postcss-copy', init);