-
Notifications
You must be signed in to change notification settings - Fork 47
/
cmify.js
87 lines (71 loc) · 2.27 KB
/
cmify.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
var stream = require('stream');
var util = require('util');
var assign = require('object-assign');
var path = require('path');
util.inherits(Cmify, stream.Transform);
function Cmify (filename, opts) {
if (!(this instanceof Cmify)) {
return new Cmify(filename, opts);
}
stream.Transform.call(this);
this.cssFilePattern = new RegExp(opts.cssFilePattern || '\.css$');
this._data = '';
this._filename = filename;
this._cssOutFilename = opts.cssOutFilename;
this._loader = opts.loader;
this._tokensByFile = opts.tokensByFile;
this._rootDir = opts.rootDir;
opts.cssFiles.push(filename);
}
Cmify.prototype.isCssFile = function (filename) {
return this.cssFilePattern.test(filename);
};
Cmify.prototype._transform = function (buf, enc, callback) {
// only handle .css files
if (!this.isCssFile(this._filename)) {
this.push(buf);
return callback();
}
this._data += buf;
callback();
};
Cmify.prototype._flush = function (callback) {
var self = this;
var filename = this._filename;
// only handle .css files
if (!this.isCssFile(filename)) { return callback(); }
// grab the correct loader
var loader = this._loader;
var tokensByFile = this._tokensByFile;
// convert css to js before pushing
// reset the `tokensByFile` state
var relFilename = path.relative(this._rootDir, filename);
tokensByFile[filename] = loader.tokensByFile[filename] = null;
loader.fetch(relFilename, '/').then(function (tokens) {
var deps = loader.deps.dependenciesOf(filename);
var output = deps.map(function (f) {
return 'require("' + f + '")';
});
output.push('module.exports = ' + JSON.stringify(tokens));
var isValid = true;
var isUndefined = /\bundefined\b/;
Object.keys(tokens).forEach(function (k) {
if (isUndefined.test(tokens[k])) {
isValid = false;
}
});
if (!isValid) {
var err = 'Composition in ' + filename + ' contains an undefined reference';
console.error(err);
output.push('console.error("' + err + '");');
}
assign(tokensByFile, loader.tokensByFile);
self.push(output.join('\n'));
return callback();
}).catch(function (err) {
self.push('console.error("' + err + '");');
self.emit('error', err);
return callback();
});
};
module.exports = Cmify;