@futdevpro/nts-dynamo 1.15.103 → 1.15.104

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