-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
379 lines (322 loc) · 11.3 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
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
var url = require("url");
var fs = require("fs");
var path = require("path");
var crypto = require("crypto");
var lru = require("lru-cache");
var getBuffer = (function() {
var buffers = lru({ max: 1024 * 500, length: function(n) { return n.length; } });
function watchBuffer(filePath) {
if(buffers.has(filePath)) { return; }
buffers.del(filePath);
fs.watchFile(filePath, function() { buffers.del(filePath); });
}
return function getBuffer(filePath, callback) {
if(buffers.has(filePath)) { return callback(null, buffers.get(filePath)); }
fs.stat(filePath, function(err, stats) {
if(err && err.code === "ENOENT") {
return callback({ "file-not-found": true, path: filePath }, null);
}
if(err) { return callback(err, null); }
if(!stats.isFile()) {
return callback({ "not-a-file": true, path: filePath }, null);
}
fs.readFile(filePath, function(err, data) {
if(err) { return callback(err, null); }
watchBuffer(filePath);
buffers.set(filePath, {
data: data,
sum: crypto.createHash("sha1").update(data).digest("hex")
});
callback(null, buffers.get(filePath));
});
});
};
})();
function sendBuffer(req, res, mimeType, maxAge) {
return function(err, buffer) {
if(err) {
if(err["file-not-found"]) {
console.error("Could not find file: " + err.path);
return default404(req, res);
} else if(err["not-a-file"]) {
console.error("Not a file: " + err.path);
return default404(req, res);
}
throw err;
}
if(maxAge == null) { maxAge = 365 * 24 * 60 * 60; }
res.removeHeader("Set-Cookie");
res.setHeader("Cache-Control", "private, max-age=" + maxAge);
res.setHeader("ETag", buffer.sum);
if(req.headers["if-none-match"] === buffer.sum) {
res.writeHead(304);
return res.end();
} else {
res.writeHead(
res.statusCode || 200,
{ "Content-Length": buffer.data.length, "Content-Type": mimeType }
);
return res.end(buffer.data, "binary");
}
};
}
var staticFile = (function() {
function handler(filePath, mimeType, req, res, maxAge) {
getBuffer(filePath, sendBuffer(req, res, mimeType, maxAge));
}
return function staticFile(filePath, mime, maxAge) {
return function(req, res) { handler(filePath, mime, req, res, maxAge); };
};
})();
function staticDir(rootDir, mimeLookup, maxAge) {
for(var key in mimeLookup) {
if(key.charAt(0) !== ".") {
console.warn("Extension found without a leading periond ('.'): '" + key + "'");
}
}
return function(req, res, extra, matches) {
matches = matches || extra;
var filePath = path.join.apply(path, [ rootDir ].concat(matches));
var ext = path.extname(filePath).toLowerCase();
if(!(ext in mimeLookup)) {
console.error("Unknown file extension -- file: " + filePath + "; extension: " + ext);
return default404(req, res);
}
if(path.relative(rootDir, filePath).indexOf("..") !== -1) {
console.error(
"Attempted access to parent directory -- root: " + rootDir + "; subdir: " + filePath
);
return default404(req, res);
}
getBuffer(filePath, sendBuffer(req, res, mimeLookup[ext], maxAge));
};
}
function default404(req, res, next) {
if(next) { return next(); }
var body = "404'd";
res.writeHead(404, { "Content-Length": body.length, "Content-Type": "text/plain" });
res.end(body);
console.log("Someone 404'd: " + req.url);
}
function default405(req, res, next) {
if(next) { return next(); }
var body = "405'd";
res.writeHead(405, { "Content-Length": body.length, "Content-Type": "text/plain" });
res.end(body);
console.log("Someone 405'd -- url: " + req.url + "; verb: " + req.method);
}
function default500(req, res, err, next) {
if(next) { return next(err); }
console.error("Error accessing: " + req.method + " " + req.url);
console.error(err.message);
console.error(err.stack);
var body = [ "500'd" ];
body.push("An exception was thrown while accessing: " + req.method + " " + req.url);
body.push("Exception: " + err.message);
body = body.join("\n");
res.writeHead(500, { "Content-Length": body.length, "Content-Type": "text/plain" });
res.end(body);
}
function findPattern(patterns, urlPath) {
for(var i = 0, l = patterns.length; i < l; i++) {
if(patterns[i].regex.test(urlPath)) {
return {
handler: patterns[i].handler,
extra: patterns[i].regex.exec(urlPath).slice(1)
};
}
}
return null;
}
function findGeneric(generics, req) {
for(var i = 0, l = generics.length; i < l; i++) {
if(generics[i].test(req)) { return generics[i].handler; }
}
return null;
}
var rRegExUrl = /^r`(.*)`$/, rToken = /`(.*?)(?:(?:\:\s*(.*?))|(\.\.\.)?)`/g;
function createTokenHandler(tokens, handler) {
return function(req, res, oriVals, next) {
var extra = Object.create(null);
var newVals = new Array(tokens.length);
for(var i = 0; i < tokens.length; i++) {
var token = tokens[i];
extra[token.name] = decodeURIComponent(oriVals[token.captureIdx]);
newVals[i] = oriVals[token.captureIdx];
}
executeHandler(handler, this, req, res, { extra: extra, vals: newVals, next: next });
};
}
var rHasFullCapture = /^\((?!\?[:!=]).*\)$/;
function processEmbeddedRegex(regex) {
regex = regex.trim();
var rTest = new RegExp("|" + regex);
var numCaptures = rTest.exec("").length - 1;
if(numCaptures <= 0) { return { regex: "(" + regex + ")", numCaptures: 1 }; }
if(rHasFullCapture.test(regex)) { return { regex: regex, numCaptures: numCaptures }; }
return { regex: "(" + regex + ")", numCaptures: numCaptures + 1 };
}
var rHasBackreference = /\\[1-9]/;
function parseToken(rule, handler) {
var tokens = [], captureIdx = 0;
var transform = rule.replace(rToken, function replaceToken(_, name, regex, isExtend) {
if(!regex) {
tokens.push({ name: name, captureIdx: captureIdx });
captureIdx += 1;
} else {
var info = processEmbeddedRegex(regex);
regex = info.regex;
tokens.push({ name: name, captureIdx: captureIdx });
captureIdx += info.numCaptures;
if(rHasBackreference.test(regex)) {
console.warn("Backreference are not supported -- url: " + rule);
}
}
return regex || (isExtend ? "(.*?)" : "([^/]*?)");
});
var rRule = new RegExp("^" + transform + "$");
return { regex: rRule, handler: createTokenHandler(tokens, handler) };
}
function executeHandler(handler, thisp, req, res, opts) {
var override = req.headers && req.headers["x-http-method-override"];
handler = (handler[override] || handler[req.method] || handler.any || handler);
var extra = opts.extra, vals = opts.vals, next = opts.next;
if(extra && vals) { req.params = extra; }
if(next) {
if(extra && vals) { handler.call(thisp, req, res, extra, vals, next); }
else if(extra) { handler.call(thisp, req, res, extra, next); }
else { handler.call(thisp, req, res, next); }
} else {
if(extra && vals) { handler.call(thisp, req, res, extra, vals); }
else if(extra) { handler.call(thisp, req, res, extra); }
else { handler.call(thisp, req, res); }
}
}
function expandVerbs(handler) { // Expands "POST GET": handler to "POST": handler, "GET": handler
if(handler.test) { // For `generic` type handlers
handler.handler = expandVerbs(handler.handler);
return handler;
}
for(var key in handler) {
key.split(/\s+/).forEach(function(method) {
handler[method] = handler[key];
});
}
return handler;
}
var rWhitespace = /[\x20\t\r\n\f]/;
function splitRules(key) {
var rules = [];
var isQuoted = false, isPrevSpace = false;
var ruleIdx = 0, curIdx = 0;
while(curIdx < key.length) {
var chr = key.charAt(curIdx);
if(chr === "`") { isQuoted = !isQuoted; curIdx += 1; continue; }
if(isQuoted) { curIdx += 1; continue; }
if(!rWhitespace.test(chr)) { curIdx += 1; continue; }
rules.push(key.substring(ruleIdx, curIdx));
do { // consume whitespace
curIdx += 1;
chr = key.charAt(curIdx);
} while(curIdx < key.length && rWhitespace.test(chr));
ruleIdx = curIdx;
}
if(isQuoted) { console.warn("Invalid beeline rule: " + key.substring(ruleIdx)); }
else if(ruleIdx !== curIdx) { rules.push(key.substring(ruleIdx)); }
return rules;
}
function route(routes) {
var preprocess = [], urls = Object.create(null), patterns = [], generics = [];
var missing = default404, missingVerb = default405, error = default500;
function handler(req, res, next) {
try {
var urlPath = url.parse(req.url).pathname;
var info = (
urls[urlPath] ||
findPattern(patterns, urlPath) ||
findGeneric(generics, req) ||
missing
);
var handler = info.handler || info;
var extra = info.extra;
preprocess.forEach(function(process) { process(req, res); });
executeHandler(handler, this, req, res, { extra: extra, next: next });
} catch(err) {
error.call(this, req, res, err, next);
}
}
function missingVerbHandler(req, res) {
var next = arguments[arguments.length - 1];
if(typeof next !== "function") { missingVerb.call(this, req, res); }
else { missingVerb.call(this, req, res, next); }
}
handler.add = function(routes) {
for(var key in routes) {
var handler = routes[key];
if(Object.prototype.toString.call(handler) === "[object Object]") {
handler.any = handler.any || missingVerbHandler;
}
if(key === "`preprocess`") {
if(!Array.isArray(handler)) { preprocess.push(handler); }
else { Array.prototype.push.apply(preprocess, handler); }
continue;
}
splitRules(key).forEach(function(rule) {
if(rule.indexOf("`") === -1) {
if(rule in urls) { console.warn("Duplicate beeline rule: " + rule); }
if(rule.charAt(0) !== "/") {
console.warn("Url doesn't have leading slash (/): " + rule);
}
urls[rule] = expandVerbs(handler);
} else if(rule === "`404`" || rule === "`missing`" || rule === "`default`") {
if(missing !== default404) { console.warn("Duplicate beeline rule: " + rule); }
missing = expandVerbs(handler);
} else if(
rule === "`405`" || rule === "`missing-verb`" || rule === "`missingVerb`"
) {
if(missingVerb !== default405) {
console.warn("Duplicate beeline rule: " + rule);
}
missingVerb = expandVerbs(handler);
} else if(rule === "`500`" || rule === "`error`") {
if(error !== default500) { console.warn("Duplicate beeline rule: " + rule); }
error = expandVerbs(handler);
} else if(rule === "`generics`") {
Array.prototype.push.apply(generics, handler.map(expandVerbs));
} else if(rRegExUrl.test(rule)) {
var rRule = new RegExp(rRegExUrl.exec(rule)[1]);
var cmpRegEx = function(p) { return p.regex.toString() === rRule.toString(); };
if(patterns.some(cmpRegEx)) {
console.warn("Duplicate beeline rule: " + rule);
}
patterns.push({ regex: rRule, handler: expandVerbs(handler) });
} else if(rToken.test(rule)) {
var pattern = parseToken(rule, expandVerbs(handler));
var cmpPattern = function(p) {
return p.regex.toString() === pattern.regex.toString();
};
if(patterns.some(cmpPattern)) {
console.warn("Duplicate beeline rule: " + rule);
}
patterns.push(pattern);
} else {
console.warn("Invalid beeline rule: " + rule);
}
});
}
};
handler.missing = function(req, res, thisp) {
missing.call(thisp, req, res);
};
handler.missingVerb = function(req, res, thisp) {
missingVerb.call(thisp, req, res);
};
handler.error = function(req, res, err, thisp) {
error.call(thisp, req, res, err);
};
handler.add(routes);
return handler;
}
exports.route = route;
exports.staticFile = staticFile;
exports.staticDir = staticDir;