/
processor.js
469 lines (365 loc) · 13.7 KB
/
processor.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/* eslint-disable no-await-in-loop */
"use strict";
const fs = require("fs");
const path = require("path");
const Graph = require("dependency-graph").DepGraph;
const postcss = require("postcss");
const slug = require("unique-slug");
const mapValues = require("lodash/mapValues");
const output = require("./lib/output.js");
const message = require("./lib/message.js");
const relative = require("./lib/relative.js");
const tiered = require("./lib/graph-tiers.js");
const resolve = require("./lib/resolve.js");
const normalize = require("./lib/normalize.js");
const noop = () => true;
const params = ({ _options, _files, _graph, _resolve }, args) => Object.assign(
Object.create(null),
_options,
_options.postcss,
{
from : null,
files : _files,
graph : _graph,
resolve : _resolve,
},
args
);
class Processor {
constructor(opts) {
/* eslint max-statements: [ "warn", 25 ] */
const options = Object.assign(
Object.create(null),
{
cwd : process.cwd(),
map : false,
rewrite : true,
verbose : false,
resolvers : [],
postcss : {},
dupewarn : true,
},
opts
);
this._options = options;
if(!path.isAbsolute(options.cwd)) {
options.cwd = path.resolve(options.cwd);
}
if(typeof options.namer === "string") {
options.namer = require(options.namer)();
}
if(typeof options.namer !== "function") {
options.namer = (file, selector) =>
`mc${slug(relative(options.cwd, file))}_${selector}`;
}
this._log = options.verbose ?
// eslint-disable-next-line no-console
console.log.bind(console, "[processor]") :
// eslint-disable-next-line no-empty-function
() => {};
this._resolve = resolve.resolvers(options.resolvers);
this._normalize = normalize.bind(null, this._options.cwd);
this._files = Object.create(null);
this._graph = new Graph();
this._ids = new Map();
this._before = postcss([
...(options.before || []),
require("./plugins/values-local.js"),
require("./plugins/values-export.js"),
require("./plugins/values-replace.js"),
require("./plugins/graph-nodes.js"),
]);
this._process = postcss([
require("./plugins/at-composes.js"),
require("./plugins/values-composed.js"),
require("./plugins/values-imported.js"),
require("./plugins/values-export.js"),
require("./plugins/values-namespaced.js"),
require("./plugins/values-replace.js"),
require("./plugins/scoping.js"),
require("./plugins/externals.js"),
require("./plugins/composition.js"),
require("./plugins/keyframes.js"),
...(options.processing || []),
]);
this._after = postcss(options.after || [ noop ]);
// Add postcss-url to the afters if requested
if(options.rewrite) {
this._after.use(require("postcss-url")(options.rewrite));
}
this._done = postcss(options.done || [ noop ]);
}
// Add a file on disk to the dependency graph
file(file) {
const id = this._normalize(file);
this._log("file()", id);
return this._add(id, fs.readFileSync(id, "utf8"));
}
// Add a file by name + contents to the dependency graph
string(file, text) {
const id = this._normalize(file);
this._log("string()", id);
return this._add(id, text);
}
// Remove a file from the dependency graph
remove(input) {
// Only want files actually in the array
const files = (Array.isArray(input) ? input : [ input ])
.map(this._normalize)
.filter((file) => this._graph.hasNode(file));
if(!files.length) {
return files;
}
files.forEach((file) => {
delete this._files[file];
this._graph.removeNode(file);
this._log("remove()", file);
});
return files;
}
// Return the corrected-path version of the file
normalize(file) {
return this._normalize(file);
}
// Check if a file exists in the currently-processed set
has(input) {
const file = this._normalize(input);
return file in this._files;
}
// Mark a file and everything that depends on it as invalid so
// it can be overwritten
invalidate(input) {
if(!input) {
throw new Error("invalidate() requires a file argument");
}
// Only want files actually in the array
const source = this._normalize(input);
if(!this._graph.hasNode(source)) {
throw new Error(`Unknown file: ${input}`);
}
const deps = this.dependents(source);
[ ...deps, source ].forEach((file) => {
this._log("invalidate()", file);
this._files[file].valid = false;
this._ids.delete(file.toLowerCase());
});
}
// Get the dependency order for a file or the entire tree
dependencies(file, options = false) {
const { leavesOnly } = options;
if(file) {
const id = this._normalize(file);
return this._graph.dependenciesOf(id, leavesOnly);
}
return this._graph.overallOrder(leavesOnly);
}
// Get the dependant files for a file
dependents(file, options = false) {
if(!file) {
throw new Error("Must provide a file to processor.dependants()");
}
const id = this._normalize(file);
const { leavesOnly } = options;
return this._graph.dependantsOf(id, leavesOnly);
}
// Get the ultimate output for specific files or the entire tree
async output(args = false) {
const { to } = args;
let { files } = args;
if(!Array.isArray(files)) {
files = tiered(this._graph);
}
// Throw normalize values into a Set to remove dupes
files = new Set(files.map(this._normalize));
// Then turn it back into array because the iteration story is better
files = [ ...files.values() ];
// Verify that all requested files have been fully processed & succeeded
// See
// - https://github.com/tivac/modular-css/issues/248
// - https://github.com/tivac/modular-css/issues/324
await Promise.all(files.map((file) => {
if(!this._files[file]) {
throw new Error(`Unknown file requested: ${file}`);
}
return this._files[file].result;
}));
// Rewrite relative URLs before adding
// Have to do this every time because target file might be different!
const results = [];
for(const dep of files) {
this._log("_after()", dep);
const result = await this._after.process(
// NOTE: the call to .clone() is really important here, otherwise this call
// modifies the .result root itself and you process URLs multiple times
// See https://github.com/tivac/modular-css/issues/35
this._files[dep].result.root.clone(),
params(this, {
from : dep,
to,
})
);
results.push(result);
}
// Clone the first result if available to get valid source information
const root = results.length ? results[0].root.clone() : postcss.root();
// Then destroy all its children before adding new ones
root.removeAll();
results.forEach((result) => {
// Add file path comment
const comment = postcss.comment({
text : relative(this._options.cwd, result.opts.from),
// Add a bogus-ish source property so postcss won't make weird-looking
// source-maps that break the visualizer
//
// https://github.com/postcss/postcss/releases/tag/5.1.0
// https://github.com/postcss/postcss/pull/761
// https://github.com/tivac/modular-css/pull/157
//
source : Object.assign(
{},
result.root.source,
{ end : result.root.source.start }
),
});
root.append([ comment, ...result.root.nodes ]);
const idx = root.index(comment);
// Need to manually insert a newline after the comment, but can only
// do that via whatever comes after it for some reason?
// I'm not clear why comment nodes lack a `.raws.after` property
//
// https://github.com/postcss/postcss/issues/44
if(root.nodes[idx + 1]) {
root.nodes[idx + 1].raws.before = "\n";
}
});
const result = await this._done.process(
root,
params(this, args)
);
Object.defineProperty(result, "compositions", {
get : () => output.compositions(this),
});
return result;
}
// Expose files
get files() {
return this._files;
}
// Expose combined options object
get options() {
return this._options;
}
// Expose the dependency graph
get graph() {
return this._graph;
}
// Return all the compositions for the files loaded into the processor instance
get compositions() {
// Ensure all files are fully-processed first
return Promise.all(
Object.values(this._files).map(({ result }) => result)
)
.then(() => output.compositions(this));
}
// Take a file id and some text, walk it for dependencies, then
// process and return details
async _add(id, text) {
const check = id.toLowerCase();
// Warn about potential dupes if an ID goes past we've seen before
if(this._options.dupewarn) {
const other = this._ids.get(check);
if(other && other !== id) {
console.warn(`POTENTIAL DUPLICATE FILES:\n\t${relative(this._options.cwd, other)}\n\t${relative(this._options.cwd, id)}`);
}
}
this._ids.set(check, id);
this._log("_add()", id);
await this._walk(id, text);
const deps = [ ...this._graph.dependenciesOf(id), id ];
for(const dep of deps) {
const file = this._files[dep];
if(!file.processed) {
this._log("_process()", dep);
file.processed = this._process.process(
file.before,
params(this, {
from : dep,
namer : this._options.namer,
})
);
}
file.result = await file.processed;
const { result } = file;
file.exports = Object.assign(
Object.create(null),
// export @value entries
mapValues(file.values, ({ value }) => value),
// export classes
message(result, "classes"),
// Export anything from plugins named "modular-css-export*"
result.messages.reduce((out, { plugin, exports : exported }) => {
if(plugin.indexOf("modular-css-export") !== 0) {
return out;
}
return Object.assign(out, exported);
}, Object.create(null))
);
}
return {
id,
file : id,
files : this._files,
details : this._files[id],
exports : this._files[id].exports,
};
}
// Process files and walk their composition/value dependency tree to find
// new files we need to process
async _walk(name, text) {
// No need to re-process files unless they've been marked invalid
if(this._files[name] && this._files[name].valid) {
return;
}
this._graph.addNode(name, 0);
this._log("_before()", name);
let walked;
const file = this._files[name] = {
text,
exports : false,
values : false,
valid : true,
before : this._before.process(
text,
params(this, {
from : name,
})
),
walked : new Promise((done) => (walked = done)),
};
await file.before;
// Add all the found dependencies to the graph
file.before.messages.forEach(({ plugin, dependency }) => {
if(plugin !== "modular-css-graph-nodes") {
return;
}
const dep = this._normalize(dependency);
this._graph.addNode(dep, 0);
this._graph.addDependency(name, dep);
});
// Walk this node's dependencies, reading new files from disk as necessary
await Promise.all(
this._graph.dependenciesOf(name).map((dependency) => {
const { valid, walked : complete } = this._files[dependency] || false;
// If the file hasn't been invalidated wait for it to be done processing
if(valid) {
return complete;
}
// Otherwise add it to the queue
return this.file(dependency);
})
);
// Mark the walk of this file & its dependencies complete
walked();
}
}
module.exports = Processor;