-
Notifications
You must be signed in to change notification settings - Fork 84
/
index.js
748 lines (604 loc) · 15.2 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*!
* router
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2022 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('router')
var flatten = require('array-flatten').flatten
var Layer = require('./lib/layer')
var methods = require('methods')
var mixin = require('utils-merge')
var parseUrl = require('parseurl')
var Route = require('./lib/route')
var setPrototypeOf = require('setprototypeof')
/**
* Module variables.
* @private
*/
var slice = Array.prototype.slice
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
? setImmediate
: function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
/**
* Expose `Router`.
*/
module.exports = Router
/**
* Expose `Route`.
*/
module.exports.Route = Route
/**
* Initialize a new `Router` with the given `options`.
*
* @param {object} [options]
* @return {Router} which is a callable function
* @public
*/
function Router(options) {
if (!(this instanceof Router)) {
return new Router(options)
}
var opts = options || {}
function router(req, res, next) {
router.handle(req, res, next)
}
// inherit from the correct prototype
setPrototypeOf(router, this)
router.caseSensitive = opts.caseSensitive
router.mergeParams = opts.mergeParams
router.params = {}
router.strict = opts.strict
router.stack = []
return router
}
/**
* Router prototype inherits from a Function.
*/
/* istanbul ignore next */
Router.prototype = function () {}
/**
* Map the given param placeholder `name`(s) to the given callback.
*
* Parameter mapping is used to provide pre-conditions to routes
* which use normalized placeholders. For example a _:user_id_ parameter
* could automatically load a user's information from the database without
* any additional code.
*
* The callback uses the same signature as middleware, the only difference
* being that the value of the placeholder is passed, in this case the _id_
* of the user. Once the `next()` function is invoked, just like middleware
* it will continue on to execute the route, or subsequent parameter functions.
*
* Just like in middleware, you must either respond to the request or call next
* to avoid stalling the request.
*
* router.param('user_id', function(req, res, next, id){
* User.find(id, function(err, user){
* if (err) {
* return next(err)
* } else if (!user) {
* return next(new Error('failed to load user'))
* }
* req.user = user
* next()
* })
* })
*
* @param {string} name
* @param {function} fn
* @public
*/
Router.prototype.param = function param(name, fn) {
if (!name) {
throw new TypeError('argument name is required')
}
if (typeof name !== 'string') {
throw new TypeError('argument name must be a string')
}
if (!fn) {
throw new TypeError('argument fn is required')
}
if (typeof fn !== 'function') {
throw new TypeError('argument fn must be a function')
}
var params = this.params[name]
if (!params) {
params = this.params[name] = []
}
params.push(fn)
return this
}
/**
* Dispatch a req, res into the router.
*
* @private
*/
Router.prototype.handle = function handle(req, res, callback) {
if (!callback) {
throw new TypeError('argument callback is required')
}
debug('dispatching %s %s', req.method, req.url)
var idx = 0
var methods
var protohost = getProtohost(req.url) || ''
var removed = ''
var self = this
var slashAdded = false
var sync = 0
var paramcalled = {}
// middleware and routes
var stack = this.stack
// manage inter-router variables
var parentParams = req.params
var parentUrl = req.baseUrl || ''
var done = restore(callback, req, 'baseUrl', 'next', 'params')
// setup next layer
req.next = next
// for options requests, respond with a default if nothing else responds
if (req.method === 'OPTIONS') {
methods = []
done = wrap(done, generateOptionsResponder(res, methods))
}
// setup basic req values
req.baseUrl = parentUrl
req.originalUrl = req.originalUrl || req.url
next()
function next(err) {
var layerError = err === 'route'
? null
: err
// remove added slash
if (slashAdded) {
req.url = req.url.slice(1)
slashAdded = false
}
// restore altered req.url
if (removed.length !== 0) {
req.baseUrl = parentUrl
req.url = protohost + removed + req.url.slice(protohost.length)
removed = ''
}
// signal to exit router
if (layerError === 'router') {
defer(done, null)
return
}
// no more matching layers
if (idx >= stack.length) {
defer(done, layerError)
return
}
// max sync stack
if (++sync > 100) {
return defer(next, err)
}
// get pathname of request
var path = getPathname(req)
if (path == null) {
return done(layerError)
}
// find next matching layer
var layer
var match
var route
while (match !== true && idx < stack.length) {
layer = stack[idx++]
match = matchLayer(layer, path)
route = layer.route
if (typeof match !== 'boolean') {
// hold on to layerError
layerError = layerError || match
}
if (match !== true) {
continue
}
if (!route) {
// process non-route handlers normally
continue
}
if (layerError) {
// routes do not match with a pending error
match = false
continue
}
var method = req.method
var has_method = route._handles_method(method)
// build up automatic options response
if (!has_method && method === 'OPTIONS' && methods) {
methods.push.apply(methods, route._methods())
}
// don't even bother matching route
if (!has_method && method !== 'HEAD') {
match = false
continue
}
}
// no match
if (match !== true) {
return done(layerError)
}
// store route for dispatch on change
if (route) {
req.route = route
}
// Capture one-time layer values
req.params = self.mergeParams
? mergeParams(layer.params, parentParams)
: layer.params
var layerPath = layer.path
// this should be done for the layer
self.process_params(layer, paramcalled, req, res, function (err) {
if (err) {
next(layerError || err)
} else if (route) {
layer.handle_request(req, res, next)
} else {
trim_prefix(layer, layerError, layerPath, path)
}
sync = 0
})
}
function trim_prefix(layer, layerError, layerPath, path) {
if (layerPath.length !== 0) {
// Validate path is a prefix match
if (layerPath !== path.substring(0, layerPath.length)) {
next(layerError)
return
}
// Validate path breaks on a path separator
var c = path[layerPath.length]
if (c && c !== '/') {
next(layerError)
return
}
// Trim off the part of the url that matches the route
// middleware (.use stuff) needs to have the path stripped
debug('trim prefix (%s) from url %s', layerPath, req.url)
removed = layerPath
req.url = protohost + req.url.slice(protohost.length + removed.length)
// Ensure leading slash
if (!protohost && req.url[0] !== '/') {
req.url = '/' + req.url
slashAdded = true
}
// Setup base URL (no trailing slash)
req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
? removed.substring(0, removed.length - 1)
: removed)
}
debug('%s %s : %s', layer.name, layerPath, req.originalUrl)
if (layerError) {
layer.handle_error(layerError, req, res, next)
} else {
layer.handle_request(req, res, next)
}
}
}
/**
* Process any parameters for the layer.
*
* @private
*/
Router.prototype.process_params = function process_params(layer, called, req, res, done) {
var params = this.params
// captured parameters from the layer, keys and values
var keys = layer.keys
// fast track
if (!keys || keys.length === 0) {
return done()
}
var i = 0
var name
var paramIndex = 0
var key
var paramVal
var paramCallbacks
var paramCalled
// process params in order
// param callbacks can be async
function param(err) {
if (err) {
return done(err)
}
if (i >= keys.length ) {
return done()
}
paramIndex = 0
key = keys[i++]
name = key.name
paramVal = req.params[name]
paramCallbacks = params[name]
paramCalled = called[name]
if (paramVal === undefined || !paramCallbacks) {
return param()
}
// param previously called with same value or error occurred
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
req.params[name] = paramCalled.value
// next param
return param(paramCalled.error)
}
called[name] = paramCalled = {
error: null,
match: paramVal,
value: paramVal
}
paramCallback()
}
// single param callbacks
function paramCallback(err) {
var fn = paramCallbacks[paramIndex++]
// store updated value
paramCalled.value = req.params[key.name]
if (err) {
// store error
paramCalled.error = err
param(err)
return
}
if (!fn) return param()
try {
fn(req, res, paramCallback, paramVal, key.name)
} catch (e) {
paramCallback(e)
}
}
param()
}
/**
* Use the given middleware function, with optional path, defaulting to "/".
*
* Use (like `.all`) will run for any http METHOD, but it will not add
* handlers for those methods so OPTIONS requests will not consider `.use`
* functions even if they could respond.
*
* The other difference is that _route_ path is stripped and not visible
* to the handler function. The main effect of this feature is that mounted
* handlers can operate without any code changes regardless of the "prefix"
* pathname.
*
* @public
*/
Router.prototype.use = function use(handler) {
var offset = 0
var path = '/'
// default path to '/'
// disambiguate router.use([handler])
if (typeof handler !== 'function') {
var arg = handler
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0]
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1
path = handler
}
}
var callbacks = flatten(slice.call(arguments, offset))
if (callbacks.length === 0) {
throw new TypeError('argument handler is required')
}
for (var i = 0; i < callbacks.length; i++) {
var fn = callbacks[i]
if (typeof fn !== 'function') {
throw new TypeError('argument handler must be a function')
}
// add the middleware
debug('use %o %s', path, fn.name || '<anonymous>')
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: false,
end: false
}, fn)
layer.route = undefined
this.stack.push(layer)
}
return this
}
/**
* Create a new Route for the given path.
*
* Each route contains a separate middleware stack and VERB handlers.
*
* See the Route api documentation for details on adding handlers
* and middleware to routes.
*
* @param {string} path
* @return {Route}
* @public
*/
Router.prototype.route = function route(path) {
var route = new Route(path)
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: this.strict,
end: true
}, handle)
function handle(req, res, next) {
route.dispatch(req, res, next)
}
layer.route = route
this.stack.push(layer)
return route
}
// create Router#VERB functions
methods.concat('all').forEach(function(method){
Router.prototype[method] = function (path) {
var route = this.route(path)
route[method].apply(route, slice.call(arguments, 1))
return this
}
})
/**
* Generate a callback that will make an OPTIONS response.
*
* @param {OutgoingMessage} res
* @param {array} methods
* @private
*/
function generateOptionsResponder(res, methods) {
return function onDone(fn, err) {
if (err || methods.length === 0) {
return fn(err)
}
trySendOptionsResponse(res, methods, fn)
}
}
/**
* Get pathname of request.
*
* @param {IncomingMessage} req
* @private
*/
function getPathname(req) {
try {
return parseUrl(req).pathname
} catch (err) {
return undefined
}
}
/**
* Get get protocol + host for a URL.
*
* @param {string} url
* @private
*/
function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}
var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substring(0, pathLength).indexOf('://')
return fqdnIndex !== -1
? url.substring(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
}
/**
* Match path to a layer.
*
* @param {Layer} layer
* @param {string} path
* @private
*/
function matchLayer(layer, path) {
try {
return layer.match(path)
} catch (err) {
return err
}
}
/**
* Merge params with parent params
*
* @private
*/
function mergeParams(params, parent) {
if (typeof parent !== 'object' || !parent) {
return params
}
// make copy of parent for base
var obj = mixin({}, parent)
// simple non-numeric merging
if (!(0 in params) || !(0 in parent)) {
return mixin(obj, params)
}
var i = 0
var o = 0
// determine numeric gap in params
while (i in params) {
i++
}
// determine numeric gap in parent
while (o in parent) {
o++
}
// offset numeric indices in params before merge
for (i--; i >= 0; i--) {
params[i + o] = params[i]
// create holes for the merge when necessary
if (i < o) {
delete params[i]
}
}
return mixin(obj, params)
}
/**
* Restore obj props after function
*
* @private
*/
function restore(fn, obj) {
var props = new Array(arguments.length - 2)
var vals = new Array(arguments.length - 2)
for (var i = 0; i < props.length; i++) {
props[i] = arguments[i + 2]
vals[i] = obj[props[i]]
}
return function(){
// restore vals
for (var i = 0; i < props.length; i++) {
obj[props[i]] = vals[i]
}
return fn.apply(this, arguments)
}
}
/**
* Send an OPTIONS response.
*
* @private
*/
function sendOptionsResponse(res, methods) {
var options = Object.create(null)
// build unique method map
for (var i = 0; i < methods.length; i++) {
options[methods[i]] = true
}
// construct the allow list
var allow = Object.keys(options).sort().join(', ')
// send response
res.setHeader('Allow', allow)
res.setHeader('Content-Length', Buffer.byteLength(allow))
res.setHeader('Content-Type', 'text/plain')
res.setHeader('X-Content-Type-Options', 'nosniff')
res.end(allow)
}
/**
* Try to send an OPTIONS response.
*
* @private
*/
function trySendOptionsResponse(res, methods, next) {
try {
sendOptionsResponse(res, methods)
} catch (err) {
next(err)
}
}
/**
* Wrap a function
*
* @private
*/
function wrap(old, fn) {
return function proxy() {
var args = new Array(arguments.length + 1)
args[0] = old
for (var i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i]
}
fn.apply(this, args)
}
}