@catbee/utils 0.0.8-next.0 → 0.0.8-rc.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 (284) hide show
  1. package/README.md +1 -26
  2. package/build/esm/config.d.ts +122 -0
  3. package/build/esm/config.js +133 -0
  4. package/build/esm/config.js.map +1 -0
  5. package/build/esm/index.d.ts +27 -0
  6. package/build/esm/index.js +50 -0
  7. package/build/esm/index.js.map +1 -0
  8. package/build/esm/servers/server.builder.d.ts +508 -0
  9. package/build/esm/servers/server.builder.js +702 -0
  10. package/build/esm/servers/server.builder.js.map +1 -0
  11. package/build/esm/servers/server.d.ts +256 -0
  12. package/build/esm/servers/server.js +1248 -0
  13. package/build/esm/servers/server.js.map +1 -0
  14. package/build/esm/types/api-response.d.ts +152 -0
  15. package/build/esm/types/api-response.js +34 -0
  16. package/build/esm/types/api-response.js.map +1 -0
  17. package/build/esm/types/index.d.ts +125 -0
  18. package/build/esm/types/index.js +25 -0
  19. package/build/esm/types/index.js.map +1 -0
  20. package/build/esm/types/server.d.ts +268 -0
  21. package/build/esm/types/server.js +25 -0
  22. package/build/esm/types/server.js.map +1 -0
  23. package/build/esm/utils/array.utils.d.ts +168 -0
  24. package/build/esm/utils/array.utils.js +382 -0
  25. package/build/esm/utils/array.utils.js.map +1 -0
  26. package/build/esm/utils/async.utils.d.ts +265 -0
  27. package/build/esm/utils/async.utils.js +896 -0
  28. package/build/esm/utils/async.utils.js.map +1 -0
  29. package/build/esm/utils/cache.utils.d.ts +153 -0
  30. package/build/esm/utils/cache.utils.js +499 -0
  31. package/build/esm/utils/cache.utils.js.map +1 -0
  32. package/build/esm/utils/context-store.utils.d.ts +189 -0
  33. package/build/esm/utils/context-store.utils.js +307 -0
  34. package/build/esm/utils/context-store.utils.js.map +1 -0
  35. package/build/esm/utils/crypto.utils.d.ts +160 -0
  36. package/build/esm/utils/crypto.utils.js +375 -0
  37. package/build/esm/utils/crypto.utils.js.map +1 -0
  38. package/build/esm/utils/date.utils.d.ts +159 -0
  39. package/build/esm/utils/date.utils.js +389 -0
  40. package/build/esm/utils/date.utils.js.map +1 -0
  41. package/build/esm/utils/decorators.utils.d.ts +315 -0
  42. package/build/esm/utils/decorators.utils.js +666 -0
  43. package/build/esm/utils/decorators.utils.js.map +1 -0
  44. package/build/esm/utils/dir.utils.d.ts +196 -0
  45. package/build/esm/utils/dir.utils.js +998 -0
  46. package/build/esm/utils/dir.utils.js.map +1 -0
  47. package/build/esm/utils/env.utils.d.ts +377 -0
  48. package/build/esm/utils/env.utils.js +873 -0
  49. package/build/esm/utils/env.utils.js.map +1 -0
  50. package/build/esm/utils/exception.utils.d.ts +230 -0
  51. package/build/esm/utils/exception.utils.js +559 -0
  52. package/build/esm/utils/exception.utils.js.map +1 -0
  53. package/build/esm/utils/fs.utils.d.ts +164 -0
  54. package/build/esm/utils/fs.utils.js +580 -0
  55. package/build/esm/utils/fs.utils.js.map +1 -0
  56. package/build/esm/utils/http-status-codes.d.ts +266 -0
  57. package/build/esm/utils/http-status-codes.js +295 -0
  58. package/build/esm/utils/http-status-codes.js.map +1 -0
  59. package/build/esm/utils/id.utils.d.ts +36 -0
  60. package/build/esm/utils/id.utils.js +87 -0
  61. package/build/esm/utils/id.utils.js.map +1 -0
  62. package/build/esm/utils/logger.utils.d.ts +160 -0
  63. package/build/esm/utils/logger.utils.js +341 -0
  64. package/build/esm/utils/logger.utils.js.map +1 -0
  65. package/build/esm/utils/middleware.utils.d.ts +100 -0
  66. package/build/esm/utils/middleware.utils.js +325 -0
  67. package/build/esm/utils/middleware.utils.js.map +1 -0
  68. package/build/esm/utils/obj.utils.d.ts +124 -0
  69. package/build/esm/utils/obj.utils.js +519 -0
  70. package/build/esm/utils/obj.utils.js.map +1 -0
  71. package/build/esm/utils/performance.utils.d.ts +136 -0
  72. package/build/esm/utils/performance.utils.js +376 -0
  73. package/build/esm/utils/performance.utils.js.map +1 -0
  74. package/build/esm/utils/request.utils.d.ts +86 -0
  75. package/build/esm/utils/request.utils.js +223 -0
  76. package/build/esm/utils/request.utils.js.map +1 -0
  77. package/build/esm/utils/response.utils.d.ts +163 -0
  78. package/build/esm/utils/response.utils.js +284 -0
  79. package/build/esm/utils/response.utils.js.map +1 -0
  80. package/build/esm/utils/stream.utils.d.ts +88 -0
  81. package/build/esm/utils/stream.utils.js +284 -0
  82. package/build/esm/utils/stream.utils.js.map +1 -0
  83. package/build/esm/utils/string.utils.d.ts +93 -0
  84. package/build/esm/utils/string.utils.js +169 -0
  85. package/build/esm/utils/string.utils.js.map +1 -0
  86. package/build/esm/utils/type.utils.d.ts +90 -0
  87. package/build/esm/utils/type.utils.js +190 -0
  88. package/build/esm/utils/type.utils.js.map +1 -0
  89. package/build/esm/utils/url.utils.d.ts +141 -0
  90. package/build/esm/utils/url.utils.js +381 -0
  91. package/build/esm/utils/url.utils.js.map +1 -0
  92. package/build/esm/utils/validate.utils.d.ts +177 -0
  93. package/build/esm/utils/validate.utils.js +336 -0
  94. package/build/esm/utils/validate.utils.js.map +1 -0
  95. package/build/esnext/config.d.ts +122 -0
  96. package/build/esnext/config.js +133 -0
  97. package/build/esnext/config.js.map +1 -0
  98. package/build/esnext/index.d.ts +27 -0
  99. package/build/esnext/index.js +50 -0
  100. package/build/esnext/index.js.map +1 -0
  101. package/build/esnext/servers/server.builder.d.ts +508 -0
  102. package/build/esnext/servers/server.builder.js +657 -0
  103. package/build/esnext/servers/server.builder.js.map +1 -0
  104. package/build/esnext/servers/server.d.ts +256 -0
  105. package/build/esnext/servers/server.js +955 -0
  106. package/build/esnext/servers/server.js.map +1 -0
  107. package/build/esnext/types/api-response.d.ts +152 -0
  108. package/build/esnext/types/api-response.js +34 -0
  109. package/build/esnext/types/api-response.js.map +1 -0
  110. package/build/esnext/types/index.d.ts +125 -0
  111. package/build/esnext/types/index.js +25 -0
  112. package/build/esnext/types/index.js.map +1 -0
  113. package/build/esnext/types/server.d.ts +268 -0
  114. package/build/esnext/types/server.js +25 -0
  115. package/build/esnext/types/server.js.map +1 -0
  116. package/build/esnext/utils/array.utils.d.ts +168 -0
  117. package/build/esnext/utils/array.utils.js +345 -0
  118. package/build/esnext/utils/array.utils.js.map +1 -0
  119. package/build/esnext/utils/async.utils.d.ts +265 -0
  120. package/build/esnext/utils/async.utils.js +620 -0
  121. package/build/esnext/utils/async.utils.js.map +1 -0
  122. package/build/esnext/utils/cache.utils.d.ts +153 -0
  123. package/build/esnext/utils/cache.utils.js +293 -0
  124. package/build/esnext/utils/cache.utils.js.map +1 -0
  125. package/build/esnext/utils/context-store.utils.d.ts +189 -0
  126. package/build/esnext/utils/context-store.utils.js +289 -0
  127. package/build/esnext/utils/context-store.utils.js.map +1 -0
  128. package/build/esnext/utils/crypto.utils.d.ts +160 -0
  129. package/build/esnext/utils/crypto.utils.js +276 -0
  130. package/build/esnext/utils/crypto.utils.js.map +1 -0
  131. package/build/esnext/utils/date.utils.d.ts +159 -0
  132. package/build/esnext/utils/date.utils.js +384 -0
  133. package/build/esnext/utils/date.utils.js.map +1 -0
  134. package/build/esnext/utils/decorators.utils.d.ts +315 -0
  135. package/build/esnext/utils/decorators.utils.js +504 -0
  136. package/build/esnext/utils/decorators.utils.js.map +1 -0
  137. package/build/esnext/utils/dir.utils.d.ts +196 -0
  138. package/build/esnext/utils/dir.utils.js +477 -0
  139. package/build/esnext/utils/dir.utils.js.map +1 -0
  140. package/build/esnext/utils/env.utils.d.ts +377 -0
  141. package/build/esnext/utils/env.utils.js +785 -0
  142. package/build/esnext/utils/env.utils.js.map +1 -0
  143. package/build/esnext/utils/exception.utils.d.ts +230 -0
  144. package/build/esnext/utils/exception.utils.js +381 -0
  145. package/build/esnext/utils/exception.utils.js.map +1 -0
  146. package/build/esnext/utils/fs.utils.d.ts +164 -0
  147. package/build/esnext/utils/fs.utils.js +349 -0
  148. package/build/esnext/utils/fs.utils.js.map +1 -0
  149. package/build/esnext/utils/http-status-codes.d.ts +266 -0
  150. package/build/esnext/utils/http-status-codes.js +295 -0
  151. package/build/esnext/utils/http-status-codes.js.map +1 -0
  152. package/build/esnext/utils/id.utils.d.ts +36 -0
  153. package/build/esnext/utils/id.utils.js +84 -0
  154. package/build/esnext/utils/id.utils.js.map +1 -0
  155. package/build/esnext/utils/logger.utils.d.ts +160 -0
  156. package/build/esnext/utils/logger.utils.js +300 -0
  157. package/build/esnext/utils/logger.utils.js.map +1 -0
  158. package/build/esnext/utils/middleware.utils.d.ts +100 -0
  159. package/build/esnext/utils/middleware.utils.js +236 -0
  160. package/build/esnext/utils/middleware.utils.js.map +1 -0
  161. package/build/esnext/utils/obj.utils.d.ts +124 -0
  162. package/build/esnext/utils/obj.utils.js +413 -0
  163. package/build/esnext/utils/obj.utils.js.map +1 -0
  164. package/build/esnext/utils/performance.utils.d.ts +136 -0
  165. package/build/esnext/utils/performance.utils.js +271 -0
  166. package/build/esnext/utils/performance.utils.js.map +1 -0
  167. package/build/esnext/utils/request.utils.d.ts +86 -0
  168. package/build/esnext/utils/request.utils.js +186 -0
  169. package/build/esnext/utils/request.utils.js.map +1 -0
  170. package/build/esnext/utils/response.utils.d.ts +163 -0
  171. package/build/esnext/utils/response.utils.js +247 -0
  172. package/build/esnext/utils/response.utils.js.map +1 -0
  173. package/build/esnext/utils/stream.utils.d.ts +88 -0
  174. package/build/esnext/utils/stream.utils.js +210 -0
  175. package/build/esnext/utils/stream.utils.js.map +1 -0
  176. package/build/esnext/utils/string.utils.d.ts +93 -0
  177. package/build/esnext/utils/string.utils.js +165 -0
  178. package/build/esnext/utils/string.utils.js.map +1 -0
  179. package/build/esnext/utils/type.utils.d.ts +90 -0
  180. package/build/esnext/utils/type.utils.js +187 -0
  181. package/build/esnext/utils/type.utils.js.map +1 -0
  182. package/build/esnext/utils/url.utils.d.ts +141 -0
  183. package/build/esnext/utils/url.utils.js +304 -0
  184. package/build/esnext/utils/url.utils.js.map +1 -0
  185. package/build/esnext/utils/validate.utils.d.ts +177 -0
  186. package/build/esnext/utils/validate.utils.js +320 -0
  187. package/build/esnext/utils/validate.utils.js.map +1 -0
  188. package/build/src/config.d.ts +122 -0
  189. package/build/src/config.js +138 -0
  190. package/build/src/config.js.map +1 -0
  191. package/build/src/index.d.ts +27 -0
  192. package/build/src/index.js +69 -0
  193. package/build/src/index.js.map +1 -0
  194. package/build/src/servers/server.builder.d.ts +508 -0
  195. package/build/src/servers/server.builder.js +661 -0
  196. package/build/src/servers/server.builder.js.map +1 -0
  197. package/build/src/servers/server.d.ts +256 -0
  198. package/build/src/servers/server.js +962 -0
  199. package/build/src/servers/server.js.map +1 -0
  200. package/build/src/types/api-response.d.ts +152 -0
  201. package/build/src/types/api-response.js +37 -0
  202. package/build/src/types/api-response.js.map +1 -0
  203. package/build/src/types/index.d.ts +125 -0
  204. package/build/src/types/index.js +26 -0
  205. package/build/src/types/index.js.map +1 -0
  206. package/build/src/types/server.d.ts +268 -0
  207. package/build/src/types/server.js +26 -0
  208. package/build/src/types/server.js.map +1 -0
  209. package/build/src/utils/array.utils.d.ts +168 -0
  210. package/build/src/utils/array.utils.js +364 -0
  211. package/build/src/utils/array.utils.js.map +1 -0
  212. package/build/src/utils/async.utils.d.ts +265 -0
  213. package/build/src/utils/async.utils.js +641 -0
  214. package/build/src/utils/async.utils.js.map +1 -0
  215. package/build/src/utils/cache.utils.d.ts +153 -0
  216. package/build/src/utils/cache.utils.js +297 -0
  217. package/build/src/utils/cache.utils.js.map +1 -0
  218. package/build/src/utils/context-store.utils.d.ts +189 -0
  219. package/build/src/utils/context-store.utils.js +296 -0
  220. package/build/src/utils/context-store.utils.js.map +1 -0
  221. package/build/src/utils/crypto.utils.d.ts +160 -0
  222. package/build/src/utils/crypto.utils.js +293 -0
  223. package/build/src/utils/crypto.utils.js.map +1 -0
  224. package/build/src/utils/date.utils.d.ts +159 -0
  225. package/build/src/utils/date.utils.js +396 -0
  226. package/build/src/utils/date.utils.js.map +1 -0
  227. package/build/src/utils/decorators.utils.d.ts +315 -0
  228. package/build/src/utils/decorators.utils.js +516 -0
  229. package/build/src/utils/decorators.utils.js.map +1 -0
  230. package/build/src/utils/dir.utils.d.ts +196 -0
  231. package/build/src/utils/dir.utils.js +501 -0
  232. package/build/src/utils/dir.utils.js.map +1 -0
  233. package/build/src/utils/env.utils.d.ts +377 -0
  234. package/build/src/utils/env.utils.js +789 -0
  235. package/build/src/utils/env.utils.js.map +1 -0
  236. package/build/src/utils/exception.utils.d.ts +230 -0
  237. package/build/src/utils/exception.utils.js +407 -0
  238. package/build/src/utils/exception.utils.js.map +1 -0
  239. package/build/src/utils/fs.utils.d.ts +164 -0
  240. package/build/src/utils/fs.utils.js +372 -0
  241. package/build/src/utils/fs.utils.js.map +1 -0
  242. package/build/src/utils/http-status-codes.d.ts +266 -0
  243. package/build/src/utils/http-status-codes.js +298 -0
  244. package/build/src/utils/http-status-codes.js.map +1 -0
  245. package/build/src/utils/id.utils.d.ts +36 -0
  246. package/build/src/utils/id.utils.js +91 -0
  247. package/build/src/utils/id.utils.js.map +1 -0
  248. package/build/src/utils/logger.utils.d.ts +160 -0
  249. package/build/src/utils/logger.utils.js +346 -0
  250. package/build/src/utils/logger.utils.js.map +1 -0
  251. package/build/src/utils/middleware.utils.d.ts +100 -0
  252. package/build/src/utils/middleware.utils.js +244 -0
  253. package/build/src/utils/middleware.utils.js.map +1 -0
  254. package/build/src/utils/obj.utils.d.ts +124 -0
  255. package/build/src/utils/obj.utils.js +429 -0
  256. package/build/src/utils/obj.utils.js.map +1 -0
  257. package/build/src/utils/performance.utils.d.ts +136 -0
  258. package/build/src/utils/performance.utils.js +278 -0
  259. package/build/src/utils/performance.utils.js.map +1 -0
  260. package/build/src/utils/request.utils.d.ts +86 -0
  261. package/build/src/utils/request.utils.js +195 -0
  262. package/build/src/utils/request.utils.js.map +1 -0
  263. package/build/src/utils/response.utils.d.ts +163 -0
  264. package/build/src/utils/response.utils.js +260 -0
  265. package/build/src/utils/response.utils.js.map +1 -0
  266. package/build/src/utils/stream.utils.d.ts +88 -0
  267. package/build/src/utils/stream.utils.js +218 -0
  268. package/build/src/utils/stream.utils.js.map +1 -0
  269. package/build/src/utils/string.utils.d.ts +93 -0
  270. package/build/src/utils/string.utils.js +179 -0
  271. package/build/src/utils/string.utils.js.map +1 -0
  272. package/build/src/utils/type.utils.d.ts +90 -0
  273. package/build/src/utils/type.utils.js +196 -0
  274. package/build/src/utils/type.utils.js.map +1 -0
  275. package/build/src/utils/url.utils.d.ts +141 -0
  276. package/build/src/utils/url.utils.js +317 -0
  277. package/build/src/utils/url.utils.js.map +1 -0
  278. package/build/src/utils/validate.utils.d.ts +177 -0
  279. package/build/src/utils/validate.utils.js +345 -0
  280. package/build/src/utils/validate.utils.js.map +1 -0
  281. package/package.json +66 -12
  282. package/build/index.cjs +0 -6888
  283. package/build/index.d.ts +0 -5242
  284. package/build/index.mjs +0 -6615
