@oxog/spark 1.1.1 → 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 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -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 +703 -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 +536 -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,959 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * @fileoverview Core Application class for the Spark Web Framework
5
- * @author Spark Framework Team
6
- * @since 1.0.0
7
- * @version 1.0.0
8
- */
9
-
10
- const http = require('http');
11
- const https = require('https');
12
- const cluster = require('cluster');
13
- const os = require('os');
14
- const EventEmitter = require('events');
15
- const { URL } = require('url');
16
-
17
- const Context = require('./context');
18
- const Router = require('../router/router');
19
- const { createMiddleware } = require('./middleware');
20
- const { errorHandler } = require('../utils/async-handler');
21
-
22
- /**
23
- * Core Application class that extends EventEmitter to provide a web server framework
24
- *
25
- * The Application class is the foundation of the Spark framework, providing HTTP/HTTPS server
26
- * capabilities, middleware support, routing, error handling, and graceful shutdown mechanisms.
27
- * It supports both single-process and cluster modes for high-performance applications.
28
- *
29
- * @class Application
30
- * @extends EventEmitter
31
- * @since 1.0.0
32
- *
33
- * @fires Application#error - Emitted when an application error occurs
34
- * @fires Application#listening - Emitted when the server starts listening
35
- * @fires Application#close - Emitted when the server closes
36
- * @fires Application#uncaughtException - Emitted when an uncaught exception occurs
37
- * @fires Application#unhandledRejection - Emitted when an unhandled promise rejection occurs
38
- *
39
- * @example
40
- * // Basic HTTP server
41
- * const app = new Application({ port: 3000 });
42
- *
43
- * app.use((ctx, next) => {
44
- * // Console.log removed for production
45
- * return next();
46
- * });
47
- *
48
- * app.get('/', (ctx) => {
49
- * ctx.json({ message: 'Hello World!' });
50
- * });
51
- *
52
- * app.listen();
53
- *
54
- * @example
55
- * // HTTPS server with security options
56
- * const fs = require('fs');
57
- * const app = new Application({
58
- * port: 443,
59
- * https: {
60
- * key: fs.readFileSync('private-key.pem'),
61
- * cert: fs.readFileSync('certificate.pem')
62
- * },
63
- * security: {
64
- * cors: { origin: 'https://example.com' },
65
- * rateLimit: { max: 100, window: 60000 }
66
- * }
67
- * });
68
- *
69
- * app.listen();
70
- *
71
- * @example
72
- * // Cluster mode for multi-core systems
73
- * const app = new Application({
74
- * port: 8080,
75
- * cluster: true
76
- * });
77
- *
78
- * app.listen();
79
- */
80
- class Application extends EventEmitter {
81
- /**
82
- * Create a new Application instance
83
- *
84
- * @param {Object} [options={}] - Configuration options for the application
85
- * @param {number} [options.port=3000] - Port number to listen on (also reads from PORT env var)
86
- * @param {string} [options.host='127.0.0.1'] - Host address to bind to (also reads from HOST env var)
87
- * @param {boolean} [options.cluster=false] - Enable cluster mode for multi-core systems
88
- * @param {boolean} [options.compression=true] - Enable response compression
89
- * @param {Object} [options.https] - HTTPS configuration with key and cert properties
90
- * @param {Object} [options.security] - Security configuration options
91
- * @param {Object} [options.security.cors] - CORS configuration
92
- * @param {Object} [options.security.rateLimit] - Rate limiting configuration
93
- * @param {boolean} [options.security.csrf=true] - Enable CSRF protection
94
- * @param {boolean} [options.security.helmet=true] - Enable security headers
95
- * @param {boolean} [options.exitOnUncaughtException=true] - Exit process on uncaught exceptions
96
- * @param {boolean} [options.exitOnUnhandledRejection=false] - Exit process on unhandled rejections
97
- *
98
- * @since 1.0.0
99
- *
100
- * @example
101
- * // Basic configuration
102
- * const app = new Application({
103
- * port: 8080,
104
- * host: '0.0.0.0'
105
- * });
106
- *
107
- * @example
108
- * // With security options
109
- * const app = new Application({
110
- * port: 443,
111
- * security: {
112
- * cors: { origin: ['https://example.com'] },
113
- * rateLimit: { max: 200, window: 60000 },
114
- * csrf: true
115
- * }
116
- * });
117
- */
118
- constructor(options = {}) {
119
- super();
120
-
121
- // Set max event listeners to prevent warning
122
- this.setMaxListeners(50);
123
-
124
- this.options = {
125
- port: process.env.PORT || 3000,
126
- host: process.env.HOST || '127.0.0.1', // Secure default: localhost only
127
- cluster: false,
128
- compression: true,
129
- security: {
130
- cors: {
131
- origin: false, // Secure default: CORS disabled
132
- credentials: true,
133
- maxAge: 86400
134
- },
135
- rateLimit: { max: 100, window: 60000 }, // More restrictive default
136
- csrf: true, // Secure default: CSRF protection enabled
137
- helmet: true, // Enable security headers by default
138
- contentSecurityPolicy: true,
139
- hsts: {
140
- maxAge: 31536000,
141
- includeSubDomains: true,
142
- preload: true
143
- }
144
- },
145
- ...options
146
- };
147
-
148
- /**
149
- * Array of middleware functions
150
- * @type {Function[]}
151
- * @private
152
- */
153
- this.middlewares = [];
154
-
155
- /**
156
- * Router instance for handling routes
157
- * @type {Router}
158
- * @private
159
- */
160
- this.router = new Router();
161
-
162
- /**
163
- * HTTP/HTTPS server instance
164
- * @type {http.Server|https.Server|null}
165
- * @private
166
- */
167
- this.server = null;
168
-
169
- /**
170
- * Whether the server is currently listening
171
- * @type {boolean}
172
- * @private
173
- */
174
- this.listening = false;
175
-
176
- /**
177
- * Array of cleanup handler functions
178
- * @type {Function[]}
179
- * @private
180
- */
181
- this.cleanupHandlers = [];
182
-
183
- /**
184
- * Middleware factory instance
185
- * @type {Object}
186
- * @private
187
- */
188
- this.middleware = createMiddleware(this);
189
-
190
- this.setupErrorHandling();
191
- this.setupShutdownHandlers();
192
- }
193
-
194
- /**
195
- * Set up error handling for the application
196
- *
197
- * Configures event listeners for application errors, uncaught exceptions,
198
- * and unhandled promise rejections. Provides graceful error handling
199
- * and optional automatic shutdown on critical errors.
200
- *
201
- * @private
202
- * @since 1.0.0
203
- */
204
- setupErrorHandling() {
205
- this.on('error', (error) => {
206
- console.error('Application error:', error);
207
- });
208
-
209
- // Handle uncaught exceptions with recovery option
210
- process.on('uncaughtException', (error) => {
211
- console.error('Uncaught Exception:', error);
212
-
213
- // Emit error event for application-level handling
214
- this.emit('uncaughtException', error);
215
-
216
- // Only shutdown if explicitly configured or error is critical
217
- if (this.options.exitOnUncaughtException !== false) {
218
- console.error('Shutting down due to uncaught exception...');
219
- this.gracefulShutdown();
220
- } else {
221
- console.error('Continuing after uncaught exception (not recommended for production)');
222
- }
223
- });
224
-
225
- process.on('unhandledRejection', (reason, promise) => {
226
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
227
-
228
- // Emit error event for application-level handling
229
- this.emit('unhandledRejection', reason, promise);
230
-
231
- // Only shutdown if explicitly configured
232
- if (this.options.exitOnUnhandledRejection === true) {
233
- console.error('Shutting down due to unhandled rejection...');
234
- this.gracefulShutdown();
235
- }
236
- });
237
- }
238
-
239
- /**
240
- * Set up graceful shutdown handlers for process signals
241
- *
242
- * Configures signal handlers for SIGTERM, SIGINT, and SIGBREAK (Windows)
243
- * to enable graceful shutdown of the application when receiving termination signals.
244
- *
245
- * @private
246
- * @since 1.0.0
247
- */
248
- setupShutdownHandlers() {
249
- // Graceful shutdown on SIGTERM and SIGINT
250
- const shutdownHandler = (signal) => {
251
- // Console.log removed for production
252
- this.gracefulShutdown();
253
- };
254
-
255
- process.once('SIGTERM', () => shutdownHandler('SIGTERM'));
256
- process.once('SIGINT', () => shutdownHandler('SIGINT'));
257
-
258
- // Windows-specific shutdown handling
259
- if (process.platform === 'win32') {
260
- process.once('SIGBREAK', () => shutdownHandler('SIGBREAK'));
261
- }
262
- }
263
-
264
- /**
265
- * Add middleware to the application
266
- *
267
- * Middleware functions are executed in the order they are added. Each middleware
268
- * function receives the context object and a next function to continue to the next middleware.
269
- *
270
- * @param {string|Function|Router} pathOrMiddleware - Path prefix, middleware function, or router instance
271
- * @param {Function} [middleware] - Middleware function when first parameter is a path
272
- * @returns {Application} The application instance for method chaining
273
- *
274
- * @since 1.0.0
275
- *
276
- * @example
277
- * // Global middleware
278
- * app.use((ctx, next) => {
279
- * // Console.log removed for production
280
- * return next();
281
- * });
282
- *
283
- * @example
284
- * // Path-specific middleware
285
- * app.use('/api', (ctx, next) => {
286
- * ctx.set('X-API-Version', '1.0');
287
- * return next();
288
- * });
289
- *
290
- * @example
291
- * // Router middleware
292
- * const router = new Router();
293
- * router.get('/users', (ctx) => ctx.json({ users: [] }));
294
- * app.use('/api', router);
295
- */
296
- use(pathOrMiddleware, middleware) {
297
- if (typeof pathOrMiddleware === 'function') {
298
- this.middlewares.push(pathOrMiddleware);
299
-
300
- // Register cleanup handler if middleware has one
301
- if (pathOrMiddleware.cleanup) {
302
- this.cleanupHandlers.push(pathOrMiddleware.cleanup);
303
- }
304
- } else if (typeof middleware === 'function') {
305
- const wrappedMiddleware = async (ctx, next) => {
306
- if (ctx.path.startsWith(pathOrMiddleware)) {
307
- // Store the original path and prefix
308
- const originalPath = ctx.path;
309
- const strippedPath = ctx.path.slice(pathOrMiddleware.length) || '/';
310
-
311
- // Set the path for the middleware
312
- ctx.path = strippedPath;
313
- ctx.mountpath = pathOrMiddleware;
314
-
315
- try {
316
- await middleware(ctx, next);
317
- } finally {
318
- // Restore the original state
319
- ctx.path = originalPath;
320
- delete ctx.mountpath;
321
- }
322
- } else {
323
- await next();
324
- }
325
- };
326
- this.middlewares.push(wrappedMiddleware);
327
-
328
- // Register cleanup handler if middleware has one
329
- if (middleware.cleanup) {
330
- this.cleanupHandlers.push(middleware.cleanup);
331
- }
332
- } else if (typeof pathOrMiddleware === 'string' && middleware && typeof middleware === 'object' && middleware.handle) {
333
- // This is a router being mounted with a path prefix
334
- const mountPath = pathOrMiddleware;
335
- const router = middleware;
336
- this.middlewares.push((ctx, next) => {
337
- if (ctx.path.startsWith(mountPath)) {
338
- // Temporarily modify the path for the router
339
- const originalPath = ctx.path;
340
- ctx.path = ctx.path.slice(mountPath.length) || '/';
341
-
342
- return router.handle(ctx, next).finally(() => {
343
- // Restore original path
344
- ctx.path = originalPath;
345
- });
346
- }
347
- return next();
348
- });
349
- } else if (pathOrMiddleware && typeof pathOrMiddleware === 'object' && pathOrMiddleware.handle) {
350
- // This is a router being mounted without path prefix
351
- const router = pathOrMiddleware;
352
- this.middlewares.push((ctx, next) => {
353
- return router.handle(ctx, next);
354
- });
355
- }
356
- return this;
357
- }
358
-
359
- /**
360
- * Register a GET route handler
361
- *
362
- * @param {string} path - Route path pattern
363
- * @param {...Function} handlers - One or more handler functions
364
- * @returns {Application} The application instance for method chaining
365
- *
366
- * @since 1.0.0
367
- *
368
- * @example
369
- * app.get('/', (ctx) => {
370
- * ctx.json({ message: 'Hello World!' });
371
- * });
372
- *
373
- * @example
374
- * // With middleware
375
- * app.get('/protected', authenticate, (ctx) => {
376
- * ctx.json({ user: ctx.user });
377
- * });
378
- */
379
- get(path, ...handlers) {
380
- this.router.get(path, ...handlers);
381
- return this;
382
- }
383
-
384
- /**
385
- * Register a POST route handler
386
- *
387
- * @param {string} path - Route path pattern
388
- * @param {...Function} handlers - One or more handler functions
389
- * @returns {Application} The application instance for method chaining
390
- *
391
- * @since 1.0.0
392
- *
393
- * @example
394
- * app.post('/users', (ctx) => {
395
- * const userData = ctx.body;
396
- * ctx.json({ id: 123, ...userData });
397
- * });
398
- */
399
- post(path, ...handlers) {
400
- this.router.post(path, ...handlers);
401
- return this;
402
- }
403
-
404
- /**
405
- * Register a PUT route handler
406
- *
407
- * @param {string} path - Route path pattern
408
- * @param {...Function} handlers - One or more handler functions
409
- * @returns {Application} The application instance for method chaining
410
- *
411
- * @since 1.0.0
412
- *
413
- * @example
414
- * app.put('/users/:id', (ctx) => {
415
- * const id = ctx.params.id;
416
- * const userData = ctx.body;
417
- * ctx.json({ id, ...userData });
418
- * });
419
- */
420
- put(path, ...handlers) {
421
- this.router.put(path, ...handlers);
422
- return this;
423
- }
424
-
425
- /**
426
- * Register a DELETE route handler
427
- *
428
- * @param {string} path - Route path pattern
429
- * @param {...Function} handlers - One or more handler functions
430
- * @returns {Application} The application instance for method chaining
431
- *
432
- * @since 1.0.0
433
- *
434
- * @example
435
- * app.delete('/users/:id', (ctx) => {
436
- * const id = ctx.params.id;
437
- * // Delete user logic here
438
- * ctx.status(204).end();
439
- * });
440
- */
441
- delete(path, ...handlers) {
442
- this.router.delete(path, ...handlers);
443
- return this;
444
- }
445
-
446
- /**
447
- * Register a PATCH route handler
448
- *
449
- * @param {string} path - Route path pattern
450
- * @param {...Function} handlers - One or more handler functions
451
- * @returns {Application} The application instance for method chaining
452
- *
453
- * @since 1.0.0
454
- *
455
- * @example
456
- * app.patch('/users/:id', (ctx) => {
457
- * const id = ctx.params.id;
458
- * const updates = ctx.body;
459
- * ctx.json({ id, ...updates });
460
- * });
461
- */
462
- patch(path, ...handlers) {
463
- this.router.patch(path, ...handlers);
464
- return this;
465
- }
466
-
467
- /**
468
- * Register a HEAD route handler
469
- *
470
- * @param {string} path - Route path pattern
471
- * @param {...Function} handlers - One or more handler functions
472
- * @returns {Application} The application instance for method chaining
473
- *
474
- * @since 1.0.0
475
- *
476
- * @example
477
- * app.head('/users/:id', (ctx) => {
478
- * // Check if user exists
479
- * ctx.status(200).end();
480
- * });
481
- */
482
- head(path, ...handlers) {
483
- this.router.head(path, ...handlers);
484
- return this;
485
- }
486
-
487
- /**
488
- * Register an OPTIONS route handler
489
- *
490
- * @param {string} path - Route path pattern
491
- * @param {...Function} handlers - One or more handler functions
492
- * @returns {Application} The application instance for method chaining
493
- *
494
- * @since 1.0.0
495
- *
496
- * @example
497
- * app.options('/api/*', (ctx) => {
498
- * ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
499
- * ctx.status(200).end();
500
- * });
501
- */
502
- options(path, ...handlers) {
503
- this.router.options(path, ...handlers);
504
- return this;
505
- }
506
-
507
- /**
508
- * Register a route handler for all HTTP methods
509
- *
510
- * @param {string} path - Route path pattern
511
- * @param {...Function} handlers - One or more handler functions
512
- * @returns {Application} The application instance for method chaining
513
- *
514
- * @since 1.0.0
515
- *
516
- * @example
517
- * app.all('/api/*', (ctx, next) => {
518
- * ctx.set('X-API-Version', '1.0');
519
- * return next();
520
- * });
521
- */
522
- all(path, ...handlers) {
523
- this.router.all(path, ...handlers);
524
- return this;
525
- }
526
-
527
- /**
528
- * Handle an incoming HTTP request
529
- *
530
- * Creates a new context object and executes the middleware chain.
531
- * Catches and handles any errors that occur during request processing.
532
- *
533
- * @param {http.IncomingMessage} req - The HTTP request object
534
- * @param {http.ServerResponse} res - The HTTP response object
535
- * @returns {Promise<void>}
536
- *
537
- * @private
538
- * @since 1.0.0
539
- */
540
- async handleRequest(req, res) {
541
- const ctx = new Context(req, res, this);
542
-
543
- try {
544
- await this.executeMiddleware(ctx);
545
- } catch (error) {
546
- await this.handleError(error, ctx);
547
- }
548
- }
549
-
550
- /**
551
- * Execute the middleware chain for a request
552
- *
553
- * Runs all registered middleware functions in order, followed by the router.
554
- * If no middleware handles the request, returns a 404 Not Found response.
555
- *
556
- * @param {Context} ctx - The request context object
557
- * @returns {Promise<void>}
558
- *
559
- * @private
560
- * @since 1.0.0
561
- */
562
- async executeMiddleware(ctx) {
563
- const middlewares = [...this.middlewares];
564
-
565
- middlewares.push((ctx, next) => {
566
- return this.router.handle(ctx, next);
567
- });
568
-
569
- let index = 0;
570
-
571
- const next = async (error) => {
572
- // If an error is passed, handle it
573
- if (error) {
574
- await this.handleError(error, ctx);
575
- return;
576
- }
577
-
578
- if (index >= middlewares.length) {
579
- if (!ctx.responded) {
580
- ctx.status(404).json({ error: 'Not Found' });
581
- }
582
- return;
583
- }
584
-
585
- const middleware = middlewares[index++];
586
- await middleware(ctx, next);
587
- };
588
-
589
- await next();
590
- }
591
-
592
- /**
593
- * Handle errors that occur during request processing
594
- *
595
- * Emits an 'error' event and sends an appropriate error response to the client.
596
- * In development mode, includes the error message in the response.
597
- *
598
- * @param {Error} error - The error that occurred
599
- * @param {Context} ctx - The request context object
600
- * @returns {Promise<void>}
601
- *
602
- * @private
603
- * @since 1.0.0
604
- */
605
- async handleError(error, ctx) {
606
- // Only emit error event if not in test mode
607
- if (!process.env.TEST_MODE) {
608
- this.emit('error', error, ctx);
609
- }
610
-
611
- if (!ctx.responded) {
612
- try {
613
- // Get status code from error or default to 500
614
- const statusCode = error.status || error.statusCode || 500;
615
-
616
- // Prepare error response
617
- const errorResponse = {
618
- error: error.message || 'Internal Server Error',
619
- status: statusCode
620
- };
621
-
622
- // Add additional error properties if they exist
623
- if (error.code) {
624
- errorResponse.code = error.code;
625
- }
626
-
627
- if (error.details) {
628
- errorResponse.details = error.details;
629
- }
630
-
631
- // Add stack trace in development
632
- if (process.env.NODE_ENV === 'development') {
633
- errorResponse.stack = error.stack;
634
- }
635
-
636
- ctx.status(statusCode).json(errorResponse);
637
- } catch (responseError) {
638
- console.error('Error sending error response:', responseError);
639
- }
640
- }
641
- }
642
-
643
- /**
644
- * Create an HTTP or HTTPS server instance
645
- *
646
- * Creates either an HTTP or HTTPS server based on the configuration.
647
- * Sets up error handling for server and client errors.
648
- *
649
- * @returns {http.Server|https.Server} The created server instance
650
- *
651
- * @private
652
- * @since 1.0.0
653
- */
654
- createServer() {
655
- if (this.options.https) {
656
- this.server = https.createServer(this.options.https, (req, res) => {
657
- this.handleRequest(req, res);
658
- });
659
- } else {
660
- this.server = http.createServer((req, res) => {
661
- this.handleRequest(req, res);
662
- });
663
- }
664
-
665
- this.server.on('error', (error) => {
666
- this.emit('error', error);
667
- });
668
-
669
- this.server.on('clientError', (error, socket) => {
670
- if (error.code === 'ECONNRESET' || !socket.writable) {
671
- return;
672
- }
673
- socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
674
- });
675
-
676
- return this.server;
677
- }
678
-
679
- /**
680
- * Start listening for incoming requests
681
- *
682
- * Starts the server in either cluster mode (if configured) or single-process mode.
683
- * Supports various parameter combinations for flexibility.
684
- *
685
- * @param {number|Function} [port] - Port number or callback function
686
- * @param {string|Function} [host] - Host address or callback function
687
- * @param {Function} [callback] - Callback function called when server starts listening
688
- * @returns {Application} The application instance for method chaining
689
- *
690
- * @since 1.0.0
691
- *
692
- * @example
693
- * // Use default port and host
694
- * app.listen();
695
- *
696
- * @example
697
- * // Specify port
698
- * app.listen(8080);
699
- *
700
- * @example
701
- * // Specify port and host
702
- * app.listen(8080, '0.0.0.0');
703
- *
704
- * @example
705
- * // With callback
706
- * app.listen(3000, () => {
707
- * // Console.log removed for production
708
- * });
709
- */
710
- listen(port, host, callback) {
711
- if (typeof port === 'function') {
712
- callback = port;
713
- port = this.options.port;
714
- host = this.options.host;
715
- } else if (typeof host === 'function') {
716
- callback = host;
717
- host = this.options.host;
718
- }
719
-
720
- port = port !== undefined ? port : this.options.port;
721
- host = host || this.options.host;
722
-
723
- if (this.options.cluster && cluster.isMaster) {
724
- return this.startCluster(port, host, callback);
725
- }
726
-
727
- return this.startServer(port, host, callback);
728
- }
729
-
730
- /**
731
- * Start the application in cluster mode
732
- *
733
- * Creates worker processes equal to the number of CPU cores.
734
- * Automatically restarts workers if they die.
735
- *
736
- * @param {number} port - Port number to listen on
737
- * @param {string} host - Host address to bind to
738
- * @param {Function} [callback] - Callback function called when cluster starts
739
- * @returns {Application} The application instance for method chaining
740
- *
741
- * @private
742
- * @since 1.0.0
743
- */
744
- startCluster(port, host, callback) {
745
- const numCPUs = os.cpus().length;
746
-
747
- // Console.log removed for production
748
-
749
- for (let i = 0; i < numCPUs; i++) {
750
- cluster.fork();
751
- }
752
-
753
- cluster.on('exit', (worker, code, signal) => {
754
- // Console.log removed for production
755
- cluster.fork();
756
- });
757
-
758
- if (callback) {
759
- callback();
760
- }
761
-
762
- return this;
763
- }
764
-
765
- /**
766
- * Start the server in single-process mode
767
- *
768
- * Creates the server and starts listening on the specified port and host.
769
- * Emits a 'listening' event when the server is ready.
770
- *
771
- * @param {number} port - Port number to listen on
772
- * @param {string} host - Host address to bind to
773
- * @param {Function} [callback] - Callback function called when server starts listening
774
- * @returns {Application} The application instance for method chaining
775
- *
776
- * @throws {Error} Throws an error if the server is already listening
777
- *
778
- * @private
779
- * @since 1.0.0
780
- */
781
- startServer(port, host, callback) {
782
- if (this.listening) {
783
- throw new Error('Server is already listening');
784
- }
785
-
786
- this.createServer();
787
-
788
- this.server.listen(port, host, () => {
789
- this.listening = true;
790
- const address = this.server.address();
791
- // Console.log removed for production
792
-
793
- if (callback) {
794
- callback();
795
- }
796
-
797
- this.emit('listening');
798
- });
799
-
800
- return this;
801
- }
802
-
803
- /**
804
- * Close the server and clean up resources
805
- *
806
- * Runs all registered cleanup handlers and gracefully closes the server.
807
- * Forces connection termination after a timeout to prevent hanging.
808
- *
809
- * @returns {Promise<void>} Promise that resolves when the server is closed
810
- *
811
- * @since 1.0.0
812
- *
813
- * @example
814
- * // Graceful shutdown
815
- * await app.close();
816
- * // Console.log removed for production
817
- */
818
- async close() {
819
- if (!this.server) {
820
- return;
821
- }
822
-
823
- // Run all cleanup handlers
824
- await this.runCleanupHandlers();
825
-
826
- return new Promise((resolve, reject) => {
827
- // Set a timeout for server close
828
- const closeTimeout = setTimeout(() => {
829
- console.error('Server close timeout, forcing shutdown...');
830
- resolve();
831
- }, 30000); // 30 seconds timeout
832
-
833
- this.server.close((error) => {
834
- clearTimeout(closeTimeout);
835
-
836
- if (error) {
837
- reject(error);
838
- } else {
839
- this.listening = false;
840
- this.emit('close');
841
- resolve();
842
- }
843
- });
844
-
845
- // Force close all connections after 10 seconds
846
- setTimeout(() => {
847
- if (this.server && this.server.listening) {
848
- // Console.log removed for production
849
- this.server.unref();
850
- }
851
- }, 10000);
852
- });
853
- }
854
-
855
- /**
856
- * Run all registered cleanup handlers
857
- *
858
- * Executes cleanup functions registered by middleware in the order they were added.
859
- * Errors in cleanup handlers are logged but do not prevent other handlers from running.
860
- *
861
- * @returns {Promise<void>}
862
- *
863
- * @private
864
- * @since 1.0.0
865
- */
866
- async runCleanupHandlers() {
867
- // Console.log removed for production
868
-
869
- for (const handler of this.cleanupHandlers) {
870
- try {
871
- await handler();
872
- } catch (error) {
873
- console.error('Error in cleanup handler:', error);
874
- }
875
- }
876
-
877
- // Clear the handlers array
878
- this.cleanupHandlers = [];
879
- }
880
-
881
- /**
882
- * Perform a graceful shutdown of the application
883
- *
884
- * Stops accepting new connections, waits for existing requests to complete,
885
- * runs cleanup handlers, and exits the process. Prevents multiple shutdown attempts.
886
- *
887
- * @returns {Promise<void>}
888
- *
889
- * @since 1.0.0
890
- *
891
- * @example
892
- * // Trigger graceful shutdown
893
- * process.on('SIGTERM', () => {
894
- * app.gracefulShutdown();
895
- * });
896
- */
897
- async gracefulShutdown() {
898
- // Console.log removed for production
899
-
900
- // Prevent multiple shutdown attempts
901
- if (this.shuttingDown) {
902
- // Console.log removed for production
903
- return;
904
- }
905
- this.shuttingDown = true;
906
-
907
- try {
908
- // Stop accepting new connections immediately
909
- if (this.server && this.server.listening) {
910
- this.server.close();
911
- }
912
-
913
- // Give ongoing requests time to complete
914
- await Promise.race([
915
- this.close(),
916
- new Promise(resolve => setTimeout(resolve, 30000)) // 30 seconds max
917
- ]);
918
-
919
- // Console.log removed for production
920
- process.exit(0);
921
- } catch (error) {
922
- console.error('Error during shutdown:', error);
923
- process.exit(1);
924
- }
925
- }
926
-
927
- /**
928
- * Register a cleanup handler for application shutdown
929
- *
930
- * Cleanup handlers are called during graceful shutdown to clean up resources
931
- * like database connections, file handles, or external service connections.
932
- *
933
- * @param {Function} handler - Async function to call during shutdown
934
- * @returns {Application} The application instance for method chaining
935
- *
936
- * @since 1.0.0
937
- *
938
- * @example
939
- * // Register database cleanup
940
- * app.onShutdown(async () => {
941
- * await database.close();
942
- * // Console.log removed for production
943
- * });
944
- *
945
- * @example
946
- * // Register multiple cleanup handlers
947
- * app.onShutdown(() => cache.disconnect())
948
- * .onShutdown(() => logger.flush());
949
- */
950
- onShutdown(handler) {
951
- if (typeof handler === 'function') {
952
- this.cleanupHandlers.push(handler);
953
- }
954
- return this;
955
- }
956
-
957
- }
958
-
959
- module.exports = Application;