/
core.js
346 lines (303 loc) · 8.64 KB
/
core.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
// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var multipart = require('multipart'),
utils = require('express/utils'),
events = require('events'),
fs = require('fs')
global.merge(require('sys'))
global.merge(require('express/event'))
global.merge(require('express/request'))
global.merge(require('express/plugin'))
global.merge(require('express/dsl'))
// --- Route
Route = Class({
/**
* Initialize a route with the given _method_,
* _path_, and callback _fn_.
*
* The given _path_ becomes #originalPath,
* #path is then a normalized version converted
* to a regular expression for routing.
*
* @param {string} method
* @param {string} path
* @param {function} fn
* @param {hash} options
* @api private
*/
init: function(method, path, fn, options){
this.method = method
this.originalPath = path
this.path = this.normalize(path)
this.fn = fn
},
/**
* Normalize _path_. When a RegExp it is simply returned,
* otherwise a string is converted to a regular expression
* surrounded by ^$. So /user/:id/edit would become:
*
* /^\/user\/([^\/]+)\/edit$/i
*
* Each param key (:id) will be captured and placed in the
* params array, so param('id') would give the string captured.
*
* The following are valid routes:
*
* - /user/:id Ex: '/user/12'
* - /user/:id? Ex: '/user', '/user/12'
* - /report.:format Ex: '/report.pdf', 'report.csv'
* - /public/* Ex: '/public/app.js', '/public/javascripts/app.js'
* - /public/*.* Ex: '/public/app.js', '/public/javascripts/app.js'
*
* @param {string} path
* @return {regexp}
* @api private
*/
normalize: function(path) {
var self = this
this.keys = []
if (path instanceof RegExp) return path
return new RegExp('^' + RegExp.escape(normalizePath(path), '.')
.replace(/\*/g, '(.+)')
.replace(/(\/|\\\.):(\w+)\?/g, function(_, c, key){
self.keys.push(key)
return '(?:' + c + '([^\/]+))?'
})
.replace(/:(\w+)/g, function(_, key){
self.keys.push(key)
return '([^\/]+)'
}) + '$', 'i')
}
})
// --- Router
Router = Class({
/**
* Initialize with _request_ and parse url.
*
* @param {Request} request
* @api private
*/
init: function(request) {
this.request = request
},
/**
* Evaluate the matched route against #request.
*
* @return {mixed}
* @api private
*/
route: function() {
var body,
route = this.matchingRoute()
if (route) {
body = route.fn.apply(this.request, this.request.captures.slice(1));
if (this.request.passed) {
if (typeof this.request.passed === 'string')
this.request.url.pathname = this.request.passed
this.request.passed = false
return this.route()
}
return body
}
else if (this.request.accepts('html') && set('helpful 404'))
this.request.halt(404, require('express/pages/not-found').render(this.request))
else
this.request.halt()
},
/**
* Attempt to match a route from Express.routes.
*
* @return {Route}
* @api private
*/
matchingRoute: function() {
this.lastMatchingRoute = this.lastMatchingRoute || 0
var routes = Express.routes, route
while (route = routes[this.lastMatchingRoute++])
if (this.match(route))
break
return route
},
/**
* Check if _route_ matches the current request.
* If so populate #captures and #params.
*
* @param {object} route
* @return {bool}
* @api private
*/
match: function(route) {
if (this.request.method.toLowerCase() == route.method)
if (this.request.captures = this.request.url.pathname.match(route.path)) {
this.mapParams(route)
return true
}
},
/**
* Map #request.captures to #request.params.path based on the
* given _route_ params.
*
* @param {Route} route
* @api private
*/
mapParams: function(route) {
route.keys.each(function(key, i){
this.request.params.path[key] = this.request.captures[++i]
}, this)
}
})
// --- Server
Server = Class({
/**
* Default port number.
*/
port: 3000,
/**
* Default host ip, when null node will accept requests on
* all network addresses.
*/
host: 'localhost',
/**
* Maximum number of queued connections.
*/
backlog: 128,
/**
* Run Express.
*
* - Buffers request bodies
* - Calls #route() once the request is complete
*
* @param {int} port
* @param {string} host
* @param {int} backlog
* @see run()
* @api private
*/
run: function(port, host, backlog){
var self = this
this.running = true
if (host !== undefined) this.host = host
if (port !== undefined) this.port = port
if (backlog !== undefined) this.backlog = backlog
require('http')
.createServer(function(request, response){
request.body = ''
request.setBodyEncoding('binary')
function callback(e, result) {
if (e)
self.error(e, request, response)
else if (!pendingFiles)
self.route(request, response)
}
if (request.headers['content-type'] &&
request.headers['content-type'].includes('multipart/form-data')) {
var stream = multipart.parse(request),
pendingFiles = 0
request.params = { post: {}}
stream
.addListener('partBegin', function(part) {
if (part.filename)
++pendingFiles,
part.tempfile = '/tmp/express-' + Number(new Date) + utils.uid(),
part.fileStream = fs.createWriteStream(part.tempfile)
else
part.buf = ''
})
.addListener('body', function(chunk) {
if (stream.part.fileStream)
stream.part.fileStream.write(chunk)
else
stream.part.buf += chunk
})
.addListener('partEnd', function(part) {
if (!part.name) return
if (part.fileStream)
part.fileStream.close(function(){
--pendingFiles
callback()
}),
utils.mergeParam(part.name, { filename: part.filename, tempfile: part.tempfile }, request.params.post)
else
utils.mergeParam(part.name, part.buf, request.params.post)
})
.addListener('error', callback)
.addListener('complete', callback)
}
else
request
.addListener('data', function(chunk){ request.body += chunk })
.addListener('end', callback)
})
.listen(this.port, this.host, this.backlog)
puts('Express started at http://' + this.host + ':' + this.port + '/ in ' + Express.environment + ' mode')
},
/**
* Route the given _request_ and _response_.
*
* @param {object} request
* @param {object} response
* @api private
*/
route: function(request, response){
var self = this,
request = new Request(request, response)
request.trigger('request', function(e) {
try {
if (e) throw e
if (request.response.finished) return
if (typeof (body = (new Router(request)).route()) === 'string')
request.halt(200, body)
} catch (e) {
self.error(e, request)
}
})
},
/**
* Handle errors.
*
* @param {Error} e
* @param {object} request
* @param {object} response
* @api private
*/
error: function (e, request, response) {
if (!(request instanceof Request))
request = new Request(request, response),
request.trigger('request')
if (request.accepts('html') && set('show exceptions'))
request.halt(500, require('express/pages/show-exceptions').render(request, e))
else
request.halt(500)
if (set('throw exceptions'))
throw e
}
})
// --- Express
Express = {
version: '0.7.3',
config: [],
routes: [],
plugins: [],
settings: {},
server: new Server
}
// --- Defaults
configure(function(){
use(require('express/plugins/view').View)
use(require('express/plugins/cache').Cache)
use(require('express/plugins/redirect').Redirect)
use(require('express/plugins/body-decoder').BodyDecoder)
})
configure('development', function(){
enable('helpful 404')
enable('show exceptions')
})
configure('test', function(){
enable('throw exceptions')
})
configure('production', function(){
enable('cache view contents')
enable('cache static files')
})