@@ -0,0 +1,962 @@
1
+ "use strict";
2
+ /*
3
+ * The MIT License
4
+ *
5
+ * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in all
15
+ * copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ * SOFTWARE.
24
+ */
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ExpressServer = void 0;
30
+ const express_1 = __importDefault(require("express"));
31
+ const https_1 = __importDefault(require("https"));
32
+ const http_status_codes_1 = require("../utils/http-status-codes");
33
+ const response_utils_1 = require("../utils/response.utils");
34
+ const middleware_utils_1 = require("../utils/middleware.utils");
35
+ const env_utils_1 = require("../utils/env.utils");
36
+ const logger_utils_1 = require("../utils/logger.utils");
37
+ const exception_utils_1 = require("../utils/exception.utils");
38
+ const exception_utils_2 = require("../utils/exception.utils");
39
+ const fs_1 = __importDefault(require("fs"));
40
+ const config_1 = require("../config");
41
+ const obj_utils_1 = require("../utils/obj.utils");
42
+ const fs_utils_1 = require("../utils/fs.utils");
43
+ const server_builder_1 = require("./server.builder");
44
+ const validate_utils_1 = require("../utils/validate.utils");
45
+ /**
46
+ * Production-ready Express server with enterprise features.
47
+ *
48
+ * Core Features:
49
+ * - Security: Helmet, CORS, rate limiting, timeouts
50
+ * - Monitoring: Request logs, metrics, health checks
51
+ * - Performance: Compression, caching, static files
52
+ * - Reliability: Graceful shutdown, error handling
53
+ * - Developer UX: OpenAPI docs, debugging tools
54
+ * - Extensibility: Hooks, middleware, custom routes
55
+ *
56
+ * Designed for microservices and production workloads.
57
+ * Includes K8s readiness probes and zero-downtime support.
58
+ */
59
+ class ExpressServer {
60
+ /**
61
+ * Initializes server with intelligent defaults and security best practices.
62
+ * All settings can be customized via config and hooks.
63
+ *
64
+ * Default Security:
65
+ * - Secure headers (Helmet)
66
+ * - Rate limiting
67
+ * - Request timeouts
68
+ * - Body size limits
69
+ * - CORS protection
70
+ *
71
+ * Default Monitoring:
72
+ * - Request/Response logging
73
+ * - Prometheus metrics
74
+ * - Health checks
75
+ * - Request tracing
76
+ */
77
+ constructor(config, hooks = {}) {
78
+ var _a, _b, _c;
79
+ /** Prometheus client registry for metrics collection */
80
+ this.register = null;
81
+ /** HTTP server instance (null when not running) */
82
+ this.server = null;
83
+ /** Set of active WebSocket connections */
84
+ this.connections = new Set();
85
+ /** Flag indicating if the server is shutting down */
86
+ this.isShuttingDown = false;
87
+ /**
88
+ * Collection of registered health check functions.
89
+ * These are executed when the health check endpoint is accessed.
90
+ */
91
+ this.healthChecks = [];
92
+ if (ExpressServer.isBuiltServerConfig(config)) {
93
+ this.config = config;
94
+ }
95
+ else {
96
+ // Deep merge config with user overrides
97
+ this.config = (0, obj_utils_1.deepObjMerge)({}, config_1.defaultServerConfig, config);
98
+ }
99
+ if (!(0, validate_utils_1.isPort)(this.config.port)) {
100
+ (0, logger_utils_1.getLogger)().error(`Port must be a valid number between 1 and 65535, got: ${this.config.port}`);
101
+ process.exit(1);
102
+ }
103
+ // Sanitize app name for metrics (replace invalid characters with underscore)
104
+ const safeAppName = (this.config.appName || 'express_app').toLowerCase().replace(/[^a-z0-9_]/g, '_');
105
+ if ((_a = this.config.metrics) === null || _a === void 0 ? void 0 : _a.enable) {
106
+ const client = ExpressServer.optionalRequire('prom-client');
107
+ if (!client) {
108
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install prom-client' }, 'prom-client is required for metrics but not installed. Please add it to your dependencies');
109
+ process.exit(1);
110
+ }
111
+ this.register = new client.Registry();
112
+ // Initialize Prometheus metrics with sanitized names
113
+ this.requestCounter = new client.Counter({
114
+ name: `${safeAppName}_http_requests_total`,
115
+ help: 'Total HTTP requests',
116
+ labelNames: ['method', 'route', 'status'],
117
+ registers: [this.register]
118
+ });
119
+ this.routeTimings = new client.Histogram({
120
+ name: `${safeAppName}_http_request_duration_seconds`,
121
+ help: 'Duration of HTTP requests by route',
122
+ labelNames: ['method', 'route', 'status'],
123
+ buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10],
124
+ registers: [this.register]
125
+ });
126
+ this.requestSizes = new client.Histogram({
127
+ name: `${safeAppName}_http_request_size_bytes`,
128
+ help: 'Size of HTTP request bodies',
129
+ labelNames: ['method', 'route'],
130
+ buckets: [100, 1000, 10000, 100000, 1000000],
131
+ registers: [this.register]
132
+ });
133
+ this.clientIPs = new client.Counter({
134
+ name: `${safeAppName}_http_client_ip_total`,
135
+ help: 'Client IP request counter',
136
+ labelNames: ['ip', 'method'],
137
+ registers: [this.register]
138
+ });
139
+ // Default system metrics (CPU, memory, event loop lag, etc.)
140
+ client.collectDefaultMetrics({
141
+ register: this.register,
142
+ prefix: `${safeAppName}_`
143
+ });
144
+ }
145
+ // Health checks
146
+ if ((_b = config.healthCheck) === null || _b === void 0 ? void 0 : _b.checks) {
147
+ this.healthChecks.push(...config.healthCheck.checks);
148
+ }
149
+ // Set global prefix (normalize to empty string or "/prefix" without trailing slash)
150
+ this.globalPrefix = this.normalizePath((_c = this.config.globalPrefix) !== null && _c !== void 0 ? _c : '', false);
151
+ this.hooks = hooks;
152
+ this.app = (0, express_1.default)();
153
+ this.rootRouter = express_1.default.Router();
154
+ // Store initialization promise to prevent race conditions with start()
155
+ this.initPromise = this.initialize();
156
+ }
157
+ /**
158
+ * Execute a lifecycle hook safely with comprehensive error handling.
159
+ * Prevents hook failures from crashing the server while logging issues.
160
+ *
161
+ * @param hook Name of the lifecycle hook to execute
162
+ * @param args Arguments to pass to the hook function
163
+ */
164
+ async runHook(hook, ...args) {
165
+ try {
166
+ const fn = this.hooks[hook];
167
+ if (fn)
168
+ await fn.apply(null, args);
169
+ }
170
+ catch (err) {
171
+ (0, logger_utils_1.getLogger)().error({ err, hook }, `Error executing ${hook} hook:`);
172
+ }
173
+ }
174
+ /**
175
+ * Initialize the Express server with middleware and routes.
176
+ */
177
+ async initialize() {
178
+ await this.runHook('beforeInit', this);
179
+ // Set up middleware stack (order is critical)
180
+ await this.setupMiddleware();
181
+ // Set up default routes and error handling
182
+ await this.setupRoutes();
183
+ await this.runHook('afterInit', this);
184
+ }
185
+ /**
186
+ * Configure and register all middlewares in the optimal order.
187
+ *
188
+ * Middleware Order (CRITICAL - don't change without understanding implications):
189
+ * 1. Basic server configuration (trust proxy, x-powered-by)
190
+ * 2. Request ID generation (for tracing)
191
+ * 3. Request context setup (for logging correlation)
192
+ * 4. Timeout protection (prevents hanging requests)
193
+ * 5. Response time tracking (for performance monitoring)
194
+ * 6. Request logging (after ID/context setup)
195
+ * 7. Custom request hooks
196
+ * 8. Security middleware (rate limiting, CORS, Helmet)
197
+ * 9. Response compression
198
+ * 10. Static file serving
199
+ * 11. Request parsing (body parsing, cookies)
200
+ * 12. API documentation (OpenAPI)
201
+ * 13. Global headers
202
+ * 14. Custom response hooks
203
+ */
204
+ async setupMiddleware() {
205
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
206
+ if (this.config.https) {
207
+ await this.validateHttpsFiles();
208
+ }
209
+ // Basic middleware should be first
210
+ this.app.disable('x-powered-by');
211
+ if (this.config.trustProxy) {
212
+ this.app.set('trust proxy', true);
213
+ }
214
+ // Request ID generation - must be first for proper tracing
215
+ this.app.use((0, middleware_utils_1.requestId)({
216
+ headerName: (_a = this.config.requestId) === null || _a === void 0 ? void 0 : _a.headerName,
217
+ exposeHeader: (_b = this.config.requestId) === null || _b === void 0 ? void 0 : _b.exposeHeader,
218
+ generator: (_c = this.config.requestId) === null || _c === void 0 ? void 0 : _c.generator
219
+ }));
220
+ // Request context setup for logging correlation
221
+ this.app.use((0, middleware_utils_1.setupRequestContext)({
222
+ headerName: (_d = this.config.requestId) === null || _d === void 0 ? void 0 : _d.headerName,
223
+ autoLog: false
224
+ }));
225
+ // Early shutdown-awareness middleware (lets load balancers drain connections gracefully)
226
+ this.app.use((_req, res, next) => {
227
+ if (this.isShuttingDown) {
228
+ res.setHeader('Connection', 'close');
229
+ return res
230
+ .status(http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE)
231
+ .json(new exception_utils_1.ServiceUnavailableException('Server is shutting down'));
232
+ }
233
+ next();
234
+ return;
235
+ });
236
+ // Security middleware should come early
237
+ if (this.config.helmet) {
238
+ const helmet = ExpressServer.optionalRequire('helmet');
239
+ if (!helmet) {
240
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install helmet' }, 'helmet is required but not installed. Please add it to your dependencies');
241
+ process.exit(1);
242
+ }
243
+ if (typeof this.config.helmet === 'object') {
244
+ this.app.use(helmet(this.config.helmet));
245
+ }
246
+ else {
247
+ this.app.use(helmet());
248
+ }
249
+ }
250
+ // CORS middleware should be early
251
+ if (this.config.cors) {
252
+ const cors = ExpressServer.optionalRequire('cors');
253
+ if (!cors) {
254
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install cors' }, 'cors is required but not installed. Please add it to your dependencies');
255
+ process.exit(1);
256
+ }
257
+ this.app.use(cors(this.config.cors === true ? {} : this.config.cors));
258
+ }
259
+ // Global headers
260
+ this.app.use((_req, res, next) => {
261
+ var _a, _b, _c, _d;
262
+ if (this.config.globalHeaders) {
263
+ for (const key in this.config.globalHeaders) {
264
+ const value = this.config.globalHeaders[key];
265
+ res.setHeader(key, typeof value === 'function' ? value() : value);
266
+ }
267
+ }
268
+ if (this.config.isMicroservice) {
269
+ res.setHeader('X-Microservice', this.config.appName || 'express_app');
270
+ }
271
+ if ((_a = this.config.serviceVersion) === null || _a === void 0 ? void 0 : _a.enable) {
272
+ const version = typeof ((_b = this.config.serviceVersion) === null || _b === void 0 ? void 0 : _b.version) === 'function'
273
+ ? this.config.serviceVersion.version()
274
+ : (_c = this.config.serviceVersion) === null || _c === void 0 ? void 0 : _c.version;
275
+ res.setHeader(((_d = this.config.serviceVersion) === null || _d === void 0 ? void 0 : _d.headerName) || 'x-service-version', version || '0.0.0');
276
+ }
277
+ next();
278
+ });
279
+ // Global request timeout protection
280
+ if (this.config.requestTimeout) {
281
+ this.app.use((0, middleware_utils_1.timeout)(this.config.requestTimeout));
282
+ }
283
+ // Response time tracking for performance monitoring
284
+ if ((_e = this.config.responseTime) === null || _e === void 0 ? void 0 : _e.enable) {
285
+ this.app.use((0, middleware_utils_1.responseTime)({
286
+ addHeader: this.config.responseTime.addHeader,
287
+ logOnComplete: this.config.responseTime.logOnComplete
288
+ }));
289
+ }
290
+ // Rate limiting should be early to prevent unnecessary processing
291
+ if ((_f = this.config.rateLimit) === null || _f === void 0 ? void 0 : _f.enable) {
292
+ const rateLimit = ExpressServer.optionalRequire('express-rate-limit');
293
+ if (!rateLimit) {
294
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install express-rate-limit' }, 'express-rate-limit is required but not installed. Please add it to your dependencies');
295
+ process.exit(1);
296
+ }
297
+ this.app.use(rateLimit({
298
+ windowMs: (_g = this.config.rateLimit.windowMs) !== null && _g !== void 0 ? _g : 15 * 60 * 1000,
299
+ max: (_h = this.config.rateLimit.max) !== null && _h !== void 0 ? _h : 100,
300
+ handler: (req, res) => {
301
+ var _a;
302
+ const status = http_status_codes_1.HttpStatusCodes.TOO_MANY_REQUESTS;
303
+ const response = (0, response_utils_1.createFinalErrorResponse)(req, status, ((_a = this.config.rateLimit) === null || _a === void 0 ? void 0 : _a.message) || 'Too many requests');
304
+ res.status(status).json(response);
305
+ },
306
+ standardHeaders: (_j = this.config.rateLimit.standardHeaders) !== null && _j !== void 0 ? _j : true,
307
+ legacyHeaders: (_k = this.config.rateLimit.legacyHeaders) !== null && _k !== void 0 ? _k : false
308
+ }));
309
+ }
310
+ // Request logging with filtering
311
+ if ((_l = this.config.requestLogging) === null || _l === void 0 ? void 0 : _l.enable) {
312
+ this.app.use((req, res, next) => {
313
+ var _a, _b, _c, _d, _e, _f;
314
+ if (typeof ((_a = this.config.requestLogging) === null || _a === void 0 ? void 0 : _a.ignorePaths) === 'function') {
315
+ const skip = (_c = (_b = this.config.requestLogging) === null || _b === void 0 ? void 0 : _b.ignorePaths) === null || _c === void 0 ? void 0 : _c.call(_b, req, res);
316
+ if (skip)
317
+ return next();
318
+ }
319
+ else if (Array.isArray((_d = this.config.requestLogging) === null || _d === void 0 ? void 0 : _d.ignorePaths)) {
320
+ const skip = (_f = (_e = this.config.requestLogging) === null || _e === void 0 ? void 0 : _e.ignorePaths) === null || _f === void 0 ? void 0 : _f.includes(req.path);
321
+ if (skip)
322
+ return next();
323
+ }
324
+ const logger = (0, logger_utils_1.getLogger)();
325
+ const incomingRequestMetaData = {
326
+ requestId: req.id,
327
+ method: req.method,
328
+ url: req.originalUrl || req.url,
329
+ ip: req.ip
330
+ };
331
+ logger.info(incomingRequestMetaData, 'Incoming Request');
332
+ next();
333
+ });
334
+ }
335
+ // Custom request preprocessing hook
336
+ if (this.hooks.onRequest) {
337
+ this.app.use(this.hooks.onRequest);
338
+ }
339
+ // Response compression for better performance
340
+ if (this.config.compression) {
341
+ const compression = ExpressServer.optionalRequire('compression');
342
+ if (!compression) {
343
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install compression' }, 'compression is required but not installed. Please add it to your dependencies');
344
+ process.exit(1);
345
+ }
346
+ if (typeof this.config.compression === 'object') {
347
+ this.app.use(compression(this.config.compression));
348
+ }
349
+ else {
350
+ this.app.use(compression());
351
+ }
352
+ }
353
+ // Static file serving (do NOT normalize filesystem path; only normalize route)
354
+ if (this.config.staticFolders) {
355
+ this.config.staticFolders.forEach(folder => {
356
+ var _a;
357
+ this.app.use(this.normalizePath((_a = folder.path) !== null && _a !== void 0 ? _a : '/'), express_1.default.static(folder.directory, {
358
+ maxAge: folder.maxAge || 0,
359
+ etag: folder.etag !== false,
360
+ immutable: folder.immutable === true,
361
+ lastModified: folder.lastModified !== false,
362
+ cacheControl: folder.cacheControl !== false
363
+ }));
364
+ (0, logger_utils_1.getLogger)().info(`Serving static folder: ${folder.directory} at path ${folder.path || '/'}`);
365
+ });
366
+ }
367
+ // Request body parsing with size limits
368
+ if (this.config.bodyParser) {
369
+ if (this.config.bodyParser.json) {
370
+ this.app.use(express_1.default.json(this.config.bodyParser.json));
371
+ }
372
+ if (this.config.bodyParser.urlencoded) {
373
+ this.app.use(express_1.default.urlencoded(this.config.bodyParser.urlencoded));
374
+ }
375
+ }
376
+ // Cookie parser middleware
377
+ if (this.config.cookieParser) {
378
+ const cookieParser = ExpressServer.optionalRequire('cookie-parser');
379
+ if (!cookieParser) {
380
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install cookie-parser' }, 'cookie-parser is required but not installed. Please add it to your dependencies');
381
+ process.exit(1);
382
+ }
383
+ if (typeof this.config.cookieParser === 'object') {
384
+ this.app.use(cookieParser(undefined, this.config.cookieParser));
385
+ }
386
+ else {
387
+ this.app.use(cookieParser());
388
+ }
389
+ }
390
+ // OpenAPI docs via @scalar/express-api-reference
391
+ if ((_m = this.config.openApi) === null || _m === void 0 ? void 0 : _m.enable) {
392
+ try {
393
+ const openApiMountPath = this.normalizePath((_o = this.config.openApi.mountPath) !== null && _o !== void 0 ? _o : '/docs', this.config.openApi.withGlobalPrefix);
394
+ const openApiFilePath = this.config.openApi.filePath;
395
+ if (!openApiFilePath) {
396
+ (0, logger_utils_1.getLogger)().error('OpenAPI file path is required');
397
+ process.exit(1);
398
+ }
399
+ const isOpenApiFilePathExists = await (0, fs_utils_1.fileExists)(openApiFilePath);
400
+ if (!isOpenApiFilePathExists) {
401
+ (0, logger_utils_1.getLogger)().error(`OpenAPI spec file not found at ${openApiFilePath}`);
402
+ process.exit(1);
403
+ }
404
+ if ((_p = this.config.openApi) === null || _p === void 0 ? void 0 : _p.verbose) {
405
+ (0, logger_utils_1.getLogger)().info(`Mounting OpenAPI docs at ${openApiMountPath}`);
406
+ (0, logger_utils_1.getLogger)().info(`Using OpenAPI spec file at ${openApiFilePath}`);
407
+ }
408
+ const apiReference = ExpressServer.optionalRequire('@scalar/express-api-reference').apiReference;
409
+ if (!apiReference) {
410
+ (0, logger_utils_1.getLogger)().error({ command: 'npm install @scalar/express-api-reference' }, '@scalar/express-api-reference is required for OpenAPI docs but not installed. Please add it to your dependencies');
411
+ process.exit(1);
412
+ }
413
+ this.app.use(openApiMountPath, apiReference({
414
+ spec: {
415
+ content: await fs_1.default.promises.readFile(openApiFilePath, 'utf8')
416
+ }
417
+ }));
418
+ if ((_q = this.config.openApi) === null || _q === void 0 ? void 0 : _q.verbose) {
419
+ (0, logger_utils_1.getLogger)().info(`Mounted OpenAPI docs at ${openApiMountPath}`);
420
+ }
421
+ }
422
+ catch (err) {
423
+ (0, logger_utils_1.getLogger)().error({ err }, 'Failed to mount OpenAPI docs');
424
+ }
425
+ }
426
+ // Custom response preprocessing hook (apply global prefix if set)
427
+ if (this.hooks.onResponse) {
428
+ this.app.use(this.globalPrefix, this.hooks.onResponse);
429
+ }
430
+ if ((_r = this.config.metrics) === null || _r === void 0 ? void 0 : _r.enable) {
431
+ // Add metrics tracking middleware
432
+ this.app.use((req, res, next) => {
433
+ var _a, _b;
434
+ const start = process.hrtime();
435
+ // Track client IPs
436
+ (_a = this.clientIPs) === null || _a === void 0 ? void 0 : _a.inc({ ip: req.ip, method: req.method });
437
+ // Track request sizes (parse safely)
438
+ const cl = req.headers['content-length'];
439
+ if (cl) {
440
+ const size = Number(cl);
441
+ if (!Number.isNaN(size) && size >= 0) {
442
+ const route = this.normalizeRouteForMetrics(req, res);
443
+ (_b = this.requestSizes) === null || _b === void 0 ? void 0 : _b.observe({ method: req.method, route }, size);
444
+ }
445
+ }
446
+ res.once('finish', () => {
447
+ var _a, _b;
448
+ const [seconds, nanoseconds] = process.hrtime(start);
449
+ const finalRoute = this.normalizeRouteForMetrics(req, res);
450
+ (_a = this.requestCounter) === null || _a === void 0 ? void 0 : _a.inc({
451
+ method: req.method,
452
+ route: finalRoute,
453
+ status: res.statusCode.toString()
454
+ });
455
+ (_b = this.routeTimings) === null || _b === void 0 ? void 0 : _b.observe({
456
+ method: req.method,
457
+ route: finalRoute,
458
+ status: res.statusCode.toString()
459
+ }, seconds + nanoseconds / 1e9);
460
+ });
461
+ next();
462
+ });
463
+ }
464
+ }
465
+ /**
466
+ * Configure server routes and error handling.
467
+ * Sets up in following order:
468
+ *
469
+ * 1. Built-in routes (health, metrics)
470
+ * 2. Application routes
471
+ * 3. 404 handler
472
+ * 4. Error handler
473
+ */
474
+ async setupRoutes() {
475
+ var _a, _b, _c, _d, _e;
476
+ // Health check endpoint
477
+ const healthCheckPath = this.normalizePath(((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.path) || '/healthz', (_b = this.config.healthCheck) === null || _b === void 0 ? void 0 : _b.withGlobalPrefix);
478
+ this.app.get(healthCheckPath, async (_req, res) => {
479
+ var _a;
480
+ try {
481
+ if (!this.healthChecks.length) {
482
+ return res.status(http_status_codes_1.HttpStatusCodes.OK).json(new response_utils_1.SuccessResponse('OK'));
483
+ }
484
+ const checkResults = await Promise.allSettled(this.healthChecks.map(async ({ name, check }) => {
485
+ try {
486
+ const status = await Promise.resolve(check());
487
+ return { name, status, error: null };
488
+ }
489
+ catch (error) {
490
+ return { name, status: false, error: error.message };
491
+ }
492
+ }));
493
+ const results = checkResults.map(result => {
494
+ if (result.status === 'fulfilled')
495
+ return result.value;
496
+ return { name: 'unknown', status: false, error: result.reason };
497
+ });
498
+ const allOk = results.every(r => r.status);
499
+ const status = allOk ? http_status_codes_1.HttpStatusCodes.OK : http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE;
500
+ const response = new response_utils_1.SuccessResponse(allOk ? 'OK' : 'Service unavailable');
501
+ if (!allOk)
502
+ response.error = true;
503
+ if ((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.detailed)
504
+ response.data = { checks: results };
505
+ return res.status(status).json(response);
506
+ }
507
+ catch (_b) {
508
+ return res
509
+ .status(http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR)
510
+ .json(new exception_utils_1.InternalServerErrorException('Health check failed'));
511
+ }
512
+ });
513
+ // Metrics endpoint
514
+ if ((_c = this.config.metrics) === null || _c === void 0 ? void 0 : _c.enable) {
515
+ const metricsPath = this.normalizePath((_d = this.config.metrics.path) !== null && _d !== void 0 ? _d : '/metrics', (_e = this.config.metrics) === null || _e === void 0 ? void 0 : _e.withGlobalPrefix);
516
+ this.app.get(metricsPath, async (_req, res) => {
517
+ res.set('Content-Type', this.register.contentType);
518
+ res.end(await this.register.metrics());
519
+ });
520
+ }
521
+ // Application routes
522
+ const routerToUse = this.externalRouter || this.rootRouter;
523
+ this.app.use(this.globalPrefix, routerToUse);
524
+ // 404 handler (must be after all other routes)
525
+ this.app.use((req, res) => {
526
+ const status = http_status_codes_1.HttpStatusCodes.NOT_FOUND;
527
+ const response = (0, response_utils_1.createFinalErrorResponse)(req, status, `Route ${req.method.toUpperCase()} ${req.path} not found`);
528
+ res.status(status).json(response);
529
+ });
530
+ // Global error handler (must be the last middleware)
531
+ this.app.use((err, req, res, next) => {
532
+ var _a;
533
+ // Check if this is a 404 error that should be handled with special logging rules
534
+ const isNotFoundError = err instanceof exception_utils_2.NotFoundException;
535
+ const shouldSkipLogging = !this.hooks.onError &&
536
+ isNotFoundError &&
537
+ ((_a = this.config.requestLogging) === null || _a === void 0 ? void 0 : _a.enable) &&
538
+ this.config.requestLogging.skipNotFoundRoutes === true;
539
+ if (this.hooks.onError) {
540
+ // Use custom error handler if provided
541
+ this.hooks.onError(err, req, res, next);
542
+ }
543
+ else {
544
+ // Default error handler with logging
545
+ const errorHandlerMiddleware = (0, middleware_utils_1.errorHandler)({
546
+ logErrors: !shouldSkipLogging,
547
+ includeDetails: env_utils_1.Env.isDev() // Only show stack traces in development
548
+ });
549
+ errorHandlerMiddleware(err, req, res, next);
550
+ }
551
+ });
552
+ }
553
+ /**
554
+ * Register a new health check function for monitoring service dependencies.
555
+ *
556
+ * Health checks are executed when the health endpoint is accessed and
557
+ * help determine if the service is ready to handle requests.
558
+ *
559
+ * Examples:
560
+ * - Database connectivity
561
+ * - External service availability
562
+ * - File system access
563
+ * - Memory/CPU usage checks
564
+ *
565
+ * @param name Unique identifier for the check (used in detailed responses)
566
+ * @param check Function returning boolean or Promise<boolean> indicating health
567
+ * @returns This instance for method chaining
568
+ */
569
+ registerHealthCheck(name, check) {
570
+ this.healthChecks.push({ name, check });
571
+ return this;
572
+ }
573
+ /**
574
+ * Get the underlying Express application instance.
575
+ * Use this for advanced Express features not exposed by this wrapper.
576
+ *
577
+ * @returns The raw Express app instance
578
+ */
579
+ getApp() {
580
+ return this.app;
581
+ }
582
+ /**
583
+ * Get the active HTTP/HTTPS server instance.
584
+ * Returns null if the server is not currently running.
585
+ *
586
+ * @returns The HTTP/HTTPS server instance or null
587
+ */
588
+ getServer() {
589
+ return this.server;
590
+ }
591
+ /**
592
+ * Start the HTTP server and begin listening for requests.
593
+ *
594
+ * This method:
595
+ * - Executes beforeStart hooks
596
+ * - Binds to the configured host/port
597
+ * - Sets up error handling for startup failures
598
+ * - Executes afterStart hooks on success
599
+ * - Logs startup information
600
+ *
601
+ * @returns Promise resolving to the running HTTP server instance
602
+ * @throws Error if server fails to start or port is already in use
603
+ */
604
+ async start() {
605
+ // Ensure initialization (middleware + routes) completed before starting
606
+ await this.initPromise;
607
+ await this.runHook('beforeStart', this.app);
608
+ return new Promise((resolve, reject) => {
609
+ try {
610
+ // Prepare listen arguments with optional host parameter
611
+ const listenArgs = [
612
+ this.config.port,
613
+ this.config.host,
614
+ async () => {
615
+ var _a, _b, _c;
616
+ const protocol = this.config.https ? 'https' : 'http';
617
+ const url = `${protocol}://${this.config.host}:${this.config.port}`;
618
+ (0, logger_utils_1.getLogger)().info(`Server running on ${url}`);
619
+ if ((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.path) {
620
+ (0, logger_utils_1.getLogger)().info(`Health check available at ${url}${this.normalizePath(this.config.healthCheck.path, this.config.healthCheck.withGlobalPrefix)}`);
621
+ }
622
+ if (((_b = this.config.metrics) === null || _b === void 0 ? void 0 : _b.enable) && this.config.metrics.path) {
623
+ (0, logger_utils_1.getLogger)().info(`Metrics available at ${url}${this.normalizePath(this.config.metrics.path, this.config.metrics.withGlobalPrefix)}`);
624
+ }
625
+ if ((_c = this.config.openApi) === null || _c === void 0 ? void 0 : _c.enable) {
626
+ (0, logger_utils_1.getLogger)().info(`API docs available at ${url}${this.normalizePath(this.config.openApi.mountPath, this.config.openApi.withGlobalPrefix)}`);
627
+ }
628
+ if (this.server)
629
+ await this.runHook('afterStart', this.server);
630
+ resolve(this.server);
631
+ }
632
+ ];
633
+ if (this.config.https) {
634
+ const httpsOptions = Object.assign(Object.assign({}, this.config.https), { key: fs_1.default.readFileSync(this.config.https.key), cert: fs_1.default.readFileSync(this.config.https.cert) });
635
+ if (this.config.https.ca) {
636
+ httpsOptions.ca = fs_1.default.readFileSync(this.config.https.ca);
637
+ }
638
+ if (this.config.https.passphrase) {
639
+ httpsOptions.passphrase = this.config.https.passphrase;
640
+ }
641
+ this.server = https_1.default.createServer(httpsOptions, this.app).listen(...listenArgs);
642
+ }
643
+ else {
644
+ // Start the HTTP server
645
+ this.server = this.app.listen(...listenArgs);
646
+ }
647
+ // Track connections
648
+ this.server.on('connection', (conn) => {
649
+ this.connections.add(conn);
650
+ conn.on('close', () => this.connections.delete(conn));
651
+ });
652
+ // Handle server startup errors (port in use, permission denied, etc.)
653
+ this.server.on('error', err => {
654
+ (0, logger_utils_1.getLogger)().error({ err }, 'Server failed to start');
655
+ reject(err);
656
+ });
657
+ }
658
+ catch (error) {
659
+ reject(error);
660
+ }
661
+ });
662
+ }
663
+ /**
664
+ * Stop the HTTP server gracefully.
665
+ *
666
+ * This method:
667
+ * - Executes beforeStop hooks
668
+ * - Stops accepting new connections
669
+ * - Waits for existing connections to finish
670
+ * - Closes the server
671
+ * - Executes afterStop hooks
672
+ * - Logs shutdown information
673
+ *
674
+ * Graceful shutdown ensures:
675
+ * - No requests are dropped
676
+ * - Resources are properly cleaned up
677
+ * - Monitoring systems are notified
678
+ */
679
+ async stop(force = false) {
680
+ if (!this.server) {
681
+ (0, logger_utils_1.getLogger)().warn('Stop called but server is not running');
682
+ return;
683
+ }
684
+ if (this.isShuttingDown) {
685
+ (0, logger_utils_1.getLogger)().warn('Stop called while shutdown is already in progress');
686
+ return;
687
+ }
688
+ this.isShuttingDown = true;
689
+ await this.runHook('beforeStop', this.server);
690
+ const shutdownTimeout = 10000; // 10s max wait
691
+ const serverClosePromise = new Promise((resolve, reject) => {
692
+ this.server.close(async (err) => {
693
+ if (err) {
694
+ (0, logger_utils_1.getLogger)().error({ err }, 'Error while closing server');
695
+ reject(err);
696
+ return;
697
+ }
698
+ this.server = null;
699
+ this.isShuttingDown = false;
700
+ (0, logger_utils_1.getLogger)().info('Server stopped gracefully');
701
+ await this.runHook('afterStop');
702
+ resolve();
703
+ });
704
+ });
705
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Shutdown timeout')), shutdownTimeout));
706
+ try {
707
+ await Promise.race([serverClosePromise, timeoutPromise]);
708
+ }
709
+ catch (err) {
710
+ (0, logger_utils_1.getLogger)().error({ err }, 'Graceful shutdown timed out');
711
+ if (force) {
712
+ (0, logger_utils_1.getLogger)().warn('Forcing connection destroy due to shutdown timeout');
713
+ }
714
+ }
715
+ finally {
716
+ // Always clean up connections
717
+ await this.destroyConnections();
718
+ }
719
+ }
720
+ /**
721
+ * Enable graceful shutdown on OS signals for production deployment.
722
+ *
723
+ * This is essential for:
724
+ * - Container orchestration (Docker, Kubernetes)
725
+ * - Process managers (PM2, systemd)
726
+ * - Load balancer health checks
727
+ * - Zero-downtime deployments
728
+ *
729
+ * @param signals Array of process signals to listen for (default: SIGINT, SIGTERM)
730
+ */
731
+ enableGracefulShutdown(signals = ['SIGINT', 'SIGTERM']) {
732
+ signals.forEach(signal => {
733
+ process.on(signal, async () => {
734
+ (0, logger_utils_1.getLogger)().info(`Received ${signal}, initiating graceful shutdown...`);
735
+ try {
736
+ await this.stop();
737
+ process.exit(0);
738
+ }
739
+ catch (err) {
740
+ (0, logger_utils_1.getLogger)().error({ err }, 'Error during graceful shutdown, forcing stop...');
741
+ try {
742
+ await this.stop(true); // fallback to forced shutdown
743
+ process.exit(1);
744
+ }
745
+ catch (forceError) {
746
+ (0, logger_utils_1.getLogger)().fatal({ forceError }, 'Forced shutdown failed, exiting hard');
747
+ process.exit(1);
748
+ }
749
+ }
750
+ });
751
+ });
752
+ return this;
753
+ }
754
+ /**
755
+ * Set an externally created base router.
756
+ * This will override the internal rootRouter.
757
+ */
758
+ setBaseRouter(router) {
759
+ this.externalRouter = router;
760
+ return this;
761
+ }
762
+ /**
763
+ * Create and register a new router (only used if not injecting one externally - use `setBaseRouter` instead).
764
+ */
765
+ createRouter(prefix = '') {
766
+ const router = express_1.default.Router();
767
+ const path = this.normalizePath(prefix, true);
768
+ this.rootRouter.use(path, router);
769
+ return router;
770
+ }
771
+ /**
772
+ * Register a new route handler with support for multiple HTTP methods.
773
+ * The route is automatically registered under the globalPrefix if set.
774
+ *
775
+ * @param methods Array of HTTP methods (get, post, put, delete, etc.)
776
+ * @param path Route path with Express path patterns support
777
+ * @param handlers One or more Express request handlers (middleware + final handler)
778
+ * @returns This instance for method chaining
779
+ */
780
+ registerRoute(methods, path, ...handlers) {
781
+ const fullPath = this.normalizePath(path, true);
782
+ const methodMap = {
783
+ get: this.app.get.bind(this.app),
784
+ post: this.app.post.bind(this.app),
785
+ put: this.app.put.bind(this.app),
786
+ delete: this.app.delete.bind(this.app),
787
+ patch: this.app.patch.bind(this.app),
788
+ options: this.app.options.bind(this.app),
789
+ head: this.app.head.bind(this.app)
790
+ };
791
+ methods.forEach(m => {
792
+ const fn = methodMap[m];
793
+ if (fn) {
794
+ fn(fullPath, ...handlers);
795
+ }
796
+ else {
797
+ throw new Error(`Unsupported HTTP method: ${m}`);
798
+ }
799
+ });
800
+ return this;
801
+ }
802
+ /**
803
+ * Register custom middleware with optional path restriction.
804
+ *
805
+ * Use this for:
806
+ * - Adding authentication to specific routes
807
+ * - Custom logging or validation
808
+ * - Request transformation
809
+ * - Third-party middleware integration
810
+ *
811
+ * @param path Optional path prefix or middleware function if no path
812
+ * @param middleware Middleware handler (required if path is provided)
813
+ * @returns This instance for method chaining
814
+ */
815
+ registerMiddleware(path, middleware) {
816
+ if (typeof path === 'string') {
817
+ const normalizedPath = this.normalizePath(path);
818
+ if (normalizedPath) {
819
+ this.app.use(normalizedPath, middleware);
820
+ }
821
+ else {
822
+ this.app.use(middleware);
823
+ }
824
+ }
825
+ else {
826
+ this.app.use(path);
827
+ }
828
+ return this;
829
+ }
830
+ /**
831
+ * Register one or more middleware functions to be applied globally.
832
+ * This is a simpler alternative to registerMiddleware when you just want
833
+ * to add middleware without path restrictions.
834
+ *
835
+ * @param middlewares One or more Express middleware functions
836
+ * @returns This instance for method chaining
837
+ */
838
+ useMiddleware(...middlewares) {
839
+ middlewares.forEach(middleware => {
840
+ this.app.use(middleware);
841
+ });
842
+ return this;
843
+ }
844
+ /**
845
+ * Get Prometheus registry (to add custom counters/histograms)
846
+ *
847
+ * @return {*} {client.Registry}
848
+ */
849
+ getMetricsRegistry() {
850
+ var _a;
851
+ if (!((_a = this.config.metrics) === null || _a === void 0 ? void 0 : _a.enable)) {
852
+ throw new Error('Metrics are not enabled in the server configuration');
853
+ }
854
+ return this.register;
855
+ }
856
+ /**
857
+ * Get server configuration
858
+ *
859
+ * @return {*} {ServerConfig}
860
+ */
861
+ getConfig() {
862
+ return this.config;
863
+ }
864
+ /**
865
+ * Wait until server initialization (middleware + routes) has completed.
866
+ * Useful for integration tests that inspect app before starting.
867
+ */
868
+ async waitUntilReady() {
869
+ await this.initPromise;
870
+ }
871
+ normalizePath(path, withGlobalPrefix = false) {
872
+ const sanitize = (p) => {
873
+ return ('/' +
874
+ p
875
+ .trim()
876
+ .replace(/^\/+/, '') // remove leading slashes
877
+ .replace(/\/{2,}/g, '/') // collapse multiple slashes
878
+ .replace(/\/+$/, '')); // remove trailing slash
879
+ };
880
+ // Resolve global prefix if enabled
881
+ const prefix = withGlobalPrefix && this.globalPrefix ? sanitize(this.globalPrefix) : '';
882
+ // If path is invalid, default to prefix or root
883
+ if (typeof path !== 'string' || !path.trim()) {
884
+ return prefix || '/';
885
+ }
886
+ return sanitize(prefix + '/' + path);
887
+ }
888
+ normalizeRouteForMetrics(req, res) {
889
+ var _a;
890
+ // Prevent high cardinality metrics by normalizing routes
891
+ if ((_a = req === null || req === void 0 ? void 0 : req.route) === null || _a === void 0 ? void 0 : _a.path) {
892
+ // Use Express route pattern instead of actual URL
893
+ return req.route.path;
894
+ }
895
+ // Group common patterns
896
+ if (res.statusCode === 404)
897
+ return '/404';
898
+ const path = (req.path || 'unknown').split('?')[0];
899
+ // Replace IDs and UUIDs with placeholders
900
+ return path
901
+ .replace(/\/[0-9]+/g, '/:id')
902
+ .replace(/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '/:uuid');
903
+ }
904
+ /**
905
+ * Destroy all active connections (gracefully if possible).
906
+ * If a connection does not close cleanly, it will be force-destroyed.
907
+ */
908
+ async destroyConnections() {
909
+ const total = this.connections.size;
910
+ if (total === 0) {
911
+ (0, logger_utils_1.getLogger)().debug('No active connections to close');
912
+ return;
913
+ }
914
+ const timeoutMs = 5000;
915
+ await Promise.race([
916
+ Promise.all(Array.from(this.connections).map(conn => new Promise(resolve => {
917
+ conn.end(() => {
918
+ if (!conn.destroyed)
919
+ conn.destroy();
920
+ resolve();
921
+ });
922
+ conn.on('error', () => {
923
+ conn.destroy();
924
+ resolve();
925
+ });
926
+ }))),
927
+ new Promise(resolve => setTimeout(resolve, timeoutMs))
928
+ ]);
929
+ this.connections.clear();
930
+ (0, logger_utils_1.getLogger)().info(`Closed ${total} active connections`);
931
+ }
932
+ async validateHttpsFiles() {
933
+ if (!(await (0, fs_utils_1.fileExists)(this.config.https.key))) {
934
+ (0, logger_utils_1.getLogger)().error(`HTTPS key file not found: ${this.config.https.key}`);
935
+ process.exit(1);
936
+ }
937
+ if (!(await (0, fs_utils_1.fileExists)(this.config.https.cert))) {
938
+ (0, logger_utils_1.getLogger)().error(`HTTPS cert file not found: ${this.config.https.cert}`);
939
+ process.exit(1);
940
+ }
941
+ if (this.config.https.ca && !(await (0, fs_utils_1.fileExists)(this.config.https.ca))) {
942
+ (0, logger_utils_1.getLogger)().error(`HTTPS CA file not found: ${this.config.https.ca}`);
943
+ process.exit(1);
944
+ }
945
+ }
946
+ static isBuiltServerConfig(config) {
947
+ if (config[server_builder_1.BUILD_MARKER]) {
948
+ return true;
949
+ }
950
+ return false;
951
+ }
952
+ static optionalRequire(name) {
953
+ try {
954
+ return require(name);
955
+ }
956
+ catch (_a) {
957
+ return null;
958
+ }
959
+ }
960
+ }
961
+ exports.ExpressServer = ExpressServer;
962
+ //# sourceMappingURL=server.js.map