clean.js
7.64 KB
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
/**
* Clean-css - https://github.com/jakubpawlowicz/clean-css
* Released under the terms of MIT license
*
* Copyright (C) 2015 JakubPawlowicz.com
*/
var ImportInliner = require('./imports/inliner');
var rebaseUrls = require('./urls/rebase');
var tokenize = require('./tokenizer/tokenize');
var simpleOptimize = require('./selectors/simple');
var advancedOptimize = require('./selectors/advanced');
var simpleStringify = require('./stringifier/simple');
var sourceMapStringify = require('./stringifier/source-maps');
var CommentsProcessor = require('./text/comments-processor');
var ExpressionsProcessor = require('./text/expressions-processor');
var FreeTextProcessor = require('./text/free-text-processor');
var UrlsProcessor = require('./text/urls-processor');
var Compatibility = require('./utils/compatibility');
var InputSourceMapTracker = require('./utils/input-source-map-tracker');
var SourceTracker = require('./utils/source-tracker');
var SourceReader = require('./utils/source-reader');
var Validator = require('./properties/validator');
var fs = require('fs');
var path = require('path');
var url = require('url');
var override = require('./utils/object').override;
var DEFAULT_TIMEOUT = 5000;
var CleanCSS = module.exports = function CleanCSS(options) {
options = options || {};
this.options = {
advanced: undefined === options.advanced ? true : !!options.advanced,
aggressiveMerging: undefined === options.aggressiveMerging ? true : !!options.aggressiveMerging,
benchmark: options.benchmark,
compatibility: new Compatibility(options.compatibility).toOptions(),
debug: options.debug,
explicitRoot: !!options.root,
explicitTarget: !!options.target,
inliner: options.inliner || {},
keepBreaks: options.keepBreaks || false,
keepSpecialComments: 'keepSpecialComments' in options ? options.keepSpecialComments : '*',
mediaMerging: undefined === options.mediaMerging ? true : !!options.mediaMerging,
processImport: undefined === options.processImport ? true : !!options.processImport,
processImportFrom: importOptionsFrom(options.processImportFrom),
rebase: undefined === options.rebase ? true : !!options.rebase,
relativeTo: options.relativeTo,
restructuring: undefined === options.restructuring ? true : !!options.restructuring,
root: options.root || process.cwd(),
roundingPrecision: options.roundingPrecision,
semanticMerging: undefined === options.semanticMerging ? false : !!options.semanticMerging,
shorthandCompacting: undefined === options.shorthandCompacting ? true : !!options.shorthandCompacting,
sourceMap: options.sourceMap,
sourceMapInlineSources: !!options.sourceMapInlineSources,
target: !options.target || missingDirectory(options.target) || presentDirectory(options.target) ? options.target : path.dirname(options.target)
};
this.options.inliner.timeout = this.options.inliner.timeout || DEFAULT_TIMEOUT;
this.options.inliner.request = override(
/* jshint camelcase: false */
proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy),
this.options.inliner.request || {}
);
};
function importOptionsFrom(rules) {
return undefined === rules ? ['all'] : rules;
}
function missingDirectory(filepath) {
return !fs.existsSync(filepath) && !/\.css$/.test(filepath);
}
function presentDirectory(filepath) {
return fs.existsSync(filepath) && fs.statSync(filepath).isDirectory();
}
function proxyOptionsFrom(httpProxy) {
return httpProxy ?
{
hostname: url.parse(httpProxy).hostname,
port: parseInt(url.parse(httpProxy).port)
} :
{};
}
CleanCSS.prototype.minify = function (data, callback) {
var context = {
stats: {},
errors: [],
warnings: [],
options: this.options,
debug: this.options.debug,
localOnly: !callback,
sourceTracker: new SourceTracker(),
validator: new Validator(this.options.compatibility)
};
if (context.options.sourceMap)
context.inputSourceMapTracker = new InputSourceMapTracker(context);
context.sourceReader = new SourceReader(context, data);
data = context.sourceReader.toString();
if (context.options.processImport || data.indexOf('@shallow') > 0) {
// inline all imports
var runner = callback ?
process.nextTick :
function (callback) { return callback(); };
return runner(function () {
return new ImportInliner(context).process(data, {
localOnly: context.localOnly,
imports: context.options.processImportFrom,
whenDone: runMinifier(callback, context)
});
});
} else {
return runMinifier(callback, context)(data);
}
};
function runMinifier(callback, context) {
function whenSourceMapReady (data) {
data = context.options.debug ?
minifyWithDebug(context, data) :
minify(context, data);
data = withMetadata(context, data);
return callback ?
callback.call(null, context.errors.length > 0 ? context.errors : null, data) :
data;
}
return function (data) {
if (context.options.sourceMap) {
return context.inputSourceMapTracker.track(data, function () {
if (context.options.sourceMapInlineSources) {
return context.inputSourceMapTracker.resolveSources(function () {
return whenSourceMapReady(data);
});
} else {
return whenSourceMapReady(data);
}
});
} else {
return whenSourceMapReady(data);
}
};
}
function withMetadata(context, data) {
data.stats = context.stats;
data.errors = context.errors;
data.warnings = context.warnings;
return data;
}
function minifyWithDebug(context, data) {
var startedAt = process.hrtime();
context.stats.originalSize = context.sourceTracker.removeAll(data).length;
data = minify(context, data);
var elapsed = process.hrtime(startedAt);
context.stats.timeSpent = ~~(elapsed[0] * 1e3 + elapsed[1] / 1e6);
context.stats.efficiency = 1 - data.styles.length / context.stats.originalSize;
context.stats.minifiedSize = data.styles.length;
return data;
}
function benchmark(runner) {
return function (processor, action) {
var name = processor.constructor.name + '#' + action;
var start = process.hrtime();
runner(processor, action);
var itTook = process.hrtime(start);
console.log('%d ms: ' + name, 1000 * itTook[0] + itTook[1] / 1000000);
};
}
function minify(context, data) {
var options = context.options;
var commentsProcessor = new CommentsProcessor(context, options.keepSpecialComments, options.keepBreaks, options.sourceMap);
var expressionsProcessor = new ExpressionsProcessor(options.sourceMap);
var freeTextProcessor = new FreeTextProcessor(options.sourceMap);
var urlsProcessor = new UrlsProcessor(context, options.sourceMap, options.compatibility.properties.urlQuotes);
var stringify = options.sourceMap ? sourceMapStringify : simpleStringify;
var run = function (processor, action) {
data = typeof processor == 'function' ?
processor(data) :
processor[action](data);
};
if (options.benchmark)
run = benchmark(run);
run(commentsProcessor, 'escape');
run(expressionsProcessor, 'escape');
run(urlsProcessor, 'escape');
run(freeTextProcessor, 'escape');
function restoreEscapes(data, prefixContent) {
data = freeTextProcessor.restore(data, prefixContent);
data = urlsProcessor.restore(data);
data = options.rebase ? rebaseUrls(data, context) : data;
data = expressionsProcessor.restore(data);
return commentsProcessor.restore(data);
}
var tokens = tokenize(data, context);
simpleOptimize(tokens, options, context);
if (options.advanced)
advancedOptimize(tokens, options, context, true);
return stringify(tokens, options, restoreEscapes, context.inputSourceMapTracker);
}