forked from temich/less-features-connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (77 loc) · 2.45 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
var less = require('less-context-functions'),
path = require('path'),
url = require('url'),
qs = require('querystring'),
fs = require('fs'),
domain = require('domain');
var root = path.resolve(process.cwd(), '..'),
config = { libs: [] },
cache = {},
logger;
function filename(uri) {
return path.resolve(root, url.parse(uri).pathname.substr(1)).replace(/\.css\b/, '.less');
}
function feature(feats) {
return function (n) {
return feats.indexOf(n.value) !== -1 ? less.tree.True : less.tree.False;
}
}
function features(uri) {
var s = url.parse(uri).search,
q = s ? qs.parse(s.substring(1)) : undefined,
feats = [];
if (q && q.features)
feats = q.features.split('|');
return feats;
}
function options(filename, req) {
var opts = {};
opts.paths = [path.dirname(filename), config.libs];
opts.compress = config.compress;
opts.functions = { feature: feature(features(req.url)) };
return opts;
}
function read(file, next) {
fs.readFile(file, 'utf-8', function (err, data) {
logger && logger.trace('Reading file ' + file);
next(err, data);
});
}
function handle(req, res, next) {
var d = domain.create();
d.on('error', function(err) {
err = err || {};
logger.error('Error processing request', req.url, err);
console.error('Error processing request', req.url, err);
try {
err && err.code !== 'ENOENT'
? res.error().end()
: res.notFound().end();
} catch (e) {
logger.error('Error sending 500', err, req.url);
}
});
d.add(req);
d.add(res);
if (cache[req.url])
return res.css(cache[req.url]);
logger && logger.trace('Processing request' + req.url);
var file = filename(req.url);
read(file, d.intercept(function(data) {
logger && logger.trace('Rendering file ' + file);
less.render(data, options(file, req), d.intercept(function (data) {
logger && logger.trace('Sending data (%d bytes) %s', data ? data.length : 0, req.url);
config.caching && (cache[req.url] = data);
res.css(data);
logger && logger.trace('%s has been served successfully', req.url);
}));
}));
}
module.exports = function (cfg, log) {
config = cfg;
logger = log;
if (config.root) {
root = path.resolve(root, config.root);
}
return handle;
};