@futdevpro/nts-dynamo 1.15.86 → 1.15.89

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 (382) hide show
  1. package/.c8rc.json +26 -26
  2. package/.copilot/patterns.json +7 -7
  3. package/.cursor/rules/__assistant_guide.mdc +30 -30
  4. package/.cursor/rules/_ag_backend-structure.mdc +85 -85
  5. package/.cursor/rules/_ag_backend.mdc +16 -16
  6. package/.cursor/rules/_ag_frontend-structure.mdc +86 -86
  7. package/.cursor/rules/_ag_frontend.mdc +39 -39
  8. package/.cursor/rules/_ag_import-rules.mdc +44 -44
  9. package/.cursor/rules/_ag_naming.mdc +115 -115
  10. package/.cursor/rules/_ag_should-be.mdc +6 -6
  11. package/.cursor/rules/ai_development_guide.md +60 -60
  12. package/.cursor/rules/cursor-rules.md +160 -160
  13. package/.cursor/rules/default-command.mdc +464 -464
  14. package/.cursor/rules/error_code_pattern.md +39 -39
  15. package/.cursor/rules/saved rule mcp server use.md +15 -15
  16. package/.dynamo/pipeline.cicd.config.json +4 -0
  17. package/.vscode/settings.json +10 -10
  18. package/HOWTO.md +15 -15
  19. package/LICENSE +21 -21
  20. package/__documentations/nts-integration-tests-2026-03-17.md +26 -26
  21. package/__documentations/plans/BEDROCK-HYPERPLAN.md +95 -95
  22. package/_specifications/BACKLOG.md +92 -92
  23. package/_specifications/TODO.md +15 -15
  24. package/_specifications/agent.md +138 -138
  25. package/build/_collections/global-settings.const.d.ts.map +1 -1
  26. package/build/_collections/global-settings.const.js +7 -0
  27. package/build/_collections/global-settings.const.js.map +1 -1
  28. package/build/_collections/security-headers.util.d.ts +17 -0
  29. package/build/_collections/security-headers.util.d.ts.map +1 -0
  30. package/build/_collections/security-headers.util.js +78 -0
  31. package/build/_collections/security-headers.util.js.map +1 -0
  32. package/build/_models/interfaces/global-settings.interface.d.ts +8 -0
  33. package/build/_models/interfaces/global-settings.interface.d.ts.map +1 -1
  34. package/build/_models/interfaces/security-headers-settings.interface.d.ts +42 -0
  35. package/build/_models/interfaces/security-headers-settings.interface.d.ts.map +1 -0
  36. package/build/_models/interfaces/security-headers-settings.interface.js +3 -0
  37. package/build/_models/interfaces/security-headers-settings.interface.js.map +1 -0
  38. package/build/_services/server/app.server.d.ts +7 -0
  39. package/build/_services/server/app.server.d.ts.map +1 -1
  40. package/build/_services/server/app.server.js +22 -0
  41. package/build/_services/server/app.server.js.map +1 -1
  42. package/build/index.d.ts +2 -0
  43. package/build/index.d.ts.map +1 -1
  44. package/build/index.js +2 -0
  45. package/build/index.js.map +1 -1
  46. package/eslint.config.js +3 -3
  47. package/nodemon.json +24 -24
  48. package/package.json +5 -5
  49. package/pnpm-workspace.yaml +5 -5
  50. package/scripts/run-coverage-tests.js +28 -28
  51. package/spec/support/helpers/spec-reporter-loader.js +359 -359
  52. package/spec/support/helpers/ts-node-helper.js +93 -93
  53. package/spec/support/jasmine.coverage.json +24 -24
  54. package/spec/support/jasmine.json +24 -24
  55. package/src/_collections/archive.util.spec.ts +57 -57
  56. package/src/_collections/archive.util.ts +18 -18
  57. package/src/_collections/atlas-default-db-options.const.ts +9 -9
  58. package/src/_collections/default-fallback-cache-max-age.const.spec.ts +11 -11
  59. package/src/_collections/default-fallback-cache-max-age.const.ts +2 -2
  60. package/src/_collections/default-not-found-page.const.spec.ts +19 -19
  61. package/src/_collections/default-not-found-page.const.ts +22 -22
  62. package/src/_collections/default-socket-path.const.spec.ts +12 -12
  63. package/src/_collections/default-socket-path.const.ts +2 -2
  64. package/src/_collections/get-environment-settings.util.spec.ts +210 -210
  65. package/src/_collections/get-environment-settings.util.ts +48 -48
  66. package/src/_collections/global-settings.const.ts +114 -106
  67. package/src/_collections/sample.env +21 -21
  68. package/src/_collections/security-headers.util.spec.ts +98 -0
  69. package/src/_collections/security-headers.util.ts +96 -0
  70. package/src/_collections/star.controller.spec.ts +224 -224
  71. package/src/_collections/star.controller.ts +129 -129
  72. package/src/_enums/data-model-type.enum.ts +14 -14
  73. package/src/_enums/data-service-function.enum.ts +24 -24
  74. package/src/_enums/predefined-data-types.enum.ts +16 -16
  75. package/src/_enums/route-security.enum.ts +12 -12
  76. package/src/_models/control-models/api-call-params.control-model.spec.ts +152 -152
  77. package/src/_models/control-models/api-call-params.control-model.ts +142 -142
  78. package/src/_models/control-models/app-ext-system-controls.control-model.spec.ts +52 -52
  79. package/src/_models/control-models/app-ext-system-controls.control-model.ts +9 -9
  80. package/src/_models/control-models/app-params.control-model.spec.ts +225 -225
  81. package/src/_models/control-models/app-params.control-model.ts +136 -136
  82. package/src/_models/control-models/app-system-controls.control-model.spec.ts +31 -31
  83. package/src/_models/control-models/app-system-controls.control-model.ts +9 -9
  84. package/src/_models/control-models/endpoint-params.control-model.spec.ts +627 -627
  85. package/src/_models/control-models/endpoint-params.control-model.ts +627 -627
  86. package/src/_models/control-models/http-settings.control-model.spec.ts +77 -77
  87. package/src/_models/control-models/http-settings.control-model.ts +37 -37
  88. package/src/_models/control-models/system-control.control-model.spec.ts +27 -27
  89. package/src/_models/control-models/system-control.control-model.ts +12 -12
  90. package/src/_models/interfaces/certification-settings.interface.ts +7 -7
  91. package/src/_models/interfaces/environment-settings.interface.ts +59 -59
  92. package/src/_models/interfaces/global-log-settings.interface.ts +171 -171
  93. package/src/_models/interfaces/global-service-settings.interface.ts +47 -47
  94. package/src/_models/interfaces/global-settings.interface.ts +244 -235
  95. package/src/_models/interfaces/routing-module-settings.interface.ts +21 -21
  96. package/src/_models/interfaces/security-headers-settings.interface.ts +50 -0
  97. package/src/_models/interfaces/static-client-settings.interface.spec.ts +29 -29
  98. package/src/_models/interfaces/static-client-settings.interface.ts +28 -28
  99. package/src/_models/types/db-update.type.ts +100 -100
  100. package/src/_modules/ai/_models/ai-input-interfaces.ts +117 -117
  101. package/src/_modules/ai/_models/ai-test-generation-result.interface.ts +16 -16
  102. package/src/_modules/ai/_modules/anthropic/_services/aai-user-key.control-service.ts +138 -138
  103. package/src/_modules/ai/_modules/anthropic/index.ts +5 -5
  104. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.spec.ts +242 -242
  105. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.ts +639 -639
  106. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.spec.ts +295 -295
  107. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.ts +518 -518
  108. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.spec.ts +209 -209
  109. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.ts +85 -85
  110. package/src/_modules/ai/_modules/document-ai/_enums/dai-compare-result-type.enum.ts +7 -7
  111. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-chunk.data-model.ts +146 -146
  112. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-page.data-model.ts +162 -162
  113. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-document.data-model.ts +99 -99
  114. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-code-chunk.interface.ts +68 -68
  115. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-chunk-compare-result.interface.ts +18 -18
  116. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-page-compare-result.interface.ts +19 -19
  117. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-document-compare-result.interface.ts +25 -25
  118. package/src/_modules/ai/_modules/document-ai/index.ts +30 -30
  119. package/src/_modules/ai/_modules/fdp-ai/_services/fdpai-user-key.control-service.ts +189 -189
  120. package/src/_modules/ai/_modules/fdp-ai/index.ts +5 -5
  121. package/src/_modules/ai/_modules/open-ai/_collections/oai-global-settings.const.ts +9 -9
  122. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests-hu.conts.ts +82 -82
  123. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests.conts.ts +75 -75
  124. package/src/_modules/ai/_modules/open-ai/_enums/oai-gpt-message-role.enum.ts +45 -45
  125. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-global-settings.interface.ts +7 -7
  126. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-gpt-message.interface.ts +7 -7
  127. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-llm-predefined-requests.interface.ts +57 -57
  128. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-doc-chunk-data.service.ts +292 -292
  129. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-document.data-service.spec.ts +342 -342
  130. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.spec.ts +550 -550
  131. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.ts +630 -630
  132. package/src/_modules/ai/_modules/open-ai/_services/oai-embedding.control-service.spec.ts +332 -332
  133. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.spec.ts +462 -462
  134. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.ts +634 -634
  135. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.spec.ts +489 -489
  136. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.tools.spec.ts +173 -173
  137. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.ts +1033 -1033
  138. package/src/_modules/ai/_modules/open-ai/_services/oai-user-key.control-service.ts +157 -157
  139. package/src/_modules/ai/_services/ai-embedding-mock.service.spec.ts +115 -115
  140. package/src/_modules/ai/_services/ai-embedding-mock.service.ts +212 -212
  141. package/src/_modules/ai/_services/ai-embedding-provider.registry.spec.ts +110 -110
  142. package/src/_modules/ai/_services/ai-embedding-provider.registry.ts +110 -110
  143. package/src/_modules/ai/_services/ai-embedding.service-base.spec.ts +98 -98
  144. package/src/_modules/ai/_services/ai-embedding.service-base.ts +48 -48
  145. package/src/_modules/ai/_services/ai-llm-chat.service-base.spec.ts +229 -229
  146. package/src/_modules/ai/_services/ai-llm-chat.service-base.ts +68 -68
  147. package/src/_modules/ai/_services/ai-llm.service-base.spec.ts +250 -250
  148. package/src/_modules/ai/_services/ai-llm.service-base.ts +519 -519
  149. package/src/_modules/ai/_services/ai-provider.service-base.spec.ts +158 -158
  150. package/src/_modules/ai/_services/ai-user-key.service-base.ts +59 -59
  151. package/src/_modules/ai/_services/lmstudio-embedding.control-service.spec.ts +197 -197
  152. package/src/_modules/ai/_services/lmstudio-embedding.control-service.ts +371 -371
  153. package/src/_modules/ai/index.ts +23 -23
  154. package/src/_modules/assistant/_collections/ass-global-settings.const.ts +13 -13
  155. package/src/_modules/assistant/_collections/ass.util.spec.ts +176 -176
  156. package/src/_modules/assistant/_collections/ass.util.ts +50 -50
  157. package/src/_modules/assistant/_models/ass-global-settings.interface.ts +15 -15
  158. package/src/_modules/assistant/_services/ass-io.control-service.spec.ts +140 -140
  159. package/src/_modules/assistant/_services/ass-main.control-service.spec.ts +192 -192
  160. package/src/_modules/assistant/_services/ass-main.control-service.ts +107 -107
  161. package/src/_modules/bot/_collections/bot-default-commands.const.ts +12 -12
  162. package/src/_modules/bot/_collections/bot-global-settings.const.ts +39 -39
  163. package/src/_modules/bot/_models/bot-channel-wrapper.interface.ts +62 -62
  164. package/src/_modules/bot/_models/bot-command.interface.ts +8 -8
  165. package/src/_modules/bot/_models/bot-global-settings.interface.ts +96 -96
  166. package/src/_modules/bot/_models/bot-last-mention-date.interface.ts +6 -6
  167. package/src/_modules/bot/_models/bot-last-message-date.interface.ts +5 -5
  168. package/src/_modules/bot/_models/bot-user-wrapper.interface.ts +41 -41
  169. package/src/_modules/bot/_modules/discord-bot/_models/dib-platform.types.ts +9 -9
  170. package/src/_modules/bot/_modules/discord-bot/_services/dib-messaging-provider.control-service.spec.ts +431 -431
  171. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.spec.ts +160 -160
  172. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.ts +55 -55
  173. package/src/_modules/bot/_modules/dynamo-bot/_models/dyb-platform.types.ts +15 -15
  174. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.spec.ts +374 -374
  175. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.ts +447 -447
  176. package/src/_modules/bot/_modules/dynamo-bot/index.ts +15 -15
  177. package/src/_modules/bot/_modules/slack-bot/_models/slb-platform.types.ts +9 -9
  178. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.spec.ts +344 -344
  179. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.ts +197 -197
  180. package/src/_modules/bot/_modules/teams-bot/_models/teb-platform.types.ts +9 -9
  181. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.spec.ts +345 -345
  182. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.ts +197 -197
  183. package/src/_modules/bot/_services/bot-commands.control-service.spec.ts +116 -116
  184. package/src/_modules/bot/_services/bot-io.control-service.spec.ts +285 -285
  185. package/src/_modules/bot/_services/bot-main.control-service.spec.ts +208 -208
  186. package/src/_modules/bot/_services/bot-messaging-provider.service-base.spec.ts +349 -349
  187. package/src/_modules/bot/_services/bot-routines.control-service.spec.ts +111 -111
  188. package/src/_modules/custom-data/custom-data.controller.spec.ts +49 -49
  189. package/src/_modules/custom-data/custom-data.controller.ts +67 -67
  190. package/src/_modules/custom-data/custom-data.data-service.spec.ts +54 -54
  191. package/src/_modules/custom-data/custom-data.data-service.ts +21 -21
  192. package/src/_modules/custom-data/get-custom-data-routing-module.util.spec.ts +28 -28
  193. package/src/_modules/custom-data/get-custom-data-routing-module.util.ts +24 -24
  194. package/src/_modules/custom-data/index.ts +9 -9
  195. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.spec.ts +161 -161
  196. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.ts +203 -203
  197. package/src/_modules/data-readers/_models/interfaces/dynts-sqlite-reader.interface.ts +33 -33
  198. package/src/_modules/data-readers/index.ts +11 -11
  199. package/src/_modules/defaults/_collections/default-endpoints.util.ts +487 -487
  200. package/src/_modules/defaults/_models/default-user.data-model.ts +72 -72
  201. package/src/_modules/defaults/_services/default-auth.service.spec.ts +269 -269
  202. package/src/_modules/defaults/_services/default-auth.service.ts +177 -177
  203. package/src/_modules/defaults/_services/default-socket-events.service.spec.ts +42 -42
  204. package/src/_modules/defaults/_services/default-socket-events.service.ts +61 -61
  205. package/src/_modules/defaults/_services/default-user.data-service.spec.ts +187 -187
  206. package/src/_modules/defaults/_services/default-user.data-service.ts +98 -98
  207. package/src/_modules/defaults/index.ts +17 -17
  208. package/src/_modules/discord-assistant/_collections/dias-global-settings.const.ts +19 -19
  209. package/src/_modules/discord-assistant/_collections/dias.util.spec.ts +366 -366
  210. package/src/_modules/discord-assistant/_collections/dias.util.ts +132 -132
  211. package/src/_modules/discord-assistant/_models/dias-global-settings.interface.ts +19 -19
  212. package/src/_modules/discord-assistant/_models/dias-knowledge.data-model.ts +52 -52
  213. package/src/_modules/discord-assistant/_services/dias-chunk.data-service.ts +177 -177
  214. package/src/_modules/discord-assistant/_services/dias-io.control-service.spec.ts +108 -108
  215. package/src/_modules/discord-assistant/_services/dias-io.control-service.ts +69 -69
  216. package/src/_modules/discord-assistant/_services/dias-main.control-service.spec.ts +22 -22
  217. package/src/_modules/discord-assistant/_services/dias-main.control-service.ts +27 -27
  218. package/src/_modules/discord-assistant/_services/dias.service-base.spec.ts +195 -195
  219. package/src/_modules/discord-assistant/_services/dias.service-base.ts +76 -76
  220. package/src/_modules/discord-assistant/index.ts +38 -38
  221. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.spec.ts +34 -34
  222. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.ts +11 -11
  223. package/src/_modules/discord-assistant-voiced/index.ts +36 -36
  224. package/src/_modules/discord-bot/_collections/dibo-default-commands.const.ts +16 -16
  225. package/src/_modules/discord-bot/_collections/dibo-global-settings.conts.ts +55 -55
  226. package/src/_modules/discord-bot/_collections/dibo-operations.util.spec.ts +214 -214
  227. package/src/_modules/discord-bot/_collections/dibo-operations.util.ts +387 -387
  228. package/src/_modules/discord-bot/_models/dibo-command.interface.ts +12 -12
  229. package/src/_modules/discord-bot/_models/dibo-global-settings.interface.ts +98 -98
  230. package/src/_modules/discord-bot/_models/dibo-last-mention-date.inteface.ts +7 -7
  231. package/src/_modules/discord-bot/_models/dibo-last-message-date.interface.ts +6 -6
  232. package/src/_modules/discord-bot/_services/dibo-commands.control-service.spec.ts +154 -154
  233. package/src/_modules/discord-bot/_services/dibo-commands.control-service.ts +153 -153
  234. package/src/_modules/discord-bot/_services/dibo-io.control-service.spec.ts +264 -264
  235. package/src/_modules/discord-bot/_services/dibo-io.control-service.ts +306 -306
  236. package/src/_modules/discord-bot/_services/dibo-main.control-service.spec.ts +408 -408
  237. package/src/_modules/discord-bot/_services/dibo-main.control-service.ts +487 -487
  238. package/src/_modules/discord-bot/_services/dibo-routines.control-service.spec.ts +105 -105
  239. package/src/_modules/discord-bot/index.ts +36 -36
  240. package/src/_modules/local-vector-search/_enums/lvs-search-mode.enum.ts +35 -35
  241. package/src/_modules/local-vector-search/_models/data-models/lvs-vector-persist.data-model.ts +59 -59
  242. package/src/_modules/local-vector-search/_models/lvs-search-result.interface.ts +17 -17
  243. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.spec.ts +418 -418
  244. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.ts +276 -276
  245. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.spec.ts +480 -480
  246. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.ts +416 -416
  247. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.spec.ts +198 -198
  248. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.ts +146 -146
  249. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.spec.ts +167 -167
  250. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.ts +106 -106
  251. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.spec.ts +507 -507
  252. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.ts +272 -272
  253. package/src/_modules/local-vector-search/index.ts +16 -16
  254. package/src/_modules/logs/index.ts +11 -11
  255. package/src/_modules/mcp/_models/interfaces/dynts-mcp.interface.ts +111 -111
  256. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.spec.ts +142 -142
  257. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.ts +120 -120
  258. package/src/_modules/mcp/_services/dynts-mcp.adapter.ts +168 -168
  259. package/src/_modules/mcp/index.ts +13 -13
  260. package/src/_modules/messaging/README.md +354 -354
  261. package/src/_modules/messaging/_collections/get-messaging-routing-module.util.ts +26 -26
  262. package/src/_modules/messaging/_collections/msg-global-settings.const.ts +22 -22
  263. package/src/_modules/messaging/_collections/msg.util.spec.ts +226 -226
  264. package/src/_modules/messaging/_models/msg-global-settings.interface.ts +37 -37
  265. package/src/_modules/messaging/_services/msg-conversation.data-service.ts +146 -146
  266. package/src/_modules/messaging/_services/msg-events.service.spec.ts +219 -219
  267. package/src/_modules/messaging/_services/msg-events.service.ts +267 -267
  268. package/src/_modules/messaging/_services/msg-integration.control-service.ts +179 -179
  269. package/src/_modules/messaging/_services/msg-main.control-service.spec.ts +147 -147
  270. package/src/_modules/messaging/_services/msg-main.control-service.ts +571 -571
  271. package/src/_modules/messaging/_services/msg-message.data-service.ts +129 -129
  272. package/src/_modules/messaging/_services/msg.controller.spec.ts +201 -201
  273. package/src/_modules/messaging/index.ts +30 -30
  274. package/src/_modules/mock/app-extended-server.mock.ts +201 -201
  275. package/src/_modules/mock/app-integration-test.mock.ts +51 -51
  276. package/src/_modules/mock/app-params.mock.spec.ts +21 -21
  277. package/src/_modules/mock/app-params.mock.ts +9 -9
  278. package/src/_modules/mock/app-server.mock.ts +188 -188
  279. package/src/_modules/mock/auth-service.mock.spec.ts +47 -47
  280. package/src/_modules/mock/auth-service.mock.ts +28 -28
  281. package/src/_modules/mock/controller.mock.spec.ts +26 -26
  282. package/src/_modules/mock/controller.mock.ts +16 -16
  283. package/src/_modules/mock/data-model.mock.spec.ts +111 -111
  284. package/src/_modules/mock/data-model.mock.ts +82 -82
  285. package/src/_modules/mock/email-service-collection.mock.spec.ts +24 -24
  286. package/src/_modules/mock/email-service-collection.mock.ts +15 -15
  287. package/src/_modules/mock/email-service.mock.spec.ts +17 -17
  288. package/src/_modules/mock/email-service.mock.ts +20 -20
  289. package/src/_modules/mock/email-template.mock.html +14 -14
  290. package/src/_modules/mock/endpoint.mock.ts +91 -91
  291. package/src/_modules/mock/socket-client.mock.spec.ts +40 -40
  292. package/src/_modules/mock/socket-client.mock.ts +45 -45
  293. package/src/_modules/mock/socket-server.mock.spec.ts +44 -44
  294. package/src/_modules/mock/socket-server.mock.ts +46 -46
  295. package/src/_modules/oauth2/_routes/oauth2.controller.spec.ts +107 -107
  296. package/src/_modules/oauth2/_routes/oauth2.controller.ts +98 -98
  297. package/src/_modules/oauth2/_services/oauth2.auth-service.spec.ts +254 -254
  298. package/src/_modules/oauth2/_services/oauth2.auth-service.ts +232 -232
  299. package/src/_modules/oauth2/_services/oauth2.control-service.spec.ts +585 -585
  300. package/src/_modules/oauth2/_services/oauth2.control-service.ts +653 -653
  301. package/src/_modules/oauth2/index.ts +17 -17
  302. package/src/_modules/scoped-config/_enums/dynts-scoped-config-level.enum.ts +22 -22
  303. package/src/_modules/scoped-config/_models/data-models/dynts-scoped-config.data-model.ts +81 -81
  304. package/src/_modules/scoped-config/_models/interfaces/dynts-scoped-config.interface.ts +107 -107
  305. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.spec.ts +306 -306
  306. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.ts +295 -295
  307. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.spec.ts +118 -118
  308. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.ts +105 -105
  309. package/src/_modules/scoped-config/index.ts +17 -17
  310. package/src/_modules/server/errors/errors.control-service.spec.ts +238 -238
  311. package/src/_modules/server/errors/errors.control-service.ts +100 -100
  312. package/src/_modules/server/errors/errors.controller.spec.ts +268 -268
  313. package/src/_modules/server/errors/errors.controller.ts +515 -515
  314. package/src/_modules/server/errors/errors.data-service.spec.ts +480 -480
  315. package/src/_modules/server/index.ts +30 -30
  316. package/src/_modules/server/server-status/server-status-snapshot.control-service.spec.ts +70 -70
  317. package/src/_modules/server/server-status/server-status-snapshot.control-service.ts +17 -17
  318. package/src/_modules/server/server-status/server-status-snapshot.data-service.spec.ts +77 -77
  319. package/src/_modules/server/server-status/server-status-snapshot.data-service.ts +37 -37
  320. package/src/_modules/server/server-status/server-status.control-service.spec.ts +576 -576
  321. package/src/_modules/server/server-status/server-status.control-service.ts +396 -396
  322. package/src/_modules/server/server-status/server-status.controller.spec.ts +255 -255
  323. package/src/_modules/server/server-status/server-status.controller.ts +272 -272
  324. package/src/_modules/socket/_enums/socket-security.enum.ts +11 -11
  325. package/src/_modules/socket/_models/socket-client-service-params.control-model.spec.ts +32 -32
  326. package/src/_modules/socket/_models/socket-client-service-params.control-model.ts +22 -22
  327. package/src/_modules/socket/_models/socket-presence.control-model.spec.ts +164 -164
  328. package/src/_modules/socket/_models/socket-presence.control-model.ts +210 -210
  329. package/src/_modules/socket/_models/socket-server-service-params.control-model.spec.ts +46 -46
  330. package/src/_modules/socket/_models/socket-server-service-params.control-model.ts +22 -22
  331. package/src/_modules/socket/_services/socket-client.service.spec.ts +15 -15
  332. package/src/_modules/socket/_services/socket-client.service.ts +260 -260
  333. package/src/_modules/socket/_services/socket-server.service.spec.ts +11 -11
  334. package/src/_modules/socket/app-extended.integration.spec.ts +85 -85
  335. package/src/_modules/socket/app-extended.server.ts +630 -630
  336. package/src/_modules/socket/index.ts +42 -42
  337. package/src/_modules/test/get-test-routing-module.util.spec.ts +28 -28
  338. package/src/_modules/test/get-test-routing-module.util.ts +23 -23
  339. package/src/_modules/test/index.ts +11 -11
  340. package/src/_modules/test/test.controller.spec.ts +72 -72
  341. package/src/_modules/test/test.controller.ts +115 -115
  342. package/src/_modules/usage/get-usage-routing-module.util.ts +22 -22
  343. package/src/_modules/usage/index.ts +15 -15
  344. package/src/_modules/usage/usage.controller.spec.ts +81 -81
  345. package/src/_modules/usage/usage.controller.ts +126 -126
  346. package/src/_modules/usage/usage.data-service.spec.ts +332 -332
  347. package/src/_modules/usage/usage.data-service.ts +185 -185
  348. package/src/_services/base/api.service-base.spec.ts +125 -125
  349. package/src/_services/base/api.service-base.ts +74 -74
  350. package/src/_services/base/archive-data.service.spec.ts +209 -209
  351. package/src/_services/base/archive-data.service.ts +224 -224
  352. package/src/_services/base/data.service.spec.ts +729 -729
  353. package/src/_services/base/data.service.ts +2740 -2740
  354. package/src/_services/base/db.service.spec.ts +73 -73
  355. package/src/_services/base/db.service.ts +1575 -1575
  356. package/src/_services/base/singleton.service-base.spec.ts +28 -28
  357. package/src/_services/base/singleton.service-base.ts +24 -24
  358. package/src/_services/base/singleton.service.spec.ts +114 -114
  359. package/src/_services/base/singleton.service.ts +38 -38
  360. package/src/_services/core/api.service.spec.ts +140 -140
  361. package/src/_services/core/auth.service.spec.ts +159 -159
  362. package/src/_services/core/auth.service.ts +174 -174
  363. package/src/_services/core/email.service.spec.ts +85 -85
  364. package/src/_services/core/email.service.ts +742 -742
  365. package/src/_services/core/global.service.spec.ts +292 -292
  366. package/src/_services/core/global.service.ts +487 -487
  367. package/src/_services/core/memory-guard.service.spec.ts +245 -245
  368. package/src/_services/core/memory-guard.service.ts +481 -481
  369. package/src/_services/core/service-collection.service.spec.ts +46 -46
  370. package/src/_services/core/service-collection.service.ts +6 -6
  371. package/src/_services/route/controller.service.spec.ts +53 -53
  372. package/src/_services/route/controller.service.ts +148 -148
  373. package/src/_services/route/routing-module.service.spec.ts +98 -98
  374. package/src/_services/route/routing-module.service.ts +330 -330
  375. package/src/_services/server/app.server.ts +1941 -1912
  376. package/src/_services/shared.static-service.spec.ts +99 -99
  377. package/src/_services/shared.static-service.ts +78 -78
  378. package/src/index.ts +98 -96
  379. package/tsconfig.app.json +12 -12
  380. package/tsconfig.json +42 -42
  381. package/.dynamo/logs/cicd-pipeline/output.log +0 -2818
  382. package/.dynamo/logs/cicd-pipeline/status.json +0 -94
