forked from sass/node-sass-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
353 lines (290 loc) · 9.72 KB
/
middleware.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
'use strict';
var sass = require('node-sass'),
util = require('util'),
fs = require('fs'),
url = require('url'),
dirname = require('path').dirname,
mkdirp = require('mkdirp'),
join = require('path').join;
var imports = {};
/**
* Return Connect middleware with the given `options`.
*
* Options:
*
* all supportend options from node-sass project plus following:
*
* `src` - (String) Source directory used to find `.scss` or `.sass` files.
*
* optional configurations:
*
* `beepOnError` - Enable beep on error, false by default.
* `debug` - `[true | false]`, false by default. Output debugging information.
* `dest` - (String) Destination directory used to output `.css` files (when undefined defaults to `src`).
* `error` - A function to be called when something goes wrong.
* `force` - `[true | false]`, false by default. Always re-compile.
* `indentedSyntax` - `[true | false]`, false by default. Compiles files with the `.sass` extension instead of `.scss` in the `src` directory.
* `log` - `function(severity, key, val)`, used to log data instead of the default `console.error`
* `maxAge` - MaxAge to be passed in Cache-Control header.
* `prefix` - (String) It will tell the sass middleware that any request file will always be prefixed with `<prefix>` and this prefix should be ignored.
* `response` - `[true | false]`, true by default. To write output directly to response instead of to a file.
* `root` - (String) A base path for both source and destination directories.
*
*
* Examples:
*
* Pass the middleware to Connect, grabbing .scss files from this directory
* and saving .css files to _./public_.
*
* Following that we have a `staticProvider` layer setup to serve the .css
* files generated by Sass.
*
* var server = connect()
* .use(middleware({
* src: __dirname,
* dest: __dirname,
* }))
* .use(function(err, req, res, next) {
* res.statusCode = 500;
* res.end(err.message);
* });
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function(options) {
options = options || {};
// Accept single src/dest dir
if (typeof options === 'string') {
options = { src: options };
}
// Source directory (required)
var src = options.src || (function() {
throw new Error('sass.middleware() requires "src" directory.');
}());
// Destination directory (source by default)
var dest = options.dest || src;
// Optional base path for src and dest
var root = options.root || null;
// Force compilation everytime
var force = options.force || options.response;
// Enable debug output
var debug = options.debug;
// Enable beep on error
var beep = options.beepOnError || false;
var sassExtension = (options.indentedSyntax === true) ? '.sass' : '.scss';
var sourceMap = options.sourceMap || null;
var maxAge = options.maxAge || 0;
//Allow custom log function or default one
var log = options.log || function(severity, key, val, text) {
if (!debug && severity === 'debug') { // skip debug when debug is off
return;
}
text = text || '';
if (severity === 'error') {
console.error('[sass] \x1B[90m%s:\x1B[0m \x1B[36m%s %s\x1B[0m', key, val, text);
} else {
console.log('[sass] \x1B[90m%s:\x1B[0m \x1B[36m%s %s\x1B[0m', key, val, text);
}
};
// Default compile callback
options.compile = options.compile || function() {
return sass;
};
// Middleware
return function sass(req, res, next) {
var sassMiddlewareError = null;
// This function will be called if something goes wrong
var error = function(err, errorMessage) {
log('error', 'error', errorMessage || err);
if (options.error) {
options.error(err);
}
sassMiddlewareError = err;
};
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next();
}
var path = url.parse(req.url).pathname;
if (!/\.css$/.test(path)) {
log('debug', 'skip', path, 'nothing to do');
return next();
}
if (options.prefix) {
if (path.indexOf(options.prefix) === 0) {
path = path.substring(options.prefix.length);
} else {
log('debug', 'skip', path, 'prefix mismatch');
return next();
}
}
var cssPath = join(dest, path),
sassPath = join(src, path.replace(/\.css$/, sassExtension)),
sassDir = dirname(sassPath);
if (root) {
cssPath = join(root, dest, path.replace(new RegExp('^' + dest), ''));
sassPath = join(root, src, path
.replace(new RegExp('^' + dest), '')
.replace(/\.css$/, sassExtension));
sassDir = dirname(sassPath);
}
log('debug', 'source', sassPath);
log('debug', 'dest', options.response ? '<response>' : cssPath);
// When render is done, respond to the request accordingly
var done = function(err, result) {
if (err) {
var file = sassPath;
if (err.file && err.file !== 'stdin') {
file = err.file;
}
var fileLineColumn = file + ':' + err.line + ':' + err.column;
var errorMessage = (beep ? '\x07' : '') + '\x1B[31m' + err.message.replace(/^ +/, '') + '\n\nin ' + fileLineColumn + '\x1B[91m';
error(err, errorMessage);
return next(err);
}
var data = result.css;
log('debug', 'render', options.response ? '<response>' : sassPath);
if (sourceMap) {
log('debug', 'render', this.options.sourceMap);
}
imports[sassPath] = result.stats.includedFiles;
var cssDone = true;
var sourceMapDone = true;
function doneWriting() {
if (!cssDone || !sourceMapDone) {
return;
}
if (options.response === false) {
return next(sassMiddlewareError);
}
res.writeHead(200, {
'Content-Type': 'text/css',
'Cache-Control': 'max-age=' + maxAge
});
res.end(data);
}
// If response is true, do not write to file
if (options.response) {
return doneWriting();
}
cssDone = false;
sourceMapDone = !sourceMap;
mkdirp(dirname(cssPath), '0700', function(err) {
if (err) {
error(err);
cssDone = true;
return doneWriting();
}
fs.writeFile(cssPath, data, 'utf8', function(err) {
log('debug', 'write', cssPath);
if (err) {
error(err);
}
cssDone = true;
doneWriting();
});
});
if (sourceMap) {
var sourceMapPath = this.options.sourceMap;
mkdirp(dirname(sourceMapPath), '0700', function(err) {
if (err) {
error(err);
sourceMapDone = true;
return doneWriting();
}
fs.writeFile(sourceMapPath, result.map, 'utf8', function(err) {
log('debug', 'write', sourceMapPath);
if (err) {
error(err);
}
sourceMapDone = true;
doneWriting();
});
});
}
};
// Compile to cssPath
var compile = function() {
fs.exists(sassPath, function(exists) {
log('debug', 'read', sassPath);
if (!exists) {
log('debug', 'skip', sassPath, 'does not exist');
return next();
}
imports[sassPath] = undefined;
var style = options.compile();
var renderOptions = util._extend({}, options);
renderOptions.file = sassPath;
renderOptions.outFile = options.outFile || cssPath;
renderOptions.includePaths = [sassDir].concat(options.includePaths || []);
style.render(renderOptions, done);
});
};
// Force
if (force) {
return compile();
}
// Re-compile on server restart, disregarding
// mtimes since we need to map imports
if (!imports[sassPath]) {
return compile();
}
// Compare mtimes
fs.stat(sassPath, function(err, sassStats) {
if (err) { // sassPath can't be accessed, nothing to compile
log('debug', 'skip', sassPath, 'is unreadable');
return next();
}
fs.stat(cssPath, function(err, cssStats) {
if (err) {
if (err.code === 'ENOENT') { // CSS has not been compiled, compile it!
log('debug', 'compile', cssPath, 'was not found');
return compile();
}
error(err);
return next(err);
}
if (sassStats.mtime > cssStats.mtime) { // Source has changed, compile it
log('debug', 'compile', sassPath, 'was modified');
return compile();
}
// Already compiled, check imports
checkImports(sassPath, cssStats.mtime, function(changed) {
if (debug && changed && changed.length) {
changed.forEach(function(path) {
log('debug', 'compile', path, '(import file) was modified');
});
}
changed && changed.length ? compile() : next();
});
});
});
};
};
/**
* Check `path`'s imports to see if they have been altered.
*
* @param {String} path
* @param {Function} fn
* @api private
*/
function checkImports(path, time, fn) {
var nodes = imports[path];
if (!nodes || !nodes.length) {
return fn();
}
var pending = nodes.length,
changed = [];
// examine the imported files (nodes) for each parent sass (path)
nodes.forEach(function(imported) {
fs.stat(imported, function(err, stat) {
// error or newer mtime
if (err || stat.mtime >= time) {
changed.push(imported);
}
// decrease pending, if 0 call fn with the changed imports
--pending || fn(changed);
});
});
}