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