@futdevpro/nts-dynamo 1.15.52 → 1.15.54

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