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