@@ -1,1912 +1,1941 @@
1
-
2
- import Mongoose = require('mongoose');
3
- import Express = require('express');
4
- /* import Mongoose from 'mongoose';
5
- import Express from 'express'; */
6
-
7
- import * as BodyParser from 'body-parser';
8
- import * as FileSystem from 'fs';
9
- import * as Http from 'http';
10
- import * as Https from 'https';
11
- import * as Path from 'path';
12
- import * as dotenv from 'dotenv'
13
-
14
- /* import { version } from '../../../package.json'; */
15
-
16
- import {
17
- DyFM_AnyError,
18
- DyFM_Array,
19
- DyFM_Async,
20
- DyFM_Error,
21
- DyFM_error_defaults,
22
- DyFM_Error_Settings,
23
- DyFM_ErrorLevel,
24
- DyFM_Log,
25
- DyFM_resolveRetentionTtlSeconds,
26
- megabyte,
27
- second
28
- } from '@futdevpro/fsm-dynamo';
29
-
30
- import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
- import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
- import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
- import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
34
- import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
35
- import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
36
- import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
37
- import {
38
- DyNTS_AppSystemControls
39
- } from '../../_models/control-models/app-system-controls.control-model';
40
- import {
41
- DyNTS_Endpoint_Params
42
- } from '../../_models/control-models/endpoint-params.control-model';
43
- import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
44
- import {
45
- DyNTS_Certification_Settings
46
- } from '../../_models/interfaces/certification-settings.interface';
47
- import {
48
- DyNTS_GlobalService_Settings
49
- } from '../../_models/interfaces/global-service-settings.interface';
50
- import {
51
- DyNTS_StaticClient_Settings
52
- } from '../../_models/interfaces/static-client-settings.interface';
53
- import {
54
- DyNTS_Cors_Settings
55
- } from '../../_models/interfaces/cors-settings.interface';
56
- import { DyNTS_DBService } from '../base/db.service';
57
- import { DyNTS_SingletonService } from '../base/singleton.service';
58
- import { DyNTS_GlobalService } from '../core/global.service';
59
- import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
60
- import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
61
- import { DyNTS_RoutingModule } from '../route/routing-module.service';
62
- import { DyNTS_getStarRoute } from '../../_collections/star.controller';
63
-
64
- /**
65
- *
66
- * function MyDecorator(config: any) {
67
- return function (target: Function) {
68
- // attach metadata or modify target
69
- target.prototype.myMeta = config;
70
- };
71
- }
72
-
73
- @MyDecorator({ role: 'admin' })
74
- class User {
75
- printRole() {
76
- console.log((this as any).myMeta.role); // → "admin"
77
- }
78
- }
79
-
80
- */
81
-
82
- /**
83
- * This will be the MAIN service of our server project,
84
- * follow the types and type instructions while setting up your project
85
- *
86
- * In this service, there are abstract functions that you will need to implement,
87
- * where you need to set up the main params for your application.
88
- *
89
- * (after the example, you can find the list of services you can/should setup)
90
- *
91
- * @example
92
- * export class App extends DyNTS_AppExtended {
93
- *
94
- * ...
95
- *
96
- * // Setting up App params, and preparing project global settings
97
- * setupAppParams(): void {
98
- * this.params = new DyNTS_AppParams({
99
- * name: 'Warbots Server',
100
- * title: warbotsTitleLog,
101
- * version: version,
102
- * dbName: 'warbots',
103
- * });
104
- *
105
- * // dynamoNTS_GlobalSettings.logRequestsContent = false;
106
- * }
107
- *
108
- * ...
109
- *
110
- * // Setting up DBServices
111
- * setGlobalServiceCollection(): void {
112
- * DyNTS_GlobalService.setServices({
113
- * authService: AuthService.getInstance(),
114
- * emailServiceCollection: EmailServiceCollectionService.getInstance(),
115
- * dbModels: [
116
- * userModelParams,
117
- * userDataModelParams,
118
- * userOptionsModelParams,
119
- * userStatisticsModelParams,
120
- * userAchievementsModelParams,
121
- * userNotificationsModelParams,
122
- *
123
- * matchStatisticsModelParams,
124
- * matchDataModelParams,
125
-
126
- * DyFM_usageSession_dataParams,
127
- * DyFM_customData_dataParams,
128
- * ]
129
- * });
130
- * }
131
- *
132
- * ...
133
- *
134
- * // Setting up Routes
135
- * setupRoutingModules(): void {
136
- * this.httpPort = env.port;
137
-
138
- * this.routingModules = [
139
- * new DyNTS_RoutingModule({
140
- * route: '/user',
141
- * controllers: [
142
- * UserController.getInstance(),
143
- * UserDataController.getInstance(),
144
- * UserOptionsController.getInstance(),
145
- * UserStatisticsController.getInstance(),
146
- * UserAchievementsController.getInstance(),
147
- * UserNotificationsController.getInstance()
148
- * ]
149
- * }),
150
- * new DyNTS_RoutingModule({
151
- * route: '/match',
152
- * controllers: [
153
- * MatchController.getInstance(),
154
- * MatchDistributionController.getInstance(),
155
- * MatchStatisticsController.getInstance(),
156
- * ]
157
- * }),
158
- * new DyNTS_RoutingModule({
159
- * route: '/server',
160
- * controllers: [
161
- * ServerController.getInstance(),
162
- * ]
163
- * }),
164
-
165
- * getTestRoutingModule(),
166
- * getUsageRoutingModule()
167
- * ];
168
- * }
169
- * }
170
- *
171
- * //
172
- * // The Services available
173
- * //
174
- * // Authentication Service
175
- * // A commonly used basic service,
176
- * // which is necessary fur certain functions (such as registering call issuers)
177
- * //
178
- * // This will handle Authentication Token checking/refreshing,
179
- * // checking issuer's identifier and routeParams,
180
- * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
181
- * //
182
- * // You can create one with this Dynamo Object:
183
- * //
184
- *
185
- * @example
186
- * // follow the instructions on the abstract class (DyNTS_AuthService)
187
- * export class AuthService extends DyNTS_AuthService {}
188
- *
189
- *
190
- *
191
- * //
192
- */
193
-
194
- /**
195
- * This will be the MAIN service of our server project,
196
- * follow the types and type instructions while setting up your project
197
- *
198
- * In this service, there are abstract functions that you will need to implement,
199
- * where you need to set up the main params for your application.
200
- *
201
- * (after the example, you can find the list of services you can/should setup)
202
- *
203
- * You need to setup the following functions:
204
- * ```ts
205
- * // this is where you set up the main params for your application
206
- * getAppParams(): DyNTS_AppParams
207
- *
208
- * // this is where you connect your main services
209
- * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
210
- *
211
- * // this is where you set up your ports
212
- * getPorts(): DyNTS_PortSettings
213
- *
214
- * // this is where you set up your routes
215
- * getRoutingModules(): DyNTS_RoutingModule[]
216
- *
217
- *
218
- *
219
- * ```
220
- * optionally you can setup the following functions:
221
- * ```ts
222
- * // this is where you set up your certifications
223
- * getCertificationSettings(): DyNTS_CertificationSettings
224
- *
225
- * // this is where you set up additional root services
226
- * getRootServices(): DyNTS_SingletonService[]
227
- *
228
- * // this is where you set up your initial db entries
229
- * createEntries(): void
230
- *
231
- * // this is where you can define post setup processes
232
- * postProcess(): void
233
- *
234
- *
235
- *
236
- * ```
237
- *
238
- */
239
-
240
- /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
241
- export interface DyNTS_TtlIndexInfo {
242
- name?: string;
243
- key?: Record<string, number>;
244
- expireAfterSeconds?: number;
245
- }
246
-
247
- /**
248
- * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
249
- * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
250
- * in unit tests.
251
- */
252
- export interface DyNTS_TtlIndexCollection {
253
- indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
254
- createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
255
- dropIndex?: (name: string) => Promise<unknown>;
256
- }
257
-
258
- /**
259
- * FR-258 / SR-2 — outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
260
- * - `created`: no `__created` TTL index existed → one was created.
261
- * - `noop`: an index with the SAME TTL already existed → nothing done.
262
- * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) left UNTOUCHED,
263
- * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
264
- * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
265
- * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
266
- * maintenance, not silently at every startup.
267
- */
268
- export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
269
-
270
- export abstract class DyNTS_App extends DyNTS_SingletonService {
271
-
272
- protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
273
- get started(): boolean {
274
- return this.systemControls.app.started;
275
- }
276
- protected get superStarted(): boolean {
277
- return this.systemControls.app.started;
278
- }
279
- protected constructErrors: (Error | DyFM_Error)[] = [];
280
-
281
- /* removed since cant use version from package.json
282
- private readonly _ntsVersion: string = 'v01.07.18';
283
- protected get ntsVersion(): string {
284
- return this._ntsVersion;
285
- } */
286
-
287
- get serverName(): string {
288
- return this.params.name;
289
- }
290
-
291
- private _params: DyNTS_App_Params;
292
- protected get params(): DyNTS_App_Params {
293
- return this._params;
294
- }
295
-
296
- protected mongoose = Mongoose;
297
-
298
- private _security: DyNTS_RouteSecurity;
299
- protected get security(): DyNTS_RouteSecurity {
300
- return this._security;
301
- }
302
-
303
- protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
304
- protected get portSettings(): DyNTS_Http_Settings {
305
- return this._portSettings;
306
- }
307
-
308
- private _cert?: DyNTS_Certification_Settings;
309
- protected get cert(): DyNTS_Certification_Settings {
310
- return this._cert;
311
- }
312
-
313
- protected openExpress: Express.Application;
314
- protected secureExpress: Express.Application;
315
- protected httpsServer: Https.Server;
316
- protected httpServer: Http.Server;
317
-
318
- private globalService: DyNTS_GlobalService;
319
- private _rootServices: DyNTS_SingletonService[] = [];
320
-
321
- private _routingModules: DyNTS_RoutingModule[] = [];
322
-
323
- protected readonly defaultReadyTimeout: number = 30 * second;
324
-
325
- override readonly defaultErrorUserMsg =
326
- `We encountered an unhandled Server Error, ` +
327
- `\nplease contact the responsible development team.` +
328
- `\n(Internal Server error)`;
329
-
330
- get logSetup(): boolean {
331
- return DyNTS_global_settings.log_settings.setup;
332
- }
333
- get deepLog(): boolean {
334
- return DyNTS_global_settings.log_settings.deep;
335
- }
336
- get fnLogs(): boolean {
337
- return DyNTS_global_settings.log_settings.functions;
338
- }
339
- debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
340
-
341
- constructor(/* extended?: boolean */){
342
- super();
343
-
344
- /* dotenv.config() */
345
-
346
- process.on(
347
- 'unhandledRejection',
348
- (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
349
- if (reason_theError instanceof DyFM_Error) {
350
- reason_theError.logSimple('Unhandled Rejection');
351
- } else {
352
- DyFM_Log.H_error(
353
- 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
354
- '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
355
- /* '\n ErrorCode:', (reason as any)?.code, */
356
- '\n\n Stack:',
357
- (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
358
- );
359
- }
360
-
361
- try {
362
- DyNTS_GlobalService.globalErrorHandler?.(
363
- new DyFM_Error({
364
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
365
- message:
366
- `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
367
- userMessage: this.defaultErrorUserMsg,
368
- addECToUserMsg: true,
369
- error: reason_theError as Error,
370
- additionalContent: {
371
- reason: reason_theError,
372
- rejectedPromise: p_passWhatIsThis_maybeThePromise,
373
- },
374
- systemVersion: DyNTS_global_settings.systemVersion,
375
- level: DyFM_ErrorLevel.critical,
376
- })
377
- );
378
- } catch (error) {
379
- DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
380
- }
381
- }
382
- );
383
-
384
- this.asyncConstruct(/* extended */).catch((error: any): void => {
385
- if (error instanceof DyFM_Error) {
386
- if (error.additionalContent?.constructErrors?.length) {
387
- error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
388
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
389
- /* if (errorItem instanceof DyFM_Error) {
390
- errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
391
- } else {
392
- DyFM_Log.H_warn(
393
- '(constructor asyncConstruct.catch) additional error content:\n',
394
- errorItem
395
- );
396
- } */
397
- });
398
- } else {
399
- DyFM_Log.H_warn(
400
- '(constructor asyncConstruct.catch) additional error content:\n',
401
- error?.additionalContent
402
- );
403
- }
404
- }
405
-
406
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
407
- /* if (
408
- !DyNTS_global_settings.log_settings.highDetailedLogs &&
409
- (error instanceof DyFM_Error)
410
- ) {
411
- error.logSimple(
412
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
413
- '\n all error messages (from this stack):\n\n"' +
414
- error._messages.join('"\n\n"') + '"\n\n'
415
- );
416
- } else if (error instanceof DyFM_Error) {
417
- DyFM_Log.H_error(
418
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
419
- `\n ERROR:`, error
420
- );
421
- } */
422
-
423
- const message: string =
424
- (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
425
- (errorItem: DyFM_Error): string[] => {
426
- return errorItem?._messages ?? [];
427
- }
428
- )?.join?.('\n') ??
429
- (error as DyFM_Error)?.errors?.flatMap(
430
- (errorItem: DyFM_AnyError): string[] =>
431
- (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
432
- )?.join?.('\n') ??
433
- error?.message ??
434
- 'UNKNOWN';
435
-
436
- DyFM_Log.testError('Application start failed:\n', message);
437
-
438
- process.exit(1);
439
- });
440
- }
441
-
442
- protected async asyncConstruct(extended?: boolean): Promise<void> {
443
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
444
-
445
- try {
446
- this.systemControls.app.init = true;
447
- this._params = this.getAppParams();
448
- DyFM_Log.log(
449
- `\n\n\n\n\n\n\n\n\n\n` +
450
- `Starting ${this._params?.name}... ` +
451
- /* `v${version}` + */
452
- `\n\n\n\n\n\n\n\n\n\n`
453
- );
454
-
455
- if (!this._params) {
456
- throw new Error('getAppParams() must return a DyNTS_AppParams object!');
457
- }
458
-
459
- if (this.params.systemShortCodeName) {
460
- DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
461
- }
462
-
463
- if (this.params.systemName) {
464
- DyNTS_global_settings.systemName = this.params.systemName;
465
- DyFM_error_defaults.issuerSystem = this.params.systemName;
466
- }
467
-
468
- if (this.params.version) {
469
- DyNTS_global_settings.systemVersion = this.params.version;
470
- DyFM_error_defaults.systemVersion = this.params.version;
471
- }
472
-
473
- process.stdout.write(
474
- String.fromCharCode(27) + ']0;' +
475
- this._params?.name +
476
- String.fromCharCode(7)
477
- );
478
-
479
- DyFM_error_defaults.issuerSystem = this._params.systemName;
480
-
481
- this.overrideDynamoNTSGlobalSettings?.();
482
-
483
- if (DyNTS_global_settings.log_settings.setup) {
484
- DyFM_Log.S_info(`env settings;\n`, {
485
- systemName: DyNTS_global_settings.systemName,
486
- systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
487
- systemVersion: DyNTS_global_settings.systemVersion,
488
- environment: DyNTS_global_settings.env_settings.environment,
489
- /* log_settings: DyNTS_global_settings.log_settings,
490
- env_settings: DyNTS_global_settings.env_settings, */
491
- });
492
- }
493
-
494
- this.globalService = DyNTS_GlobalService.getInstance();
495
- await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
496
- DyNTS_GlobalService.setParams(this.params);
497
-
498
- if (this.getPortSettings) {
499
- this._portSettings = this.getPortSettings();
500
- }
501
-
502
- if (this.getCertificationSettings) {
503
- this._cert = this.getCertificationSettings();
504
- }
505
-
506
- if (this.getApiBasePath) {
507
- DyNTS_global_settings.baseUrl = this.getApiBasePath();
508
- }
509
-
510
- if (this.getRoutingModules) {
511
- this._routingModules = this.getRoutingModules();
512
-
513
- // ezt egyelőre csak tesztelem, nem kerül be
514
- /* if (
515
- !DyNTS_global_settings.dontCreateDefaultRoute &&
516
- !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
517
- ) {
518
- this._routingModules.push(
519
- DyNTS_getStarRoute()
520
- );
521
- } */
522
- }
523
-
524
- if (this._params.dbUri) {
525
- await this.startDB();
526
-
527
- // createEntries csak akkor fut, ha a DB tényleg fel-jött.
528
- // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
529
- // és nem próbálunk meg írni egy nem létező kapcsolatra.
530
- if (this.createEntries && this.systemControls.mongoose.started) {
531
- await this.createEntries();
532
- }
533
- } else {
534
- DyFM_Log.log(
535
- `\nNo database connection created.`,
536
- );
537
- }
538
-
539
- if (this._routingModules?.length) {
540
- if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
541
-
542
- this.setSecurity();
543
-
544
- await this.initExpresses();
545
- await this.startExpresses();
546
-
547
- if (this._security !== DyNTS_RouteSecurity.secure) {
548
- await this.mountOpenRoutes();
549
- }
550
-
551
- if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
552
- await this.mountSecureRoutes();
553
- }
554
-
555
- // Generikus, auth-agnosztikus extension-point: custom middleware az API
556
- // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
557
- await this.mountCustomMiddleware();
558
-
559
- await this.mountStaticClient();
560
-
561
- if (this.logSetup) {
562
- DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
563
- }
564
- } else {
565
- DyFM_Log.warn(
566
- `\nNo routes mounted!`,
567
- );
568
- }
569
-
570
- if (this.getRootServices) {
571
- this._rootServices = await this.getRootServices();
572
- }
573
-
574
- if (this.postProcess) {
575
- await this.postProcess().catch((error: any): void => {
576
- DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
577
- DyNTS_GlobalService.globalErrorHandler?.(error);
578
- });
579
- }
580
-
581
- // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
582
- // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
583
- // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
584
- // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
585
- try {
586
- if (DyNTS_global_settings.memoryGuard?.enabled) {
587
- DyNTS_MemoryGuard.getInstance().install();
588
- }
589
- } catch (memoryGuardError: unknown) {
590
- DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
591
- }
592
-
593
- // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
594
- // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
595
- // OOM. Default-on, observation-only, never throws.
596
- try {
597
- if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
598
- DyNTS_CollectionGrowthMonitor.getInstance().install();
599
- }
600
- } catch (cgmError: unknown) {
601
- DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
602
- }
603
-
604
- if (!extended) {
605
- await this.ready();
606
-
607
- if (this.params.title) {
608
- DyFM_Log.success(this.params.title);
609
- }
610
- DyFM_Log.info(`Version: ${this.params.version}`);
611
- /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
612
- DyFM_Log.H_success(`${this.params.name} started successfully.`);
613
- }
614
- } catch (error) {
615
- this.constructErrors.push(error);
616
-
617
- if (this.deepLog) {
618
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
619
- DyFM_Log.H_error(
620
- `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
621
- `\n\n construct ERRORS:`, this.constructErrors,
622
- '\n\nlast error:', error
623
- );
624
- } else {
625
- DyFM_Log.H_error(
626
- `"${this._params.name}" start failed (in asyncConstruct). `,
627
- `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
628
- '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
629
- );
630
- }
631
- }
632
-
633
- throw new DyFM_Error({
634
- ...this._getDefaultErrorSettings('asyncConstruct', error),
635
-
636
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
637
- additionalContent: {
638
- constructErrors: this.constructErrors,
639
- systemControls: this.systemControls,
640
- systemReadies: {
641
- app: this.systemControls.app.getIsReady(),
642
- mongoose: this.systemControls.mongoose.getIsReady(),
643
- httpServer: this.systemControls.httpServer.getIsReady(),
644
- httpsServer: this.systemControls.httpsServer.getIsReady(),
645
- },
646
- },
647
- });
648
- }
649
- }
650
-
651
- async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
652
- try {
653
- if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
654
-
655
- await DyFM_Async.delay(100);
656
-
657
- let ready: boolean = false;
658
- const start: number = +new Date();
659
-
660
- if (this.constructErrors.length) {
661
- if (this.deepLog) {
662
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
663
- DyFM_Log.H_error(
664
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
665
- `\n construct ERRORS:`, this.constructErrors
666
- );
667
- } else {
668
- DyFM_Log.H_error(
669
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
670
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
671
- );
672
- }
673
- }
674
-
675
- throw new DyFM_Error({
676
- ...this._getDefaultErrorSettings(
677
- 'ready',
678
- new Error(`"${this._params.name}" start failed.`)
679
- ),
680
-
681
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
682
- additionalContent:
683
- this.constructErrors.length === 1 ?
684
- { error: this.constructErrors[0] } :
685
- { errors: this.constructErrors },
686
- });
687
- }
688
-
689
- while (!ready && +new Date() - start < timeout) {
690
- if (this.systemControls.app.init) {
691
- ready = (
692
- this.systemControls.mongoose.getIsReady() &&
693
- this.systemControls.httpServer.getIsReady() &&
694
- this.systemControls.httpsServer.getIsReady()
695
- );
696
- } else {
697
- DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
698
- }
699
-
700
- if (!ready) {
701
- await DyFM_Async.wait(100);
702
- }
703
- }
704
-
705
- if (timeout < +new Date() - start) {
706
- if (this.deepLog) {
707
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
708
- DyFM_Log.H_error(
709
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
710
- `\n construct ERRORS:`, this.constructErrors
711
- );
712
- } else {
713
- DyFM_Log.H_error(
714
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
715
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
716
- );
717
- }
718
- }
719
-
720
- throw new DyFM_Error({
721
- ...this._getDefaultErrorSettings(
722
- 'ready',
723
- new Error(`"${this._params.name}" start failed. TIMEOUT`)
724
- ),
725
-
726
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
727
- additionalContent: {
728
- constructErrors: this.constructErrors,
729
- systemControls: this.systemControls,
730
- systemReadies: {
731
- mongoose: this.systemControls.mongoose.getIsReady(),
732
- httpServer: this.systemControls.httpServer.getIsReady(),
733
- httpsServer: this.systemControls.httpsServer.getIsReady(),
734
- },
735
- },
736
- });
737
- }
738
-
739
- if (this.constructErrors.length) {
740
- if (this.deepLog) {
741
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
742
- DyFM_Log.H_error(
743
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
744
- `\n construct ERRORS:`, this.constructErrors
745
- );
746
- } else {
747
- DyFM_Log.H_error(
748
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
749
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
750
- );
751
- }
752
- }
753
-
754
- throw new DyFM_Error({
755
- ...this._getDefaultErrorSettings(
756
- 'ready',
757
- new Error(`"${this._params.name}" start failed.`)
758
- ),
759
-
760
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
761
- additionalContent: this.constructErrors,
762
- });
763
- }
764
-
765
- if (ready) {
766
- this.systemControls.app.started = true;
767
-
768
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
769
-
770
- return;
771
- }
772
-
773
- this.systemControls.app.started = false;
774
-
775
- let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
776
-
777
- if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
778
- msg += `\nMongoose start failed.`;
779
- }
780
-
781
- if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
782
- msg += `\nHTTP Server start failed.`;
783
- }
784
-
785
- if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
786
- msg += `\nHTTPS Server start failed.`;
787
- }
788
-
789
- DyFM_Log.error(msg, this.constructErrors);
790
-
791
- throw new DyFM_Error({
792
- ...this._getDefaultErrorSettings('ready', new Error(msg)),
793
-
794
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
795
- additionalContent: {
796
- constructErrors: this.constructErrors,
797
- systemControls: this.systemControls,
798
- systemReadies: {
799
- app: this.systemControls.app.getIsReady(),
800
- mongoose: this.systemControls.mongoose.getIsReady(),
801
- httpServer: this.systemControls.httpServer.getIsReady(),
802
- httpsServer: this.systemControls.httpsServer.getIsReady(),
803
- },
804
- },
805
- error: this.constructErrors?.[0] ?? new Error(),
806
- });
807
- } catch (error) {
808
- throw new DyFM_Error({
809
- ...this._getDefaultErrorSettings('ready', error),
810
-
811
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
812
- });
813
- }
814
- }
815
-
816
- protected getSimplifiedConstructErrors(): string[] {
817
- return this.constructErrors.map((error: any): any => {
818
- if (error instanceof DyFM_Error) {
819
- return error.getErrorSimplified();
820
- } else {
821
- return error;
822
- }
823
- });
824
- }
825
-
826
- async stop(dontLog?: boolean): Promise<void> {
827
- try {
828
- DyFM_Log.info('\nstopping server...\n');
829
-
830
- await this.ready();
831
-
832
- if (this.started) {
833
-
834
- if (this.systemControls.mongoose.init) {
835
- DyFM_Log.info(`\nstopping Mongoose....`);
836
-
837
- let tryCount: number = 0;
838
-
839
- while (
840
- !this.systemControls.mongoose.started &&
841
- !this.constructErrors.length &&
842
- tryCount++ < 10
843
- ) {
844
- DyFM_Log.warn(`Mongoose not even started yet....`);
845
- await DyFM_Async.wait(second);
846
- }
847
- this.systemControls.mongoose.started = false;
848
-
849
- if (this.mongoose) {
850
- await DyFM_Array.asyncForEach(
851
- Object.keys(this.mongoose.models),
852
- async (modelName): Promise<void> => {
853
- this.mongoose.deleteModel(modelName);
854
- }
855
- );
856
-
857
- const disconnect: Promise<void> = new Promise((resolve): void => {
858
- this.mongoose.connection.on('disconnecting', (): void => {
859
- resolve();
860
- });
861
- });
862
-
863
- await this.mongoose.disconnect();
864
- await this.mongoose.connection.close();
865
- await disconnect;
866
-
867
- this.mongoose.connection.removeAllListeners();
868
-
869
- while (
870
- this.mongoose.connection.readyState !== 0 &&
871
- !this.constructErrors.length
872
- ) {
873
- DyFM_Log.warn(`\nMongoose still not disconnected....`);
874
- await DyFM_Async.wait(second);
875
- }
876
- } else {
877
- DyFM_Log.error(`\nMongoose not found.`);
878
- }
879
- this.systemControls.mongoose.init = false;
880
- }
881
-
882
- if (this.systemControls.httpServer.init) {
883
- this.systemControls.httpServer.started = false;
884
-
885
- if (this.httpServer) {
886
- await new Promise((resolve): void => {
887
- this.httpServer.close(resolve);
888
- });
889
- } else {
890
- DyFM_Log.error(`\nHTTP Server not found.`);
891
- }
892
- this.systemControls.httpServer.init = false;
893
- }
894
-
895
- if (this.systemControls.httpsServer.init) {
896
- this.systemControls.httpsServer.started = false;
897
-
898
- if (this.httpsServer) {
899
- await new Promise((resolve): void => {
900
- this.httpsServer.close(resolve);
901
- });
902
- } else {
903
- DyFM_Log.error(`\nHTTPS Server not found.`);
904
- }
905
- this.systemControls.httpsServer.init = false;
906
- }
907
-
908
- await DyFM_Async.wait(second);
909
-
910
- if (!dontLog) {
911
- DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
912
- }
913
- }
914
- } catch (error) {
915
- throw new DyFM_Error({
916
- ...this._getDefaultErrorSettings('stop', error),
917
-
918
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
919
- });
920
- }
921
- }
922
-
923
- /**
924
- *
925
- */
926
- private async startDB(): Promise<void> {
927
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
928
- else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
929
-
930
- if (!this._params.dbUri) {
931
- throw new DyFM_Error({
932
- ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
933
-
934
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
935
- });
936
- }
937
-
938
- if (!this._params.dbOptions) {
939
- throw new DyFM_Error({
940
- ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
941
-
942
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
943
- });
944
- }
945
-
946
- if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
947
- throw new DyFM_Error({
948
- ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
949
-
950
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
951
- });
952
- }
953
-
954
- try {
955
- await new Promise<void>(
956
- (resolve, reject): void => {
957
- this.systemControls.mongoose.init = true;
958
-
959
- this.mongoose.connection
960
- .once('open', (): void => {
961
- this.systemControls.mongoose.started = true;
962
- DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
963
-
964
- resolve();
965
-
966
- // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
967
- // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
968
- // compete with boot-readiness. We delay it well past the deploy health-probe window so a
969
- // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
970
- // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
971
- // rebuilds a live index see ensureRetentionTtlIndex.)
972
- const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
973
- void this.installRetentionTtlIndexes();
974
- }, 30000);
975
- if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
976
- })
977
- .on('error', (error): void => {
978
- if (!this.systemControls.mongoose.started) {
979
- // Initial DB-csatlakozás sikertelen:
980
- // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
981
- // App startup-ot (nincs constructErrors push, nincs reject).
982
- // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
983
- // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
984
- // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
985
- this.systemControls.mongoose.init = false;
986
-
987
- const d_error: DyFM_Error = new DyFM_Error({
988
- ...this._getDefaultErrorSettings('startDB', error),
989
-
990
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
991
- message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
992
- `ERROR: ${error}`,
993
- level: DyFM_ErrorLevel.serious,
994
- });
995
-
996
- DyFM_Log.H_error(
997
- `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
998
- `\nServer will continue WITHOUT DB connection.` +
999
- `\nDB-using endpoints will fail at runtime until connection recovers.`
1000
- );
1001
-
1002
- if (this.debugLog) DyFM_Log.S_error(
1003
- `\nMongoDB connect ERROR: `,
1004
- error
1005
- );
1006
-
1007
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1008
-
1009
- resolve();
1010
-
1011
- } else {
1012
- if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1013
-
1014
- const d_error: DyFM_Error = new DyFM_Error({
1015
- ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1016
-
1017
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1018
- message: `MongoDB ERROR: ${error}`,
1019
- level: DyFM_ErrorLevel.critical,
1020
- });
1021
-
1022
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1023
- }
1024
- });
1025
-
1026
- try {
1027
- this.mongoose.connect(
1028
- this._params.dbUri,
1029
- this._params.dbOptions
1030
- /* {
1031
- directConnection: true,
1032
- } */
1033
- );
1034
- } catch (error) {
1035
- throw new DyFM_Error({
1036
- ...this._getDefaultErrorSettings('startDB', error),
1037
-
1038
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1039
- });
1040
- }
1041
- }
1042
- );
1043
- } catch (error) {
1044
- throw new DyFM_Error({
1045
- ...this._getDefaultErrorSettings('startDB', error),
1046
-
1047
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1048
- });
1049
- }
1050
-
1051
- // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1052
- // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1053
- // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1054
- // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1055
- // grace-e UTÁN TELJES disconnect()+connect()-et csinál ÚJ MongoClient ÚJ DNS-resolve
1056
- // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1057
- // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1058
- try {
1059
- startMongoReconnectGuard({
1060
- getReadyState: (): number => this.mongoose.connection.readyState,
1061
- reconnect: async (): Promise<void> => {
1062
- await this.mongoose.disconnect().catch((): void => undefined);
1063
- await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1064
- },
1065
- log: (msg: string): void => DyFM_Log.warn(msg),
1066
- });
1067
- } catch (guardErr) {
1068
- DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1069
- }
1070
- }
1071
-
1072
- /**
1073
- * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1074
- *
1075
- * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1076
- * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1077
- * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1078
- * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1079
- * against the unbounded-collection-growth in-memory-load GC-thrash/OOM class.
1080
- *
1081
- * Guarantees:
1082
- * - **Non-fatal** any error is logged but NEVER blocks startup (called fire-and-forget).
1083
- * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1084
- * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1085
- * (the field index is restored immediately, so query coverage is preserved).
1086
- */
1087
- private async installRetentionTtlIndexes(): Promise<void> {
1088
- try {
1089
- const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1090
- let ensured: number = 0;
1091
-
1092
- for (const service of services) {
1093
- const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1094
- if (!ttlSeconds) { continue; }
1095
-
1096
- const dataName: string = service.dataParams.dataName;
1097
- // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1098
- const collection: DyNTS_TtlIndexCollection | undefined =
1099
- (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1100
- if (!collection || typeof collection.createIndex !== 'function') { continue; }
1101
-
1102
- try {
1103
- const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1104
- if (action === 'created') {
1105
- ensured++;
1106
- if (this.logSetup) {
1107
- DyFM_Log.success(
1108
- `[FR-258 retention] TTL index created on "${dataName}" — ` +
1109
- `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1110
- );
1111
- }
1112
- } else if (action === 'differs') {
1113
- // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1114
- DyFM_Log.warn(
1115
- `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1116
- `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1117
- `Apply the change via maintenance if intended.`,
1118
- );
1119
- }
1120
- } catch (idxErr: unknown) {
1121
- DyFM_Log.warn(
1122
- `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1123
- `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1124
- );
1125
- }
1126
- }
1127
-
1128
- if (ensured > 0) {
1129
- DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1130
- }
1131
- } catch (err: unknown) {
1132
- DyFM_Log.warn(
1133
- `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1134
- `${err instanceof Error ? err.message : String(err)}`,
1135
- );
1136
- }
1137
- }
1138
-
1139
- /**
1140
- * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1141
- * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1142
- * - no existing `__created` index → create it → `'created'`
1143
- * - existing with the SAME TTL no-op → `'noop'`
1144
- * - existing with a DIFFERENT TTL / non-TTL leave it as-is `'differs'` (warn only NO drop+recreate)
1145
- *
1146
- * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1147
- * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1148
- * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1149
- * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1150
- * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1151
- */
1152
- static async ensureRetentionTtlIndex(
1153
- collection: DyNTS_TtlIndexCollection,
1154
- ttlSeconds: number,
1155
- ): Promise<DyNTS_TtlIndexAction> {
1156
- const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1157
- ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1158
- : [];
1159
- const existing: DyNTS_TtlIndexInfo | undefined =
1160
- existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1161
-
1162
- if (!existing) {
1163
- await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1164
- return 'created';
1165
- }
1166
- if (existing.expireAfterSeconds === ttlSeconds) {
1167
- return 'noop';
1168
- }
1169
- // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1170
- // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1171
- return 'differs';
1172
- }
1173
-
1174
- /**
1175
- *
1176
- */
1177
- private async initExpresses(): Promise<void> {
1178
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1179
-
1180
- try {
1181
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1182
- if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1183
- let errorMsg: string =
1184
- `\nYou have open routes, but httpPort is not set!` +
1185
- `\nThere are ${this._routingModules.filter(
1186
- m => m.security != DyNTS_RouteSecurity.secure
1187
- ).length} open/both routes` +
1188
- `\nroot security: ${this._security}` +
1189
- `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1190
-
1191
- errorMsg += '\n\nThe routes setted to use open server:';
1192
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1193
- if (module.security != DyNTS_RouteSecurity.secure) {
1194
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1195
- errorMsg += `\n subroutes using open sever:`;
1196
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1197
- if (endpoint.security != DyNTS_RouteSecurity.secure) {
1198
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1199
- }
1200
- });
1201
- }
1202
- });
1203
-
1204
- const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1205
- const errorStack: string[] = error.stack.split('\n');
1206
-
1207
- errorStack.splice(1, 2);
1208
- error.stack = errorStack.join('\n');
1209
-
1210
- DyFM_Log.error(errorMsg);
1211
-
1212
- throw error;
1213
- }
1214
-
1215
- await this.initOpenExpress();
1216
- }
1217
-
1218
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1219
- if (!this._cert || !this._portSettings.httpsPort) {
1220
- let errorMsg: string =
1221
- `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1222
- `\nThere are ${this._routingModules.filter(
1223
- m => m.security && m.security !== DyNTS_RouteSecurity.open
1224
- ).length} secure routes` +
1225
- `\nroot security: ${this._security}` +
1226
- `\nset...` +
1227
- `\n(missing exact howto...)` +
1228
- /* `\n httpsPort and` +
1229
- `\n cert: {` +
1230
- `\n keyPath: FileSystem.PathLike,` +
1231
- `\n certPath: FileSystem.PathLike,` +
1232
- `\n }` + */
1233
- `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1234
-
1235
- errorMsg += '\n\nThe routes setted to use secure server:';
1236
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1237
- if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1238
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1239
- errorMsg += `\n location: ${module.stackLocation}`;
1240
- errorMsg += `\n subroutes using secure sever:`;
1241
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1242
- if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1243
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1244
- errorMsg += `\n location: ${endpoint.stackLocation}`;
1245
- }
1246
- });
1247
- }
1248
- });
1249
-
1250
- const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1251
- const errorStack: string[] = error.stack.split('\n');
1252
-
1253
- errorStack.splice(1, 2);
1254
- error.stack = errorStack.join('\n');
1255
-
1256
- DyFM_Log.error(errorMsg);
1257
-
1258
- throw error;
1259
- }
1260
-
1261
- await this.initSecureExpress();
1262
- }
1263
- } catch (error) {
1264
- throw new DyFM_Error({
1265
- ...this._getDefaultErrorSettings('initExpresses', error),
1266
-
1267
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1268
- });
1269
- }
1270
- }
1271
-
1272
- /**
1273
- *
1274
- */
1275
- protected async initOpenExpress(): Promise<void> {
1276
- if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1277
- this.openExpress = Express();
1278
- this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1279
- this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1280
- this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1281
- // FR-041 CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1282
- this.mountCors(this.openExpress);
1283
- }
1284
-
1285
- /**
1286
- *
1287
- */
1288
- protected async initSecureExpress(): Promise<void> {
1289
- if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1290
- this.secureExpress = Express();
1291
- this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1292
- this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1293
- // FR-041 — CORS allowlist enforcement (same as open express).
1294
- this.mountCors(this.secureExpress);
1295
-
1296
- const options = {
1297
- key: FileSystem.readFileSync(this._cert.keyPath),
1298
- cert: FileSystem.readFileSync(this._cert.certPath),
1299
- maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1300
- };
1301
-
1302
- this.httpsServer = Https.createServer(options, this.secureExpress);
1303
- }
1304
-
1305
- /**
1306
- *
1307
- */
1308
- private async startExpresses(): Promise<void> {
1309
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1310
-
1311
- try {
1312
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1313
- await new Promise<void>((resolve, reject): void => {
1314
- this.systemControls.httpsServer.init = true;
1315
- this.httpsServer
1316
- .listen(
1317
- this._portSettings.httpsPort,
1318
- this.params.secureHost,
1319
- this.params.expressBacklog,
1320
- (): void => {
1321
- this.systemControls.httpsServer.started = true;
1322
- DyFM_Log.success(
1323
- `\nHTTPS (secure) server is listening on port: ` +
1324
- `${this.params.secureHost}:${this._portSettings.httpsPort}`
1325
- );
1326
-
1327
- resolve();
1328
- })
1329
- .on('error', (error): void => {
1330
- if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1331
-
1332
- if (!this.systemControls.httpsServer.started) {
1333
- const d_error: DyFM_Error = new DyFM_Error({
1334
- ...this._getDefaultErrorSettings('startExpresses', error),
1335
-
1336
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1337
- message: `HTTPS (secure) start server ERROR`,
1338
- });
1339
-
1340
- this.constructErrors.push(d_error);
1341
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1342
-
1343
- reject(d_error);
1344
-
1345
- } else {
1346
- const d_error: DyFM_Error = new DyFM_Error({
1347
- ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1348
-
1349
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1350
- message: `HTTPS (secure) server ERROR`,
1351
- level: DyFM_ErrorLevel.serious,
1352
- });
1353
-
1354
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1355
- }
1356
- })
1357
- .on('uncaughtException', (exception): void => {
1358
- const d_error: DyFM_Error = new DyFM_Error({
1359
- ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1360
-
1361
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1362
- message: `HTTPS (secure) server uncaughtException`,
1363
- level: DyFM_ErrorLevel.critical,
1364
- });
1365
-
1366
- if (this.debugLog) DyFM_Log.warn(
1367
- `\nHTTPS (secure) server uncaughtException`,
1368
- d_error
1369
- );
1370
-
1371
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1372
- });
1373
- });
1374
- }
1375
-
1376
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1377
- this.systemControls.httpServer.init = true;
1378
- await new Promise<void>((resolve, reject): void => {
1379
- this.httpServer = this.openExpress
1380
- .listen(
1381
- this._portSettings.httpPort,
1382
- this.params.openHost,
1383
- this.params.expressBacklog,
1384
- (): void => {
1385
- this.systemControls.httpServer.started = true;
1386
-
1387
- const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1388
-
1389
- if (this._portSettings.httpPort === 0) {
1390
- DyFM_Log.H_warn(
1391
- `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1392
- `\n (httpPort was set to 0 — this is intended for testing only)`
1393
- );
1394
- }
1395
-
1396
- DyFM_Log.success(
1397
- `\nHTTP (open) server is listening on port: ` +
1398
- `${this.params.openHost}:${resolvedPort}`
1399
- );
1400
-
1401
- resolve();
1402
- }
1403
- )
1404
- .on('error', (error): void => {
1405
- if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1406
-
1407
- if (!this.systemControls.httpServer.started) {
1408
- const d_error: DyFM_Error = new DyFM_Error({
1409
- ...this._getDefaultErrorSettings('startExpresses', error),
1410
-
1411
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1412
- message: `HTTP (open) start server ERROR`,
1413
- });
1414
-
1415
- this.constructErrors.push(d_error);
1416
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1417
-
1418
- reject(d_error);
1419
-
1420
- } else {
1421
- const d_error: DyFM_Error = new DyFM_Error({
1422
- ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1423
-
1424
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1425
- message: `HTTP (open) server ERROR`,
1426
- level: DyFM_ErrorLevel.serious,
1427
- });
1428
-
1429
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1430
- }
1431
- })
1432
- .on('uncaughtException', (exception): void => {
1433
- const d_error: DyFM_Error = new DyFM_Error({
1434
- ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1435
-
1436
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1437
- message: `HTTP (open) server uncaughtException`,
1438
- level: DyFM_ErrorLevel.critical,
1439
- });
1440
-
1441
- if (this.debugLog) {
1442
- DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1443
- }
1444
-
1445
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1446
- });
1447
- });
1448
- }
1449
- } catch (error) {
1450
- throw new DyFM_Error({
1451
- ...this._getDefaultErrorSettings('startExpresses', error),
1452
-
1453
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1454
- });
1455
- }
1456
- }
1457
-
1458
- /**
1459
- *
1460
- */
1461
- private async expressErrorHandling(error, req, res, next): Promise<void> {
1462
- try {
1463
- if (error) {
1464
- const d_error: DyFM_Error = new DyFM_Error({
1465
- ...this._getDefaultErrorSettings('expressErrorHandling', error),
1466
-
1467
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1468
- message: `Express ERROR`,
1469
- additionalContent: {
1470
- req,
1471
- res,
1472
- },
1473
- level: DyFM_ErrorLevel.error,
1474
- });
1475
-
1476
- await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1477
-
1478
- res.send(error)
1479
- } else {
1480
- DyFM_Log.H_error(
1481
- 'WTF??? express error; without error?...' +
1482
- '\nerr:', error,
1483
- '\nreq:', req,
1484
- '\nres:', res
1485
- );
1486
- }
1487
- } catch (error) {
1488
- DyFM_Log.H_error(
1489
- 'MULTILEVEL ERROR (expressErrorHandling)....' +
1490
- '\n', error
1491
- );
1492
- }
1493
- }
1494
-
1495
- /**
1496
- *
1497
- */
1498
- private async mountSecureRoutes (): Promise<void> {
1499
- try {
1500
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1501
-
1502
- if (!this.secureExpress) {
1503
- throw new Error(
1504
- 'secureExpress was not initialized. ' +
1505
- 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1506
- '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1507
- '\n\nYou need to set cert files in getCertificationSettings.'
1508
- );
1509
- }
1510
-
1511
- this.secureExpress.use(
1512
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1513
- );
1514
-
1515
- await DyFM_Array.asyncForEach(
1516
- this._routingModules,
1517
- async (module: DyNTS_RoutingModule): Promise<void> => {
1518
- if (module.security !== DyNTS_RouteSecurity.open) {
1519
- if (this.logSetup) {
1520
- DyFM_Log.log(`route mount (secure): ${module.route}`);
1521
- }
1522
-
1523
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1524
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1525
- );
1526
-
1527
- if (1 < existingRoutes.length) {
1528
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1529
- /* const errorStack: string[] = error.stack.split('\n');
1530
-
1531
- errorStack.splice(1, 4);
1532
- error.stack = errorStack.join('\n'); */
1533
- error.stack = module.stackLocation;
1534
-
1535
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1536
-
1537
- throw new DyFM_Error({
1538
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1539
-
1540
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1541
- message: `ROUTE DUPLICATION: ${module.route}`,
1542
- });
1543
- }
1544
-
1545
- this.secureExpress.use(module.route, module.secureRouter);
1546
- }
1547
- }
1548
- );
1549
- } catch (error) {
1550
- throw new DyFM_Error({
1551
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1552
-
1553
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1554
- });
1555
- }
1556
- }
1557
-
1558
- /**
1559
- *
1560
- */
1561
- private async mountOpenRoutes(): Promise<void> {
1562
- try {
1563
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1564
-
1565
- if (!this.openExpress) {
1566
- throw new Error(
1567
- 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1568
- '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1569
- );
1570
- }
1571
-
1572
- this.openExpress.use(
1573
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1574
- );
1575
-
1576
- await DyFM_Array.asyncForEach(
1577
- this._routingModules,
1578
- async (module: DyNTS_RoutingModule): Promise<void> => {
1579
- if (module.security !== DyNTS_RouteSecurity.secure) {
1580
- if (this.logSetup) {
1581
- DyFM_Log.log(`route mount (open): ${module.route}`);
1582
- }
1583
-
1584
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1585
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1586
- );
1587
-
1588
- if (1 < existingRoutes.length) {
1589
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1590
- /* const errorStack: string[] = error.stack.split('\n');
1591
-
1592
- errorStack.splice(1, 4);
1593
- error.stack = errorStack.join('\n'); */
1594
- error.stack = module.stackLocation;
1595
-
1596
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1597
-
1598
- throw new DyFM_Error({
1599
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1600
-
1601
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1602
- message: `ROUTE DUPLICATION: ${module.route}`,
1603
- });
1604
- }
1605
-
1606
- this.openExpress.use(module.route, module.openRouter);
1607
- }
1608
- }
1609
- );
1610
- } catch (error) {
1611
- throw new DyFM_Error({
1612
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1613
-
1614
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1615
- });
1616
- }
1617
- }
1618
-
1619
- /**
1620
- * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1621
- * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1622
- * adds the canonical `Access-Control-*` companion headers, and short-circuits
1623
- * the OPTIONS preflight with a 204.
1624
- *
1625
- * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1626
- * back-compat for apps that have always been same-origin and never needed
1627
- * CORS (the typical pre-FR-041 case).
1628
- *
1629
- * Why hand-rolled instead of the `cors` npm package:
1630
- * - ~30 lines, zero new dependency.
1631
- * - Full control over Vary/credentials/preflight semantics.
1632
- * - Aligns with FDP "no unnecessary deps" philosophy.
1633
- */
1634
- protected mountCors(express: Express.Application): void {
1635
- const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1636
- if (!settings) {
1637
- return;
1638
- }
1639
-
1640
- const allowCreds: boolean = settings.allowCredentials !== false;
1641
- const methods: string[] = settings.allowedMethods ?? [
1642
- 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1643
- ];
1644
- const headers: string[] = settings.allowedHeaders ?? [
1645
- 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1646
- ];
1647
- const exposed: string[] = settings.exposedHeaders ?? [
1648
- 'Content-Length', 'Content-Type',
1649
- ];
1650
- const maxAge: number = settings.maxAgeSeconds ?? 86400;
1651
-
1652
- const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1653
- if (settings.allowedOrigins === '*') return true;
1654
- if (typeof settings.allowedOrigins === 'function') {
1655
- return settings.allowedOrigins(origin);
1656
- }
1657
- return settings.allowedOrigins.includes(origin);
1658
- };
1659
-
1660
- express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1661
- const origin: string | undefined = req.headers.origin;
1662
- if (origin && isAllowed(origin)) {
1663
- // Echo the matching origin (NOT wildcard) because credentials require it.
1664
- res.setHeader('Access-Control-Allow-Origin', origin);
1665
- if (allowCreds) {
1666
- res.setHeader('Access-Control-Allow-Credentials', 'true');
1667
- }
1668
- res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1669
- res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1670
- res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1671
- res.setHeader('Access-Control-Max-Age', String(maxAge));
1672
- res.setHeader('Vary', 'Origin');
1673
- }
1674
- if (req.method === 'OPTIONS') {
1675
- res.status(204).end();
1676
- return;
1677
- }
1678
- next();
1679
- });
1680
- }
1681
-
1682
- /**
1683
- * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1684
- * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1685
- * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1686
- * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1687
- * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1688
- */
1689
- private async mountCustomMiddleware(): Promise<void> {
1690
- if (!this.registerCustomMiddleware) {
1691
- return;
1692
- }
1693
-
1694
- if (this.openExpress) {
1695
- await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1696
- }
1697
-
1698
- if (this.secureExpress) {
1699
- await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1700
- }
1701
-
1702
- if (this.logSetup) {
1703
- DyFM_Log.log('\nCustom middleware registered (pre-static).');
1704
- }
1705
- }
1706
-
1707
- /**
1708
- * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1709
- * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1710
- * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1711
- * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1712
- */
1713
- private async mountStaticClient(): Promise<void> {
1714
- const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1715
- if (!settings) {
1716
- return;
1717
- }
1718
-
1719
- const absoluteRoot: string = Path.isAbsolute(settings.root)
1720
- ? settings.root
1721
- : Path.resolve(process.cwd(), settings.root);
1722
-
1723
- const hasAssetCache: boolean =
1724
- settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1725
- const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1726
- hasAssetCache && settings.assetCacheMaxAge !== undefined
1727
- ? {
1728
- setHeaders: (res: Express.Response, filePath: string): void => {
1729
- // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1730
- // immutable long-cache-t — lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1731
- res.setHeader(
1732
- 'Cache-Control',
1733
- DyNTS_resolveStaticCacheControlHeader({
1734
- filePath: filePath,
1735
- assetCacheMaxAge: settings.assetCacheMaxAge!,
1736
- assetCacheImmutable: settings.assetCacheImmutable === true,
1737
- }),
1738
- );
1739
- },
1740
- }
1741
- : undefined;
1742
-
1743
- const staticMiddleware: Express.Handler =
1744
- staticOptions
1745
- ? Express.static(absoluteRoot, staticOptions)
1746
- : Express.static(absoluteRoot);
1747
-
1748
- const fallbackMaxAge: number =
1749
- settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1750
-
1751
- if (this.openExpress) {
1752
- this.openExpress.use('/', staticMiddleware);
1753
- if (settings.fallbackPath) {
1754
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1755
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1756
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1757
- });
1758
- } else {
1759
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1760
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1761
- });
1762
- }
1763
- }
1764
-
1765
- if (this.secureExpress) {
1766
- this.secureExpress.use('/', staticMiddleware);
1767
- if (settings.fallbackPath) {
1768
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1769
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1770
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1771
- });
1772
- } else {
1773
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1774
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1775
- });
1776
- }
1777
- }
1778
-
1779
- if (this.logSetup) {
1780
- DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1781
- }
1782
- }
1783
-
1784
- /**
1785
- *
1786
- */
1787
- private setSecurity(): void {
1788
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1789
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1790
- if (!module.security) {
1791
- DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1792
-
1793
- } else if (!this._security) {
1794
- this._security = module.security;
1795
-
1796
- } else if (this._security !== module.security) {
1797
- this._security = DyNTS_RouteSecurity.both;
1798
- }
1799
- });
1800
-
1801
- if (!this._security) {
1802
- let msg = `Could not set security for the server! (${this.security})`;
1803
-
1804
- msg += '\n RoutingModules:';
1805
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1806
- msg += `\n ${module.route} (security: ${module.security})`;
1807
- });
1808
-
1809
- if (this._routingModules.length === 0) {
1810
- msg += '\n - no RoutingModule found -\n';
1811
- }
1812
- DyFM_Log.warn(msg);
1813
- }
1814
- }
1815
-
1816
- private _getDefaultErrorSettings(
1817
- fnName: string,
1818
- error: DyFM_AnyError
1819
- ): DyFM_Error_Settings {
1820
- return {
1821
- status: (error as DyFM_Error)?.___status ?? 500,
1822
- message: (error as Error)?.message ??
1823
- (error as DyFM_Error)?._message ??
1824
- `${fnName} was UNSUCCESSFUL (NTS)`,
1825
- userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1826
- addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1827
- issuerService: `${this?.constructor?.name}-DyNTS_App`,
1828
- level: DyFM_ErrorLevel.fatal,
1829
- error: error,
1830
- systemVersion: DyNTS_global_settings.systemVersion,
1831
- };
1832
- }
1833
-
1834
- /**
1835
- * MISSING Description (TODO)
1836
- */
1837
- abstract getAppParams(): DyNTS_App_Params;
1838
-
1839
- /**
1840
- * MISSING Description (TODO)
1841
- */
1842
- abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1843
-
1844
- /**
1845
- * MISSING Description (TODO)
1846
- */
1847
- abstract getPortSettings(): DyNTS_Http_Settings;
1848
-
1849
- /**
1850
- * MISSING Description (TODO)
1851
- */
1852
- overrideDynamoNTSGlobalSettings?(): void;
1853
-
1854
- /**
1855
- * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1856
- * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1857
- */
1858
- getApiBasePath?(): string;
1859
-
1860
- /**
1861
- * MISSING Description (TODO)
1862
- */
1863
- getRoutingModules?(): DyNTS_RoutingModule[];
1864
-
1865
- /**
1866
- * MISSING Description (TODO)
1867
- */
1868
- getRootServices?(): Promise<any[]>;
1869
-
1870
- /**
1871
- * MISSING Description (TODO)
1872
- */
1873
- getCertificationSettings?(): DyNTS_Certification_Settings;
1874
-
1875
- /**
1876
- * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1877
- * Opcionális fallbackPath pl. SPA index.html-hez.
1878
- */
1879
- getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1880
-
1881
- /**
1882
- * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1883
- * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1884
- * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1885
- * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1886
- * Ha undefined → no CORS headers, no preflight handling — back-compat.
1887
- */
1888
- getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1889
-
1890
- /**
1891
- * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1892
- * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1893
- * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1894
- * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1895
- * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1896
- */
1897
- registerCustomMiddleware?(
1898
- express: Express.Application,
1899
- security: DyNTS_RouteSecurity,
1900
- ): void | Promise<void>;
1901
-
1902
- /**
1903
- * MISSING Description (TODO)
1904
- */
1905
- createEntries?(): Promise<void>;
1906
-
1907
- /**
1908
- * MISSING Description (TODO)
1909
- */
1910
- postProcess?(): Promise<void>;
1911
-
1912
- }
1
+
2
+ import Mongoose = require('mongoose');
3
+ import Express = require('express');
4
+ /* import Mongoose from 'mongoose';
5
+ import Express from 'express'; */
6
+
7
+ import * as BodyParser from 'body-parser';
8
+ import * as FileSystem from 'fs';
9
+ import * as Http from 'http';
10
+ import * as Https from 'https';
11
+ import * as Path from 'path';
12
+ import * as dotenv from 'dotenv'
13
+
14
+ /* import { version } from '../../../package.json'; */
15
+
16
+ import {
17
+ DyFM_AnyError,
18
+ DyFM_Array,
19
+ DyFM_Async,
20
+ DyFM_Error,
21
+ DyFM_error_defaults,
22
+ DyFM_Error_Settings,
23
+ DyFM_ErrorLevel,
24
+ DyFM_Log,
25
+ DyFM_resolveRetentionTtlSeconds,
26
+ megabyte,
27
+ second
28
+ } from '@futdevpro/fsm-dynamo';
29
+
30
+ import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
+ import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
+ import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
+ import { DyNTS_getEnvironment_settings } from '../../_collections/get-environment-settings.util';
34
+ import { DyNTS_createSecurityHeadersMiddleware } from '../../_collections/security-headers.util';
35
+ import { DyNTS_SecurityHeaders_Settings } from '../../_models/interfaces/security-headers-settings.interface';
36
+ import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
37
+ import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
38
+ import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
39
+ import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
40
+ import {
41
+ DyNTS_AppSystemControls
42
+ } from '../../_models/control-models/app-system-controls.control-model';
43
+ import {
44
+ DyNTS_Endpoint_Params
45
+ } from '../../_models/control-models/endpoint-params.control-model';
46
+ import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
47
+ import {
48
+ DyNTS_Certification_Settings
49
+ } from '../../_models/interfaces/certification-settings.interface';
50
+ import {
51
+ DyNTS_GlobalService_Settings
52
+ } from '../../_models/interfaces/global-service-settings.interface';
53
+ import {
54
+ DyNTS_StaticClient_Settings
55
+ } from '../../_models/interfaces/static-client-settings.interface';
56
+ import {
57
+ DyNTS_Cors_Settings
58
+ } from '../../_models/interfaces/cors-settings.interface';
59
+ import { DyNTS_DBService } from '../base/db.service';
60
+ import { DyNTS_SingletonService } from '../base/singleton.service';
61
+ import { DyNTS_GlobalService } from '../core/global.service';
62
+ import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
63
+ import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
64
+ import { DyNTS_RoutingModule } from '../route/routing-module.service';
65
+ import { DyNTS_getStarRoute } from '../../_collections/star.controller';
66
+
67
+ /**
68
+ *
69
+ * function MyDecorator(config: any) {
70
+ return function (target: Function) {
71
+ // attach metadata or modify target
72
+ target.prototype.myMeta = config;
73
+ };
74
+ }
75
+
76
+ @MyDecorator({ role: 'admin' })
77
+ class User {
78
+ printRole() {
79
+ console.log((this as any).myMeta.role); // → "admin"
80
+ }
81
+ }
82
+
83
+ */
84
+
85
+ /**
86
+ * This will be the MAIN service of our server project,
87
+ * follow the types and type instructions while setting up your project
88
+ *
89
+ * In this service, there are abstract functions that you will need to implement,
90
+ * where you need to set up the main params for your application.
91
+ *
92
+ * (after the example, you can find the list of services you can/should setup)
93
+ *
94
+ * @example
95
+ * export class App extends DyNTS_AppExtended {
96
+ *
97
+ * ...
98
+ *
99
+ * // Setting up App params, and preparing project global settings
100
+ * setupAppParams(): void {
101
+ * this.params = new DyNTS_AppParams({
102
+ * name: 'Warbots Server',
103
+ * title: warbotsTitleLog,
104
+ * version: version,
105
+ * dbName: 'warbots',
106
+ * });
107
+ *
108
+ * // dynamoNTS_GlobalSettings.logRequestsContent = false;
109
+ * }
110
+ *
111
+ * ...
112
+ *
113
+ * // Setting up DBServices
114
+ * setGlobalServiceCollection(): void {
115
+ * DyNTS_GlobalService.setServices({
116
+ * authService: AuthService.getInstance(),
117
+ * emailServiceCollection: EmailServiceCollectionService.getInstance(),
118
+ * dbModels: [
119
+ * userModelParams,
120
+ * userDataModelParams,
121
+ * userOptionsModelParams,
122
+ * userStatisticsModelParams,
123
+ * userAchievementsModelParams,
124
+ * userNotificationsModelParams,
125
+ *
126
+ * matchStatisticsModelParams,
127
+ * matchDataModelParams,
128
+
129
+ * DyFM_usageSession_dataParams,
130
+ * DyFM_customData_dataParams,
131
+ * ]
132
+ * });
133
+ * }
134
+ *
135
+ * ...
136
+ *
137
+ * // Setting up Routes
138
+ * setupRoutingModules(): void {
139
+ * this.httpPort = env.port;
140
+
141
+ * this.routingModules = [
142
+ * new DyNTS_RoutingModule({
143
+ * route: '/user',
144
+ * controllers: [
145
+ * UserController.getInstance(),
146
+ * UserDataController.getInstance(),
147
+ * UserOptionsController.getInstance(),
148
+ * UserStatisticsController.getInstance(),
149
+ * UserAchievementsController.getInstance(),
150
+ * UserNotificationsController.getInstance()
151
+ * ]
152
+ * }),
153
+ * new DyNTS_RoutingModule({
154
+ * route: '/match',
155
+ * controllers: [
156
+ * MatchController.getInstance(),
157
+ * MatchDistributionController.getInstance(),
158
+ * MatchStatisticsController.getInstance(),
159
+ * ]
160
+ * }),
161
+ * new DyNTS_RoutingModule({
162
+ * route: '/server',
163
+ * controllers: [
164
+ * ServerController.getInstance(),
165
+ * ]
166
+ * }),
167
+
168
+ * getTestRoutingModule(),
169
+ * getUsageRoutingModule()
170
+ * ];
171
+ * }
172
+ * }
173
+ *
174
+ * //
175
+ * // The Services available
176
+ * //
177
+ * // Authentication Service
178
+ * // A commonly used basic service,
179
+ * // which is necessary fur certain functions (such as registering call issuers)
180
+ * //
181
+ * // This will handle Authentication Token checking/refreshing,
182
+ * // checking issuer's identifier and routeParams,
183
+ * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
184
+ * //
185
+ * // You can create one with this Dynamo Object:
186
+ * //
187
+ *
188
+ * @example
189
+ * // follow the instructions on the abstract class (DyNTS_AuthService)
190
+ * export class AuthService extends DyNTS_AuthService {}
191
+ *
192
+ *
193
+ *
194
+ * //
195
+ */
196
+
197
+ /**
198
+ * This will be the MAIN service of our server project,
199
+ * follow the types and type instructions while setting up your project
200
+ *
201
+ * In this service, there are abstract functions that you will need to implement,
202
+ * where you need to set up the main params for your application.
203
+ *
204
+ * (after the example, you can find the list of services you can/should setup)
205
+ *
206
+ * You need to setup the following functions:
207
+ * ```ts
208
+ * // this is where you set up the main params for your application
209
+ * getAppParams(): DyNTS_AppParams
210
+ *
211
+ * // this is where you connect your main services
212
+ * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
213
+ *
214
+ * // this is where you set up your ports
215
+ * getPorts(): DyNTS_PortSettings
216
+ *
217
+ * // this is where you set up your routes
218
+ * getRoutingModules(): DyNTS_RoutingModule[]
219
+ *
220
+ *
221
+ *
222
+ * ```
223
+ * optionally you can setup the following functions:
224
+ * ```ts
225
+ * // this is where you set up your certifications
226
+ * getCertificationSettings(): DyNTS_CertificationSettings
227
+ *
228
+ * // this is where you set up additional root services
229
+ * getRootServices(): DyNTS_SingletonService[]
230
+ *
231
+ * // this is where you set up your initial db entries
232
+ * createEntries(): void
233
+ *
234
+ * // this is where you can define post setup processes
235
+ * postProcess(): void
236
+ *
237
+ *
238
+ *
239
+ * ```
240
+ *
241
+ */
242
+
243
+ /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
244
+ export interface DyNTS_TtlIndexInfo {
245
+ name?: string;
246
+ key?: Record<string, number>;
247
+ expireAfterSeconds?: number;
248
+ }
249
+
250
+ /**
251
+ * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
252
+ * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
253
+ * in unit tests.
254
+ */
255
+ export interface DyNTS_TtlIndexCollection {
256
+ indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
257
+ createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
258
+ dropIndex?: (name: string) => Promise<unknown>;
259
+ }
260
+
261
+ /**
262
+ * FR-258 / SR-2 outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
263
+ * - `created`: no `__created` TTL index existed one was created.
264
+ * - `noop`: an index with the SAME TTL already existed nothing done.
265
+ * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) left UNTOUCHED,
266
+ * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
267
+ * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
268
+ * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
269
+ * maintenance, not silently at every startup.
270
+ */
271
+ export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
272
+
273
+ export abstract class DyNTS_App extends DyNTS_SingletonService {
274
+
275
+ protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
276
+ get started(): boolean {
277
+ return this.systemControls.app.started;
278
+ }
279
+ protected get superStarted(): boolean {
280
+ return this.systemControls.app.started;
281
+ }
282
+ protected constructErrors: (Error | DyFM_Error)[] = [];
283
+
284
+ /* removed since cant use version from package.json
285
+ private readonly _ntsVersion: string = 'v01.07.18';
286
+ protected get ntsVersion(): string {
287
+ return this._ntsVersion;
288
+ } */
289
+
290
+ get serverName(): string {
291
+ return this.params.name;
292
+ }
293
+
294
+ private _params: DyNTS_App_Params;
295
+ protected get params(): DyNTS_App_Params {
296
+ return this._params;
297
+ }
298
+
299
+ protected mongoose = Mongoose;
300
+
301
+ private _security: DyNTS_RouteSecurity;
302
+ protected get security(): DyNTS_RouteSecurity {
303
+ return this._security;
304
+ }
305
+
306
+ protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
307
+ protected get portSettings(): DyNTS_Http_Settings {
308
+ return this._portSettings;
309
+ }
310
+
311
+ private _cert?: DyNTS_Certification_Settings;
312
+ protected get cert(): DyNTS_Certification_Settings {
313
+ return this._cert;
314
+ }
315
+
316
+ protected openExpress: Express.Application;
317
+ protected secureExpress: Express.Application;
318
+ protected httpsServer: Https.Server;
319
+ protected httpServer: Http.Server;
320
+
321
+ private globalService: DyNTS_GlobalService;
322
+ private _rootServices: DyNTS_SingletonService[] = [];
323
+
324
+ private _routingModules: DyNTS_RoutingModule[] = [];
325
+
326
+ protected readonly defaultReadyTimeout: number = 30 * second;
327
+
328
+ override readonly defaultErrorUserMsg =
329
+ `We encountered an unhandled Server Error, ` +
330
+ `\nplease contact the responsible development team.` +
331
+ `\n(Internal Server error)`;
332
+
333
+ get logSetup(): boolean {
334
+ return DyNTS_global_settings.log_settings.setup;
335
+ }
336
+ get deepLog(): boolean {
337
+ return DyNTS_global_settings.log_settings.deep;
338
+ }
339
+ get fnLogs(): boolean {
340
+ return DyNTS_global_settings.log_settings.functions;
341
+ }
342
+ debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
343
+
344
+ constructor(/* extended?: boolean */){
345
+ super();
346
+
347
+ /* dotenv.config() */
348
+
349
+ process.on(
350
+ 'unhandledRejection',
351
+ (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
352
+ if (reason_theError instanceof DyFM_Error) {
353
+ reason_theError.logSimple('Unhandled Rejection');
354
+ } else {
355
+ DyFM_Log.H_error(
356
+ 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
357
+ '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
358
+ /* '\n ErrorCode:', (reason as any)?.code, */
359
+ '\n\n Stack:',
360
+ (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
361
+ );
362
+ }
363
+
364
+ try {
365
+ DyNTS_GlobalService.globalErrorHandler?.(
366
+ new DyFM_Error({
367
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
368
+ message:
369
+ `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
370
+ userMessage: this.defaultErrorUserMsg,
371
+ addECToUserMsg: true,
372
+ error: reason_theError as Error,
373
+ additionalContent: {
374
+ reason: reason_theError,
375
+ rejectedPromise: p_passWhatIsThis_maybeThePromise,
376
+ },
377
+ systemVersion: DyNTS_global_settings.systemVersion,
378
+ level: DyFM_ErrorLevel.critical,
379
+ })
380
+ );
381
+ } catch (error) {
382
+ DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
383
+ }
384
+ }
385
+ );
386
+
387
+ this.asyncConstruct(/* extended */).catch((error: any): void => {
388
+ if (error instanceof DyFM_Error) {
389
+ if (error.additionalContent?.constructErrors?.length) {
390
+ error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
391
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
392
+ /* if (errorItem instanceof DyFM_Error) {
393
+ errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
394
+ } else {
395
+ DyFM_Log.H_warn(
396
+ '(constructor asyncConstruct.catch) additional error content:\n',
397
+ errorItem
398
+ );
399
+ } */
400
+ });
401
+ } else {
402
+ DyFM_Log.H_warn(
403
+ '(constructor asyncConstruct.catch) additional error content:\n',
404
+ error?.additionalContent
405
+ );
406
+ }
407
+ }
408
+
409
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
410
+ /* if (
411
+ !DyNTS_global_settings.log_settings.highDetailedLogs &&
412
+ (error instanceof DyFM_Error)
413
+ ) {
414
+ error.logSimple(
415
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
416
+ '\n all error messages (from this stack):\n\n"' +
417
+ error._messages.join('"\n\n"') + '"\n\n'
418
+ );
419
+ } else if (error instanceof DyFM_Error) {
420
+ DyFM_Log.H_error(
421
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
422
+ `\n ERROR:`, error
423
+ );
424
+ } */
425
+
426
+ const message: string =
427
+ (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
428
+ (errorItem: DyFM_Error): string[] => {
429
+ return errorItem?._messages ?? [];
430
+ }
431
+ )?.join?.('\n') ??
432
+ (error as DyFM_Error)?.errors?.flatMap(
433
+ (errorItem: DyFM_AnyError): string[] =>
434
+ (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
435
+ )?.join?.('\n') ??
436
+ error?.message ??
437
+ 'UNKNOWN';
438
+
439
+ DyFM_Log.testError('Application start failed:\n', message);
440
+
441
+ process.exit(1);
442
+ });
443
+ }
444
+
445
+ protected async asyncConstruct(extended?: boolean): Promise<void> {
446
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
447
+
448
+ try {
449
+ this.systemControls.app.init = true;
450
+ this._params = this.getAppParams();
451
+ DyFM_Log.log(
452
+ `\n\n\n\n\n\n\n\n\n\n` +
453
+ `Starting ${this._params?.name}... ` +
454
+ /* `v${version}` + */
455
+ `\n\n\n\n\n\n\n\n\n\n`
456
+ );
457
+
458
+ if (!this._params) {
459
+ throw new Error('getAppParams() must return a DyNTS_AppParams object!');
460
+ }
461
+
462
+ if (this.params.systemShortCodeName) {
463
+ DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
464
+ }
465
+
466
+ if (this.params.systemName) {
467
+ DyNTS_global_settings.systemName = this.params.systemName;
468
+ DyFM_error_defaults.issuerSystem = this.params.systemName;
469
+ }
470
+
471
+ if (this.params.version) {
472
+ DyNTS_global_settings.systemVersion = this.params.version;
473
+ DyFM_error_defaults.systemVersion = this.params.version;
474
+ }
475
+
476
+ process.stdout.write(
477
+ String.fromCharCode(27) + ']0;' +
478
+ this._params?.name +
479
+ String.fromCharCode(7)
480
+ );
481
+
482
+ DyFM_error_defaults.issuerSystem = this._params.systemName;
483
+
484
+ this.overrideDynamoNTSGlobalSettings?.();
485
+
486
+ if (DyNTS_global_settings.log_settings.setup) {
487
+ DyFM_Log.S_info(`env settings;\n`, {
488
+ systemName: DyNTS_global_settings.systemName,
489
+ systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
490
+ systemVersion: DyNTS_global_settings.systemVersion,
491
+ environment: DyNTS_global_settings.env_settings.environment,
492
+ /* log_settings: DyNTS_global_settings.log_settings,
493
+ env_settings: DyNTS_global_settings.env_settings, */
494
+ });
495
+ }
496
+
497
+ this.globalService = DyNTS_GlobalService.getInstance();
498
+ await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
499
+ DyNTS_GlobalService.setParams(this.params);
500
+
501
+ if (this.getPortSettings) {
502
+ this._portSettings = this.getPortSettings();
503
+ }
504
+
505
+ if (this.getCertificationSettings) {
506
+ this._cert = this.getCertificationSettings();
507
+ }
508
+
509
+ if (this.getApiBasePath) {
510
+ DyNTS_global_settings.baseUrl = this.getApiBasePath();
511
+ }
512
+
513
+ if (this.getRoutingModules) {
514
+ this._routingModules = this.getRoutingModules();
515
+
516
+ // ezt egyelőre csak tesztelem, nem kerül be
517
+ /* if (
518
+ !DyNTS_global_settings.dontCreateDefaultRoute &&
519
+ !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
520
+ ) {
521
+ this._routingModules.push(
522
+ DyNTS_getStarRoute()
523
+ );
524
+ } */
525
+ }
526
+
527
+ if (this._params.dbUri) {
528
+ await this.startDB();
529
+
530
+ // createEntries csak akkor fut, ha a DB tényleg fel-jött.
531
+ // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
532
+ // és nem próbálunk meg írni egy nem létező kapcsolatra.
533
+ if (this.createEntries && this.systemControls.mongoose.started) {
534
+ await this.createEntries();
535
+ }
536
+ } else {
537
+ DyFM_Log.log(
538
+ `\nNo database connection created.`,
539
+ );
540
+ }
541
+
542
+ if (this._routingModules?.length) {
543
+ if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
544
+
545
+ this.setSecurity();
546
+
547
+ await this.initExpresses();
548
+ await this.startExpresses();
549
+
550
+ if (this._security !== DyNTS_RouteSecurity.secure) {
551
+ await this.mountOpenRoutes();
552
+ }
553
+
554
+ if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
555
+ await this.mountSecureRoutes();
556
+ }
557
+
558
+ // Generikus, auth-agnosztikus extension-point: custom middleware az API
559
+ // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
560
+ await this.mountCustomMiddleware();
561
+
562
+ await this.mountStaticClient();
563
+
564
+ if (this.logSetup) {
565
+ DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
566
+ }
567
+ } else {
568
+ DyFM_Log.warn(
569
+ `\nNo routes mounted!`,
570
+ );
571
+ }
572
+
573
+ if (this.getRootServices) {
574
+ this._rootServices = await this.getRootServices();
575
+ }
576
+
577
+ if (this.postProcess) {
578
+ await this.postProcess().catch((error: any): void => {
579
+ DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
580
+ DyNTS_GlobalService.globalErrorHandler?.(error);
581
+ });
582
+ }
583
+
584
+ // FR-193 bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
585
+ // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
586
+ // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
587
+ // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
588
+ try {
589
+ if (DyNTS_global_settings.memoryGuard?.enabled) {
590
+ DyNTS_MemoryGuard.getInstance().install();
591
+ }
592
+ } catch (memoryGuardError: unknown) {
593
+ DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
594
+ }
595
+
596
+ // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
597
+ // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
598
+ // OOM. Default-on, observation-only, never throws.
599
+ try {
600
+ if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
601
+ DyNTS_CollectionGrowthMonitor.getInstance().install();
602
+ }
603
+ } catch (cgmError: unknown) {
604
+ DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
605
+ }
606
+
607
+ if (!extended) {
608
+ await this.ready();
609
+
610
+ if (this.params.title) {
611
+ DyFM_Log.success(this.params.title);
612
+ }
613
+ DyFM_Log.info(`Version: ${this.params.version}`);
614
+ /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
615
+ DyFM_Log.H_success(`${this.params.name} started successfully.`);
616
+ }
617
+ } catch (error) {
618
+ this.constructErrors.push(error);
619
+
620
+ if (this.deepLog) {
621
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
622
+ DyFM_Log.H_error(
623
+ `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
624
+ `\n\n construct ERRORS:`, this.constructErrors,
625
+ '\n\nlast error:', error
626
+ );
627
+ } else {
628
+ DyFM_Log.H_error(
629
+ `"${this._params.name}" start failed (in asyncConstruct). `,
630
+ `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
631
+ '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
632
+ );
633
+ }
634
+ }
635
+
636
+ throw new DyFM_Error({
637
+ ...this._getDefaultErrorSettings('asyncConstruct', error),
638
+
639
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
640
+ additionalContent: {
641
+ constructErrors: this.constructErrors,
642
+ systemControls: this.systemControls,
643
+ systemReadies: {
644
+ app: this.systemControls.app.getIsReady(),
645
+ mongoose: this.systemControls.mongoose.getIsReady(),
646
+ httpServer: this.systemControls.httpServer.getIsReady(),
647
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
648
+ },
649
+ },
650
+ });
651
+ }
652
+ }
653
+
654
+ async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
655
+ try {
656
+ if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
657
+
658
+ await DyFM_Async.delay(100);
659
+
660
+ let ready: boolean = false;
661
+ const start: number = +new Date();
662
+
663
+ if (this.constructErrors.length) {
664
+ if (this.deepLog) {
665
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
666
+ DyFM_Log.H_error(
667
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
668
+ `\n construct ERRORS:`, this.constructErrors
669
+ );
670
+ } else {
671
+ DyFM_Log.H_error(
672
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
673
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
674
+ );
675
+ }
676
+ }
677
+
678
+ throw new DyFM_Error({
679
+ ...this._getDefaultErrorSettings(
680
+ 'ready',
681
+ new Error(`"${this._params.name}" start failed.`)
682
+ ),
683
+
684
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
685
+ additionalContent:
686
+ this.constructErrors.length === 1 ?
687
+ { error: this.constructErrors[0] } :
688
+ { errors: this.constructErrors },
689
+ });
690
+ }
691
+
692
+ while (!ready && +new Date() - start < timeout) {
693
+ if (this.systemControls.app.init) {
694
+ ready = (
695
+ this.systemControls.mongoose.getIsReady() &&
696
+ this.systemControls.httpServer.getIsReady() &&
697
+ this.systemControls.httpsServer.getIsReady()
698
+ );
699
+ } else {
700
+ DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
701
+ }
702
+
703
+ if (!ready) {
704
+ await DyFM_Async.wait(100);
705
+ }
706
+ }
707
+
708
+ if (timeout < +new Date() - start) {
709
+ if (this.deepLog) {
710
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
711
+ DyFM_Log.H_error(
712
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
713
+ `\n construct ERRORS:`, this.constructErrors
714
+ );
715
+ } else {
716
+ DyFM_Log.H_error(
717
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
718
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
719
+ );
720
+ }
721
+ }
722
+
723
+ throw new DyFM_Error({
724
+ ...this._getDefaultErrorSettings(
725
+ 'ready',
726
+ new Error(`"${this._params.name}" start failed. TIMEOUT`)
727
+ ),
728
+
729
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
730
+ additionalContent: {
731
+ constructErrors: this.constructErrors,
732
+ systemControls: this.systemControls,
733
+ systemReadies: {
734
+ mongoose: this.systemControls.mongoose.getIsReady(),
735
+ httpServer: this.systemControls.httpServer.getIsReady(),
736
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
737
+ },
738
+ },
739
+ });
740
+ }
741
+
742
+ if (this.constructErrors.length) {
743
+ if (this.deepLog) {
744
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
745
+ DyFM_Log.H_error(
746
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
747
+ `\n construct ERRORS:`, this.constructErrors
748
+ );
749
+ } else {
750
+ DyFM_Log.H_error(
751
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
752
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
753
+ );
754
+ }
755
+ }
756
+
757
+ throw new DyFM_Error({
758
+ ...this._getDefaultErrorSettings(
759
+ 'ready',
760
+ new Error(`"${this._params.name}" start failed.`)
761
+ ),
762
+
763
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
764
+ additionalContent: this.constructErrors,
765
+ });
766
+ }
767
+
768
+ if (ready) {
769
+ this.systemControls.app.started = true;
770
+
771
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
772
+
773
+ return;
774
+ }
775
+
776
+ this.systemControls.app.started = false;
777
+
778
+ let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
779
+
780
+ if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
781
+ msg += `\nMongoose start failed.`;
782
+ }
783
+
784
+ if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
785
+ msg += `\nHTTP Server start failed.`;
786
+ }
787
+
788
+ if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
789
+ msg += `\nHTTPS Server start failed.`;
790
+ }
791
+
792
+ DyFM_Log.error(msg, this.constructErrors);
793
+
794
+ throw new DyFM_Error({
795
+ ...this._getDefaultErrorSettings('ready', new Error(msg)),
796
+
797
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
798
+ additionalContent: {
799
+ constructErrors: this.constructErrors,
800
+ systemControls: this.systemControls,
801
+ systemReadies: {
802
+ app: this.systemControls.app.getIsReady(),
803
+ mongoose: this.systemControls.mongoose.getIsReady(),
804
+ httpServer: this.systemControls.httpServer.getIsReady(),
805
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
806
+ },
807
+ },
808
+ error: this.constructErrors?.[0] ?? new Error(),
809
+ });
810
+ } catch (error) {
811
+ throw new DyFM_Error({
812
+ ...this._getDefaultErrorSettings('ready', error),
813
+
814
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
815
+ });
816
+ }
817
+ }
818
+
819
+ protected getSimplifiedConstructErrors(): string[] {
820
+ return this.constructErrors.map((error: any): any => {
821
+ if (error instanceof DyFM_Error) {
822
+ return error.getErrorSimplified();
823
+ } else {
824
+ return error;
825
+ }
826
+ });
827
+ }
828
+
829
+ async stop(dontLog?: boolean): Promise<void> {
830
+ try {
831
+ DyFM_Log.info('\nstopping server...\n');
832
+
833
+ await this.ready();
834
+
835
+ if (this.started) {
836
+
837
+ if (this.systemControls.mongoose.init) {
838
+ DyFM_Log.info(`\nstopping Mongoose....`);
839
+
840
+ let tryCount: number = 0;
841
+
842
+ while (
843
+ !this.systemControls.mongoose.started &&
844
+ !this.constructErrors.length &&
845
+ tryCount++ < 10
846
+ ) {
847
+ DyFM_Log.warn(`Mongoose not even started yet....`);
848
+ await DyFM_Async.wait(second);
849
+ }
850
+ this.systemControls.mongoose.started = false;
851
+
852
+ if (this.mongoose) {
853
+ await DyFM_Array.asyncForEach(
854
+ Object.keys(this.mongoose.models),
855
+ async (modelName): Promise<void> => {
856
+ this.mongoose.deleteModel(modelName);
857
+ }
858
+ );
859
+
860
+ const disconnect: Promise<void> = new Promise((resolve): void => {
861
+ this.mongoose.connection.on('disconnecting', (): void => {
862
+ resolve();
863
+ });
864
+ });
865
+
866
+ await this.mongoose.disconnect();
867
+ await this.mongoose.connection.close();
868
+ await disconnect;
869
+
870
+ this.mongoose.connection.removeAllListeners();
871
+
872
+ while (
873
+ this.mongoose.connection.readyState !== 0 &&
874
+ !this.constructErrors.length
875
+ ) {
876
+ DyFM_Log.warn(`\nMongoose still not disconnected....`);
877
+ await DyFM_Async.wait(second);
878
+ }
879
+ } else {
880
+ DyFM_Log.error(`\nMongoose not found.`);
881
+ }
882
+ this.systemControls.mongoose.init = false;
883
+ }
884
+
885
+ if (this.systemControls.httpServer.init) {
886
+ this.systemControls.httpServer.started = false;
887
+
888
+ if (this.httpServer) {
889
+ await new Promise((resolve): void => {
890
+ this.httpServer.close(resolve);
891
+ });
892
+ } else {
893
+ DyFM_Log.error(`\nHTTP Server not found.`);
894
+ }
895
+ this.systemControls.httpServer.init = false;
896
+ }
897
+
898
+ if (this.systemControls.httpsServer.init) {
899
+ this.systemControls.httpsServer.started = false;
900
+
901
+ if (this.httpsServer) {
902
+ await new Promise((resolve): void => {
903
+ this.httpsServer.close(resolve);
904
+ });
905
+ } else {
906
+ DyFM_Log.error(`\nHTTPS Server not found.`);
907
+ }
908
+ this.systemControls.httpsServer.init = false;
909
+ }
910
+
911
+ await DyFM_Async.wait(second);
912
+
913
+ if (!dontLog) {
914
+ DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
915
+ }
916
+ }
917
+ } catch (error) {
918
+ throw new DyFM_Error({
919
+ ...this._getDefaultErrorSettings('stop', error),
920
+
921
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
922
+ });
923
+ }
924
+ }
925
+
926
+ /**
927
+ *
928
+ */
929
+ private async startDB(): Promise<void> {
930
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
931
+ else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
932
+
933
+ if (!this._params.dbUri) {
934
+ throw new DyFM_Error({
935
+ ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
936
+
937
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
938
+ });
939
+ }
940
+
941
+ if (!this._params.dbOptions) {
942
+ throw new DyFM_Error({
943
+ ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
944
+
945
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
946
+ });
947
+ }
948
+
949
+ if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
950
+ throw new DyFM_Error({
951
+ ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
952
+
953
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
954
+ });
955
+ }
956
+
957
+ try {
958
+ await new Promise<void>(
959
+ (resolve, reject): void => {
960
+ this.systemControls.mongoose.init = true;
961
+
962
+ this.mongoose.connection
963
+ .once('open', (): void => {
964
+ this.systemControls.mongoose.started = true;
965
+ DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
966
+
967
+ resolve();
968
+
969
+ // FR-258 / SR-2 install declared-retention TTL indexes. DEFERRED + fire-and-forget +
970
+ // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
971
+ // compete with boot-readiness. We delay it well past the deploy health-probe window so a
972
+ // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
973
+ // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
974
+ // rebuilds a live index — see ensureRetentionTtlIndex.)
975
+ const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
976
+ void this.installRetentionTtlIndexes();
977
+ }, 30000);
978
+ if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
979
+ })
980
+ .on('error', (error): void => {
981
+ if (!this.systemControls.mongoose.started) {
982
+ // Initial DB-csatlakozás sikertelen:
983
+ // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
984
+ // App startup-ot (nincs constructErrors push, nincs reject).
985
+ // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
986
+ // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
987
+ // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
988
+ this.systemControls.mongoose.init = false;
989
+
990
+ const d_error: DyFM_Error = new DyFM_Error({
991
+ ...this._getDefaultErrorSettings('startDB', error),
992
+
993
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
994
+ message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
995
+ `ERROR: ${error}`,
996
+ level: DyFM_ErrorLevel.serious,
997
+ });
998
+
999
+ DyFM_Log.H_error(
1000
+ `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
1001
+ `\nServer will continue WITHOUT DB connection.` +
1002
+ `\nDB-using endpoints will fail at runtime until connection recovers.`
1003
+ );
1004
+
1005
+ if (this.debugLog) DyFM_Log.S_error(
1006
+ `\nMongoDB connect ERROR: `,
1007
+ error
1008
+ );
1009
+
1010
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1011
+
1012
+ resolve();
1013
+
1014
+ } else {
1015
+ if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1016
+
1017
+ const d_error: DyFM_Error = new DyFM_Error({
1018
+ ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1019
+
1020
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1021
+ message: `MongoDB ERROR: ${error}`,
1022
+ level: DyFM_ErrorLevel.critical,
1023
+ });
1024
+
1025
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1026
+ }
1027
+ });
1028
+
1029
+ try {
1030
+ this.mongoose.connect(
1031
+ this._params.dbUri,
1032
+ this._params.dbOptions
1033
+ /* {
1034
+ directConnection: true,
1035
+ } */
1036
+ );
1037
+ } catch (error) {
1038
+ throw new DyFM_Error({
1039
+ ...this._getDefaultErrorSettings('startDB', error),
1040
+
1041
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1042
+ });
1043
+ }
1044
+ }
1045
+ );
1046
+ } catch (error) {
1047
+ throw new DyFM_Error({
1048
+ ...this._getDefaultErrorSettings('startDB', error),
1049
+
1050
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1051
+ });
1052
+ }
1053
+
1054
+ // 2026-06-20 Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1055
+ // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1056
+ // a driver a HALOTT IP-n ragad ECONNREFUSED + buffering-timeout, és a service magától SOHA
1057
+ // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1058
+ // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1059
+ // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1060
+ // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1061
+ try {
1062
+ startMongoReconnectGuard({
1063
+ getReadyState: (): number => this.mongoose.connection.readyState,
1064
+ reconnect: async (): Promise<void> => {
1065
+ await this.mongoose.disconnect().catch((): void => undefined);
1066
+ await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1067
+ },
1068
+ log: (msg: string): void => DyFM_Log.warn(msg),
1069
+ });
1070
+ } catch (guardErr) {
1071
+ DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1072
+ }
1073
+ }
1074
+
1075
+ /**
1076
+ * FR-258 / SR-2 install MongoDB TTL indexes for every data-model that declared `retention`.
1077
+ *
1078
+ * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1079
+ * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1080
+ * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1081
+ * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1082
+ * against the unbounded-collection-growth in-memory-load GC-thrash/OOM class.
1083
+ *
1084
+ * Guarantees:
1085
+ * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1086
+ * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1087
+ * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1088
+ * (the field index is restored immediately, so query coverage is preserved).
1089
+ */
1090
+ private async installRetentionTtlIndexes(): Promise<void> {
1091
+ try {
1092
+ const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1093
+ let ensured: number = 0;
1094
+
1095
+ for (const service of services) {
1096
+ const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1097
+ if (!ttlSeconds) { continue; }
1098
+
1099
+ const dataName: string = service.dataParams.dataName;
1100
+ // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1101
+ const collection: DyNTS_TtlIndexCollection | undefined =
1102
+ (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1103
+ if (!collection || typeof collection.createIndex !== 'function') { continue; }
1104
+
1105
+ try {
1106
+ const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1107
+ if (action === 'created') {
1108
+ ensured++;
1109
+ if (this.logSetup) {
1110
+ DyFM_Log.success(
1111
+ `[FR-258 retention] TTL index created on "${dataName}" — ` +
1112
+ `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1113
+ );
1114
+ }
1115
+ } else if (action === 'differs') {
1116
+ // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1117
+ DyFM_Log.warn(
1118
+ `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1119
+ `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1120
+ `Apply the change via maintenance if intended.`,
1121
+ );
1122
+ }
1123
+ } catch (idxErr: unknown) {
1124
+ DyFM_Log.warn(
1125
+ `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1126
+ `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1127
+ );
1128
+ }
1129
+ }
1130
+
1131
+ if (ensured > 0) {
1132
+ DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1133
+ }
1134
+ } catch (err: unknown) {
1135
+ DyFM_Log.warn(
1136
+ `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1137
+ `${err instanceof Error ? err.message : String(err)}`,
1138
+ );
1139
+ }
1140
+ }
1141
+
1142
+ /**
1143
+ * FR-258 / SR-2 ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1144
+ * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1145
+ * - no existing `__created` index → create it → `'created'`
1146
+ * - existing with the SAME TTL no-op → `'noop'`
1147
+ * - existing with a DIFFERENT TTL / non-TTL leave it as-is `'differs'` (warn only — NO drop+recreate)
1148
+ *
1149
+ * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1150
+ * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1151
+ * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1152
+ * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1153
+ * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1154
+ */
1155
+ static async ensureRetentionTtlIndex(
1156
+ collection: DyNTS_TtlIndexCollection,
1157
+ ttlSeconds: number,
1158
+ ): Promise<DyNTS_TtlIndexAction> {
1159
+ const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1160
+ ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1161
+ : [];
1162
+ const existing: DyNTS_TtlIndexInfo | undefined =
1163
+ existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1164
+
1165
+ if (!existing) {
1166
+ await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1167
+ return 'created';
1168
+ }
1169
+ if (existing.expireAfterSeconds === ttlSeconds) {
1170
+ return 'noop';
1171
+ }
1172
+ // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1173
+ // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1174
+ return 'differs';
1175
+ }
1176
+
1177
+ /**
1178
+ *
1179
+ */
1180
+ private async initExpresses(): Promise<void> {
1181
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1182
+
1183
+ try {
1184
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1185
+ if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1186
+ let errorMsg: string =
1187
+ `\nYou have open routes, but httpPort is not set!` +
1188
+ `\nThere are ${this._routingModules.filter(
1189
+ m => m.security != DyNTS_RouteSecurity.secure
1190
+ ).length} open/both routes` +
1191
+ `\nroot security: ${this._security}` +
1192
+ `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1193
+
1194
+ errorMsg += '\n\nThe routes setted to use open server:';
1195
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1196
+ if (module.security != DyNTS_RouteSecurity.secure) {
1197
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1198
+ errorMsg += `\n subroutes using open sever:`;
1199
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1200
+ if (endpoint.security != DyNTS_RouteSecurity.secure) {
1201
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1202
+ }
1203
+ });
1204
+ }
1205
+ });
1206
+
1207
+ const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1208
+ const errorStack: string[] = error.stack.split('\n');
1209
+
1210
+ errorStack.splice(1, 2);
1211
+ error.stack = errorStack.join('\n');
1212
+
1213
+ DyFM_Log.error(errorMsg);
1214
+
1215
+ throw error;
1216
+ }
1217
+
1218
+ await this.initOpenExpress();
1219
+ }
1220
+
1221
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1222
+ if (!this._cert || !this._portSettings.httpsPort) {
1223
+ let errorMsg: string =
1224
+ `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1225
+ `\nThere are ${this._routingModules.filter(
1226
+ m => m.security && m.security !== DyNTS_RouteSecurity.open
1227
+ ).length} secure routes` +
1228
+ `\nroot security: ${this._security}` +
1229
+ `\nset...` +
1230
+ `\n(missing exact howto...)` +
1231
+ /* `\n httpsPort and` +
1232
+ `\n cert: {` +
1233
+ `\n keyPath: FileSystem.PathLike,` +
1234
+ `\n certPath: FileSystem.PathLike,` +
1235
+ `\n }` + */
1236
+ `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1237
+
1238
+ errorMsg += '\n\nThe routes setted to use secure server:';
1239
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1240
+ if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1241
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1242
+ errorMsg += `\n location: ${module.stackLocation}`;
1243
+ errorMsg += `\n subroutes using secure sever:`;
1244
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1245
+ if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1246
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1247
+ errorMsg += `\n location: ${endpoint.stackLocation}`;
1248
+ }
1249
+ });
1250
+ }
1251
+ });
1252
+
1253
+ const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1254
+ const errorStack: string[] = error.stack.split('\n');
1255
+
1256
+ errorStack.splice(1, 2);
1257
+ error.stack = errorStack.join('\n');
1258
+
1259
+ DyFM_Log.error(errorMsg);
1260
+
1261
+ throw error;
1262
+ }
1263
+
1264
+ await this.initSecureExpress();
1265
+ }
1266
+ } catch (error) {
1267
+ throw new DyFM_Error({
1268
+ ...this._getDefaultErrorSettings('initExpresses', error),
1269
+
1270
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1271
+ });
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ *
1277
+ */
1278
+ protected async initOpenExpress(): Promise<void> {
1279
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1280
+ this.openExpress = Express();
1281
+ this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1282
+ this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1283
+ this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1284
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (az OPTIONS preflight-válaszok is kapják).
1285
+ this.mountSecurityHeaders(this.openExpress);
1286
+ // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1287
+ this.mountCors(this.openExpress);
1288
+ }
1289
+
1290
+ /**
1291
+ *
1292
+ */
1293
+ protected async initSecureExpress(): Promise<void> {
1294
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1295
+ this.secureExpress = Express();
1296
+ this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1297
+ this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1298
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (mint az open expressen).
1299
+ this.mountSecurityHeaders(this.secureExpress);
1300
+ // FR-041 — CORS allowlist enforcement (same as open express).
1301
+ this.mountCors(this.secureExpress);
1302
+
1303
+ const options = {
1304
+ key: FileSystem.readFileSync(this._cert.keyPath),
1305
+ cert: FileSystem.readFileSync(this._cert.certPath),
1306
+ maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1307
+ };
1308
+
1309
+ this.httpsServer = Https.createServer(options, this.secureExpress);
1310
+ }
1311
+
1312
+ /**
1313
+ *
1314
+ */
1315
+ private async startExpresses(): Promise<void> {
1316
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1317
+
1318
+ try {
1319
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1320
+ await new Promise<void>((resolve, reject): void => {
1321
+ this.systemControls.httpsServer.init = true;
1322
+ this.httpsServer
1323
+ .listen(
1324
+ this._portSettings.httpsPort,
1325
+ this.params.secureHost,
1326
+ this.params.expressBacklog,
1327
+ (): void => {
1328
+ this.systemControls.httpsServer.started = true;
1329
+ DyFM_Log.success(
1330
+ `\nHTTPS (secure) server is listening on port: ` +
1331
+ `${this.params.secureHost}:${this._portSettings.httpsPort}`
1332
+ );
1333
+
1334
+ resolve();
1335
+ })
1336
+ .on('error', (error): void => {
1337
+ if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1338
+
1339
+ if (!this.systemControls.httpsServer.started) {
1340
+ const d_error: DyFM_Error = new DyFM_Error({
1341
+ ...this._getDefaultErrorSettings('startExpresses', error),
1342
+
1343
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1344
+ message: `HTTPS (secure) start server ERROR`,
1345
+ });
1346
+
1347
+ this.constructErrors.push(d_error);
1348
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1349
+
1350
+ reject(d_error);
1351
+
1352
+ } else {
1353
+ const d_error: DyFM_Error = new DyFM_Error({
1354
+ ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1355
+
1356
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1357
+ message: `HTTPS (secure) server ERROR`,
1358
+ level: DyFM_ErrorLevel.serious,
1359
+ });
1360
+
1361
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1362
+ }
1363
+ })
1364
+ .on('uncaughtException', (exception): void => {
1365
+ const d_error: DyFM_Error = new DyFM_Error({
1366
+ ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1367
+
1368
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1369
+ message: `HTTPS (secure) server uncaughtException`,
1370
+ level: DyFM_ErrorLevel.critical,
1371
+ });
1372
+
1373
+ if (this.debugLog) DyFM_Log.warn(
1374
+ `\nHTTPS (secure) server uncaughtException`,
1375
+ d_error
1376
+ );
1377
+
1378
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1379
+ });
1380
+ });
1381
+ }
1382
+
1383
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1384
+ this.systemControls.httpServer.init = true;
1385
+ await new Promise<void>((resolve, reject): void => {
1386
+ this.httpServer = this.openExpress
1387
+ .listen(
1388
+ this._portSettings.httpPort,
1389
+ this.params.openHost,
1390
+ this.params.expressBacklog,
1391
+ (): void => {
1392
+ this.systemControls.httpServer.started = true;
1393
+
1394
+ const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1395
+
1396
+ if (this._portSettings.httpPort === 0) {
1397
+ DyFM_Log.H_warn(
1398
+ `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1399
+ `\n (httpPort was set to 0 — this is intended for testing only)`
1400
+ );
1401
+ }
1402
+
1403
+ DyFM_Log.success(
1404
+ `\nHTTP (open) server is listening on port: ` +
1405
+ `${this.params.openHost}:${resolvedPort}`
1406
+ );
1407
+
1408
+ resolve();
1409
+ }
1410
+ )
1411
+ .on('error', (error): void => {
1412
+ if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1413
+
1414
+ if (!this.systemControls.httpServer.started) {
1415
+ const d_error: DyFM_Error = new DyFM_Error({
1416
+ ...this._getDefaultErrorSettings('startExpresses', error),
1417
+
1418
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1419
+ message: `HTTP (open) start server ERROR`,
1420
+ });
1421
+
1422
+ this.constructErrors.push(d_error);
1423
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1424
+
1425
+ reject(d_error);
1426
+
1427
+ } else {
1428
+ const d_error: DyFM_Error = new DyFM_Error({
1429
+ ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1430
+
1431
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1432
+ message: `HTTP (open) server ERROR`,
1433
+ level: DyFM_ErrorLevel.serious,
1434
+ });
1435
+
1436
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1437
+ }
1438
+ })
1439
+ .on('uncaughtException', (exception): void => {
1440
+ const d_error: DyFM_Error = new DyFM_Error({
1441
+ ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1442
+
1443
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1444
+ message: `HTTP (open) server uncaughtException`,
1445
+ level: DyFM_ErrorLevel.critical,
1446
+ });
1447
+
1448
+ if (this.debugLog) {
1449
+ DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1450
+ }
1451
+
1452
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1453
+ });
1454
+ });
1455
+ }
1456
+ } catch (error) {
1457
+ throw new DyFM_Error({
1458
+ ...this._getDefaultErrorSettings('startExpresses', error),
1459
+
1460
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1461
+ });
1462
+ }
1463
+ }
1464
+
1465
+ /**
1466
+ *
1467
+ */
1468
+ private async expressErrorHandling(error, req, res, next): Promise<void> {
1469
+ try {
1470
+ if (error) {
1471
+ const d_error: DyFM_Error = new DyFM_Error({
1472
+ ...this._getDefaultErrorSettings('expressErrorHandling', error),
1473
+
1474
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1475
+ message: `Express ERROR`,
1476
+ additionalContent: {
1477
+ req,
1478
+ res,
1479
+ },
1480
+ level: DyFM_ErrorLevel.error,
1481
+ });
1482
+
1483
+ await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1484
+
1485
+ res.send(error)
1486
+ } else {
1487
+ DyFM_Log.H_error(
1488
+ 'WTF??? express error; without error?...' +
1489
+ '\nerr:', error,
1490
+ '\nreq:', req,
1491
+ '\nres:', res
1492
+ );
1493
+ }
1494
+ } catch (error) {
1495
+ DyFM_Log.H_error(
1496
+ 'MULTILEVEL ERROR (expressErrorHandling)....' +
1497
+ '\n', error
1498
+ );
1499
+ }
1500
+ }
1501
+
1502
+ /**
1503
+ *
1504
+ */
1505
+ private async mountSecureRoutes (): Promise<void> {
1506
+ try {
1507
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1508
+
1509
+ if (!this.secureExpress) {
1510
+ throw new Error(
1511
+ 'secureExpress was not initialized. ' +
1512
+ 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1513
+ '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1514
+ '\n\nYou need to set cert files in getCertificationSettings.'
1515
+ );
1516
+ }
1517
+
1518
+ this.secureExpress.use(
1519
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1520
+ );
1521
+
1522
+ await DyFM_Array.asyncForEach(
1523
+ this._routingModules,
1524
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1525
+ if (module.security !== DyNTS_RouteSecurity.open) {
1526
+ if (this.logSetup) {
1527
+ DyFM_Log.log(`route mount (secure): ${module.route}`);
1528
+ }
1529
+
1530
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1531
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1532
+ );
1533
+
1534
+ if (1 < existingRoutes.length) {
1535
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1536
+ /* const errorStack: string[] = error.stack.split('\n');
1537
+
1538
+ errorStack.splice(1, 4);
1539
+ error.stack = errorStack.join('\n'); */
1540
+ error.stack = module.stackLocation;
1541
+
1542
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1543
+
1544
+ throw new DyFM_Error({
1545
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1546
+
1547
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1548
+ message: `ROUTE DUPLICATION: ${module.route}`,
1549
+ });
1550
+ }
1551
+
1552
+ this.secureExpress.use(module.route, module.secureRouter);
1553
+ }
1554
+ }
1555
+ );
1556
+ } catch (error) {
1557
+ throw new DyFM_Error({
1558
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1559
+
1560
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1561
+ });
1562
+ }
1563
+ }
1564
+
1565
+ /**
1566
+ *
1567
+ */
1568
+ private async mountOpenRoutes(): Promise<void> {
1569
+ try {
1570
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1571
+
1572
+ if (!this.openExpress) {
1573
+ throw new Error(
1574
+ 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1575
+ '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1576
+ );
1577
+ }
1578
+
1579
+ this.openExpress.use(
1580
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1581
+ );
1582
+
1583
+ await DyFM_Array.asyncForEach(
1584
+ this._routingModules,
1585
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1586
+ if (module.security !== DyNTS_RouteSecurity.secure) {
1587
+ if (this.logSetup) {
1588
+ DyFM_Log.log(`route mount (open): ${module.route}`);
1589
+ }
1590
+
1591
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1592
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1593
+ );
1594
+
1595
+ if (1 < existingRoutes.length) {
1596
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1597
+ /* const errorStack: string[] = error.stack.split('\n');
1598
+
1599
+ errorStack.splice(1, 4);
1600
+ error.stack = errorStack.join('\n'); */
1601
+ error.stack = module.stackLocation;
1602
+
1603
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1604
+
1605
+ throw new DyFM_Error({
1606
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1607
+
1608
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1609
+ message: `ROUTE DUPLICATION: ${module.route}`,
1610
+ });
1611
+ }
1612
+
1613
+ this.openExpress.use(module.route, module.openRouter);
1614
+ }
1615
+ }
1616
+ );
1617
+ } catch (error) {
1618
+ throw new DyFM_Error({
1619
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1620
+
1621
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1622
+ });
1623
+ }
1624
+ }
1625
+
1626
+ /**
1627
+ * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1628
+ * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1629
+ * adds the canonical `Access-Control-*` companion headers, and short-circuits
1630
+ * the OPTIONS preflight with a 204.
1631
+ *
1632
+ * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1633
+ * back-compat for apps that have always been same-origin and never needed
1634
+ * CORS (the typical pre-FR-041 case).
1635
+ *
1636
+ * Why hand-rolled instead of the `cors` npm package:
1637
+ * - ~30 lines, zero new dependency.
1638
+ * - Full control over Vary/credentials/preflight semantics.
1639
+ * - Aligns with FDP "no unnecessary deps" philosophy.
1640
+ */
1641
+ /**
1642
+ * BFR-011 / SEC-R2-8 security response-headerek mountolása (a `mountCors` tükörképe).
1643
+ * A `DyNTS_global_settings.securityHeaders` alapján (default-ON) minden válaszra ráteszi a
1644
+ * biztonsági headereket + eltávolítja az `x-powered-by`-t. A CORS-mount ELŐTT hívandó, hogy az
1645
+ * OPTIONS preflight-válaszok (amiket a mountCors 204-gyel rövidre zár) is megkapják.
1646
+ */
1647
+ protected mountSecurityHeaders(express: Express.Application): void {
1648
+ const settings: DyNTS_SecurityHeaders_Settings | undefined = DyNTS_global_settings.securityHeaders;
1649
+ if (!settings || !settings.enabled) {
1650
+ return;
1651
+ }
1652
+
1653
+ if (settings.removePoweredBy !== false) {
1654
+ express.disable('x-powered-by');
1655
+ }
1656
+
1657
+ express.use(DyNTS_createSecurityHeadersMiddleware(
1658
+ settings,
1659
+ DyNTS_getEnvironment_settings().environment,
1660
+ ));
1661
+ }
1662
+
1663
+ protected mountCors(express: Express.Application): void {
1664
+ const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1665
+ if (!settings) {
1666
+ return;
1667
+ }
1668
+
1669
+ const allowCreds: boolean = settings.allowCredentials !== false;
1670
+ const methods: string[] = settings.allowedMethods ?? [
1671
+ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1672
+ ];
1673
+ const headers: string[] = settings.allowedHeaders ?? [
1674
+ 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1675
+ ];
1676
+ const exposed: string[] = settings.exposedHeaders ?? [
1677
+ 'Content-Length', 'Content-Type',
1678
+ ];
1679
+ const maxAge: number = settings.maxAgeSeconds ?? 86400;
1680
+
1681
+ const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1682
+ if (settings.allowedOrigins === '*') return true;
1683
+ if (typeof settings.allowedOrigins === 'function') {
1684
+ return settings.allowedOrigins(origin);
1685
+ }
1686
+ return settings.allowedOrigins.includes(origin);
1687
+ };
1688
+
1689
+ express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1690
+ const origin: string | undefined = req.headers.origin;
1691
+ if (origin && isAllowed(origin)) {
1692
+ // Echo the matching origin (NOT wildcard) because credentials require it.
1693
+ res.setHeader('Access-Control-Allow-Origin', origin);
1694
+ if (allowCreds) {
1695
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
1696
+ }
1697
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1698
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1699
+ res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1700
+ res.setHeader('Access-Control-Max-Age', String(maxAge));
1701
+ res.setHeader('Vary', 'Origin');
1702
+ }
1703
+ if (req.method === 'OPTIONS') {
1704
+ res.status(204).end();
1705
+ return;
1706
+ }
1707
+ next();
1708
+ });
1709
+ }
1710
+
1711
+ /**
1712
+ * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1713
+ * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1714
+ * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1715
+ * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1716
+ * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1717
+ */
1718
+ private async mountCustomMiddleware(): Promise<void> {
1719
+ if (!this.registerCustomMiddleware) {
1720
+ return;
1721
+ }
1722
+
1723
+ if (this.openExpress) {
1724
+ await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1725
+ }
1726
+
1727
+ if (this.secureExpress) {
1728
+ await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1729
+ }
1730
+
1731
+ if (this.logSetup) {
1732
+ DyFM_Log.log('\nCustom middleware registered (pre-static).');
1733
+ }
1734
+ }
1735
+
1736
+ /**
1737
+ * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1738
+ * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1739
+ * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1740
+ * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1741
+ */
1742
+ private async mountStaticClient(): Promise<void> {
1743
+ const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1744
+ if (!settings) {
1745
+ return;
1746
+ }
1747
+
1748
+ const absoluteRoot: string = Path.isAbsolute(settings.root)
1749
+ ? settings.root
1750
+ : Path.resolve(process.cwd(), settings.root);
1751
+
1752
+ const hasAssetCache: boolean =
1753
+ settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1754
+ const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1755
+ hasAssetCache && settings.assetCacheMaxAge !== undefined
1756
+ ? {
1757
+ setHeaders: (res: Express.Response, filePath: string): void => {
1758
+ // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1759
+ // immutable long-cache-t lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1760
+ res.setHeader(
1761
+ 'Cache-Control',
1762
+ DyNTS_resolveStaticCacheControlHeader({
1763
+ filePath: filePath,
1764
+ assetCacheMaxAge: settings.assetCacheMaxAge!,
1765
+ assetCacheImmutable: settings.assetCacheImmutable === true,
1766
+ }),
1767
+ );
1768
+ },
1769
+ }
1770
+ : undefined;
1771
+
1772
+ const staticMiddleware: Express.Handler =
1773
+ staticOptions
1774
+ ? Express.static(absoluteRoot, staticOptions)
1775
+ : Express.static(absoluteRoot);
1776
+
1777
+ const fallbackMaxAge: number =
1778
+ settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1779
+
1780
+ if (this.openExpress) {
1781
+ this.openExpress.use('/', staticMiddleware);
1782
+ if (settings.fallbackPath) {
1783
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1784
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1785
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1786
+ });
1787
+ } else {
1788
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1789
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1790
+ });
1791
+ }
1792
+ }
1793
+
1794
+ if (this.secureExpress) {
1795
+ this.secureExpress.use('/', staticMiddleware);
1796
+ if (settings.fallbackPath) {
1797
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1798
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1799
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1800
+ });
1801
+ } else {
1802
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1803
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1804
+ });
1805
+ }
1806
+ }
1807
+
1808
+ if (this.logSetup) {
1809
+ DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1810
+ }
1811
+ }
1812
+
1813
+ /**
1814
+ *
1815
+ */
1816
+ private setSecurity(): void {
1817
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1818
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1819
+ if (!module.security) {
1820
+ DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1821
+
1822
+ } else if (!this._security) {
1823
+ this._security = module.security;
1824
+
1825
+ } else if (this._security !== module.security) {
1826
+ this._security = DyNTS_RouteSecurity.both;
1827
+ }
1828
+ });
1829
+
1830
+ if (!this._security) {
1831
+ let msg = `Could not set security for the server! (${this.security})`;
1832
+
1833
+ msg += '\n RoutingModules:';
1834
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1835
+ msg += `\n ${module.route} (security: ${module.security})`;
1836
+ });
1837
+
1838
+ if (this._routingModules.length === 0) {
1839
+ msg += '\n - no RoutingModule found -\n';
1840
+ }
1841
+ DyFM_Log.warn(msg);
1842
+ }
1843
+ }
1844
+
1845
+ private _getDefaultErrorSettings(
1846
+ fnName: string,
1847
+ error: DyFM_AnyError
1848
+ ): DyFM_Error_Settings {
1849
+ return {
1850
+ status: (error as DyFM_Error)?.___status ?? 500,
1851
+ message: (error as Error)?.message ??
1852
+ (error as DyFM_Error)?._message ??
1853
+ `${fnName} was UNSUCCESSFUL (NTS)`,
1854
+ userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1855
+ addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1856
+ issuerService: `${this?.constructor?.name}-DyNTS_App`,
1857
+ level: DyFM_ErrorLevel.fatal,
1858
+ error: error,
1859
+ systemVersion: DyNTS_global_settings.systemVersion,
1860
+ };
1861
+ }
1862
+
1863
+ /**
1864
+ * MISSING Description (TODO)
1865
+ */
1866
+ abstract getAppParams(): DyNTS_App_Params;
1867
+
1868
+ /**
1869
+ * MISSING Description (TODO)
1870
+ */
1871
+ abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1872
+
1873
+ /**
1874
+ * MISSING Description (TODO)
1875
+ */
1876
+ abstract getPortSettings(): DyNTS_Http_Settings;
1877
+
1878
+ /**
1879
+ * MISSING Description (TODO)
1880
+ */
1881
+ overrideDynamoNTSGlobalSettings?(): void;
1882
+
1883
+ /**
1884
+ * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1885
+ * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1886
+ */
1887
+ getApiBasePath?(): string;
1888
+
1889
+ /**
1890
+ * MISSING Description (TODO)
1891
+ */
1892
+ getRoutingModules?(): DyNTS_RoutingModule[];
1893
+
1894
+ /**
1895
+ * MISSING Description (TODO)
1896
+ */
1897
+ getRootServices?(): Promise<any[]>;
1898
+
1899
+ /**
1900
+ * MISSING Description (TODO)
1901
+ */
1902
+ getCertificationSettings?(): DyNTS_Certification_Settings;
1903
+
1904
+ /**
1905
+ * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1906
+ * Opcionális fallbackPath pl. SPA index.html-hez.
1907
+ */
1908
+ getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1909
+
1910
+ /**
1911
+ * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1912
+ * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1913
+ * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1914
+ * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1915
+ * Ha undefined → no CORS headers, no preflight handling — back-compat.
1916
+ */
1917
+ getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1918
+
1919
+ /**
1920
+ * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1921
+ * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1922
+ * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1923
+ * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1924
+ * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1925
+ */
1926
+ registerCustomMiddleware?(
1927
+ express: Express.Application,
1928
+ security: DyNTS_RouteSecurity,
1929
+ ): void | Promise<void>;
1930
+
1931
+ /**
1932
+ * MISSING Description (TODO)
1933
+ */
1934
+ createEntries?(): Promise<void>;
1935
+
1936
+ /**
1937
+ * MISSING Description (TODO)
1938
+ */
1939
+ postProcess?(): Promise<void>;
1940
+
1941
+ }