@futdevpro/nts-dynamo 1.15.98 → 1.15.100

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