@oxog/spark 1.1.1 → 1.3.0

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +538 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,758 +1,708 @@
1
1
  'use strict';
2
2
 
3
- /**
4
- * @fileoverview Router class for handling HTTP routes in Spark Framework
5
- * @author Spark Framework Team
6
- * @since 1.0.0
7
- * @version 1.0.0
8
- */
9
-
10
- const Layer = require('./layer');
11
- const Route = require('./route');
12
- const { SafeRegexCache } = require('../utils/regex-validator');
13
-
14
- /**
15
- * Router class for managing HTTP routes and middleware
16
- *
17
- * The Router class provides route registration, path matching, and middleware execution.
18
- * It supports dynamic route parameters, nested routers, route grouping, and various
19
- * HTTP methods. Routes are matched using optimized regular expressions with caching.
20
- *
21
- * @class Router
22
- * @since 1.0.0
23
- *
24
- * @example
25
- * // Basic usage
26
- * const router = new Router();
27
- *
28
- * router.get('/users', (ctx) => {
29
- * ctx.json({ users: [] });
30
- * });
31
- *
32
- * router.post('/users', (ctx) => {
33
- * const user = ctx.body;
34
- * ctx.status(201).json({ id: 123, ...user });
35
- * });
36
- *
37
- * @example
38
- * // With parameters and middleware
39
- * router.get('/users/:id', authenticate, (ctx) => {
40
- * const userId = ctx.params.id;
41
- * ctx.json({ id: userId, name: 'User' });
42
- * });
43
- *
44
- * @example
45
- * // Route grouping
46
- * router.group('/api/v1', (api) => {
47
- * api.get('/users', getUsersHandler);
48
- * api.post('/users', createUserHandler);
49
- * });
50
- */
51
- class Router {
52
- /**
53
- * Create a new Router instance
54
- *
55
- * @param {Object} [options={}] - Router configuration options
56
- * @param {boolean} [options.caseSensitive=false] - Enable case-sensitive routing
57
- * @param {boolean} [options.strict=false] - Enable strict routing (trailing slash matters)
58
- *
59
- * @since 1.0.0
60
- *
61
- * @example
62
- * // Default router
63
- * const router = new Router();
64
- *
65
- * @example
66
- * // Case-sensitive router
67
- * const router = new Router({ caseSensitive: true });
68
- *
69
- * @example
70
- * // Strict routing (trailing slash matters)
71
- * const router = new Router({ strict: true });
72
- */
73
- constructor(options = {}) {
74
- /**
75
- * Router configuration options
76
- * @type {Object}
77
- * @private
78
- */
79
- this.options = {
80
- caseSensitive: false,
81
- strict: false,
82
- ...options
83
- };
84
-
85
- /**
86
- * Array of route layers (middleware and routes)
87
- * @type {Array}
88
- * @private
89
- */
90
- this.stack = [];
91
-
92
- /**
93
- * Parameter handlers for route parameters
94
- * @type {Object}
95
- * @private
96
- */
97
- this.params = {};
98
-
99
- /**
100
- * Cache for compiled regular expressions
101
- * @type {SafeRegexCache}
102
- * @private
103
- */
104
- this.regexCache = new SafeRegexCache();
105
- }
106
-
107
- /**
108
- * Add middleware to the router
109
- *
110
- * Middleware functions are executed for routes that match the specified path.
111
- * If no path is provided, middleware applies to all routes.
112
- *
113
- * @param {string|Function} pathOrMiddleware - Path pattern or middleware function
114
- * @param {...Function} middlewares - Additional middleware functions
115
- * @returns {Router} The router instance for method chaining
116
- *
117
- * @since 1.0.0
118
- *
119
- * @example
120
- * // Global middleware
121
- * router.use((ctx, next) => {
122
- * // Console.log removed for production
123
- * return next();
124
- * });
125
- *
126
- * @example
127
- * // Path-specific middleware
128
- * router.use('/api', authenticateMiddleware);
129
- *
130
- * @example
131
- * // Multiple middleware
132
- * router.use('/admin', authenticate, authorize, logAccess);
133
- */
134
- use(pathOrMiddleware, ...middlewares) {
135
- let path = '/';
136
- let handlers = [];
137
-
138
- if (typeof pathOrMiddleware === 'string') {
139
- path = pathOrMiddleware;
140
- handlers = middlewares;
141
- } else {
142
- handlers = [pathOrMiddleware, ...middlewares];
143
- }
144
-
145
- for (const handler of handlers) {
146
- const layer = new Layer(path, {
147
- sensitive: this.options.caseSensitive,
148
- strict: this.options.strict,
149
- end: false
150
- }, handler, this);
151
-
152
- this.stack.push(layer);
153
- }
154
-
155
- return this;
156
- }
157
-
158
- /**
159
- * Register a GET route
160
- *
161
- * @param {string} path - Route path pattern
162
- * @param {...Function} handlers - Route handler functions
163
- * @returns {Route} The created route object
164
- *
165
- * @since 1.0.0
166
- *
167
- * @example
168
- * router.get('/', (ctx) => {
169
- * ctx.json({ message: 'Hello World!' });
170
- * });
171
- *
172
- * @example
173
- * // With parameters
174
- * router.get('/users/:id', (ctx) => {
175
- * const id = ctx.params.id;
176
- * ctx.json({ id, name: 'User' });
177
- * });
178
- */
179
- get(path, ...handlers) {
180
- return this.route(path, 'GET', ...handlers);
181
- }
182
-
183
- /**
184
- * Register a POST route
185
- *
186
- * @param {string} path - Route path pattern
187
- * @param {...Function} handlers - Route handler functions
188
- * @returns {Route} The created route object
189
- *
190
- * @since 1.0.0
191
- *
192
- * @example
193
- * router.post('/users', (ctx) => {
194
- * const user = ctx.body;
195
- * ctx.status(201).json({ id: 123, ...user });
196
- * });
197
- */
198
- post(path, ...handlers) {
199
- return this.route(path, 'POST', ...handlers);
200
- }
201
-
202
- /**
203
- * Register a PUT route
204
- *
205
- * @param {string} path - Route path pattern
206
- * @param {...Function} handlers - Route handler functions
207
- * @returns {Route} The created route object
208
- *
209
- * @since 1.0.0
210
- *
211
- * @example
212
- * router.put('/users/:id', (ctx) => {
213
- * const id = ctx.params.id;
214
- * const updates = ctx.body;
215
- * ctx.json({ id, ...updates });
216
- * });
217
- */
218
- put(path, ...handlers) {
219
- return this.route(path, 'PUT', ...handlers);
220
- }
221
-
222
- /**
223
- * Register a DELETE route
224
- *
225
- * @param {string} path - Route path pattern
226
- * @param {...Function} handlers - Route handler functions
227
- * @returns {Route} The created route object
228
- *
229
- * @since 1.0.0
230
- *
231
- * @example
232
- * router.delete('/users/:id', (ctx) => {
233
- * const id = ctx.params.id;
234
- * // Delete user logic
235
- * ctx.status(204).end();
236
- * });
237
- */
238
- delete(path, ...handlers) {
239
- return this.route(path, 'DELETE', ...handlers);
240
- }
241
-
242
- /**
243
- * Register a PATCH route
244
- *
245
- * @param {string} path - Route path pattern
246
- * @param {...Function} handlers - Route handler functions
247
- * @returns {Route} The created route object
248
- *
249
- * @since 1.0.0
250
- *
251
- * @example
252
- * router.patch('/users/:id', (ctx) => {
253
- * const id = ctx.params.id;
254
- * const updates = ctx.body;
255
- * ctx.json({ id, ...updates });
256
- * });
257
- */
258
- patch(path, ...handlers) {
259
- return this.route(path, 'PATCH', ...handlers);
260
- }
261
-
262
- /**
263
- * Register a HEAD route
264
- *
265
- * @param {string} path - Route path pattern
266
- * @param {...Function} handlers - Route handler functions
267
- * @returns {Route} The created route object
268
- *
269
- * @since 1.0.0
270
- *
271
- * @example
272
- * router.head('/users/:id', (ctx) => {
273
- * // Check if user exists
274
- * ctx.status(200).end();
275
- * });
276
- */
277
- head(path, ...handlers) {
278
- return this.route(path, 'HEAD', ...handlers);
279
- }
280
-
281
- /**
282
- * Register an OPTIONS route
283
- *
284
- * @param {string} path - Route path pattern
285
- * @param {...Function} handlers - Route handler functions
286
- * @returns {Route} The created route object
287
- *
288
- * @since 1.0.0
289
- *
290
- * @example
291
- * router.options('/api/*', (ctx) => {
292
- * ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
293
- * ctx.status(200).end();
294
- * });
295
- */
296
- options(path, ...handlers) {
297
- return this.route(path, 'OPTIONS', ...handlers);
298
- }
299
-
300
- /**
301
- * Register a route for all HTTP methods
302
- *
303
- * @param {string} path - Route path pattern
304
- * @param {...Function} handlers - Route handler functions
305
- * @returns {Route} The created route object
306
- *
307
- * @since 1.0.0
308
- *
309
- * @example
310
- * router.all('/api/*', (ctx, next) => {
311
- * ctx.set('X-API-Version', '1.0');
312
- * return next();
313
- * });
314
- */
315
- all(path, ...handlers) {
316
- return this.route(path, null, ...handlers);
317
- }
318
-
319
- /**
320
- * Create a new route for the specified path and method
321
- *
322
- * This is an internal method used by the HTTP method functions (get, post, etc.).
323
- * It creates a new Route instance and wraps it in a Layer for the router stack.
324
- *
325
- * @param {string} path - Route path pattern
326
- * @param {string|null} method - HTTP method or null for all methods
327
- * @param {...Function} handlers - Route handler functions
328
- * @returns {Route} The created route object
329
- *
330
- * @private
331
- * @since 1.0.0
332
- */
333
- route(path, method, ...handlers) {
334
- const route = new Route(path);
335
-
336
- if (method) {
337
- route[method.toLowerCase()](...handlers);
338
- } else {
339
- route.all(...handlers);
340
- }
341
-
342
- const layer = new Layer(path, {
343
- sensitive: this.options.caseSensitive,
344
- strict: this.options.strict,
345
- end: true
346
- }, (ctx, next) => {
347
- return route.dispatch(ctx, next);
348
- }, this);
349
-
350
- layer.route = route;
351
- this.stack.push(layer);
352
-
353
- return route;
354
- }
355
-
356
- /**
357
- * Register a parameter handler
358
- *
359
- * Parameter handlers are called when a route parameter is matched.
360
- * They can be used for validation, transformation, or loading related data.
361
- *
362
- * @param {string} name - Parameter name
363
- * @param {Function} handler - Handler function (ctx, next, value, name) => {}
364
- * @returns {Router} The router instance for method chaining
365
- *
366
- * @since 1.0.0
367
- *
368
- * @example
369
- * // Load user for :userId parameter
370
- * router.param('userId', async (ctx, next, id) => {
371
- * ctx.user = await User.findById(id);
372
- * if (!ctx.user) {
373
- * ctx.status(404).json({ error: 'User not found' });
374
- * return;
375
- * }
376
- * return next();
377
- * });
378
- *
379
- * router.get('/users/:userId', (ctx) => {
380
- * ctx.json(ctx.user); // User already loaded by param handler
381
- * });
382
- */
383
- param(name, handler) {
384
- this.params[name] = handler;
385
- return this;
386
- }
387
-
388
- /**
389
- * Handle an incoming request through the router
390
- *
391
- * Processes the request through all layers (middleware and routes) in the router stack.
392
- * Matches paths, extracts parameters, and executes appropriate handlers.
393
- *
394
- * @param {Context} ctx - The request context
395
- * @param {Function} next - The next function to call if no routes match
396
- * @returns {Promise<void>}
397
- *
398
- * @since 1.0.0
399
- */
400
- async handle(ctx, next) {
401
- let layerError = null;
402
- let layerIndex = 0;
403
-
404
- const nextLayer = async (error) => {
405
- if (error) {
406
- layerError = error;
407
- }
408
-
409
- if (layerIndex >= this.stack.length) {
410
- return next(layerError);
411
- }
412
-
413
- const layer = this.stack[layerIndex++];
414
- const match = layer.match(ctx.path);
415
-
416
- if (!match) {
417
- return nextLayer(layerError);
418
- }
419
-
420
- ctx.params = { ...ctx.params, ...match.params };
421
-
422
- if (match.path !== undefined) {
423
- ctx.path = match.path;
424
- }
425
-
426
- try {
427
- await this.processParams(ctx, layer, match.params);
428
-
429
- if (layer.route) {
430
- if (layer.route.handles_method(ctx.method)) {
431
- await layer.handle(ctx, nextLayer);
432
- } else {
433
- nextLayer();
434
- }
435
- } else {
436
- await layer.handle(ctx, nextLayer);
437
- }
438
- } catch (err) {
439
- nextLayer(err);
440
- }
441
- };
442
-
443
- await nextLayer();
444
- }
445
-
446
- /**
447
- * Process route parameters through registered parameter handlers
448
- *
449
- * Calls any registered parameter handlers for the matched route parameters.
450
- * Parameter handlers can validate, transform, or load data based on parameter values.
451
- *
452
- * @param {Context} ctx - The request context
453
- * @param {Layer} layer - The matched layer
454
- * @param {Object} params - The extracted route parameters
455
- * @returns {Promise<void>}
456
- *
457
- * @private
458
- * @since 1.0.0
459
- */
460
- async processParams(ctx, layer, params) {
461
- if (!params || Object.keys(params).length === 0) {
462
- return;
463
- }
464
-
465
- for (const [key, value] of Object.entries(params)) {
466
- if (this.params[key]) {
467
- try {
468
- await this.params[key](ctx, () => {}, value, key);
469
- } catch (error) {
470
- throw error;
471
- }
472
- }
473
- }
474
- }
475
-
476
- /**
477
- * Convert a path string to a regular expression
478
- *
479
- * Converts route path patterns to regular expressions for matching URLs.
480
- * Supports parameter patterns (:param) and wildcard patterns (*wild).
481
- *
482
- * @param {string|RegExp|Array} path - Path pattern(s) to convert
483
- * @param {Object} [options={}] - Conversion options
484
- * @param {boolean} [options.sensitive=false] - Case-sensitive matching
485
- * @param {boolean} [options.strict=false] - Strict mode (trailing slash matters)
486
- * @param {boolean} [options.end=true] - Match to end of string
487
- * @returns {Object} Object with regexp and keys properties
488
- *
489
- * @static
490
- * @since 1.0.0
491
- *
492
- * @example
493
- * // Simple path
494
- * Router.pathToRegExp('/users'); // { regexp: /^\/users\/?$/, keys: [] }
495
- *
496
- * @example
497
- * // With parameters
498
- * Router.pathToRegExp('/users/:id'); // { regexp: /^\/users\/([^/]+)\/?$/, keys: [{ name: 'id', optional: false }] }
499
- */
500
- static pathToRegExp(path, options = {}) {
501
- const { sensitive = false, strict = false, end = true } = options;
502
-
503
- if (path instanceof RegExp) {
504
- return { regexp: path, keys: [] };
505
- }
506
-
507
- if (Array.isArray(path)) {
508
- const regexps = path.map(p => Router.pathToRegExp(p, options));
509
- return {
510
- regexp: new RegExp(`(?:${regexps.map(r => r.regexp.source).join('|')})`, getFlags(options)),
511
- keys: regexps.reduce((keys, r) => keys.concat(r.keys), [])
512
- };
513
- }
514
-
515
- const keys = [];
516
- let regexp = path;
517
-
518
- regexp = regexp.replace(/\\\//g, '/');
519
-
520
- regexp = regexp.replace(/:([^(/\\]+)/g, (match, key) => {
521
- keys.push({ name: key, optional: false });
522
- return '([^/]+)';
523
- });
524
-
525
- regexp = regexp.replace(/\*([^(/\\]*)/g, (match, key) => {
526
- keys.push({ name: key || 'wild', optional: false });
527
- return '(.*)';
528
- });
529
-
530
- if (end) {
531
- regexp += strict ? '' : '/?';
532
- }
533
-
534
- regexp += end ? '$' : '';
535
-
536
- const flags = getFlags(options);
537
- return {
538
- regexp: new RegExp(`^${regexp}`, flags),
539
- keys
540
- };
541
- }
542
-
543
- /**
544
- * Match a path against a regular expression and extract parameters
545
- *
546
- * Tests if a path matches the given regular expression and extracts
547
- * parameter values based on the provided keys.
548
- *
549
- * @param {string} path - The path to match
550
- * @param {RegExp} regexp - The regular expression to test against
551
- * @param {Array} keys - Array of parameter key objects
552
- * @returns {Object|false} Match object with path and params, or false if no match
553
- *
554
- * @throws {Error} When URL parameters cannot be decoded
555
- *
556
- * @static
557
- * @since 1.0.0
558
- *
559
- * @example
560
- * const { regexp, keys } = Router.pathToRegExp('/users/:id');
561
- * const match = Router.match('/users/123', regexp, keys);
562
- * // { path: '/users/123', params: { id: '123' } }
563
- */
564
- static match(path, regexp, keys) {
565
- const match = regexp.exec(path);
566
- if (!match) return false;
567
-
568
- const params = {};
569
- for (let i = 1; i < match.length; i++) {
570
- const key = keys[i - 1];
571
- const value = match[i];
572
-
573
- if (value !== undefined) {
574
- try {
575
- params[key.name] = decodeURIComponent(value);
576
- } catch (error) {
577
- // Handle malformed URL parameters
578
- throw new Error('Invalid URL parameter');
579
- }
580
- }
581
- }
582
-
583
- return {
584
- path: match[0],
585
- params
586
- };
587
- }
588
-
589
- /**
590
- * Create a route group with a common prefix
591
- *
592
- * Groups routes under a common path prefix. The callback function receives
593
- * a new router instance to define routes within the group.
594
- *
595
- * @param {string} prefix - Common path prefix for the group
596
- * @param {Function} callback - Function that receives the group router
597
- * @returns {Router} The router instance for method chaining
598
- *
599
- * @since 1.0.0
600
- *
601
- * @example
602
- * router.group('/api', (api) => {
603
- * api.get('/users', getUsersHandler);
604
- * api.post('/users', createUserHandler);
605
- * api.get('/users/:id', getUserHandler);
606
- * });
607
- * // Creates routes: GET /api/users, POST /api/users, GET /api/users/:id
608
- */
609
- group(prefix, callback) {
610
- const router = new Router(this.options);
611
- callback(router);
612
-
613
- this.use(prefix, (ctx, next) => {
614
- const originalPath = ctx.path;
615
- if (ctx.path.startsWith(prefix)) {
616
- ctx.path = ctx.path.slice(prefix.length) || '/';
617
- }
618
-
619
- return router.handle(ctx, () => {
620
- ctx.path = originalPath;
621
- return next();
622
- });
623
- });
624
-
625
- return this;
626
- }
627
-
628
- /**
629
- * Create a versioned API group
630
- *
631
- * Convenience method for creating API version groups with /v{version} prefix.
632
- *
633
- * @param {string|number} version - API version number
634
- * @param {Function} callback - Function that receives the version router
635
- * @returns {Router} The router instance for method chaining
636
- *
637
- * @since 1.0.0
638
- *
639
- * @example
640
- * router.version('1', (v1) => {
641
- * v1.get('/users', getUsersV1);
642
- * v1.post('/users', createUserV1);
643
- * });
644
- *
645
- * router.version('2', (v2) => {
646
- * v2.get('/users', getUsersV2);
647
- * v2.post('/users', createUserV2);
648
- * });
649
- * // Creates: GET /v1/users, POST /v1/users, GET /v2/users, POST /v2/users
650
- */
651
- version(version, callback) {
652
- const versionPrefix = `/v${version}`;
653
- return this.group(versionPrefix, callback);
654
- }
655
-
656
- /**
657
- * Mount another router at the specified path
658
- *
659
- * Mounts a sub-router at the given path, allowing for modular route organization.
660
- *
661
- * @param {string} path - Path prefix where the router should be mounted
662
- * @param {Router} router - Router instance to mount
663
- * @returns {Router} The router instance for method chaining
664
- *
665
- * @since 1.0.0
666
- *
667
- * @example
668
- * const userRouter = new Router();
669
- * userRouter.get('/', getUsersHandler);
670
- * userRouter.get('/:id', getUserHandler);
671
- *
672
- * const apiRouter = new Router();
673
- * apiRouter.mount('/users', userRouter);
674
- * // Creates routes: GET /users/, GET /users/:id
675
- */
676
- mount(path, router) {
677
- this.use(path, (ctx, next) => {
678
- return router.handle(ctx, next);
679
- });
680
- return this;
681
- }
682
-
683
- /**
684
- * Get all routes (layers with route objects)
685
- *
686
- * Returns an array of layers that contain route objects, filtering out
687
- * middleware-only layers.
688
- *
689
- * @returns {Array} Array of route layers
690
- *
691
- * @since 1.0.0
692
- *
693
- * @example
694
- * const routes = router.routes;
695
- * // Console.log removed for production
696
- */
697
- get routes() {
698
- return this.stack.filter(layer => layer.route);
699
- }
700
-
701
- /**
702
- * Returns router middleware function
703
- *
704
- * @returns {Function} Middleware function for this router
705
- * @since 1.0.0
706
- *
707
- * @example
708
- * // Mount router on app
709
- * const router = new Router();
710
- * router.get('/users', handler);
711
- * app.use('/api', router.routes());
712
- */
713
- routes() {
714
- const router = this;
715
- return function routerMiddleware(ctx, next) {
716
- return router.handle(ctx, next);
717
- };
718
- }
719
-
720
- /**
721
- * Alias for routes() method
722
- * @returns {Function} Middleware function
723
- */
724
- middleware(prefix) {
725
- const router = this;
726
- return function routerMiddleware(ctx, next) {
727
- // If prefix is provided, adjust the path
728
- if (prefix && ctx.path.startsWith(prefix)) {
729
- const originalPath = ctx.path;
730
- ctx.path = ctx.path.slice(prefix.length) || '/';
731
-
732
- return router.handle(ctx, next).then(() => {
733
- ctx.path = originalPath;
734
- }).catch(err => {
735
- ctx.path = originalPath;
736
- throw err;
737
- });
738
- }
739
- return router.handle(ctx, next);
740
- };
741
- }
742
- }
743
-
744
- /**
745
- * Get regular expression flags based on options
746
- *
747
- * @param {Object} options - Router options
748
- * @param {boolean} options.sensitive - Case sensitivity flag
749
- * @returns {string} Regular expression flags
750
- *
751
- * @private
752
- * @since 1.0.0
753
- */
754
- function getFlags(options) {
755
- return options.sensitive ? '' : 'i';
756
- }
757
-
3
+ /**
4
+ * @fileoverview Router class for handling HTTP routes in Spark Framework
5
+ * @author Spark Framework Team
6
+ * @since 1.0.0
7
+ * @version 1.0.0
8
+ */
9
+
10
+ const Layer = require('./layer');
11
+ const Route = require('./route');
12
+ const { SafeRegexCache } = require('../utils/regex-validator');
13
+
14
+ const { pathToRegExp, matchPath } = Layer;
15
+
16
+ /**
17
+ * Router class for managing HTTP routes and middleware
18
+ *
19
+ * The Router class provides route registration, path matching, and middleware execution.
20
+ * It supports dynamic route parameters, nested routers, route grouping, and various
21
+ * HTTP methods. Routes are matched using optimized regular expressions with caching.
22
+ *
23
+ * @class Router
24
+ * @since 1.0.0
25
+ *
26
+ * @example
27
+ * // Basic usage
28
+ * const router = new Router();
29
+ *
30
+ * router.get('/users', (ctx) => {
31
+ * ctx.json({ users: [] });
32
+ * });
33
+ *
34
+ * router.post('/users', (ctx) => {
35
+ * const user = ctx.body;
36
+ * ctx.status(201).json({ id: 123, ...user });
37
+ * });
38
+ *
39
+ * @example
40
+ * // With parameters and middleware
41
+ * router.get('/users/:id', authenticate, (ctx) => {
42
+ * const userId = ctx.params.id;
43
+ * ctx.json({ id: userId, name: 'User' });
44
+ * });
45
+ *
46
+ * @example
47
+ * // Route grouping
48
+ * router.group('/api/v1', (api) => {
49
+ * api.get('/users', getUsersHandler);
50
+ * api.post('/users', createUserHandler);
51
+ * });
52
+ */
53
+ class Router {
54
+ /**
55
+ * Create a new Router instance
56
+ *
57
+ * @param {Object} [options={}] - Router configuration options
58
+ * @param {boolean} [options.caseSensitive=false] - Enable case-sensitive routing
59
+ * @param {boolean} [options.strict=false] - Enable strict routing (trailing slash matters)
60
+ *
61
+ * @since 1.0.0
62
+ *
63
+ * @example
64
+ * // Default router
65
+ * const router = new Router();
66
+ *
67
+ * @example
68
+ * // Case-sensitive router
69
+ * const router = new Router({ caseSensitive: true });
70
+ *
71
+ * @example
72
+ * // Strict routing (trailing slash matters)
73
+ * const router = new Router({ strict: true });
74
+ */
75
+ constructor(options = {}) {
76
+ /**
77
+ * Router configuration options
78
+ * @type {Object}
79
+ * @private
80
+ */
81
+ const config = {
82
+ ...options,
83
+ caseSensitive: Boolean(options.caseSensitive !== undefined ? options.caseSensitive : options.sensitive),
84
+ strict: Boolean(options.strict)
85
+ };
86
+ // Also callable as router.options(path, ...handlers): a plain property
87
+ // would hide the options() route method.
88
+ this.options = Object.assign(
89
+ (path, ...handlers) => Router.prototype.options.call(this, path, ...handlers),
90
+ config
91
+ );
92
+
93
+ /**
94
+ * Array of route layers (middleware and routes)
95
+ * @type {Array}
96
+ * @private
97
+ */
98
+ this.stack = [];
99
+
100
+ /**
101
+ * Parameter handlers for route parameters
102
+ * @type {Object}
103
+ * @private
104
+ */
105
+ this.params = {};
106
+
107
+ /**
108
+ * Cache for compiled regular expressions
109
+ * @type {SafeRegexCache}
110
+ * @private
111
+ */
112
+ this.regexCache = new SafeRegexCache();
113
+ }
114
+
115
+ /**
116
+ * Add middleware to the router
117
+ *
118
+ * Middleware functions are executed for routes that match the specified path.
119
+ * If no path is provided, middleware applies to all routes.
120
+ *
121
+ * @param {string|Function} pathOrMiddleware - Path pattern or middleware function
122
+ * @param {...Function} middlewares - Additional middleware functions
123
+ * @returns {Router} The router instance for method chaining
124
+ *
125
+ * @since 1.0.0
126
+ *
127
+ * @example
128
+ * // Global middleware
129
+ * router.use((ctx, next) => {
130
+ * // Console.log removed for production
131
+ * return next();
132
+ * });
133
+ *
134
+ * @example
135
+ * // Path-specific middleware
136
+ * router.use('/api', authenticateMiddleware);
137
+ *
138
+ * @example
139
+ * // Multiple middleware
140
+ * router.use('/admin', authenticate, authorize, logAccess);
141
+ */
142
+ use(pathOrMiddleware, ...middlewares) {
143
+ let path = '/';
144
+ let handlers;
145
+
146
+ if (typeof pathOrMiddleware === 'string') {
147
+ path = pathOrMiddleware;
148
+ handlers = middlewares;
149
+ } else {
150
+ handlers = [pathOrMiddleware, ...middlewares];
151
+ }
152
+
153
+ for (const handler of handlers) {
154
+ // Accept mounted routers as well as middleware functions
155
+ const fn = handler && typeof handler === 'object' && typeof handler.handle === 'function'
156
+ ? (ctx, next) => handler.handle(ctx, next)
157
+ : handler;
158
+ if (typeof fn !== 'function') {
159
+ throw new TypeError('router.use() requires middleware functions or routers');
160
+ }
161
+
162
+ const layer = new Layer(path, {
163
+ sensitive: this.options.caseSensitive,
164
+ strict: this.options.strict,
165
+ end: false
166
+ }, fn, this);
167
+
168
+ this.stack.push(layer);
169
+ }
170
+
171
+ return this;
172
+ }
173
+
174
+ /**
175
+ * Register a GET route
176
+ *
177
+ * @param {string} path - Route path pattern
178
+ * @param {...Function} handlers - Route handler functions
179
+ * @returns {Router} The router instance for method chaining
180
+ *
181
+ * @since 1.0.0
182
+ *
183
+ * @example
184
+ * router.get('/', (ctx) => {
185
+ * ctx.json({ message: 'Hello World!' });
186
+ * });
187
+ *
188
+ * @example
189
+ * // With parameters
190
+ * router.get('/users/:id', (ctx) => {
191
+ * const id = ctx.params.id;
192
+ * ctx.json({ id, name: 'User' });
193
+ * });
194
+ */
195
+ get(path, ...handlers) {
196
+ this.route(path, 'GET', ...handlers);
197
+ return this;
198
+ }
199
+
200
+ /**
201
+ * Register a POST route
202
+ *
203
+ * @param {string} path - Route path pattern
204
+ * @param {...Function} handlers - Route handler functions
205
+ * @returns {Router} The router instance for method chaining
206
+ *
207
+ * @since 1.0.0
208
+ *
209
+ * @example
210
+ * router.post('/users', (ctx) => {
211
+ * const user = ctx.body;
212
+ * ctx.status(201).json({ id: 123, ...user });
213
+ * });
214
+ */
215
+ post(path, ...handlers) {
216
+ this.route(path, 'POST', ...handlers);
217
+ return this;
218
+ }
219
+
220
+ /**
221
+ * Register a PUT route
222
+ *
223
+ * @param {string} path - Route path pattern
224
+ * @param {...Function} handlers - Route handler functions
225
+ * @returns {Router} The router instance for method chaining
226
+ *
227
+ * @since 1.0.0
228
+ *
229
+ * @example
230
+ * router.put('/users/:id', (ctx) => {
231
+ * const id = ctx.params.id;
232
+ * const updates = ctx.body;
233
+ * ctx.json({ id, ...updates });
234
+ * });
235
+ */
236
+ put(path, ...handlers) {
237
+ this.route(path, 'PUT', ...handlers);
238
+ return this;
239
+ }
240
+
241
+ /**
242
+ * Register a DELETE route
243
+ *
244
+ * @param {string} path - Route path pattern
245
+ * @param {...Function} handlers - Route handler functions
246
+ * @returns {Router} The router instance for method chaining
247
+ *
248
+ * @since 1.0.0
249
+ *
250
+ * @example
251
+ * router.delete('/users/:id', (ctx) => {
252
+ * const id = ctx.params.id;
253
+ * // Delete user logic
254
+ * ctx.status(204).end();
255
+ * });
256
+ */
257
+ delete(path, ...handlers) {
258
+ this.route(path, 'DELETE', ...handlers);
259
+ return this;
260
+ }
261
+
262
+ /**
263
+ * Register a PATCH route
264
+ *
265
+ * @param {string} path - Route path pattern
266
+ * @param {...Function} handlers - Route handler functions
267
+ * @returns {Router} The router instance for method chaining
268
+ *
269
+ * @since 1.0.0
270
+ *
271
+ * @example
272
+ * router.patch('/users/:id', (ctx) => {
273
+ * const id = ctx.params.id;
274
+ * const updates = ctx.body;
275
+ * ctx.json({ id, ...updates });
276
+ * });
277
+ */
278
+ patch(path, ...handlers) {
279
+ this.route(path, 'PATCH', ...handlers);
280
+ return this;
281
+ }
282
+
283
+ /**
284
+ * Register a HEAD route
285
+ *
286
+ * @param {string} path - Route path pattern
287
+ * @param {...Function} handlers - Route handler functions
288
+ * @returns {Router} The router instance for method chaining
289
+ *
290
+ * @since 1.0.0
291
+ *
292
+ * @example
293
+ * router.head('/users/:id', (ctx) => {
294
+ * // Check if user exists
295
+ * ctx.status(200).end();
296
+ * });
297
+ */
298
+ head(path, ...handlers) {
299
+ this.route(path, 'HEAD', ...handlers);
300
+ return this;
301
+ }
302
+
303
+ /**
304
+ * Register an OPTIONS route
305
+ *
306
+ * @param {string} path - Route path pattern
307
+ * @param {...Function} handlers - Route handler functions
308
+ * @returns {Router} The router instance for method chaining
309
+ *
310
+ * @since 1.0.0
311
+ *
312
+ * @example
313
+ * router.options('/api/*', (ctx) => {
314
+ * ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
315
+ * ctx.status(200).end();
316
+ * });
317
+ */
318
+ options(path, ...handlers) {
319
+ this.route(path, 'OPTIONS', ...handlers);
320
+ return this;
321
+ }
322
+
323
+ /**
324
+ * Register a route for all HTTP methods
325
+ *
326
+ * @param {string} path - Route path pattern
327
+ * @param {...Function} handlers - Route handler functions
328
+ * @returns {Router} The router instance for method chaining
329
+ *
330
+ * @since 1.0.0
331
+ *
332
+ * @example
333
+ * router.all('/api/*', (ctx, next) => {
334
+ * ctx.set('X-API-Version', '1.0');
335
+ * return next();
336
+ * });
337
+ */
338
+ all(path, ...handlers) {
339
+ this.route(path, null, ...handlers);
340
+ return this;
341
+ }
342
+
343
+ /**
344
+ * Create a new route for the specified path and method
345
+ *
346
+ * This is an internal method used by the HTTP method functions (get, post, etc.).
347
+ * It creates a new Route instance and wraps it in a Layer for the router stack.
348
+ *
349
+ * @param {string} path - Route path pattern
350
+ * @param {string|null} method - HTTP method or null for all methods
351
+ * @param {...Function} handlers - Route handler functions
352
+ * @returns {Router} The router instance for method chaining
353
+ *
354
+ * @private
355
+ * @since 1.0.0
356
+ */
357
+ route(path, method, ...handlers) {
358
+ const route = new Route(path);
359
+
360
+ if (method) {
361
+ route[method.toLowerCase()](...handlers);
362
+ } else {
363
+ route.all(...handlers);
364
+ }
365
+
366
+ const layer = new Layer(path, {
367
+ sensitive: this.options.caseSensitive,
368
+ strict: this.options.strict,
369
+ end: true
370
+ }, (ctx, next) => {
371
+ return route.dispatch(ctx, next);
372
+ }, this);
373
+
374
+ layer.route = route;
375
+ this.stack.push(layer);
376
+
377
+ return route;
378
+ }
379
+
380
+ /**
381
+ * Register a parameter handler
382
+ *
383
+ * Parameter handlers are called when a route parameter is matched.
384
+ * They can be used for validation, transformation, or loading related data.
385
+ *
386
+ * @param {string} name - Parameter name
387
+ * @param {Function} handler - Handler function (ctx, next, value, name) => {}
388
+ * @returns {Router} The router instance for method chaining
389
+ *
390
+ * @since 1.0.0
391
+ *
392
+ * @example
393
+ * // Load user for :userId parameter
394
+ * router.param('userId', async (ctx, next, id) => {
395
+ * ctx.user = await User.findById(id);
396
+ * if (!ctx.user) {
397
+ * ctx.status(404).json({ error: 'User not found' });
398
+ * return;
399
+ * }
400
+ * return next();
401
+ * });
402
+ *
403
+ * router.get('/users/:userId', (ctx) => {
404
+ * ctx.json(ctx.user); // User already loaded by param handler
405
+ * });
406
+ */
407
+ param(name, handler) {
408
+ this.params[name] = handler;
409
+ return this;
410
+ }
411
+
412
+ /**
413
+ * Handle an incoming request through the router
414
+ *
415
+ * Processes the request through all layers (middleware and routes) in the router stack.
416
+ * Matches paths, extracts parameters, and executes appropriate handlers.
417
+ *
418
+ * @param {Context} ctx - The request context
419
+ * @param {Function} next - The next function to call if no routes match
420
+ * @returns {Promise<void>}
421
+ *
422
+ * @since 1.0.0
423
+ */
424
+ async handle(ctx, done) {
425
+ const originalPath = ctx.path;
426
+ let index = 0;
427
+
428
+ const next = async (error) => {
429
+ // Undo prefix stripping done for a previous middleware layer
430
+ ctx.path = originalPath;
431
+
432
+ // Errors skip the remaining layers and propagate to the caller
433
+ if (error) {
434
+ return done(error);
435
+ }
436
+
437
+ while (index < this.stack.length) {
438
+ const layer = this.stack[index++];
439
+
440
+ let match;
441
+ try {
442
+ match = layer.match(ctx.path);
443
+ } catch (err) {
444
+ return done(err);
445
+ }
446
+
447
+ if (!match) {
448
+ continue;
449
+ }
450
+
451
+ if (layer.route && !layer.route.handles_method(ctx.method)) {
452
+ continue;
453
+ }
454
+
455
+ ctx.params = { ...ctx.params, ...match.params };
456
+
457
+ try {
458
+ if (await this.processParams(ctx, layer, match.params) === false) {
459
+ return undefined;
460
+ }
461
+
462
+ if (!layer.route && match.path) {
463
+ // Middleware mounted at a prefix sees the path below the prefix
464
+ ctx.path = originalPath.slice(match.path.length) || '/';
465
+ }
466
+
467
+ await layer.handle(ctx, next);
468
+ } catch (err) {
469
+ return next(err);
470
+ } finally {
471
+ ctx.path = originalPath;
472
+ }
473
+ return undefined;
474
+ }
475
+
476
+ return done();
477
+ };
478
+
479
+ await next();
480
+ }
481
+
482
+ /**
483
+ * Process route parameters through registered parameter handlers
484
+ *
485
+ * Calls any registered parameter handlers for the matched route parameters.
486
+ * Parameter handlers can validate, transform, or load data based on parameter values.
487
+ *
488
+ * @param {Context} ctx - The request context
489
+ * @param {Layer} layer - The matched layer
490
+ * @param {Object} params - The extracted route parameters
491
+ * @returns {Promise<void>}
492
+ *
493
+ * @private
494
+ * @since 1.0.0
495
+ */
496
+ async processParams(ctx, layer, params) {
497
+ if (!params || Object.keys(params).length === 0) {
498
+ return;
499
+ }
500
+
501
+ for (const [key, value] of Object.entries(params)) {
502
+ if (this.params[key]) {
503
+ let continued = false;
504
+ await this.params[key](ctx, () => {
505
+ continued = true;
506
+ }, value, key);
507
+ // A param handler that responded without calling next() ends the request
508
+ if (!continued && ctx.responded) {
509
+ return false;
510
+ }
511
+ }
512
+ }
513
+ return true;
514
+ }
515
+
516
+ /**
517
+ * Convert a path string to a regular expression
518
+ *
519
+ * Converts route path patterns to regular expressions for matching URLs.
520
+ * Supports parameter patterns (:param) and wildcard patterns (*wild).
521
+ *
522
+ * @param {string|RegExp|Array} path - Path pattern(s) to convert
523
+ * @param {Object} [options={}] - Conversion options
524
+ * @param {boolean} [options.sensitive=false] - Case-sensitive matching
525
+ * @param {boolean} [options.strict=false] - Strict mode (trailing slash matters)
526
+ * @param {boolean} [options.end=true] - Match to end of string
527
+ * @returns {Object} Object with regexp and keys properties
528
+ *
529
+ * @static
530
+ * @since 1.0.0
531
+ *
532
+ * @example
533
+ * // Simple path
534
+ * Router.pathToRegExp('/users'); // { regexp: /^\/users\/?$/, keys: [] }
535
+ *
536
+ * @example
537
+ * // With parameters
538
+ * Router.pathToRegExp('/users/:id'); // { regexp: /^\/users\/([^/]+)\/?$/, keys: [{ name: 'id', optional: false }] }
539
+ */
540
+ static pathToRegExp(path, options = {}) {
541
+ return pathToRegExp(path, options);
542
+ }
543
+
544
+ /**
545
+ * Match a path against a compiled pattern
546
+ *
547
+ * @param {string} path - Path to match
548
+ * @param {RegExp} regexp - Compiled pattern
549
+ * @param {Array} keys - Parameter keys
550
+ * @returns {false|{path: string, params: Object}} Match result
551
+ * @throws {Error} 400 error for malformed percent-encoding in a parameter
552
+ */
553
+ static match(path, regexp, keys) {
554
+ return matchPath(path, regexp, keys);
555
+ }
556
+
557
+ /**
558
+ * Create a route group with a common prefix
559
+ *
560
+ * Groups routes under a common path prefix. The callback function receives
561
+ * a new router instance to define routes within the group.
562
+ *
563
+ * @param {string} prefix - Common path prefix for the group
564
+ * @param {Function} callback - Function that receives the group router
565
+ * @returns {Router} The router instance for method chaining
566
+ *
567
+ * @since 1.0.0
568
+ *
569
+ * @example
570
+ * router.group('/api', (api) => {
571
+ * api.get('/users', getUsersHandler);
572
+ * api.post('/users', createUserHandler);
573
+ * api.get('/users/:id', getUserHandler);
574
+ * });
575
+ * // Creates routes: GET /api/users, POST /api/users, GET /api/users/:id
576
+ */
577
+ group(prefix, callback) {
578
+ const router = new Router(this.options);
579
+ callback(router);
580
+ this.use(prefix, router);
581
+ return this;
582
+ }
583
+
584
+ /**
585
+ * Create a versioned API group
586
+ *
587
+ * Convenience method for creating API version groups with /v{version} prefix.
588
+ *
589
+ * @param {string|number} version - API version number
590
+ * @param {Function} callback - Function that receives the version router
591
+ * @returns {Router} The router instance for method chaining
592
+ *
593
+ * @since 1.0.0
594
+ *
595
+ * @example
596
+ * router.version('1', (v1) => {
597
+ * v1.get('/users', getUsersV1);
598
+ * v1.post('/users', createUserV1);
599
+ * });
600
+ *
601
+ * router.version('2', (v2) => {
602
+ * v2.get('/users', getUsersV2);
603
+ * v2.post('/users', createUserV2);
604
+ * });
605
+ * // Creates: GET /v1/users, POST /v1/users, GET /v2/users, POST /v2/users
606
+ */
607
+ version(version, callback) {
608
+ const versionPrefix = `/v${version}`;
609
+ return this.group(versionPrefix, callback);
610
+ }
611
+
612
+ /**
613
+ * Mount another router at the specified path
614
+ *
615
+ * Mounts a sub-router at the given path, allowing for modular route organization.
616
+ *
617
+ * @param {string} path - Path prefix where the router should be mounted
618
+ * @param {Router} router - Router instance to mount
619
+ * @returns {Router} The router instance for method chaining
620
+ *
621
+ * @since 1.0.0
622
+ *
623
+ * @example
624
+ * const userRouter = new Router();
625
+ * userRouter.get('/', getUsersHandler);
626
+ * userRouter.get('/:id', getUserHandler);
627
+ *
628
+ * const apiRouter = new Router();
629
+ * apiRouter.mount('/users', userRouter);
630
+ * // Creates routes: GET /users/, GET /users/:id
631
+ */
632
+ mount(path, router) {
633
+ this.use(path, router);
634
+ return this;
635
+ }
636
+
637
+
638
+ /**
639
+ * Returns router middleware function
640
+ *
641
+ * @returns {Function} Middleware function for this router
642
+ * @since 1.0.0
643
+ *
644
+ * @example
645
+ * // Mount router on app
646
+ * const router = new Router();
647
+ * router.get('/users', handler);
648
+ * app.use('/api', router.routes());
649
+ */
650
+ routes() {
651
+ // eslint-disable-next-line @typescript-eslint/no-this-alias -- the returned middleware is a plain named function, as in 1.x
652
+ const router = this;
653
+ return function routerMiddleware(ctx, next) {
654
+ return router.handle(ctx, next);
655
+ };
656
+ }
657
+
658
+ /**
659
+ * Alias for routes() method
660
+ * @returns {Function} Middleware function
661
+ */
662
+ middleware(prefix) {
663
+ // eslint-disable-next-line @typescript-eslint/no-this-alias -- the returned middleware is a plain named function, as in 1.x
664
+ const router = this;
665
+ let normalized = prefix ? (prefix.startsWith('/') ? prefix : `/${prefix}`) : '';
666
+ while (normalized.length > 1 && normalized.endsWith('/')) {
667
+ normalized = normalized.slice(0, -1);
668
+ }
669
+ if (normalized === '/') {
670
+ normalized = '';
671
+ }
672
+
673
+ return async function routerMiddleware(ctx, next) {
674
+ if (!normalized) {
675
+ return router.handle(ctx, next);
676
+ }
677
+ if (ctx.path !== normalized && !ctx.path.startsWith(`${normalized}/`)) {
678
+ return next();
679
+ }
680
+
681
+ const originalPath = ctx.path;
682
+ ctx.path = originalPath.slice(normalized.length) || '/';
683
+ try {
684
+ await router.handle(ctx, (error) => {
685
+ ctx.path = originalPath;
686
+ return next(error);
687
+ });
688
+ } finally {
689
+ ctx.path = originalPath;
690
+ }
691
+ return undefined;
692
+ };
693
+ }
694
+
695
+ }
696
+
697
+ /**
698
+ * Get regular expression flags based on options
699
+ *
700
+ * @param {Object} options - Router options
701
+ * @param {boolean} options.sensitive - Case sensitivity flag
702
+ * @returns {string} Regular expression flags
703
+ *
704
+ * @private
705
+ * @since 1.0.0
706
+ */
707
+
758
708
  module.exports = Router;