-
Notifications
You must be signed in to change notification settings - Fork 140
/
index.js
665 lines (544 loc) · 19.5 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
'use strict'
/*
Char codes:
'!': 33 - !
'#': 35 - %23
'$': 36 - %24
'%': 37 - %25
'&': 38 - %26
''': 39 - '
'(': 40 - (
')': 41 - )
'*': 42 - *
'+': 43 - %2B
',': 44 - %2C
'-': 45 - -
'.': 46 - .
'/': 47 - %2F
':': 58 - %3A
';': 59 - %3B
'=': 61 - %3D
'?': 63 - %3F
'@': 64 - %40
'_': 95 - _
'~': 126 - ~
*/
const assert = require('assert')
const querystring = require('fast-querystring')
const isRegexSafe = require('safe-regex2')
const deepEqual = require('fast-deep-equal')
const { prettyPrintTree } = require('./lib/pretty-print')
const { StaticNode, NODE_TYPES } = require('./custom_node')
const Constrainer = require('./lib/constrainer')
const httpMethods = require('./lib/http-methods')
const httpMethodStrategy = require('./lib/strategies/http-method')
const { safeDecodeURI, safeDecodeURIComponent } = require('./lib/url-sanitizer')
const FULL_PATH_REGEXP = /^https?:\/\/.*?\//
const OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/
if (!isRegexSafe(FULL_PATH_REGEXP)) {
throw new Error('the FULL_PATH_REGEXP is not safe, update this module')
}
if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) {
throw new Error('the OPTIONAL_PARAM_REGEXP is not safe, update this module')
}
function Router (opts) {
if (!(this instanceof Router)) {
return new Router(opts)
}
opts = opts || {}
this._opts = opts
if (opts.defaultRoute) {
assert(typeof opts.defaultRoute === 'function', 'The default route must be a function')
this.defaultRoute = opts.defaultRoute
} else {
this.defaultRoute = null
}
if (opts.onBadUrl) {
assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function')
this.onBadUrl = opts.onBadUrl
} else {
this.onBadUrl = null
}
if (opts.buildPrettyMeta) {
assert(typeof opts.buildPrettyMeta === 'function', 'buildPrettyMeta must be a function')
this.buildPrettyMeta = opts.buildPrettyMeta
} else {
this.buildPrettyMeta = defaultBuildPrettyMeta
}
if (opts.querystringParser) {
assert(typeof opts.querystringParser === 'function', 'querystringParser must be a function')
this.querystringParser = opts.querystringParser
} else {
this.querystringParser = (query) => query === '' ? {} : querystring.parse(query)
}
this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive
this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false
this.ignoreDuplicateSlashes = opts.ignoreDuplicateSlashes || false
this.maxParamLength = opts.maxParamLength || 100
this.allowUnsafeRegex = opts.allowUnsafeRegex || false
this.constrainer = new Constrainer(opts.constraints)
this.routes = []
this.trees = {}
}
Router.prototype.on = function on (method, path, opts, handler, store) {
if (typeof opts === 'function') {
if (handler !== undefined) {
store = handler
}
handler = opts
opts = {}
}
// path validation
assert(typeof path === 'string', 'Path should be a string')
assert(path.length > 0, 'The path could not be empty')
assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`')
// handler validation
assert(typeof handler === 'function', 'Handler should be a function')
// path ends with optional parameter
const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP)
if (optionalParamMatch) {
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')
const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2')
this.on(method, pathFull, opts, handler, store)
this.on(method, pathOptional, opts, handler, store)
return
}
const route = path
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const methods = Array.isArray(method) ? method : [method]
for (const method of methods) {
assert(typeof method === 'string', 'Method should be a string')
assert(httpMethods.includes(method), `Method '${method}' is not an http method.`)
this._on(method, path, opts, handler, store, route)
}
}
Router.prototype._on = function _on (method, path, opts, handler, store) {
let constraints = {}
if (opts.constraints !== undefined) {
assert(typeof opts.constraints === 'object' && opts.constraints !== null, 'Constraints should be an object')
if (Object.keys(opts.constraints).length !== 0) {
constraints = opts.constraints
}
}
this.constrainer.validateConstraints(constraints)
// Let the constrainer know if any constraints are being used now
this.constrainer.noteUsage(constraints)
// Boot the tree for this method if it doesn't exist yet
if (this.trees[method] === undefined) {
this.trees[method] = new StaticNode('/')
}
let pattern = path
if (pattern === '*' && this.trees[method].prefix.length !== 0) {
const currentRoot = this.trees[method]
this.trees[method] = new StaticNode('')
this.trees[method].staticChildren['/'] = currentRoot
}
let currentNode = this.trees[method]
let parentNodePathIndex = currentNode.prefix.length
const params = []
for (let i = 0; i <= pattern.length; i++) {
if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {
// It's a double colon
i++
continue
}
const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58
const isWildcardNode = pattern.charCodeAt(i) === 42
if (isParametricNode || isWildcardNode || (i === pattern.length && i !== parentNodePathIndex)) {
let staticNodePath = pattern.slice(parentNodePathIndex, i)
if (!this.caseSensitive) {
staticNodePath = staticNodePath.toLowerCase()
}
staticNodePath = staticNodePath.split('::').join(':')
staticNodePath = staticNodePath.split('%').join('%25')
// add the static part of the route to the tree
currentNode = currentNode.createStaticChild(staticNodePath)
}
if (isParametricNode) {
let isRegexNode = false
const regexps = []
let lastParamStartIndex = i + 1
for (let j = lastParamStartIndex; ; j++) {
const charCode = pattern.charCodeAt(j)
const isRegexParam = charCode === 40
const isStaticPart = charCode === 45 || charCode === 46
const isEndOfNode = charCode === 47 || j === pattern.length
if (isRegexParam || isStaticPart || isEndOfNode) {
const paramName = pattern.slice(lastParamStartIndex, j)
params.push(paramName)
isRegexNode = isRegexNode || isRegexParam || isStaticPart
if (isRegexParam) {
const endOfRegexIndex = getClosingParenthensePosition(pattern, j)
const regexString = pattern.slice(j, endOfRegexIndex + 1)
if (!this.allowUnsafeRegex) {
assert(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`)
}
regexps.push(trimRegExpStartAndEnd(regexString))
j = endOfRegexIndex + 1
} else {
regexps.push('(.*?)')
}
const staticPartStartIndex = j
for (; j < pattern.length; j++) {
const charCode = pattern.charCodeAt(j)
if (charCode === 47) break
if (charCode === 58) {
const nextCharCode = pattern.charCodeAt(j + 1)
if (nextCharCode === 58) j++
else break
}
}
let staticPart = pattern.slice(staticPartStartIndex, j)
if (staticPart) {
staticPart = staticPart.split('::').join(':')
staticPart = staticPart.split('%').join('%25')
regexps.push(escapeRegExp(staticPart))
}
lastParamStartIndex = j + 1
if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {
const nodePattern = isRegexNode ? '()' + staticPart : staticPart
const nodePath = pattern.slice(i, j)
pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j)
i += nodePattern.length
const regex = isRegexNode ? new RegExp('^' + regexps.join('') + '$') : null
currentNode = currentNode.createParametricChild(regex, staticPart || null, nodePath)
parentNodePathIndex = i + 1
break
}
}
}
} else if (isWildcardNode) {
// add the wildcard parameter
params.push('*')
currentNode = currentNode.createWildcardChild()
parentNodePathIndex = i + 1
if (i !== pattern.length - 1) {
throw new Error('Wildcard must be the last character in the route')
}
}
}
if (!this.caseSensitive) {
pattern = pattern.toLowerCase()
}
if (pattern === '*') {
pattern = '/*'
}
for (const existRoute of this.routes) {
const routeConstraints = existRoute.opts.constraints || {}
if (
existRoute.method === method &&
existRoute.pattern === pattern &&
deepEqual(routeConstraints, constraints)
) {
throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`)
}
}
const route = { method, path, pattern, params, opts, handler, store }
this.routes.push(route)
currentNode.addRoute(route, this.constrainer)
}
Router.prototype.hasConstraintStrategy = function (strategyName) {
return this.constrainer.hasConstraintStrategy(strategyName)
}
Router.prototype.addConstraintStrategy = function (constraints) {
this.constrainer.addConstraintStrategy(constraints)
this._rebuild(this.routes)
}
Router.prototype.reset = function reset () {
this.trees = {}
this.routes = []
}
Router.prototype.off = function off (method, path, constraints) {
// path validation
assert(typeof path === 'string', 'Path should be a string')
assert(path.length > 0, 'The path could not be empty')
assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`')
// options validation
assert(
typeof constraints === 'undefined' ||
(typeof constraints === 'object' && !Array.isArray(constraints) && constraints !== null),
'Constraints should be an object or undefined.')
// path ends with optional parameter
const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP)
if (optionalParamMatch) {
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')
const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2')
this.off(method, pathFull, constraints)
this.off(method, pathOptional, constraints)
return
}
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const methods = Array.isArray(method) ? method : [method]
for (const method of methods) {
this._off(method, path, constraints)
}
}
Router.prototype._off = function _off (method, path, constraints) {
// method validation
assert(typeof method === 'string', 'Method should be a string')
assert(httpMethods.includes(method), `Method '${method}' is not an http method.`)
function matcherWithoutConstraints (route) {
return method !== route.method || path !== route.path
}
function matcherWithConstraints (route) {
return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {})
}
const predicate = constraints ? matcherWithConstraints : matcherWithoutConstraints
// Rebuild tree without the specific route
const newRoutes = this.routes.filter(predicate)
this._rebuild(newRoutes)
}
Router.prototype.lookup = function lookup (req, res, ctx, done) {
if (typeof ctx === 'function') {
done = ctx
ctx = undefined
}
if (done === undefined) {
const constraints = this.constrainer.deriveConstraints(req, ctx)
const handle = this.find(req.method, req.url, constraints)
return this.callHandler(handle, req, res, ctx)
}
this.constrainer.deriveConstraints(req, ctx, (err, constraints) => {
if (err !== null) {
done(err)
return
}
try {
const handle = this.find(req.method, req.url, constraints)
const result = this.callHandler(handle, req, res, ctx)
done(null, result)
} catch (err) {
done(err)
}
})
}
Router.prototype.callHandler = function callHandler (handle, req, res, ctx) {
if (handle === null) return this._defaultRoute(req, res, ctx)
return ctx === undefined
? handle.handler(req, res, handle.params, handle.store, handle.searchParams)
: handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams)
}
Router.prototype.find = function find (method, path, derivedConstraints) {
let currentNode = this.trees[method]
if (currentNode === undefined) return null
if (path.charCodeAt(0) !== 47) { // 47 is '/'
path = path.replace(FULL_PATH_REGEXP, '/')
}
// This must be run before sanitizeUrl as the resulting function
// .sliceParameter must be constructed with same URL string used
// throughout the rest of this function.
if (this.ignoreDuplicateSlashes) {
path = removeDuplicateSlashes(path)
}
let sanitizedUrl
let querystring
let shouldDecodeParam
try {
sanitizedUrl = safeDecodeURI(path)
path = sanitizedUrl.path
querystring = sanitizedUrl.querystring
shouldDecodeParam = sanitizedUrl.shouldDecodeParam
} catch (error) {
return this._onBadUrl(path)
}
if (this.ignoreTrailingSlash) {
path = trimLastSlash(path)
}
const originPath = path
if (this.caseSensitive === false) {
path = path.toLowerCase()
}
const maxParamLength = this.maxParamLength
let pathIndex = currentNode.prefix.length
const params = []
const pathLen = path.length
const brothersNodesStack = []
while (true) {
if (pathIndex === pathLen && currentNode.isLeafNode) {
const handle = currentNode.handlerStorage.getMatchingHandler(derivedConstraints)
if (handle !== null) {
return {
handler: handle.handler,
store: handle.store,
params: handle._createParamsObject(params),
searchParams: this.querystringParser(querystring)
}
}
}
let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length)
if (node === null) {
if (brothersNodesStack.length === 0) {
return null
}
const brotherNodeState = brothersNodesStack.pop()
pathIndex = brotherNodeState.brotherPathIndex
params.splice(brotherNodeState.paramsCount)
node = brotherNodeState.brotherNode
}
currentNode = node
// static route
if (currentNode.kind === NODE_TYPES.STATIC) {
pathIndex += currentNode.prefix.length
continue
}
if (currentNode.kind === NODE_TYPES.WILDCARD) {
let param = originPath.slice(pathIndex)
if (shouldDecodeParam) {
param = safeDecodeURIComponent(param)
}
params.push(param)
pathIndex = pathLen
continue
}
if (currentNode.kind === NODE_TYPES.PARAMETRIC) {
let paramEndIndex = originPath.indexOf('/', pathIndex)
if (paramEndIndex === -1) {
paramEndIndex = pathLen
}
let param = originPath.slice(pathIndex, paramEndIndex)
if (shouldDecodeParam) {
param = safeDecodeURIComponent(param)
}
if (currentNode.isRegex) {
const matchedParameters = currentNode.regex.exec(param)
if (matchedParameters === null) continue
for (let i = 1; i < matchedParameters.length; i++) {
const matchedParam = matchedParameters[i]
if (matchedParam.length > maxParamLength) {
return null
}
params.push(matchedParam)
}
} else {
if (param.length > maxParamLength) {
return null
}
params.push(param)
}
pathIndex = paramEndIndex
}
}
}
Router.prototype._rebuild = function (routes) {
this.reset()
for (const route of routes) {
const { method, path, opts, handler, store } = route
this._on(method, path, opts, handler, store)
}
}
Router.prototype._defaultRoute = function (req, res, ctx) {
if (this.defaultRoute !== null) {
return ctx === undefined
? this.defaultRoute(req, res)
: this.defaultRoute.call(ctx, req, res)
} else {
res.statusCode = 404
res.end()
}
}
Router.prototype._onBadUrl = function (path) {
if (this.onBadUrl === null) {
return null
}
const onBadUrl = this.onBadUrl
return {
handler: (req, res, ctx) => onBadUrl(path, req, res),
params: {},
store: null
}
}
Router.prototype.prettyPrint = function (options = {}) {
const method = options.method
options.buildPrettyMeta = this.buildPrettyMeta.bind(this)
if (method === undefined) {
const { version, host, ...constraints } = this.constrainer.strategies
constraints[httpMethodStrategy.name] = httpMethodStrategy
const mergedRouter = new Router({ ...this._opts, constraints })
const mergedRoutes = this.routes.map(route => {
const constraints = {
...route.opts.constraints,
[httpMethodStrategy.name]: route.method
}
return { ...route, method: 'MERGED', opts: { constraints } }
})
mergedRouter._rebuild(mergedRoutes)
return prettyPrintTree(mergedRouter.trees.MERGED, options)
}
const tree = this.trees[method]
return prettyPrintTree(tree, options)
}
for (var i in httpMethods) {
/* eslint no-prototype-builtins: "off" */
if (!httpMethods.hasOwnProperty(i)) continue
const m = httpMethods[i]
const methodName = m.toLowerCase()
if (Router.prototype[methodName]) throw new Error('Method already exists: ' + methodName)
Router.prototype[methodName] = function (path, handler, store) {
return this.on(m, path, handler, store)
}
}
Router.prototype.all = function (path, handler, store) {
this.on(httpMethods, path, handler, store)
}
module.exports = Router
function escapeRegExp (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function removeDuplicateSlashes (path) {
return path.replace(/\/\/+/g, '/')
}
function trimLastSlash (path) {
if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) {
return path.slice(0, -1)
}
return path
}
function trimRegExpStartAndEnd (regexString) {
// removes chars that marks start "^" and end "$" of regexp
if (regexString.charCodeAt(1) === 94) {
regexString = regexString.slice(0, 1) + regexString.slice(2)
}
if (regexString.charCodeAt(regexString.length - 2) === 36) {
regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1)
}
return regexString
}
function getClosingParenthensePosition (path, idx) {
// `path.indexOf()` will always return the first position of the closing parenthese,
// but it's inefficient for grouped or wrong regexp expressions.
// see issues #62 and #63 for more info
var parentheses = 1
while (idx < path.length) {
idx++
// ignore skipped chars
if (path[idx] === '\\') {
idx++
continue
}
if (path[idx] === ')') {
parentheses--
} else if (path[idx] === '(') {
parentheses++
}
if (!parentheses) return idx
}
throw new TypeError('Invalid regexp expression in "' + path + '"')
}
function defaultBuildPrettyMeta (route) {
// buildPrettyMeta function must return an object, which will be parsed into key/value pairs for display
if (!route) return {}
if (!route.store) return {}
return Object.assign({}, route.store)
}