ultimate-express 1.3.10 → 1.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/router.js CHANGED
@@ -1,617 +1,617 @@
1
- /*
2
- Copyright 2024 dimden.dev
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- const { patternToRegex, needsConversionToRegex, deprecated, findIndexStartingFrom, canBeOptimized, NullObject, EMPTY_REGEX } = require("./utils.js");
18
- const Response = require("./response.js");
19
- const Request = require("./request.js");
20
- const { EventEmitter } = require("tseep");
21
- const compileDeclarative = require("./declarative.js");
22
-
23
- let resCodes = {}, resDecMethods = ['set', 'setHeader', 'header', 'send', 'end', 'append', 'status'];
24
- for(let method of resDecMethods) {
25
- resCodes[method] = Response.prototype[method].toString();
26
- }
27
-
28
- let routeKey = 0;
29
-
30
- const methods = [
31
- 'all',
32
- 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace', 'connect',
33
- 'checkout', 'copy', 'lock', 'mkcol', 'move', 'purge', 'propfind', 'proppatch',
34
- 'search', 'subscribe', 'unsubscribe', 'report', 'mkactivity', 'mkcalendar',
35
- 'checkout', 'merge', 'm-search', 'notify', 'subscribe', 'unsubscribe', 'search'
36
- ];
37
- const supportedUwsMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', 'CONNECT', 'TRACE'];
38
-
39
- const regExParam = /:(\w+)/g;
40
-
41
- module.exports = class Router extends EventEmitter {
42
- constructor(settings = {}) {
43
- super();
44
-
45
- this._paramCallbacks = new Map();
46
- this._mountpathCache = new Map();
47
- this._routes = [];
48
- this.errorRoute = undefined;
49
- this.mountpath = '/';
50
- this.settings = settings;
51
- this._request = Request;
52
- this._response = Response;
53
- this.request = this._request.prototype;
54
- this.response = this._response.prototype;
55
-
56
- if(typeof settings.caseSensitive !== 'undefined') {
57
- this.settings['case sensitive routing'] = settings.caseSensitive;
58
- delete this.settings.caseSensitive;
59
- }
60
- if(typeof settings.strict !== 'undefined') {
61
- this.settings['strict routing'] = settings.strict;
62
- delete this.settings.strict;
63
- }
64
-
65
- if(typeof this.settings['case sensitive routing'] === 'undefined') {
66
- this.settings['case sensitive routing'] = true;
67
- }
68
-
69
- for(let method of methods) {
70
- this[method] = (path, ...callbacks) => {
71
- this.createRoute(method.toUpperCase(), path, this, ...callbacks);
72
- };
73
- };
74
- }
75
-
76
- get(path, ...callbacks) {
77
- if(typeof path === 'string' && callbacks.length === 0) {
78
- const key = path;
79
- const res = this.settings[key];
80
- if(typeof res === 'undefined' && this.parent) {
81
- return this.parent.get(key);
82
- } else {
83
- return res;
84
- }
85
- }
86
- return this.createRoute('GET', path, this, ...callbacks);
87
- }
88
-
89
- del(path, ...callbacks) {
90
- deprecated('app.del', 'app.delete');
91
- return this.createRoute('DELETE', path, this, ...callbacks);
92
- }
93
-
94
- getFullMountpath(req) {
95
- let fullStack = req._stack.join("");
96
- if(!fullStack){
97
- return EMPTY_REGEX;
98
- }
99
- let fullMountpath = this._mountpathCache.get(fullStack);
100
- if(!fullMountpath) {
101
- fullMountpath = patternToRegex(fullStack, true);
102
- this._mountpathCache.set(fullStack, fullMountpath);
103
- }
104
- return fullMountpath;
105
- }
106
-
107
- _pathMatches(route, req) {
108
- let path = req._opPath;
109
- let pattern = route.pattern;
110
-
111
- if (typeof pattern === 'string') {
112
- if(pattern === '/*') {
113
- return true;
114
- }
115
- if(path === '') {
116
- path = '/';
117
- }
118
- if(!this.get('case sensitive routing')) {
119
- path = path.toLowerCase();
120
- pattern = pattern.toLowerCase();
121
- }
122
- return pattern === path;
123
- }
124
- if (pattern === EMPTY_REGEX){
125
- return true;
126
- }
127
- return pattern.test(path);
128
- }
129
-
130
- createRoute(method, path, parent = this, ...callbacks) {
131
- callbacks = callbacks.flat();
132
- const paths = Array.isArray(path) ? path : [path];
133
- const routes = [];
134
- for(let path of paths) {
135
- if(!this.get('strict routing') && typeof path === 'string' && path.endsWith('/') && path !== '/') {
136
- path = path.slice(0, -1);
137
- }
138
- if(path === '*') {
139
- path = '/*';
140
- }
141
- const route = {
142
- method: method === 'USE' ? 'ALL' : method.toUpperCase(),
143
- path,
144
- pattern: method === 'USE' || needsConversionToRegex(path) ? patternToRegex(path, method === 'USE') : path,
145
- callbacks,
146
- routeKey: routeKey++,
147
- use: method === 'USE',
148
- all: method === 'ALL' || method === 'USE',
149
- gettable: method === 'GET' || method === 'HEAD',
150
- };
151
- routes.push(route);
152
- // normal routes optimization
153
- if(canBeOptimized(route.path) && route.pattern !== '/*' && !this.parent && this.get('case sensitive routing') && this.uwsApp) {
154
- if(supportedUwsMethods.includes(method)) {
155
- const optimizedPath = this._optimizeRoute(route, this._routes);
156
- if(optimizedPath) {
157
- this._registerUwsRoute(route, optimizedPath);
158
- }
159
- }
160
- }
161
- // router optimization
162
- if(
163
- route.use && !needsConversionToRegex(path) && path !== '/*' && // must be predictable path
164
- this.get('case sensitive routing') && // uWS only supports case sensitive routing
165
- callbacks.filter(c => c instanceof Router).length === 1 && // only 1 router can be optimized per route
166
- callbacks[callbacks.length - 1] instanceof Router // the router must be the last callback
167
- ) {
168
- let callbacksBeforeRouter = [];
169
- for(let callback of callbacks) {
170
- if(callback instanceof Router) {
171
- // get optimized path to router
172
- let optimizedPathToRouter = this._optimizeRoute(route, this._routes);
173
- if(!optimizedPathToRouter) {
174
- break;
175
- }
176
- optimizedPathToRouter = optimizedPathToRouter.slice(0, -1); // remove last element, which is the router itself
177
- if(optimizedPathToRouter) {
178
- // wait for routes in router to be registered
179
- setTimeout(() => {
180
- if(!this.listenCalled) {
181
- return; // can only optimize router whos parent is listening
182
- }
183
- for(let cbroute of callback._routes) {
184
- if(!needsConversionToRegex(cbroute.path) && cbroute.path !== '/*' && supportedUwsMethods.includes(cbroute.method)) {
185
- let optimizedRouterPath = this._optimizeRoute(cbroute, callback._routes);
186
- if(optimizedRouterPath) {
187
- optimizedRouterPath = optimizedRouterPath.slice(0, -1);
188
- const optimizedPath = [...optimizedPathToRouter, {
189
- // fake route to update req._opPath and req.url
190
- ...route,
191
- callbacks: [
192
- (req, res, next) => {
193
- next('skipPop');
194
- }
195
- ]
196
- }, ...optimizedRouterPath];
197
- this._registerUwsRoute({
198
- ...cbroute,
199
- path: route.path + cbroute.path,
200
- pattern: route.path + cbroute.path,
201
- optimizedRouter: true
202
- }, optimizedPath);
203
- }
204
- }
205
- }
206
- }, 100);
207
- }
208
- // only 1 router can be optimized per route
209
- break;
210
- } else {
211
- callbacksBeforeRouter.push(route);
212
- }
213
- }
214
- }
215
- }
216
- this._routes.push(...routes);
217
-
218
- return parent;
219
- }
220
-
221
- // if route is a simple string, its possible to pre-calculate its path
222
- // and then create a native uWS route for it, which is much faster
223
- _optimizeRoute(route, routes) {
224
- const optimizedPath = [];
225
-
226
- for(let i = 0; i < routes.length; i++) {
227
- const r = routes[i];
228
- if(r.routeKey > route.routeKey) {
229
- break;
230
- }
231
- // if the methods are not the same, and its not an all method, skip it
232
- if(!r.all && r.method !== route.method) {
233
- // check if the methods are compatible (GET and HEAD)
234
- if(!(r.method === 'HEAD' && route.method === 'GET')) {
235
- continue;
236
- }
237
- }
238
-
239
- // check if the paths match
240
- if(
241
- (r.pattern instanceof RegExp && r.pattern.test(route.path)) ||
242
- (typeof r.pattern === 'string' && (r.pattern === route.path || r.pattern === '/*'))
243
- ) {
244
- if(r.callbacks.some(c => c instanceof Router)) {
245
- return false; // cant optimize nested routers with matches
246
- }
247
- optimizedPath.push(r);
248
- }
249
- }
250
- optimizedPath.push(route);
251
-
252
- return optimizedPath;
253
- }
254
-
255
- handleRequest(res, req) {
256
- const request = new this._request(req, res, this);
257
- const response = new this._response(res, request, this);
258
- request.res = response;
259
- response.req = request;
260
- res.onAborted(() => {
261
- const err = new Error('Connection closed');
262
- err.code = 'ECONNRESET';
263
- response.aborted = true;
264
- response.finished = true;
265
- response.socket.emit('error', err);
266
- });
267
-
268
- return { request, response };
269
- }
270
-
271
- _registerUwsRoute(route, optimizedPath) {
272
- let method = route.method.toLowerCase();
273
- if(method === 'all') {
274
- method = 'any';
275
- } else if(method === 'delete') {
276
- method = 'del';
277
- }
278
- if(!route.optimizedRouter && route.path.includes(":")) {
279
- route.optimizedParams = route.path.match(regExParam).map(p => p.slice(1));
280
- }
281
- let fn = async (res, req) => {
282
- const { request, response } = this.handleRequest(res, req);
283
- if(route.optimizedParams) {
284
- request.optimizedParams = new NullObject();
285
- for(let i = 0; i < route.optimizedParams.length; i++) {
286
- request.optimizedParams[route.optimizedParams[i]] = req.getParameter(i);
287
- }
288
- }
289
- const matchedRoute = await this._routeRequest(request, response, 0, optimizedPath, true, route);
290
- if(!matchedRoute && !response.headersSent && !response.aborted) {
291
- response.status(404);
292
- request.noEtag = true;
293
- this._sendErrorPage(request, response, `Cannot ${request.method} ${request._originalPath}`, false);
294
- }
295
- };
296
- route.optimizedPath = optimizedPath;
297
-
298
- let replacedPath = route.path;
299
- const realFn = fn;
300
-
301
- // check if route is declarative
302
- if(
303
- optimizedPath.length === 1 && // must not have middlewares
304
- route.callbacks.length === 1 && // must not have multiple callbacks
305
- typeof route.callbacks[0] === 'function' && // must be a function
306
- this._paramCallbacks.size === 0 && // app.param() is not supported
307
- !resDecMethods.some(method => resCodes[method] !== this.response[method].toString()) && // must not have injected methods
308
- this.get('declarative responses') // must have declarative responses enabled
309
- ) {
310
- const decRes = compileDeclarative(route.callbacks[0], this);
311
- if(decRes) {
312
- fn = decRes;
313
- }
314
- } else {
315
- replacedPath = route.path.replace(regExParam, ':x');
316
- }
317
-
318
- this.uwsApp[method](replacedPath, fn);
319
- if(!this.get('strict routing') && route.path[route.path.length - 1] !== '/') {
320
- this.uwsApp[method](replacedPath + '/', fn);
321
- if(method === 'get') {
322
- this.uwsApp.head(replacedPath + '/', realFn);
323
- }
324
- }
325
- if(method === 'get') {
326
- this.uwsApp.head(replacedPath, realFn);
327
- }
328
- }
329
-
330
- _handleError(err, request, response) {
331
- let errorRoute = this.errorRoute, parent = this.parent;
332
- while(!errorRoute && parent) {
333
- errorRoute = parent.errorRoute;
334
- parent = parent.parent;
335
- }
336
- if(errorRoute) {
337
- return errorRoute(err, request, response, () => {
338
- if(!response.headersSent) {
339
- if(response.statusCode === 200) {
340
- response.statusCode = 500;
341
- }
342
- this._sendErrorPage(request, response, err, true);
343
- }
344
- });
345
- }
346
- console.error(err);
347
- if(response.statusCode === 200) {
348
- response.statusCode = 500;
349
- }
350
- this._sendErrorPage(request, response, err, true);
351
- }
352
-
353
- _extractParams(pattern, path) {
354
- let match = pattern.exec(path);
355
- const obj = match?.groups ?? new NullObject();
356
- for(let i = 1; i < match.length; i++) {
357
- obj[i - 1] = match[i];
358
- }
359
- return obj;
360
- }
361
-
362
- _preprocessRequest(req, res, route) {
363
- req.route = route;
364
- if(route.optimizedParams) {
365
- req.params = {...req.optimizedParams};
366
- } else if(typeof route.path === 'string' && (route.path.includes(':') || route.path.includes('*')) && route.pattern instanceof RegExp) {
367
- let path = req._originalPath;
368
- if(req._stack.length > 0) {
369
- path = path.replace(this.getFullMountpath(req), '');
370
- }
371
- req.params = {...this._extractParams(route.pattern, path)};
372
- if(req._paramStack.length > 0) {
373
- for(let params of req._paramStack) {
374
- req.params = {...params, ...req.params};
375
- }
376
- }
377
- } else {
378
- req.params = {};
379
- if(req._paramStack.length > 0) {
380
- for(let params of req._paramStack) {
381
- req.params = {...params, ...req.params};
382
- }
383
- }
384
- }
385
-
386
- if(this._paramCallbacks.size > 0) {
387
- return new Promise(async resolve => {
388
- for(let param in req.params) {
389
- const pcs = this._paramCallbacks.get(param);
390
- if(pcs && !req._gotParams.has(param)) {
391
- req._gotParams.add(param);
392
- for(let i = 0, len = pcs.length; i < len; i++) {
393
- const fn = pcs[i];
394
- await new Promise(resolveRoute => {
395
- const next = (thingamabob) => {
396
- if(thingamabob) {
397
- if(thingamabob === 'route') {
398
- return resolve('route');
399
- } else {
400
- this._handleError(thingamabob, req, res);
401
- return resolve(false);
402
- }
403
- }
404
- return resolveRoute();
405
- };
406
- req.next = next;
407
- fn(req, res, next, req.params[param], param);
408
- });
409
- }
410
- }
411
- }
412
-
413
- resolve(true)
414
- });
415
- }
416
- return true;
417
- }
418
-
419
- param(name, fn) {
420
- if(typeof name === 'function') {
421
- deprecated('app.param(callback)', 'app.param(name, callback)', true);
422
- this._paramFunction = name;
423
- } else {
424
- if(this._paramFunction) {
425
- if(!this._paramCallbacks.has(name)) {
426
- this._paramCallbacks.set(name, []);
427
- }
428
- this._paramCallbacks.get(name).push(this._paramFunction(name, fn));
429
- } else {
430
- let names = Array.isArray(name) ? name : [name];
431
- for(let name of names) {
432
- if(!this._paramCallbacks.has(name)) {
433
- this._paramCallbacks.set(name, []);
434
- }
435
- this._paramCallbacks.get(name).push(fn);
436
- }
437
- }
438
- }
439
- }
440
-
441
- async _routeRequest(req, res, startIndex = 0, routes = this._routes, skipCheck = false, skipUntil) {
442
- let routeIndex = skipCheck ? startIndex : findIndexStartingFrom(routes, r => (r.all || r.method === req.method || (r.gettable && req.method === 'HEAD')) && this._pathMatches(r, req), startIndex);
443
- const route = routes[routeIndex];
444
- if(!route) {
445
- if(!skipCheck) {
446
- // on normal unoptimized routes, if theres no match then there is no route
447
- return false;
448
- }
449
- // on optimized routes, there can be more routes, so we have to use unoptimized routing and skip until we find route we stopped at
450
- return this._routeRequest(req, res, 0, this._routes, false, skipUntil);
451
- }
452
- let callbackindex = 0;
453
-
454
- // avoid calling _preprocessRequest as async function as its slower
455
- // but it seems like calling it as async has unintended consequence of resetting max call stack size
456
- // so call it as async when the request has been through every 300 routes to reset it
457
- const continueRoute = this._paramCallbacks.size === 0 && req.routeCount % 300 !== 0 ?
458
- this._preprocessRequest(req, res, route) : await this._preprocessRequest(req, res, route);
459
-
460
- const strictRouting = this.get('strict routing');
461
- if(route.use) {
462
- req._stack.push(route.path);
463
- const fullMountpath = this.getFullMountpath(req);
464
- req._opPath = fullMountpath !== EMPTY_REGEX ? req._originalPath.replace(fullMountpath, '') : req._originalPath;
465
- if(req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
466
- if(strictRouting) {
467
- req._opPath += '/';
468
- } else {
469
- req._opPath = req._opPath.slice(0, -1);
470
- }
471
- }
472
- req.url = req._opPath + req.urlQuery;
473
- req.path = req._opPath;
474
- if(req._opPath === '') {
475
- req.url = '/';
476
- req.path = '/';
477
- }
478
- }
479
- return new Promise((resolve) => {
480
- const next = async (thingamabob) => {
481
- if(thingamabob) {
482
- if(thingamabob === 'route' || thingamabob === 'skipPop') {
483
- if(route.use && thingamabob !== 'skipPop') {
484
- req._stack.pop();
485
-
486
- req._opPath = req._stack.length > 0 ? req._originalPath.replace(this.getFullMountpath(req), '') : req._originalPath;
487
- if(strictRouting) {
488
- if(req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
489
- req._opPath += '/';
490
- }
491
- }
492
- req.url = req._opPath + req.urlQuery;
493
- req.path = req._opPath;
494
- if(req._opPath === '') {
495
- req.url = '/';
496
- req.path = '/';
497
- }
498
- if(!strictRouting && req.endsWithSlash && req._originalPath !== '/' && req._opPath[req._opPath.length - 1] === '/') {
499
- req._opPath = req._opPath.slice(0, -1);
500
- }
501
- if(req.app.parent && route.callback.constructor.name === 'Application') {
502
- req.app = req.app.parent;
503
- }
504
- }
505
- req.routeCount++;
506
- return resolve(this._routeRequest(req, res, routeIndex + 1, routes, skipCheck, skipUntil));
507
- } else {
508
- this._handleError(thingamabob, req, res);
509
- return resolve(true);
510
- }
511
- }
512
- const callback = route.callbacks[callbackindex++];
513
- if(!callback) {
514
- return next('route');
515
- }
516
- if(callback instanceof Router) {
517
- if(callback.constructor.name === 'Application') {
518
- req.app = callback;
519
- }
520
- if(callback.settings.mergeParams) {
521
- req._paramStack.push(req.params);
522
- }
523
- if(callback.settings['strict routing'] && req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
524
- req._opPath += '/';
525
- }
526
- const routed = await callback._routeRequest(req, res, 0);
527
- if(routed) return resolve(true);
528
- next();
529
- } else {
530
- try {
531
- // skipping routes we already went through via optimized path
532
- if(!skipCheck && skipUntil && skipUntil.routeKey >= route.routeKey) {
533
- return next();
534
- }
535
- const out = callback(req, res, next);
536
- if(out instanceof Promise) {
537
- out.catch(err => {
538
- if(this.get("catch async errors")) {
539
- this._handleError(err, req, res);
540
- return resolve(true);
541
- } else {
542
- throw err;
543
- }
544
- });
545
- }
546
- } catch(err) {
547
- this._handleError(err, req, res);
548
- return resolve(true);
549
- }
550
- }
551
- }
552
- req.next = next;
553
- if(continueRoute === 'route') {
554
- next('route');
555
- } else if(continueRoute) {
556
- next();
557
- } else {
558
- resolve(true);
559
- }
560
- });
561
- }
562
-
563
- use(path, ...callbacks) {
564
- if(typeof path === 'function' || path instanceof Router || (Array.isArray(path) && path.every(p => typeof p === 'function' || p instanceof Router))) {
565
- if(callbacks.length === 0 && typeof path === 'function' && path.length === 4) {
566
- this.errorRoute = path;
567
- return;
568
- }
569
- callbacks.unshift(path);
570
- path = '';
571
- }
572
- if(path === '/') {
573
- path = '';
574
- }
575
- for(let callback of callbacks) {
576
- if(callback instanceof Router) {
577
- callback.mountpath = path;
578
- callback.parent = this;
579
- callback.emit('mount', this);
580
- }
581
- }
582
- this.createRoute('USE', path, this, ...callbacks);
583
- }
584
-
585
- route(path) {
586
- let fns = new NullObject();
587
- for(let method of methods) {
588
- fns[method] = (...callbacks) => {
589
- return this.createRoute(method.toUpperCase(), path, fns, ...callbacks);
590
- };
591
- }
592
- fns.get = (...callbacks) => {
593
- return this.createRoute('GET', path, fns, ...callbacks);
594
- };
595
- return fns;
596
- }
597
-
598
- _sendErrorPage(request, response, err, checkEnv = false) {
599
- if(checkEnv && this.get('env') === 'production') {
600
- err = 'Internal Server Error';
601
- }
602
- request.noEtag = true;
603
- response.setHeader('Content-Type', 'text/html; charset=utf-8');
604
- response.setHeader('X-Content-Type-Options', 'nosniff');
605
- response.setHeader('Content-Security-Policy', "default-src 'none'");
606
- response.send(`<!DOCTYPE html>\n` +
607
- `<html lang="en">\n` +
608
- `<head>\n` +
609
- `<meta charset="utf-8">\n` +
610
- `<title>Error</title>\n` +
611
- `</head>\n` +
612
- `<body>\n` +
613
- `<pre>${err?.stack ?? err}</pre>\n` +
614
- `</body>\n` +
615
- `</html>\n`);
616
- }
617
- }
1
+ /*
2
+ Copyright 2024 dimden.dev
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ const { patternToRegex, needsConversionToRegex, deprecated, findIndexStartingFrom, canBeOptimized, NullObject, EMPTY_REGEX } = require("./utils.js");
18
+ const Response = require("./response.js");
19
+ const Request = require("./request.js");
20
+ const { EventEmitter } = require("tseep");
21
+ const compileDeclarative = require("./declarative.js");
22
+
23
+ let resCodes = {}, resDecMethods = ['set', 'setHeader', 'header', 'send', 'end', 'append', 'status'];
24
+ for(let method of resDecMethods) {
25
+ resCodes[method] = Response.prototype[method].toString();
26
+ }
27
+
28
+ let routeKey = 0;
29
+
30
+ const methods = [
31
+ 'all',
32
+ 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace', 'connect',
33
+ 'checkout', 'copy', 'lock', 'mkcol', 'move', 'purge', 'propfind', 'proppatch',
34
+ 'search', 'subscribe', 'unsubscribe', 'report', 'mkactivity', 'mkcalendar',
35
+ 'checkout', 'merge', 'm-search', 'notify', 'subscribe', 'unsubscribe', 'search'
36
+ ];
37
+ const supportedUwsMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', 'CONNECT', 'TRACE'];
38
+
39
+ const regExParam = /:(\w+)/g;
40
+
41
+ module.exports = class Router extends EventEmitter {
42
+ constructor(settings = {}) {
43
+ super();
44
+
45
+ this._paramCallbacks = new Map();
46
+ this._mountpathCache = new Map();
47
+ this._routes = [];
48
+ this.errorRoute = undefined;
49
+ this.mountpath = '/';
50
+ this.settings = settings;
51
+ this._request = Request;
52
+ this._response = Response;
53
+ this.request = this._request.prototype;
54
+ this.response = this._response.prototype;
55
+
56
+ if(typeof settings.caseSensitive !== 'undefined') {
57
+ this.settings['case sensitive routing'] = settings.caseSensitive;
58
+ delete this.settings.caseSensitive;
59
+ }
60
+ if(typeof settings.strict !== 'undefined') {
61
+ this.settings['strict routing'] = settings.strict;
62
+ delete this.settings.strict;
63
+ }
64
+
65
+ if(typeof this.settings['case sensitive routing'] === 'undefined') {
66
+ this.settings['case sensitive routing'] = true;
67
+ }
68
+
69
+ for(let method of methods) {
70
+ this[method] = (path, ...callbacks) => {
71
+ this.createRoute(method.toUpperCase(), path, this, ...callbacks);
72
+ };
73
+ };
74
+ }
75
+
76
+ get(path, ...callbacks) {
77
+ if(typeof path === 'string' && callbacks.length === 0) {
78
+ const key = path;
79
+ const res = this.settings[key];
80
+ if(typeof res === 'undefined' && this.parent) {
81
+ return this.parent.get(key);
82
+ } else {
83
+ return res;
84
+ }
85
+ }
86
+ return this.createRoute('GET', path, this, ...callbacks);
87
+ }
88
+
89
+ del(path, ...callbacks) {
90
+ deprecated('app.del', 'app.delete');
91
+ return this.createRoute('DELETE', path, this, ...callbacks);
92
+ }
93
+
94
+ getFullMountpath(req) {
95
+ let fullStack = req._stack.join("");
96
+ if(!fullStack){
97
+ return EMPTY_REGEX;
98
+ }
99
+ let fullMountpath = this._mountpathCache.get(fullStack);
100
+ if(!fullMountpath) {
101
+ fullMountpath = patternToRegex(fullStack, true);
102
+ this._mountpathCache.set(fullStack, fullMountpath);
103
+ }
104
+ return fullMountpath;
105
+ }
106
+
107
+ _pathMatches(route, req) {
108
+ let path = req._opPath;
109
+ let pattern = route.pattern;
110
+
111
+ if (typeof pattern === 'string') {
112
+ if(pattern === '/*') {
113
+ return true;
114
+ }
115
+ if(path === '') {
116
+ path = '/';
117
+ }
118
+ if(!this.get('case sensitive routing')) {
119
+ path = path.toLowerCase();
120
+ pattern = pattern.toLowerCase();
121
+ }
122
+ return pattern === path;
123
+ }
124
+ if (pattern === EMPTY_REGEX){
125
+ return true;
126
+ }
127
+ return pattern.test(path);
128
+ }
129
+
130
+ createRoute(method, path, parent = this, ...callbacks) {
131
+ callbacks = callbacks.flat();
132
+ const paths = Array.isArray(path) ? path : [path];
133
+ const routes = [];
134
+ for(let path of paths) {
135
+ if(!this.get('strict routing') && typeof path === 'string' && path.endsWith('/') && path !== '/') {
136
+ path = path.slice(0, -1);
137
+ }
138
+ if(path === '*') {
139
+ path = '/*';
140
+ }
141
+ const route = {
142
+ method: method === 'USE' ? 'ALL' : method.toUpperCase(),
143
+ path,
144
+ pattern: method === 'USE' || needsConversionToRegex(path) ? patternToRegex(path, method === 'USE') : path,
145
+ callbacks,
146
+ routeKey: routeKey++,
147
+ use: method === 'USE',
148
+ all: method === 'ALL' || method === 'USE',
149
+ gettable: method === 'GET' || method === 'HEAD',
150
+ };
151
+ routes.push(route);
152
+ // normal routes optimization
153
+ if(canBeOptimized(route.path) && route.pattern !== '/*' && !this.parent && this.get('case sensitive routing') && this.uwsApp) {
154
+ if(supportedUwsMethods.includes(method)) {
155
+ const optimizedPath = this._optimizeRoute(route, this._routes);
156
+ if(optimizedPath) {
157
+ this._registerUwsRoute(route, optimizedPath);
158
+ }
159
+ }
160
+ }
161
+ // router optimization
162
+ if(
163
+ route.use && !needsConversionToRegex(path) && path !== '/*' && // must be predictable path
164
+ this.get('case sensitive routing') && // uWS only supports case sensitive routing
165
+ callbacks.filter(c => c instanceof Router).length === 1 && // only 1 router can be optimized per route
166
+ callbacks[callbacks.length - 1] instanceof Router // the router must be the last callback
167
+ ) {
168
+ let callbacksBeforeRouter = [];
169
+ for(let callback of callbacks) {
170
+ if(callback instanceof Router) {
171
+ // get optimized path to router
172
+ let optimizedPathToRouter = this._optimizeRoute(route, this._routes);
173
+ if(!optimizedPathToRouter) {
174
+ break;
175
+ }
176
+ optimizedPathToRouter = optimizedPathToRouter.slice(0, -1); // remove last element, which is the router itself
177
+ if(optimizedPathToRouter) {
178
+ // wait for routes in router to be registered
179
+ setTimeout(() => {
180
+ if(!this.listenCalled) {
181
+ return; // can only optimize router whos parent is listening
182
+ }
183
+ for(let cbroute of callback._routes) {
184
+ if(!needsConversionToRegex(cbroute.path) && cbroute.path !== '/*' && supportedUwsMethods.includes(cbroute.method)) {
185
+ let optimizedRouterPath = this._optimizeRoute(cbroute, callback._routes);
186
+ if(optimizedRouterPath) {
187
+ optimizedRouterPath = optimizedRouterPath.slice(0, -1);
188
+ const optimizedPath = [...optimizedPathToRouter, {
189
+ // fake route to update req._opPath and req.url
190
+ ...route,
191
+ callbacks: [
192
+ (req, res, next) => {
193
+ next('skipPop');
194
+ }
195
+ ]
196
+ }, ...optimizedRouterPath];
197
+ this._registerUwsRoute({
198
+ ...cbroute,
199
+ path: route.path + cbroute.path,
200
+ pattern: route.path + cbroute.path,
201
+ optimizedRouter: true
202
+ }, optimizedPath);
203
+ }
204
+ }
205
+ }
206
+ }, 100);
207
+ }
208
+ // only 1 router can be optimized per route
209
+ break;
210
+ } else {
211
+ callbacksBeforeRouter.push(route);
212
+ }
213
+ }
214
+ }
215
+ }
216
+ this._routes.push(...routes);
217
+
218
+ return parent;
219
+ }
220
+
221
+ // if route is a simple string, its possible to pre-calculate its path
222
+ // and then create a native uWS route for it, which is much faster
223
+ _optimizeRoute(route, routes) {
224
+ const optimizedPath = [];
225
+
226
+ for(let i = 0; i < routes.length; i++) {
227
+ const r = routes[i];
228
+ if(r.routeKey > route.routeKey) {
229
+ break;
230
+ }
231
+ // if the methods are not the same, and its not an all method, skip it
232
+ if(!r.all && r.method !== route.method) {
233
+ // check if the methods are compatible (GET and HEAD)
234
+ if(!(r.method === 'HEAD' && route.method === 'GET')) {
235
+ continue;
236
+ }
237
+ }
238
+
239
+ // check if the paths match
240
+ if(
241
+ (r.pattern instanceof RegExp && r.pattern.test(route.path)) ||
242
+ (typeof r.pattern === 'string' && (r.pattern === route.path || r.pattern === '/*'))
243
+ ) {
244
+ if(r.callbacks.some(c => c instanceof Router)) {
245
+ return false; // cant optimize nested routers with matches
246
+ }
247
+ optimizedPath.push(r);
248
+ }
249
+ }
250
+ optimizedPath.push(route);
251
+
252
+ return optimizedPath;
253
+ }
254
+
255
+ handleRequest(res, req) {
256
+ const request = new this._request(req, res, this);
257
+ const response = new this._response(res, request, this);
258
+ request.res = response;
259
+ response.req = request;
260
+ res.onAborted(() => {
261
+ const err = new Error('Connection closed');
262
+ err.code = 'ECONNRESET';
263
+ response.aborted = true;
264
+ response.finished = true;
265
+ response.socket.emit('error', err);
266
+ });
267
+
268
+ return { request, response };
269
+ }
270
+
271
+ _registerUwsRoute(route, optimizedPath) {
272
+ let method = route.method.toLowerCase();
273
+ if(method === 'all') {
274
+ method = 'any';
275
+ } else if(method === 'delete') {
276
+ method = 'del';
277
+ }
278
+ if(!route.optimizedRouter && route.path.includes(":")) {
279
+ route.optimizedParams = route.path.match(regExParam).map(p => p.slice(1));
280
+ }
281
+ let fn = async (res, req) => {
282
+ const { request, response } = this.handleRequest(res, req);
283
+ if(route.optimizedParams) {
284
+ request.optimizedParams = new NullObject();
285
+ for(let i = 0; i < route.optimizedParams.length; i++) {
286
+ request.optimizedParams[route.optimizedParams[i]] = req.getParameter(i);
287
+ }
288
+ }
289
+ const matchedRoute = await this._routeRequest(request, response, 0, optimizedPath, true, route);
290
+ if(!matchedRoute && !response.headersSent && !response.aborted) {
291
+ response.status(404);
292
+ request.noEtag = true;
293
+ this._sendErrorPage(request, response, `Cannot ${request.method} ${request._originalPath}`, false);
294
+ }
295
+ };
296
+ route.optimizedPath = optimizedPath;
297
+
298
+ let replacedPath = route.path;
299
+ const realFn = fn;
300
+
301
+ // check if route is declarative
302
+ if(
303
+ optimizedPath.length === 1 && // must not have middlewares
304
+ route.callbacks.length === 1 && // must not have multiple callbacks
305
+ typeof route.callbacks[0] === 'function' && // must be a function
306
+ this._paramCallbacks.size === 0 && // app.param() is not supported
307
+ !resDecMethods.some(method => resCodes[method] !== this.response[method].toString()) && // must not have injected methods
308
+ this.get('declarative responses') // must have declarative responses enabled
309
+ ) {
310
+ const decRes = compileDeclarative(route.callbacks[0], this);
311
+ if(decRes) {
312
+ fn = decRes;
313
+ }
314
+ } else {
315
+ replacedPath = route.path.replace(regExParam, ':x');
316
+ }
317
+
318
+ this.uwsApp[method](replacedPath, fn);
319
+ if(!this.get('strict routing') && route.path[route.path.length - 1] !== '/') {
320
+ this.uwsApp[method](replacedPath + '/', fn);
321
+ if(method === 'get') {
322
+ this.uwsApp.head(replacedPath + '/', realFn);
323
+ }
324
+ }
325
+ if(method === 'get') {
326
+ this.uwsApp.head(replacedPath, realFn);
327
+ }
328
+ }
329
+
330
+ _handleError(err, request, response) {
331
+ let errorRoute = this.errorRoute, parent = this.parent;
332
+ while(!errorRoute && parent) {
333
+ errorRoute = parent.errorRoute;
334
+ parent = parent.parent;
335
+ }
336
+ if(errorRoute) {
337
+ return errorRoute(err, request, response, () => {
338
+ if(!response.headersSent) {
339
+ if(response.statusCode === 200) {
340
+ response.statusCode = 500;
341
+ }
342
+ this._sendErrorPage(request, response, err, true);
343
+ }
344
+ });
345
+ }
346
+ console.error(err);
347
+ if(response.statusCode === 200) {
348
+ response.statusCode = 500;
349
+ }
350
+ this._sendErrorPage(request, response, err, true);
351
+ }
352
+
353
+ _extractParams(pattern, path) {
354
+ let match = pattern.exec(path);
355
+ const obj = match?.groups ?? new NullObject();
356
+ for(let i = 1; i < match.length; i++) {
357
+ obj[i - 1] = match[i];
358
+ }
359
+ return obj;
360
+ }
361
+
362
+ _preprocessRequest(req, res, route) {
363
+ req.route = route;
364
+ if(route.optimizedParams) {
365
+ req.params = {...req.optimizedParams};
366
+ } else if(typeof route.path === 'string' && (route.path.includes(':') || route.path.includes('*')) && route.pattern instanceof RegExp) {
367
+ let path = req._originalPath;
368
+ if(req._stack.length > 0) {
369
+ path = path.replace(this.getFullMountpath(req), '');
370
+ }
371
+ req.params = {...this._extractParams(route.pattern, path)};
372
+ if(req._paramStack.length > 0) {
373
+ for(let params of req._paramStack) {
374
+ req.params = {...params, ...req.params};
375
+ }
376
+ }
377
+ } else {
378
+ req.params = {};
379
+ if(req._paramStack.length > 0) {
380
+ for(let params of req._paramStack) {
381
+ req.params = {...params, ...req.params};
382
+ }
383
+ }
384
+ }
385
+
386
+ if(this._paramCallbacks.size > 0) {
387
+ return new Promise(async resolve => {
388
+ for(let param in req.params) {
389
+ const pcs = this._paramCallbacks.get(param);
390
+ if(pcs && !req._gotParams.has(param)) {
391
+ req._gotParams.add(param);
392
+ for(let i = 0, len = pcs.length; i < len; i++) {
393
+ const fn = pcs[i];
394
+ await new Promise(resolveRoute => {
395
+ const next = (thingamabob) => {
396
+ if(thingamabob) {
397
+ if(thingamabob === 'route') {
398
+ return resolve('route');
399
+ } else {
400
+ this._handleError(thingamabob, req, res);
401
+ return resolve(false);
402
+ }
403
+ }
404
+ return resolveRoute();
405
+ };
406
+ req.next = next;
407
+ fn(req, res, next, req.params[param], param);
408
+ });
409
+ }
410
+ }
411
+ }
412
+
413
+ resolve(true)
414
+ });
415
+ }
416
+ return true;
417
+ }
418
+
419
+ param(name, fn) {
420
+ if(typeof name === 'function') {
421
+ deprecated('app.param(callback)', 'app.param(name, callback)', true);
422
+ this._paramFunction = name;
423
+ } else {
424
+ if(this._paramFunction) {
425
+ if(!this._paramCallbacks.has(name)) {
426
+ this._paramCallbacks.set(name, []);
427
+ }
428
+ this._paramCallbacks.get(name).push(this._paramFunction(name, fn));
429
+ } else {
430
+ let names = Array.isArray(name) ? name : [name];
431
+ for(let name of names) {
432
+ if(!this._paramCallbacks.has(name)) {
433
+ this._paramCallbacks.set(name, []);
434
+ }
435
+ this._paramCallbacks.get(name).push(fn);
436
+ }
437
+ }
438
+ }
439
+ }
440
+
441
+ async _routeRequest(req, res, startIndex = 0, routes = this._routes, skipCheck = false, skipUntil) {
442
+ let routeIndex = skipCheck ? startIndex : findIndexStartingFrom(routes, r => (r.all || r.method === req.method || (r.gettable && req.method === 'HEAD')) && this._pathMatches(r, req), startIndex);
443
+ const route = routes[routeIndex];
444
+ if(!route) {
445
+ if(!skipCheck) {
446
+ // on normal unoptimized routes, if theres no match then there is no route
447
+ return false;
448
+ }
449
+ // on optimized routes, there can be more routes, so we have to use unoptimized routing and skip until we find route we stopped at
450
+ return this._routeRequest(req, res, 0, this._routes, false, skipUntil);
451
+ }
452
+ let callbackindex = 0;
453
+
454
+ // avoid calling _preprocessRequest as async function as its slower
455
+ // but it seems like calling it as async has unintended consequence of resetting max call stack size
456
+ // so call it as async when the request has been through every 300 routes to reset it
457
+ const continueRoute = this._paramCallbacks.size === 0 && req.routeCount % 300 !== 0 ?
458
+ this._preprocessRequest(req, res, route) : await this._preprocessRequest(req, res, route);
459
+
460
+ const strictRouting = this.get('strict routing');
461
+ if(route.use) {
462
+ req._stack.push(route.path);
463
+ const fullMountpath = this.getFullMountpath(req);
464
+ req._opPath = fullMountpath !== EMPTY_REGEX ? req._originalPath.replace(fullMountpath, '') : req._originalPath;
465
+ if(req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
466
+ if(strictRouting) {
467
+ req._opPath += '/';
468
+ } else {
469
+ req._opPath = req._opPath.slice(0, -1);
470
+ }
471
+ }
472
+ req.url = req._opPath + req.urlQuery;
473
+ req.path = req._opPath;
474
+ if(req._opPath === '') {
475
+ req.url = '/';
476
+ req.path = '/';
477
+ }
478
+ }
479
+ return new Promise((resolve) => {
480
+ const next = async (thingamabob) => {
481
+ if(thingamabob) {
482
+ if(thingamabob === 'route' || thingamabob === 'skipPop') {
483
+ if(route.use && thingamabob !== 'skipPop') {
484
+ req._stack.pop();
485
+
486
+ req._opPath = req._stack.length > 0 ? req._originalPath.replace(this.getFullMountpath(req), '') : req._originalPath;
487
+ if(strictRouting) {
488
+ if(req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
489
+ req._opPath += '/';
490
+ }
491
+ }
492
+ req.url = req._opPath + req.urlQuery;
493
+ req.path = req._opPath;
494
+ if(req._opPath === '') {
495
+ req.url = '/';
496
+ req.path = '/';
497
+ }
498
+ if(!strictRouting && req.endsWithSlash && req._originalPath !== '/' && req._opPath[req._opPath.length - 1] === '/') {
499
+ req._opPath = req._opPath.slice(0, -1);
500
+ }
501
+ if(req.app.parent && route.callback.constructor.name === 'Application') {
502
+ req.app = req.app.parent;
503
+ }
504
+ }
505
+ req.routeCount++;
506
+ return resolve(this._routeRequest(req, res, routeIndex + 1, routes, skipCheck, skipUntil));
507
+ } else {
508
+ this._handleError(thingamabob, req, res);
509
+ return resolve(true);
510
+ }
511
+ }
512
+ const callback = route.callbacks[callbackindex++];
513
+ if(!callback) {
514
+ return next('route');
515
+ }
516
+ if(callback instanceof Router) {
517
+ if(callback.constructor.name === 'Application') {
518
+ req.app = callback;
519
+ }
520
+ if(callback.settings.mergeParams) {
521
+ req._paramStack.push(req.params);
522
+ }
523
+ if(callback.settings['strict routing'] && req.endsWithSlash && req._opPath[req._opPath.length - 1] !== '/') {
524
+ req._opPath += '/';
525
+ }
526
+ const routed = await callback._routeRequest(req, res, 0);
527
+ if(routed) return resolve(true);
528
+ next();
529
+ } else {
530
+ try {
531
+ // skipping routes we already went through via optimized path
532
+ if(!skipCheck && skipUntil && skipUntil.routeKey >= route.routeKey) {
533
+ return next();
534
+ }
535
+ const out = callback(req, res, next);
536
+ if(out instanceof Promise) {
537
+ out.catch(err => {
538
+ if(this.get("catch async errors")) {
539
+ this._handleError(err, req, res);
540
+ return resolve(true);
541
+ } else {
542
+ throw err;
543
+ }
544
+ });
545
+ }
546
+ } catch(err) {
547
+ this._handleError(err, req, res);
548
+ return resolve(true);
549
+ }
550
+ }
551
+ }
552
+ req.next = next;
553
+ if(continueRoute === 'route') {
554
+ next('route');
555
+ } else if(continueRoute) {
556
+ next();
557
+ } else {
558
+ resolve(true);
559
+ }
560
+ });
561
+ }
562
+
563
+ use(path, ...callbacks) {
564
+ if(typeof path === 'function' || path instanceof Router || (Array.isArray(path) && path.every(p => typeof p === 'function' || p instanceof Router))) {
565
+ if(callbacks.length === 0 && typeof path === 'function' && path.length === 4) {
566
+ this.errorRoute = path;
567
+ return;
568
+ }
569
+ callbacks.unshift(path);
570
+ path = '';
571
+ }
572
+ if(path === '/') {
573
+ path = '';
574
+ }
575
+ for(let callback of callbacks) {
576
+ if(callback instanceof Router) {
577
+ callback.mountpath = path;
578
+ callback.parent = this;
579
+ callback.emit('mount', this);
580
+ }
581
+ }
582
+ this.createRoute('USE', path, this, ...callbacks);
583
+ }
584
+
585
+ route(path) {
586
+ let fns = new NullObject();
587
+ for(let method of methods) {
588
+ fns[method] = (...callbacks) => {
589
+ return this.createRoute(method.toUpperCase(), path, fns, ...callbacks);
590
+ };
591
+ }
592
+ fns.get = (...callbacks) => {
593
+ return this.createRoute('GET', path, fns, ...callbacks);
594
+ };
595
+ return fns;
596
+ }
597
+
598
+ _sendErrorPage(request, response, err, checkEnv = false) {
599
+ if(checkEnv && this.get('env') === 'production') {
600
+ err = 'Internal Server Error';
601
+ }
602
+ request.noEtag = true;
603
+ response.setHeader('Content-Type', 'text/html; charset=utf-8');
604
+ response.setHeader('X-Content-Type-Options', 'nosniff');
605
+ response.setHeader('Content-Security-Policy', "default-src 'none'");
606
+ response.send(`<!DOCTYPE html>\n` +
607
+ `<html lang="en">\n` +
608
+ `<head>\n` +
609
+ `<meta charset="utf-8">\n` +
610
+ `<title>Error</title>\n` +
611
+ `</head>\n` +
612
+ `<body>\n` +
613
+ `<pre>${err?.stack ?? err}</pre>\n` +
614
+ `</body>\n` +
615
+ `</html>\n`);
616
+ }
617
+ }