@resolveio/server-lib 22.3.54 → 22.3.55

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 (691) hide show
  1. package/.nodemon.json +5 -0
  2. package/.vscode/settings.json +21 -0
  3. package/AGENTS.md +189 -0
  4. package/README.md +22 -0
  5. package/build_package.sh +5 -0
  6. package/compileDTS.pl +64 -0
  7. package/docs/ai-assistant-nightly-eval.md +65 -0
  8. package/docs/ai-assistant-preflight-checklist.md +23 -0
  9. package/docs/ai-assistant-report-builder-bridge-playbook.md +115 -0
  10. package/eslint-plugin-custom/index.js +7 -0
  11. package/eslint-plugin-custom/rules/no-filter-zero-index.js +44 -0
  12. package/eslint.config.js +103 -0
  13. package/gulpfile.js +216 -0
  14. package/methodAndPublicationListGenerator.py +375 -0
  15. package/mongodbensurers.js +2 -0
  16. package/mongostop.js +3 -0
  17. package/package.json +1 -1
  18. package/scripts/cleanup-bypassed-callmethod-logs.js +616 -0
  19. package/settings.development.json +25 -0
  20. package/settings.development.redacted.json +25 -0
  21. package/src/.env +12 -0
  22. package/src/ai/assistant-core-heuristics.ts +379 -0
  23. package/src/ai/resolveio-platform-intelligence-memory-corpus.ts +185 -0
  24. package/src/ai/resolveio-platform-intelligence-memory.ts +325 -0
  25. package/{ai/resolveio-platform-intelligence-types.d.ts → src/ai/resolveio-platform-intelligence-types.ts} +20 -15
  26. package/src/ai/resolveio-platform-intelligence.ts +462 -0
  27. package/src/client-server-app.ts +12 -0
  28. package/src/collections/ai-terminal-conversation.collection.ts +91 -0
  29. package/src/collections/ai-terminal-issue-report.collection.ts +99 -0
  30. package/src/collections/ai-terminal-message.collection.ts +77 -0
  31. package/src/collections/app-setting.collection.ts +104 -0
  32. package/src/collections/app-status.collection.ts +58 -0
  33. package/src/collections/communication-metric.collection.ts +84 -0
  34. package/src/collections/counter.collection.ts +56 -0
  35. package/src/collections/cron-job-history.collection.ts +94 -0
  36. package/src/collections/cron-job.collection.ts +92 -0
  37. package/src/collections/customer-notification.collection.ts +131 -0
  38. package/src/collections/customer-portal-password.collection.ts +76 -0
  39. package/src/collections/email-history.collection.ts +127 -0
  40. package/src/collections/email-verified.collection.ts +62 -0
  41. package/src/collections/file.collection.ts +74 -0
  42. package/src/collections/flag-update.collection.ts +57 -0
  43. package/src/collections/flag.collection.ts +57 -0
  44. package/src/collections/log-method-latency.collection.ts +77 -0
  45. package/src/collections/log-subscription.collection.ts +80 -0
  46. package/src/collections/log.collection.ts +93 -0
  47. package/src/collections/logged-in-users.collection.ts +67 -0
  48. package/src/collections/monitor-cpu.collection.ts +65 -0
  49. package/src/collections/monitor-function.collection.ts +74 -0
  50. package/src/collections/monitor-memory.collection.ts +77 -0
  51. package/src/collections/monitor-mongo.collection.ts +71 -0
  52. package/src/collections/notification.collection.ts +57 -0
  53. package/src/collections/openai-usage-ledger.collection.ts +77 -0
  54. package/src/collections/report-builder-dashboard-builder.collection.ts +109 -0
  55. package/src/collections/report-builder-library.collection.ts +89 -0
  56. package/src/collections/report-builder-report.collection.ts +184 -0
  57. package/src/collections/user-group.collection.ts +89 -0
  58. package/src/collections/user-guide.collection.ts +57 -0
  59. package/src/collections/user.collection.ts +181 -0
  60. package/src/cron/cron.ts +117 -0
  61. package/src/fixtures/cron-jobs.ts +95 -0
  62. package/src/fixtures/init.ts +35 -0
  63. package/src/http/auth.ts +764 -0
  64. package/src/http/health.ts +7 -0
  65. package/src/http/home.ts +90 -0
  66. package/src/http/slow-query-publication.ts +49 -0
  67. package/src/index.ts +1 -0
  68. package/src/managers/ai-assistant-codex-manager.manager.ts +1131 -0
  69. package/src/managers/communication-metric.manager.ts +82 -0
  70. package/src/managers/cron.manager.ts +333 -0
  71. package/src/managers/customer-notification-content.manager.ts +236 -0
  72. package/src/managers/diagnostic-manager-bootstrap.ts +165 -0
  73. package/src/managers/error-auto-fix.manager.ts +2767 -0
  74. package/src/managers/local-log.manager.ts +113 -0
  75. package/src/managers/method.manager.ts +1827 -0
  76. package/src/managers/mongo.manager.ts +4575 -0
  77. package/src/managers/monitor.manager.ts +507 -0
  78. package/src/managers/openai-usage-ledger.manager.ts +116 -0
  79. package/src/managers/slow-query-verifier.manager.ts +3590 -0
  80. package/src/managers/slow-query.manager.ts +519 -0
  81. package/src/managers/subscription.manager.ts +3128 -0
  82. package/src/managers/websocket.manager.ts +746 -0
  83. package/src/managers/worker-dispatcher.manager.ts +1360 -0
  84. package/src/managers/worker-server.manager.ts +536 -0
  85. package/src/methods/accounts.ts +532 -0
  86. package/src/methods/ai-terminal.ts +23134 -0
  87. package/src/methods/app-settings.ts +114 -0
  88. package/src/methods/aws.ts +649 -0
  89. package/src/methods/collections.ts +641 -0
  90. package/src/methods/counters.ts +69 -0
  91. package/src/methods/cron-jobs.ts +2614 -0
  92. package/src/methods/customer-notifications.ts +458 -0
  93. package/src/methods/diagnostics.ts +616 -0
  94. package/src/methods/flag-updates.ts +7 -0
  95. package/src/methods/flags.ts +7 -0
  96. package/src/methods/logs.ts +657 -0
  97. package/src/methods/mongo-explorer.ts +1880 -0
  98. package/src/methods/monitor.ts +540 -0
  99. package/src/methods/pdf.ts +1236 -0
  100. package/src/methods/publications.ts +129 -0
  101. package/src/methods/report-builder.ts +3300 -0
  102. package/src/methods/support.ts +335 -0
  103. package/src/models/ai-terminal-conversation.model.ts +19 -0
  104. package/src/models/ai-terminal-issue-report.model.ts +21 -0
  105. package/src/models/ai-terminal-message.model.ts +24 -0
  106. package/src/models/app-setting.model.ts +17 -0
  107. package/{models/app-status.model.d.ts → src/models/app-status.model.ts} +3 -2
  108. package/{models/billing-logged-in-users.model.d.ts → src/models/billing-logged-in-users.model.ts} +5 -4
  109. package/src/models/collection-document.model.ts +24 -0
  110. package/src/models/communication-metric.model.ts +23 -0
  111. package/{models/counter.model.d.ts → src/models/counter.model.ts} +4 -3
  112. package/src/models/cron-job-history.model.ts +16 -0
  113. package/src/models/cron-job.model.ts +15 -0
  114. package/src/models/customer-notification.model.ts +28 -0
  115. package/src/models/customer-portal-password.model.ts +12 -0
  116. package/src/models/dialog.model.ts +25 -0
  117. package/{models/email-history.model.js → src/models/email-history.model.ts} +35 -4
  118. package/{models/email-verified.model.d.ts → src/models/email-verified.model.ts} +6 -5
  119. package/{models/file.model.d.ts → src/models/file.model.ts} +8 -7
  120. package/{models/flag-update.model.d.ts → src/models/flag-update.model.ts} +4 -3
  121. package/{models/flag.model.d.ts → src/models/flag.model.ts} +4 -3
  122. package/src/models/log-method-latency.model.ts +11 -0
  123. package/{models/log-subscription.model.d.ts → src/models/log-subscription.model.ts} +11 -9
  124. package/src/models/log.model.ts +19 -0
  125. package/{models/logged-in-users.model.d.ts → src/models/logged-in-users.model.ts} +6 -5
  126. package/{models/method-response.model.d.ts → src/models/method-response.model.ts} +7 -6
  127. package/src/models/method.model.ts +25 -0
  128. package/{models/monitor-cpu.model.d.ts → src/models/monitor-cpu.model.ts} +9 -7
  129. package/src/models/monitor-function.model.ts +16 -0
  130. package/src/models/monitor-memory.model.ts +17 -0
  131. package/src/models/monitor-mongo.model.ts +15 -0
  132. package/{models/notification.model.d.ts → src/models/notification.model.ts} +6 -4
  133. package/src/models/openai-usage-ledger.model.ts +16 -0
  134. package/src/models/pagination.model.ts +35 -0
  135. package/src/models/permission.model.ts +14 -0
  136. package/src/models/report-builder-dashboard-builder.model.ts +29 -0
  137. package/src/models/report-builder-library.model.ts +20 -0
  138. package/src/models/report-builder-report.model.ts +136 -0
  139. package/src/models/report-builder.model.ts +68 -0
  140. package/src/models/select-data-label.model.ts +9 -0
  141. package/src/models/server-message.model.ts +31 -0
  142. package/src/models/slow-query-report.model.ts +23 -0
  143. package/src/models/subscription.model.ts +73 -0
  144. package/src/models/support-ticket.model.ts +104 -0
  145. package/src/models/user-group.model.ts +24 -0
  146. package/{models/user-guide.model.d.ts → src/models/user-guide.model.ts} +5 -4
  147. package/src/models/user.model.ts +96 -0
  148. package/src/private/images/ResolveIO.png +0 -0
  149. package/src/publications/ai-terminal.ts +73 -0
  150. package/src/publications/app-settings.ts +25 -0
  151. package/src/publications/app-status.ts +13 -0
  152. package/src/publications/cron-jobs.ts +40 -0
  153. package/src/publications/customer-notifications.ts +101 -0
  154. package/src/publications/files.ts +33 -0
  155. package/src/publications/flags-update.ts +19 -0
  156. package/src/publications/flags.ts +19 -0
  157. package/src/publications/logs.ts +163 -0
  158. package/src/publications/notifications.ts +13 -0
  159. package/src/publications/report-builder-dashboard-builders.ts +39 -0
  160. package/src/publications/report-builder-libraries.ts +41 -0
  161. package/src/publications/report-builder-reports.ts +47 -0
  162. package/src/publications/super-admin.ts +13 -0
  163. package/src/publications/user-groups.ts +12 -0
  164. package/src/publications/user-guides.ts +12 -0
  165. package/src/resolveio-server-app.ts +617 -0
  166. package/src/server-app.ts +3354 -0
  167. package/src/services/codex-client.ts +1223 -0
  168. package/src/services/openai-client.ts +265 -0
  169. package/src/types/error-report.ts +26 -0
  170. package/src/types/js-tiktoken.d.ts +11 -0
  171. package/src/types/slow-query-report.ts +28 -0
  172. package/src/util/ai-qa-policy.ts +879 -0
  173. package/src/util/ai-runner-artifacts.ts +430 -0
  174. package/src/util/ai-runner-qa-auth.ts +356 -0
  175. package/src/util/ai-runner-qa-tools.ts +708 -0
  176. package/src/util/common.ts +649 -0
  177. package/src/util/customer-portal-password.ts +183 -0
  178. package/src/util/error-reporter.ts +332 -0
  179. package/src/util/error-tracking.ts +79 -0
  180. package/src/util/report-builder-unwinds.ts +180 -0
  181. package/src/util/runner-process-janitor.ts +195 -0
  182. package/src/util/schema-report-builder.ts +448 -0
  183. package/src/util/slow-query-reporter.ts +216 -0
  184. package/src/util/subscription-dependency-context.ts +1096 -0
  185. package/src/util/tokenizer.ts +38 -0
  186. package/src/workers/codex-runner.worker.ts +142 -0
  187. package/start_server.sh +5 -0
  188. package/tests/ai-assistant-corpus-build.ts +484 -0
  189. package/tests/ai-assistant-corpus-replay-e2e.ts +774 -0
  190. package/tests/ai-assistant-data-parity-e2e.ts +1989 -0
  191. package/tests/ai-assistant-eval-triage.ts +831 -0
  192. package/tests/ai-assistant-openai-e2e.ts +1061 -0
  193. package/tests/ai-assistant-openai-git-e2e.ts +155 -0
  194. package/tests/ai-assistant-preflight-matrix.ts +215 -0
  195. package/tests/ai-assistant-routing-eval.test.ts +560 -0
  196. package/tests/ai-assistant-snf-live-eval.ts +975 -0
  197. package/tests/ai-assistant-utils.test.ts +2968 -0
  198. package/tests/ai-runner-contract.test.ts +287 -0
  199. package/tests/error-reporter.test.ts +145 -0
  200. package/tests/method-publication-generator.test.ts +46 -0
  201. package/tests/report-builder-linking.test.ts +79 -0
  202. package/tests/resolveio-platform-intelligence.test.ts +352 -0
  203. package/tests/server-app-cron-owner.test.ts +127 -0
  204. package/tests/subscription-connect-race.test.ts +158 -0
  205. package/tests/subscription-dependency-context.test.ts +324 -0
  206. package/tests/subscription-manager-collection-tracking.test.ts +86 -0
  207. package/tests/subscription-manager-invalidation.test.ts +86 -0
  208. package/tsconfig.json +34 -0
  209. package/ai/assistant-core-heuristics.d.ts +0 -11
  210. package/ai/assistant-core-heuristics.js +0 -356
  211. package/ai/assistant-core-heuristics.js.map +0 -1
  212. package/ai/resolveio-platform-intelligence-memory-corpus.d.ts +0 -3
  213. package/ai/resolveio-platform-intelligence-memory-corpus.js +0 -214
  214. package/ai/resolveio-platform-intelligence-memory-corpus.js.map +0 -1
  215. package/ai/resolveio-platform-intelligence-memory.d.ts +0 -20
  216. package/ai/resolveio-platform-intelligence-memory.js +0 -341
  217. package/ai/resolveio-platform-intelligence-memory.js.map +0 -1
  218. package/ai/resolveio-platform-intelligence-types.js +0 -4
  219. package/ai/resolveio-platform-intelligence-types.js.map +0 -1
  220. package/ai/resolveio-platform-intelligence.d.ts +0 -6
  221. package/ai/resolveio-platform-intelligence.js +0 -463
  222. package/ai/resolveio-platform-intelligence.js.map +0 -1
  223. package/client-server-app.d.ts +0 -1
  224. package/client-server-app.js +0 -68
  225. package/client-server-app.js.map +0 -1
  226. package/collections/ai-terminal-conversation.collection.d.ts +0 -2
  227. package/collections/ai-terminal-conversation.collection.js +0 -140
  228. package/collections/ai-terminal-conversation.collection.js.map +0 -1
  229. package/collections/ai-terminal-issue-report.collection.d.ts +0 -2
  230. package/collections/ai-terminal-issue-report.collection.js +0 -148
  231. package/collections/ai-terminal-issue-report.collection.js.map +0 -1
  232. package/collections/ai-terminal-message.collection.d.ts +0 -2
  233. package/collections/ai-terminal-message.collection.js +0 -121
  234. package/collections/ai-terminal-message.collection.js.map +0 -1
  235. package/collections/app-setting.collection.d.ts +0 -3
  236. package/collections/app-setting.collection.js +0 -103
  237. package/collections/app-setting.collection.js.map +0 -1
  238. package/collections/app-status.collection.d.ts +0 -3
  239. package/collections/app-status.collection.js +0 -57
  240. package/collections/app-status.collection.js.map +0 -1
  241. package/collections/communication-metric.collection.d.ts +0 -2
  242. package/collections/communication-metric.collection.js +0 -133
  243. package/collections/communication-metric.collection.js.map +0 -1
  244. package/collections/counter.collection.d.ts +0 -3
  245. package/collections/counter.collection.js +0 -56
  246. package/collections/counter.collection.js.map +0 -1
  247. package/collections/cron-job-history.collection.d.ts +0 -3
  248. package/collections/cron-job-history.collection.js +0 -137
  249. package/collections/cron-job-history.collection.js.map +0 -1
  250. package/collections/cron-job.collection.d.ts +0 -3
  251. package/collections/cron-job.collection.js +0 -92
  252. package/collections/cron-job.collection.js.map +0 -1
  253. package/collections/customer-notification.collection.d.ts +0 -3
  254. package/collections/customer-notification.collection.js +0 -130
  255. package/collections/customer-notification.collection.js.map +0 -1
  256. package/collections/customer-portal-password.collection.d.ts +0 -3
  257. package/collections/customer-portal-password.collection.js +0 -75
  258. package/collections/customer-portal-password.collection.js.map +0 -1
  259. package/collections/email-history.collection.d.ts +0 -3
  260. package/collections/email-history.collection.js +0 -127
  261. package/collections/email-history.collection.js.map +0 -1
  262. package/collections/email-verified.collection.d.ts +0 -3
  263. package/collections/email-verified.collection.js +0 -62
  264. package/collections/email-verified.collection.js.map +0 -1
  265. package/collections/file.collection.d.ts +0 -3
  266. package/collections/file.collection.js +0 -74
  267. package/collections/file.collection.js.map +0 -1
  268. package/collections/flag-update.collection.d.ts +0 -3
  269. package/collections/flag-update.collection.js +0 -57
  270. package/collections/flag-update.collection.js.map +0 -1
  271. package/collections/flag.collection.d.ts +0 -3
  272. package/collections/flag.collection.js +0 -57
  273. package/collections/flag.collection.js.map +0 -1
  274. package/collections/log-method-latency.collection.d.ts +0 -3
  275. package/collections/log-method-latency.collection.js +0 -77
  276. package/collections/log-method-latency.collection.js.map +0 -1
  277. package/collections/log-subscription.collection.d.ts +0 -3
  278. package/collections/log-subscription.collection.js +0 -80
  279. package/collections/log-subscription.collection.js.map +0 -1
  280. package/collections/log.collection.d.ts +0 -3
  281. package/collections/log.collection.js +0 -93
  282. package/collections/log.collection.js.map +0 -1
  283. package/collections/logged-in-users.collection.d.ts +0 -3
  284. package/collections/logged-in-users.collection.js +0 -67
  285. package/collections/logged-in-users.collection.js.map +0 -1
  286. package/collections/monitor-cpu.collection.d.ts +0 -3
  287. package/collections/monitor-cpu.collection.js +0 -65
  288. package/collections/monitor-cpu.collection.js.map +0 -1
  289. package/collections/monitor-function.collection.d.ts +0 -3
  290. package/collections/monitor-function.collection.js +0 -74
  291. package/collections/monitor-function.collection.js.map +0 -1
  292. package/collections/monitor-memory.collection.d.ts +0 -3
  293. package/collections/monitor-memory.collection.js +0 -77
  294. package/collections/monitor-memory.collection.js.map +0 -1
  295. package/collections/monitor-mongo.collection.d.ts +0 -3
  296. package/collections/monitor-mongo.collection.js +0 -71
  297. package/collections/monitor-mongo.collection.js.map +0 -1
  298. package/collections/notification.collection.d.ts +0 -3
  299. package/collections/notification.collection.js +0 -57
  300. package/collections/notification.collection.js.map +0 -1
  301. package/collections/openai-usage-ledger.collection.d.ts +0 -2
  302. package/collections/openai-usage-ledger.collection.js +0 -124
  303. package/collections/openai-usage-ledger.collection.js.map +0 -1
  304. package/collections/report-builder-dashboard-builder.collection.d.ts +0 -3
  305. package/collections/report-builder-dashboard-builder.collection.js +0 -109
  306. package/collections/report-builder-dashboard-builder.collection.js.map +0 -1
  307. package/collections/report-builder-library.collection.d.ts +0 -3
  308. package/collections/report-builder-library.collection.js +0 -87
  309. package/collections/report-builder-library.collection.js.map +0 -1
  310. package/collections/report-builder-report.collection.d.ts +0 -4
  311. package/collections/report-builder-report.collection.js +0 -184
  312. package/collections/report-builder-report.collection.js.map +0 -1
  313. package/collections/user-group.collection.d.ts +0 -4
  314. package/collections/user-group.collection.js +0 -89
  315. package/collections/user-group.collection.js.map +0 -1
  316. package/collections/user-guide.collection.d.ts +0 -3
  317. package/collections/user-guide.collection.js +0 -57
  318. package/collections/user-guide.collection.js.map +0 -1
  319. package/collections/user.collection.d.ts +0 -4
  320. package/collections/user.collection.js +0 -180
  321. package/collections/user.collection.js.map +0 -1
  322. package/cron/cron.d.ts +0 -14
  323. package/cron/cron.js +0 -216
  324. package/cron/cron.js.map +0 -1
  325. package/fixtures/cron-jobs.d.ts +0 -1
  326. package/fixtures/cron-jobs.js +0 -150
  327. package/fixtures/cron-jobs.js.map +0 -1
  328. package/fixtures/init.d.ts +0 -1
  329. package/fixtures/init.js +0 -91
  330. package/fixtures/init.js.map +0 -1
  331. package/http/auth.d.ts +0 -2
  332. package/http/auth.js +0 -906
  333. package/http/auth.js.map +0 -1
  334. package/http/health.d.ts +0 -1
  335. package/http/health.js +0 -11
  336. package/http/health.js.map +0 -1
  337. package/http/home.d.ts +0 -1
  338. package/http/home.js +0 -134
  339. package/http/home.js.map +0 -1
  340. package/http/slow-query-publication.d.ts +0 -2
  341. package/http/slow-query-publication.js +0 -99
  342. package/http/slow-query-publication.js.map +0 -1
  343. package/index.d.ts +0 -1
  344. package/index.js +0 -19
  345. package/index.js.map +0 -1
  346. package/managers/ai-assistant-codex-manager.manager.d.ts +0 -67
  347. package/managers/ai-assistant-codex-manager.manager.js +0 -1113
  348. package/managers/ai-assistant-codex-manager.manager.js.map +0 -1
  349. package/managers/communication-metric.manager.d.ts +0 -16
  350. package/managers/communication-metric.manager.js +0 -134
  351. package/managers/communication-metric.manager.js.map +0 -1
  352. package/managers/cron.manager.d.ts +0 -20
  353. package/managers/cron.manager.js +0 -534
  354. package/managers/cron.manager.js.map +0 -1
  355. package/managers/customer-notification-content.manager.d.ts +0 -55
  356. package/managers/customer-notification-content.manager.js +0 -158
  357. package/managers/customer-notification-content.manager.js.map +0 -1
  358. package/managers/diagnostic-manager-bootstrap.d.ts +0 -9
  359. package/managers/diagnostic-manager-bootstrap.js +0 -260
  360. package/managers/diagnostic-manager-bootstrap.js.map +0 -1
  361. package/managers/error-auto-fix.manager.d.ts +0 -149
  362. package/managers/error-auto-fix.manager.js +0 -3064
  363. package/managers/error-auto-fix.manager.js.map +0 -1
  364. package/managers/local-log.manager.d.ts +0 -18
  365. package/managers/local-log.manager.js +0 -88
  366. package/managers/local-log.manager.js.map +0 -1
  367. package/managers/method.manager.d.ts +0 -83
  368. package/managers/method.manager.js +0 -1941
  369. package/managers/method.manager.js.map +0 -1
  370. package/managers/mongo.manager.d.ts +0 -224
  371. package/managers/mongo.manager.js +0 -5000
  372. package/managers/mongo.manager.js.map +0 -1
  373. package/managers/monitor.manager.d.ts +0 -70
  374. package/managers/monitor.manager.js +0 -550
  375. package/managers/monitor.manager.js.map +0 -1
  376. package/managers/openai-usage-ledger.manager.d.ts +0 -15
  377. package/managers/openai-usage-ledger.manager.js +0 -144
  378. package/managers/openai-usage-ledger.manager.js.map +0 -1
  379. package/managers/slow-query-verifier.manager.d.ts +0 -144
  380. package/managers/slow-query-verifier.manager.js +0 -3857
  381. package/managers/slow-query-verifier.manager.js.map +0 -1
  382. package/managers/slow-query.manager.d.ts +0 -28
  383. package/managers/slow-query.manager.js +0 -468
  384. package/managers/slow-query.manager.js.map +0 -1
  385. package/managers/subscription.manager.d.ts +0 -169
  386. package/managers/subscription.manager.js +0 -3434
  387. package/managers/subscription.manager.js.map +0 -1
  388. package/managers/websocket.manager.d.ts +0 -73
  389. package/managers/websocket.manager.js +0 -673
  390. package/managers/websocket.manager.js.map +0 -1
  391. package/managers/worker-dispatcher.manager.d.ts +0 -120
  392. package/managers/worker-dispatcher.manager.js +0 -1266
  393. package/managers/worker-dispatcher.manager.js.map +0 -1
  394. package/managers/worker-server.manager.d.ts +0 -35
  395. package/managers/worker-server.manager.js +0 -582
  396. package/managers/worker-server.manager.js.map +0 -1
  397. package/methods/accounts.d.ts +0 -2
  398. package/methods/accounts.js +0 -624
  399. package/methods/accounts.js.map +0 -1
  400. package/methods/ai-terminal.d.ts +0 -336
  401. package/methods/ai-terminal.js +0 -22782
  402. package/methods/ai-terminal.js.map +0 -1
  403. package/methods/app-settings.d.ts +0 -2
  404. package/methods/app-settings.js +0 -169
  405. package/methods/app-settings.js.map +0 -1
  406. package/methods/aws.d.ts +0 -2
  407. package/methods/aws.js +0 -877
  408. package/methods/aws.js.map +0 -1
  409. package/methods/collections.d.ts +0 -2
  410. package/methods/collections.js +0 -719
  411. package/methods/collections.js.map +0 -1
  412. package/methods/counters.d.ts +0 -2
  413. package/methods/counters.js +0 -113
  414. package/methods/counters.js.map +0 -1
  415. package/methods/cron-jobs.d.ts +0 -2
  416. package/methods/cron-jobs.js +0 -2475
  417. package/methods/cron-jobs.js.map +0 -1
  418. package/methods/customer-notifications.d.ts +0 -2
  419. package/methods/customer-notifications.js +0 -528
  420. package/methods/customer-notifications.js.map +0 -1
  421. package/methods/diagnostics.d.ts +0 -2
  422. package/methods/diagnostics.js +0 -703
  423. package/methods/diagnostics.js.map +0 -1
  424. package/methods/flag-updates.d.ts +0 -2
  425. package/methods/flag-updates.js +0 -8
  426. package/methods/flag-updates.js.map +0 -1
  427. package/methods/flags.d.ts +0 -2
  428. package/methods/flags.js +0 -8
  429. package/methods/flags.js.map +0 -1
  430. package/methods/logs.d.ts +0 -2
  431. package/methods/logs.js +0 -751
  432. package/methods/logs.js.map +0 -1
  433. package/methods/mongo-explorer.d.ts +0 -2
  434. package/methods/mongo-explorer.js +0 -1808
  435. package/methods/mongo-explorer.js.map +0 -1
  436. package/methods/monitor.d.ts +0 -2
  437. package/methods/monitor.js +0 -543
  438. package/methods/monitor.js.map +0 -1
  439. package/methods/pdf.d.ts +0 -2
  440. package/methods/pdf.js +0 -1216
  441. package/methods/pdf.js.map +0 -1
  442. package/methods/publications.d.ts +0 -1
  443. package/methods/publications.js +0 -183
  444. package/methods/publications.js.map +0 -1
  445. package/methods/report-builder.d.ts +0 -2
  446. package/methods/report-builder.js +0 -3094
  447. package/methods/report-builder.js.map +0 -1
  448. package/methods/support.d.ts +0 -2
  449. package/methods/support.js +0 -430
  450. package/methods/support.js.map +0 -1
  451. package/models/ai-terminal-conversation.model.d.ts +0 -17
  452. package/models/ai-terminal-conversation.model.js +0 -4
  453. package/models/ai-terminal-conversation.model.js.map +0 -1
  454. package/models/ai-terminal-issue-report.model.d.ts +0 -19
  455. package/models/ai-terminal-issue-report.model.js +0 -4
  456. package/models/ai-terminal-issue-report.model.js.map +0 -1
  457. package/models/ai-terminal-message.model.d.ts +0 -22
  458. package/models/ai-terminal-message.model.js +0 -4
  459. package/models/ai-terminal-message.model.js.map +0 -1
  460. package/models/app-setting.model.d.ts +0 -16
  461. package/models/app-setting.model.js +0 -4
  462. package/models/app-setting.model.js.map +0 -1
  463. package/models/app-status.model.js +0 -4
  464. package/models/app-status.model.js.map +0 -1
  465. package/models/billing-logged-in-users.model.js +0 -4
  466. package/models/billing-logged-in-users.model.js.map +0 -1
  467. package/models/collection-document.model.d.ts +0 -21
  468. package/models/collection-document.model.js +0 -4
  469. package/models/collection-document.model.js.map +0 -1
  470. package/models/communication-metric.model.d.ts +0 -20
  471. package/models/communication-metric.model.js +0 -4
  472. package/models/communication-metric.model.js.map +0 -1
  473. package/models/counter.model.js +0 -4
  474. package/models/counter.model.js.map +0 -1
  475. package/models/cron-job-history.model.d.ts +0 -15
  476. package/models/cron-job-history.model.js +0 -4
  477. package/models/cron-job-history.model.js.map +0 -1
  478. package/models/cron-job.model.d.ts +0 -14
  479. package/models/cron-job.model.js +0 -4
  480. package/models/cron-job.model.js.map +0 -1
  481. package/models/customer-notification.model.d.ts +0 -26
  482. package/models/customer-notification.model.js +0 -4
  483. package/models/customer-notification.model.js.map +0 -1
  484. package/models/customer-portal-password.model.d.ts +0 -11
  485. package/models/customer-portal-password.model.js +0 -4
  486. package/models/customer-portal-password.model.js.map +0 -1
  487. package/models/dialog.model.d.ts +0 -23
  488. package/models/dialog.model.js +0 -4
  489. package/models/dialog.model.js.map +0 -1
  490. package/models/email-history.model.d.ts +0 -31
  491. package/models/email-history.model.js.map +0 -1
  492. package/models/email-verified.model.js +0 -4
  493. package/models/email-verified.model.js.map +0 -1
  494. package/models/file.model.js +0 -4
  495. package/models/file.model.js.map +0 -1
  496. package/models/flag-update.model.js +0 -4
  497. package/models/flag-update.model.js.map +0 -1
  498. package/models/flag.model.js +0 -4
  499. package/models/flag.model.js.map +0 -1
  500. package/models/log-method-latency.model.d.ts +0 -10
  501. package/models/log-method-latency.model.js +0 -4
  502. package/models/log-method-latency.model.js.map +0 -1
  503. package/models/log-subscription.model.js +0 -4
  504. package/models/log-subscription.model.js.map +0 -1
  505. package/models/log.model.d.ts +0 -17
  506. package/models/log.model.js +0 -4
  507. package/models/log.model.js.map +0 -1
  508. package/models/logged-in-users.model.js +0 -4
  509. package/models/logged-in-users.model.js.map +0 -1
  510. package/models/method-response.model.js +0 -4
  511. package/models/method-response.model.js.map +0 -1
  512. package/models/method.model.d.ts +0 -26
  513. package/models/method.model.js +0 -4
  514. package/models/method.model.js.map +0 -1
  515. package/models/monitor-cpu.model.js +0 -4
  516. package/models/monitor-cpu.model.js.map +0 -1
  517. package/models/monitor-function.model.d.ts +0 -14
  518. package/models/monitor-function.model.js +0 -4
  519. package/models/monitor-function.model.js.map +0 -1
  520. package/models/monitor-memory.model.d.ts +0 -15
  521. package/models/monitor-memory.model.js +0 -4
  522. package/models/monitor-memory.model.js.map +0 -1
  523. package/models/monitor-mongo.model.d.ts +0 -13
  524. package/models/monitor-mongo.model.js +0 -4
  525. package/models/monitor-mongo.model.js.map +0 -1
  526. package/models/notification.model.js +0 -4
  527. package/models/notification.model.js.map +0 -1
  528. package/models/openai-usage-ledger.model.d.ts +0 -15
  529. package/models/openai-usage-ledger.model.js +0 -4
  530. package/models/openai-usage-ledger.model.js.map +0 -1
  531. package/models/pagination.model.d.ts +0 -11
  532. package/models/pagination.model.js +0 -28
  533. package/models/pagination.model.js.map +0 -1
  534. package/models/permission.model.d.ts +0 -12
  535. package/models/permission.model.js +0 -4
  536. package/models/permission.model.js.map +0 -1
  537. package/models/report-builder-dashboard-builder.model.d.ts +0 -25
  538. package/models/report-builder-dashboard-builder.model.js +0 -4
  539. package/models/report-builder-dashboard-builder.model.js.map +0 -1
  540. package/models/report-builder-library.model.d.ts +0 -17
  541. package/models/report-builder-library.model.js +0 -4
  542. package/models/report-builder-library.model.js.map +0 -1
  543. package/models/report-builder-report.model.d.ts +0 -121
  544. package/models/report-builder-report.model.js +0 -4
  545. package/models/report-builder-report.model.js.map +0 -1
  546. package/models/report-builder.model.d.ts +0 -61
  547. package/models/report-builder.model.js +0 -4
  548. package/models/report-builder.model.js.map +0 -1
  549. package/models/select-data-label.model.d.ts +0 -9
  550. package/models/select-data-label.model.js +0 -4
  551. package/models/select-data-label.model.js.map +0 -1
  552. package/models/server-message.model.d.ts +0 -32
  553. package/models/server-message.model.js +0 -4
  554. package/models/server-message.model.js.map +0 -1
  555. package/models/slow-query-report.model.d.ts +0 -23
  556. package/models/slow-query-report.model.js +0 -4
  557. package/models/slow-query-report.model.js.map +0 -1
  558. package/models/subscription.model.d.ts +0 -31
  559. package/models/subscription.model.js +0 -4
  560. package/models/subscription.model.js.map +0 -1
  561. package/models/support-ticket.model.d.ts +0 -87
  562. package/models/support-ticket.model.js +0 -4
  563. package/models/support-ticket.model.js.map +0 -1
  564. package/models/user-group.model.d.ts +0 -20
  565. package/models/user-group.model.js +0 -4
  566. package/models/user-group.model.js.map +0 -1
  567. package/models/user-guide.model.js +0 -4
  568. package/models/user-guide.model.js.map +0 -1
  569. package/models/user.model.d.ts +0 -84
  570. package/models/user.model.js +0 -4
  571. package/models/user.model.js.map +0 -1
  572. package/private/images/ResolveIO.png +0 -0
  573. package/public_api.js +0 -116
  574. package/public_api.js.map +0 -1
  575. package/publications/ai-terminal.d.ts +0 -1
  576. package/publications/ai-terminal.js +0 -122
  577. package/publications/ai-terminal.js.map +0 -1
  578. package/publications/app-settings.d.ts +0 -2
  579. package/publications/app-settings.js +0 -28
  580. package/publications/app-settings.js.map +0 -1
  581. package/publications/app-status.d.ts +0 -2
  582. package/publications/app-status.js +0 -16
  583. package/publications/app-status.js.map +0 -1
  584. package/publications/cron-jobs.d.ts +0 -2
  585. package/publications/cron-jobs.js +0 -88
  586. package/publications/cron-jobs.js.map +0 -1
  587. package/publications/customer-notifications.d.ts +0 -2
  588. package/publications/customer-notifications.js +0 -161
  589. package/publications/customer-notifications.js.map +0 -1
  590. package/publications/files.d.ts +0 -2
  591. package/publications/files.js +0 -36
  592. package/publications/files.js.map +0 -1
  593. package/publications/flags-update.d.ts +0 -2
  594. package/publications/flags-update.js +0 -22
  595. package/publications/flags-update.js.map +0 -1
  596. package/publications/flags.d.ts +0 -2
  597. package/publications/flags.js +0 -22
  598. package/publications/flags.js.map +0 -1
  599. package/publications/logs.d.ts +0 -2
  600. package/publications/logs.js +0 -164
  601. package/publications/logs.js.map +0 -1
  602. package/publications/notifications.d.ts +0 -2
  603. package/publications/notifications.js +0 -16
  604. package/publications/notifications.js.map +0 -1
  605. package/publications/report-builder-dashboard-builders.d.ts +0 -2
  606. package/publications/report-builder-dashboard-builders.js +0 -42
  607. package/publications/report-builder-dashboard-builders.js.map +0 -1
  608. package/publications/report-builder-libraries.d.ts +0 -2
  609. package/publications/report-builder-libraries.js +0 -90
  610. package/publications/report-builder-libraries.js.map +0 -1
  611. package/publications/report-builder-reports.d.ts +0 -2
  612. package/publications/report-builder-reports.js +0 -50
  613. package/publications/report-builder-reports.js.map +0 -1
  614. package/publications/super-admin.d.ts +0 -2
  615. package/publications/super-admin.js +0 -16
  616. package/publications/super-admin.js.map +0 -1
  617. package/publications/user-groups.d.ts +0 -1
  618. package/publications/user-groups.js +0 -16
  619. package/publications/user-groups.js.map +0 -1
  620. package/publications/user-guides.d.ts +0 -1
  621. package/publications/user-guides.js +0 -16
  622. package/publications/user-guides.js.map +0 -1
  623. package/resolveio-server-app.d.ts +0 -70
  624. package/resolveio-server-app.js +0 -801
  625. package/resolveio-server-app.js.map +0 -1
  626. package/server-app.d.ts +0 -228
  627. package/server-app.js +0 -3566
  628. package/server-app.js.map +0 -1
  629. package/services/codex-client.d.ts +0 -126
  630. package/services/codex-client.js +0 -1622
  631. package/services/codex-client.js.map +0 -1
  632. package/services/openai-client.d.ts +0 -46
  633. package/services/openai-client.js +0 -318
  634. package/services/openai-client.js.map +0 -1
  635. package/types/error-report.d.ts +0 -25
  636. package/types/error-report.js +0 -4
  637. package/types/error-report.js.map +0 -1
  638. package/types/slow-query-report.d.ts +0 -27
  639. package/types/slow-query-report.js +0 -6
  640. package/types/slow-query-report.js.map +0 -1
  641. package/util/ai-qa-policy.d.ts +0 -124
  642. package/util/ai-qa-policy.js +0 -707
  643. package/util/ai-qa-policy.js.map +0 -1
  644. package/util/ai-runner-artifacts.d.ts +0 -74
  645. package/util/ai-runner-artifacts.js +0 -531
  646. package/util/ai-runner-artifacts.js.map +0 -1
  647. package/util/ai-runner-qa-auth.d.ts +0 -5
  648. package/util/ai-runner-qa-auth.js +0 -357
  649. package/util/ai-runner-qa-auth.js.map +0 -1
  650. package/util/ai-runner-qa-tools.d.ts +0 -19
  651. package/util/ai-runner-qa-tools.js +0 -684
  652. package/util/ai-runner-qa-tools.js.map +0 -1
  653. package/util/common.d.ts +0 -31
  654. package/util/common.js +0 -683
  655. package/util/common.js.map +0 -1
  656. package/util/customer-portal-password.d.ts +0 -13
  657. package/util/customer-portal-password.js +0 -209
  658. package/util/customer-portal-password.js.map +0 -1
  659. package/util/error-reporter.d.ts +0 -52
  660. package/util/error-reporter.js +0 -326
  661. package/util/error-reporter.js.map +0 -1
  662. package/util/error-tracking.d.ts +0 -13
  663. package/util/error-tracking.js +0 -120
  664. package/util/error-tracking.js.map +0 -1
  665. package/util/report-builder-unwinds.d.ts +0 -15
  666. package/util/report-builder-unwinds.js +0 -156
  667. package/util/report-builder-unwinds.js.map +0 -1
  668. package/util/runner-process-janitor.d.ts +0 -25
  669. package/util/runner-process-janitor.js +0 -177
  670. package/util/runner-process-janitor.js.map +0 -1
  671. package/util/schema-report-builder.d.ts +0 -6
  672. package/util/schema-report-builder.js +0 -481
  673. package/util/schema-report-builder.js.map +0 -1
  674. package/util/slow-query-reporter.d.ts +0 -28
  675. package/util/slow-query-reporter.js +0 -226
  676. package/util/slow-query-reporter.js.map +0 -1
  677. package/util/subscription-dependency-context.d.ts +0 -34
  678. package/util/subscription-dependency-context.js +0 -1283
  679. package/util/subscription-dependency-context.js.map +0 -1
  680. package/util/tokenizer.d.ts +0 -5
  681. package/util/tokenizer.js +0 -41
  682. package/util/tokenizer.js.map +0 -1
  683. package/workers/codex-runner.worker.d.ts +0 -1
  684. package/workers/codex-runner.worker.js +0 -192
  685. package/workers/codex-runner.worker.js.map +0 -1
  686. /package/{private → src/private}/email-templates/enrollment.html +0 -0
  687. /package/{private → src/private}/email-templates/forgot-password.html +0 -0
  688. /package/{private → src/private}/email-templates/support-ticket-deleted.html +0 -0
  689. /package/{private → src/private}/email-templates/support-ticket-modified.html +0 -0
  690. /package/{private → src/private}/email-templates/support-ticket.html +0 -0
  691. /package/{public_api.d.ts → src/public_api.ts} +0 -0
@@ -0,0 +1,1827 @@
1
+ import { S3 } from '@aws-sdk/client-s3';
2
+ import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
3
+ import { EventEmitter, once } from 'events';
4
+ import * as fs from 'fs';
5
+ import * as nodemailer from 'nodemailer';
6
+ import * as path from 'path';
7
+ import { setTimeout as delay } from 'timers/promises';
8
+ import { EmailHistories } from '../collections/email-history.collection';
9
+ import { Flags } from '../collections/flag.collection';
10
+ import { Logs } from '../collections/log.collection';
11
+ import { loadServerCronJobs } from '../fixtures/cron-jobs';
12
+ import { loadServerInit } from '../fixtures/init';
13
+ import { loadAccountMethods } from '../methods/accounts';
14
+ import { loadAppSettingsMethods } from '../methods/app-settings';
15
+ import { loadAWSMethods } from '../methods/aws';
16
+ import { loadAiTerminalMethods } from '../methods/ai-terminal';
17
+ import { loadCollectionMethods } from '../methods/collections';
18
+ import { loadCustomerNotificationMethods } from '../methods/customer-notifications';
19
+ import { loadCounterMethods } from '../methods/counters';
20
+ import { loadCronJobMethods } from '../methods/cron-jobs';
21
+ import { loadDiagnosticMethods } from '../methods/diagnostics';
22
+ import { loadFlagUpdatesMethods } from '../methods/flag-updates';
23
+ import { loadFlagMethods } from '../methods/flags';
24
+ import { loadLogMethods } from '../methods/logs';
25
+ import { loadMonitorMethods } from '../methods/monitor';
26
+ import { loadMongoExplorerMethods } from '../methods/mongo-explorer';
27
+ import { loadPublicationMethods } from '../methods/publications';
28
+ import { loadPDFMethods } from '../methods/pdf';
29
+ import { loadReportBuilderMethods } from '../methods/report-builder';
30
+ import { loadSupportMethods } from '../methods/support';
31
+ import { EmailHistoryModel, EmailHistoryOccurrence } from '../models/email-history.model';
32
+ import { MethodAllModel, MethodModel } from '../models/method.model';
33
+ import { ResolveIOServer } from '../resolveio-server-app';
34
+ import { getBinarySize, objectIdHexString } from '../util/common';
35
+ import { ErrorReporter } from '../util/error-reporter';
36
+ import { ensureErrorWithCorrelation, getCorrelationId, runWithCorrelationContext } from '../util/error-tracking';
37
+ import { MonitorManagerFunction } from './monitor.manager';
38
+ import { WebSocketManager } from './websocket.manager';
39
+ import { recordEmailMetric, recordTextMessageMetric } from './communication-metric.manager';
40
+
41
+ interface SendEmailOptions {
42
+ correlationId?: string;
43
+ meta?: Record<string, any>;
44
+ headers?: Record<string, string>;
45
+ waitForCompletion?: boolean;
46
+ waitForCompletionTimeoutMs?: number;
47
+ waitForCompletionPollMs?: number;
48
+ }
49
+
50
+ const CALL_METHOD_LOG_SKIP_LIST = new Set([
51
+ 'countQuery',
52
+ 'getSignedUrls',
53
+ 'getSignedUrl',
54
+ 'getSignedUrlWithId',
55
+ 'getSignedUrlsAndFilesWithId',
56
+ 'updateDocumentProps',
57
+ 'insertDocument',
58
+ 'updateDocument',
59
+ 'uploadFileAndSave'
60
+ ]);
61
+
62
+ function shouldWriteCallMethodLog(methodName: string, method?: MethodAllModel): boolean {
63
+ if (method?.bypassLog || method?.bypassLogs) {
64
+ return false;
65
+ }
66
+
67
+ if (CALL_METHOD_LOG_SKIP_LIST.has(methodName)) {
68
+ return false;
69
+ }
70
+
71
+ return true;
72
+ }
73
+
74
+ function appendCorrelationIdToSubject(subject: string, correlationId?: string): string {
75
+ if (!correlationId) {
76
+ return subject;
77
+ }
78
+
79
+ const correlationTag = `[${correlationId}]`;
80
+
81
+ if (subject && subject.includes(correlationTag)) {
82
+ return subject;
83
+ }
84
+
85
+ return `${subject} ${correlationTag}`.trim();
86
+ }
87
+
88
+ function createEmailOccurrence(subject: string, text?: string, html?: string, meta?: Record<string, any>): EmailHistoryOccurrence {
89
+ return {
90
+ _id: objectIdHexString(),
91
+ createdAt: new Date(),
92
+ subject,
93
+ text,
94
+ html,
95
+ meta
96
+ };
97
+ }
98
+
99
+ function formatGroupedEmailContent(correlationId: string, occurrences: EmailHistoryOccurrence[]): { text: string; html: string } {
100
+ const lines: string[] = [];
101
+ lines.push(`Correlation ID: ${correlationId}`);
102
+
103
+ occurrences.forEach((occurrence, index) => {
104
+ const timestamp = occurrence.createdAt instanceof Date ? occurrence.createdAt.toISOString() : new Date(occurrence.createdAt).toISOString();
105
+ lines.push('');
106
+ lines.push(`Occurrence #${index + 1} (${timestamp})`);
107
+ lines.push(`Subject: ${occurrence.subject}`);
108
+ if (occurrence.text) {
109
+ lines.push(occurrence.text);
110
+ }
111
+ });
112
+
113
+ const htmlSections = occurrences.map((occurrence, index) => {
114
+ const timestamp = occurrence.createdAt instanceof Date ? occurrence.createdAt.toISOString() : new Date(occurrence.createdAt).toISOString();
115
+ const escapedText = occurrence.text ? occurrence.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
116
+ return `<div><h4>Occurrence #${index + 1} (${timestamp})</h4><p><strong>Subject:</strong> ${occurrence.subject}</p>${escapedText ? `<pre>${escapedText}</pre>` : ''}</div>`;
117
+ });
118
+
119
+ const html = [
120
+ `<p><strong>Correlation ID:</strong> ${correlationId}</p>`,
121
+ ...htmlSections
122
+ ].join('');
123
+
124
+ return {
125
+ text: lines.join('\n'),
126
+ html
127
+ };
128
+ }
129
+
130
+ const EMAIL_HISTORY_TEXT_MAX_CHARS = 12000;
131
+ const EMAIL_HISTORY_HTML_MAX_CHARS = 20000;
132
+ const EMAIL_HISTORY_ERROR_MAX_CHARS = 8000;
133
+ const EMAIL_HISTORY_META_MAX_CHARS = 6000;
134
+ const EMAIL_HISTORY_ATTACHMENT_MAX_COUNT = 10;
135
+ const EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS = 1024;
136
+ const EMAIL_HISTORY_OCCURRENCE_MAX_COUNT = 20;
137
+ const EMAIL_HISTORY_OCCURRENCE_TEXT_MAX_CHARS = 4000;
138
+ const EMAIL_HISTORY_OCCURRENCE_HTML_MAX_CHARS = 6000;
139
+
140
+ function truncateTextForHistory(value: unknown, maxChars: number): string {
141
+ if (typeof value !== 'string') {
142
+ return '';
143
+ }
144
+
145
+ if (value.length <= maxChars) {
146
+ return value;
147
+ }
148
+
149
+ const suffix = '...[truncated]';
150
+ const keepLength = Math.max(0, maxChars - suffix.length);
151
+ return `${value.slice(0, keepLength)}${suffix}`;
152
+ }
153
+
154
+ function sanitizeMetaForHistory(meta?: Record<string, any>): Record<string, any> | undefined {
155
+ if (!meta || typeof meta !== 'object') {
156
+ return undefined;
157
+ }
158
+
159
+ try {
160
+ const serialized = JSON.stringify(meta);
161
+ if (!serialized) {
162
+ return undefined;
163
+ }
164
+
165
+ if (serialized.length <= EMAIL_HISTORY_META_MAX_CHARS) {
166
+ return JSON.parse(serialized);
167
+ }
168
+
169
+ return {
170
+ truncated: true,
171
+ originalSize: serialized.length,
172
+ preview: truncateTextForHistory(serialized, EMAIL_HISTORY_META_MAX_CHARS)
173
+ };
174
+ }
175
+ catch {
176
+ return {
177
+ truncated: true,
178
+ preview: '[unserializable meta]'
179
+ };
180
+ }
181
+ }
182
+
183
+ function estimateAttachmentContentLength(content: any, encoding?: string): number | undefined {
184
+ if (Buffer.isBuffer(content)) {
185
+ return content.length;
186
+ }
187
+
188
+ if (content instanceof Uint8Array) {
189
+ return content.byteLength;
190
+ }
191
+
192
+ if (content && typeof content === 'object') {
193
+ if (content._bsontype === 'Binary' && content.buffer && typeof content.buffer.length === 'number') {
194
+ return content.buffer.length;
195
+ }
196
+
197
+ if (Array.isArray(content.data)) {
198
+ return content.data.length;
199
+ }
200
+ }
201
+
202
+ if (typeof content === 'string') {
203
+ if (encoding === 'base64') {
204
+ const normalized = content.replace(/\s/g, '');
205
+ const padding = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
206
+ return Math.max(0, Math.floor((normalized.length * 3) / 4) - padding);
207
+ }
208
+
209
+ return Buffer.byteLength(content, 'utf8');
210
+ }
211
+
212
+ return undefined;
213
+ }
214
+
215
+ function sanitizeAttachmentForHistory(attachment: any): Record<string, any> {
216
+ const source = attachment && typeof attachment === 'object' ? attachment : {};
217
+ const summary: Record<string, any> = {
218
+ contentStored: false
219
+ };
220
+
221
+ if (typeof source.filename === 'string') {
222
+ summary.filename = truncateTextForHistory(source.filename, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
223
+ }
224
+ if (typeof source.contentType === 'string') {
225
+ summary.contentType = truncateTextForHistory(source.contentType, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
226
+ }
227
+ if (typeof source.contentDisposition === 'string') {
228
+ summary.contentDisposition = truncateTextForHistory(source.contentDisposition, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
229
+ }
230
+ if (typeof source.cid === 'string') {
231
+ summary.cid = truncateTextForHistory(source.cid, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
232
+ }
233
+ if (typeof source.path === 'string') {
234
+ summary.path = truncateTextForHistory(source.path, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
235
+ }
236
+ if (typeof source.href === 'string') {
237
+ summary.href = truncateTextForHistory(source.href, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
238
+ }
239
+ if (typeof source.encoding === 'string') {
240
+ summary.encoding = truncateTextForHistory(source.encoding, EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS);
241
+ }
242
+
243
+ const contentLength = typeof source.size === 'number'
244
+ ? source.size
245
+ : estimateAttachmentContentLength(source.content, source.encoding);
246
+ if (typeof contentLength === 'number' && Number.isFinite(contentLength) && contentLength >= 0) {
247
+ summary.contentLength = contentLength;
248
+ }
249
+
250
+ return summary;
251
+ }
252
+
253
+ function sanitizeAttachmentsForHistory(attachments: any[]): Record<string, any>[] {
254
+ if (!Array.isArray(attachments) || !attachments.length) {
255
+ return [];
256
+ }
257
+
258
+ const summarized = attachments
259
+ .slice(0, EMAIL_HISTORY_ATTACHMENT_MAX_COUNT)
260
+ .map((attachment) => sanitizeAttachmentForHistory(attachment));
261
+
262
+ if (attachments.length > EMAIL_HISTORY_ATTACHMENT_MAX_COUNT) {
263
+ summarized.push({
264
+ contentStored: false,
265
+ omittedCount: attachments.length - EMAIL_HISTORY_ATTACHMENT_MAX_COUNT
266
+ });
267
+ }
268
+
269
+ return summarized;
270
+ }
271
+
272
+ function sanitizeOccurrencesForHistory(occurrences?: EmailHistoryOccurrence[]): EmailHistoryOccurrence[] | undefined {
273
+ if (!Array.isArray(occurrences) || !occurrences.length) {
274
+ return undefined;
275
+ }
276
+
277
+ return occurrences.slice(-EMAIL_HISTORY_OCCURRENCE_MAX_COUNT).map((occurrence) => {
278
+ const createdAtCandidate = occurrence.createdAt instanceof Date ? occurrence.createdAt : new Date(occurrence.createdAt);
279
+ const createdAt = Number.isNaN(createdAtCandidate.getTime()) ? new Date() : createdAtCandidate;
280
+ const sanitized: EmailHistoryOccurrence = {
281
+ _id: occurrence._id || objectIdHexString(),
282
+ createdAt,
283
+ subject: truncateTextForHistory(occurrence.subject || '', EMAIL_HISTORY_ATTACHMENT_FIELD_MAX_CHARS)
284
+ };
285
+
286
+ if (typeof occurrence.text === 'string' && occurrence.text.length > 0) {
287
+ sanitized.text = truncateTextForHistory(occurrence.text, EMAIL_HISTORY_OCCURRENCE_TEXT_MAX_CHARS);
288
+ }
289
+ if (typeof occurrence.html === 'string' && occurrence.html.length > 0) {
290
+ sanitized.html = truncateTextForHistory(occurrence.html, EMAIL_HISTORY_OCCURRENCE_HTML_MAX_CHARS);
291
+ }
292
+
293
+ const sanitizedMeta = sanitizeMetaForHistory(occurrence.meta);
294
+ if (sanitizedMeta) {
295
+ sanitized.meta = sanitizedMeta;
296
+ }
297
+
298
+ return sanitized;
299
+ });
300
+ }
301
+
302
+ function createNodeMailerSESV2Transport(sesClient: SESv2Client): nodemailer.Transporter {
303
+ const transport: any = {
304
+ name: 'resolveio-sesv2-transport',
305
+ version: '1.0.0',
306
+ send: (mail: any, callback: any) => {
307
+ const stream = mail.message.createReadStream();
308
+ const chunks: Uint8Array[] = [];
309
+ let didFinish = false;
310
+
311
+ const finish = (error: any, info?: any) => {
312
+ if (didFinish) {
313
+ return;
314
+ }
315
+
316
+ didFinish = true;
317
+ callback(error, info);
318
+ };
319
+
320
+ stream.on('data', (chunk) => {
321
+ const chunkData = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
322
+ chunks.push(new Uint8Array(chunkData));
323
+ });
324
+
325
+ stream.on('error', (error) => {
326
+ finish(error);
327
+ });
328
+
329
+ stream.on('end', async () => {
330
+ try {
331
+ const rawData = Buffer.concat(chunks);
332
+ const rawMessageData = new Uint8Array(rawData);
333
+ const envelope = typeof mail.message.getEnvelope === 'function' ? mail.message.getEnvelope() : mail.data?.envelope;
334
+
335
+ const fromEmailAddress = envelope?.from || undefined;
336
+ const toAddresses = envelope?.to
337
+ ? (Array.isArray(envelope.to) ? envelope.to : [envelope.to]).filter(Boolean)
338
+ : [];
339
+
340
+ const replyToAddresses = mail.data?.replyTo
341
+ ? (Array.isArray(mail.data.replyTo) ? mail.data.replyTo : [mail.data.replyTo]).filter(Boolean)
342
+ : undefined;
343
+
344
+ const response = await sesClient.send(new SendEmailCommand({
345
+ FromEmailAddress: fromEmailAddress,
346
+ Destination: toAddresses.length ? { ToAddresses: toAddresses } : undefined,
347
+ ReplyToAddresses: replyToAddresses,
348
+ Content: {
349
+ Raw: {
350
+ Data: rawMessageData
351
+ }
352
+ }
353
+ }));
354
+
355
+ finish(null, {
356
+ envelope,
357
+ messageId: response.MessageId,
358
+ response: response.MessageId
359
+ });
360
+ }
361
+ catch (error) {
362
+ finish(error);
363
+ }
364
+ });
365
+ }
366
+ };
367
+
368
+ return nodemailer.createTransport(transport);
369
+ }
370
+
371
+ export class AWS {
372
+ private _s3: S3 = null;
373
+ private _s3USEast1: S3 = null;
374
+
375
+ constructor() {}
376
+
377
+ public create() {
378
+ const aws = new AWS();
379
+ aws.initialize();
380
+ return aws;
381
+ }
382
+
383
+ private initialize() {
384
+
385
+ }
386
+
387
+ public s3(): S3 {
388
+ if (this._s3) {
389
+ return this._s3;
390
+ }
391
+
392
+ this._s3 = new S3({
393
+ credentials: {
394
+ accessKeyId: process.env.AWS_ACCESS_KEY,
395
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
396
+ },
397
+ region: process.env.AWS_REGION,
398
+ apiVersion: '2006-03-01'
399
+ });
400
+
401
+ return this._s3;
402
+ }
403
+
404
+ public s3USEast1(): S3 {
405
+ if (process.env.AWS_REGION === 'us-east-1') {
406
+ return this.s3();
407
+ }
408
+ else {
409
+ if (this._s3USEast1) {
410
+ return this._s3USEast1;
411
+ }
412
+
413
+ this._s3USEast1 = new S3({
414
+ credentials: {
415
+ accessKeyId: process.env.AWS_ACCESS_KEY,
416
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
417
+ },
418
+ region: 'us-east-1',
419
+ apiVersion: '2006-03-01'
420
+ });
421
+
422
+ return this._s3USEast1;
423
+ }
424
+ }
425
+ }
426
+
427
+ export class MethodManager {
428
+ private _websocketManager: WebSocketManager;
429
+ public _methods: MethodModel = {};
430
+ private _mailerSES: nodemailer.Transporter;
431
+ private _mailerCustom: nodemailer.Transporter;
432
+ private _aws: AWS;
433
+ private _monitorManagerFunction: MonitorManagerFunction;
434
+ private _isWorkersEnabled = false;
435
+ private _isWorkerInstance = false;
436
+
437
+ private emailQueue: Set<string> = new Set(); // Set to store pending email IDs
438
+ private isEmailProcessing = false;
439
+ private readonly _emailProcessingDelayMs = 5000;
440
+
441
+ private _debugcallMethodHits = 0;
442
+ private _debugCallMethodHits = 0;
443
+ private _debugCallMethodCronJobHits = 0;
444
+ private _debugSendQueueHits = 0;
445
+ private _enableDebug = false;
446
+ private _ready = false;
447
+ private _readyEmitter = new EventEmitter();
448
+ private _readyError: any = null;
449
+
450
+ private _localActiveCounts: Map<string, number> = new Map();
451
+ private _localWaitQueues: Map<string, Array<() => void>> = new Map();
452
+
453
+ public clientDir = '';
454
+ public serverConfig: Record<string, any> = {};
455
+
456
+ constructor() {}
457
+
458
+ static create(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {
459
+ const methodManager = new MethodManager();
460
+ methodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);
461
+ return methodManager;
462
+ }
463
+
464
+ private initialize(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {
465
+ this._websocketManager = websocketManager;
466
+ this._monitorManagerFunction = monitorManagerFunction;
467
+ this._isWorkersEnabled = isWorkersEnabled;
468
+ this._isWorkerInstance = isWorkerInstance;
469
+
470
+ this.clientDir = ResolveIOServer.getClientDir();
471
+ this.serverConfig = ResolveIOServer.getServerConfig();
472
+
473
+ // Fixtures
474
+ if (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {
475
+ if (process.env.IS_WORKERS_ENABLED === 'false' || process.env.NODE_APP_INSTANCE === '1') {
476
+ setTimeout(async () => {
477
+ console.log(new Date(), 'Start Server Fixture');
478
+ await loadServerInit();
479
+ console.log(new Date(), 'End Server Fixture');
480
+ }, 5000);
481
+ }
482
+ }
483
+
484
+ setImmediate(async () => {
485
+ try {
486
+ // Methods
487
+ await loadServerCronJobs();
488
+
489
+ loadAccountMethods(this);
490
+ loadAppSettingsMethods(this);
491
+ loadAWSMethods(this);
492
+ loadAiTerminalMethods(this);
493
+ loadCollectionMethods(this);
494
+ loadCustomerNotificationMethods(this);
495
+ loadCounterMethods(this);
496
+ loadLogMethods(this);
497
+ loadPDFMethods(this);
498
+ loadCronJobMethods(this);
499
+ loadFlagMethods(this);
500
+ loadFlagUpdatesMethods(this);
501
+ loadReportBuilderMethods(this);
502
+ loadSupportMethods(this);
503
+ loadMonitorMethods(this);
504
+ loadMongoExplorerMethods(this);
505
+ loadPublicationMethods(this);
506
+ loadDiagnosticMethods(this);
507
+
508
+ let flag = await Flags.findOne({type: 'Enable Debug'});
509
+
510
+ if (flag && flag.value) {
511
+ this._enableDebug = true;
512
+ }
513
+ else {
514
+ this._enableDebug = false;
515
+ }
516
+
517
+ await this.loadPendingEmails();
518
+ this.markReady();
519
+ }
520
+ catch (error) {
521
+ console.error(new Date(), 'Method Manager init failed', error);
522
+ this.markReadyFailure(error);
523
+ }
524
+ });
525
+
526
+ this._aws = new AWS();
527
+
528
+ const sesRegion = process.env.AWS_SES_REGION
529
+ || this.serverConfig?.AWS_SES_REGION
530
+ || this.serverConfig?.AWSSES_REGION
531
+ || process.env.AWS_REGION
532
+ || process.env.AWS_DEFAULT_REGION
533
+ || 'us-east-1';
534
+ const sesCredentials = process.env.AWS_ACCESS_KEY && process.env.AWS_SECRET_ACCESS_KEY ? {
535
+ accessKeyId: process.env.AWS_ACCESS_KEY,
536
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
537
+ sessionToken: process.env.AWS_SESSION_TOKEN
538
+ } : undefined;
539
+
540
+ this._mailerSES = createNodeMailerSESV2Transport(new SESv2Client({
541
+ region: sesRegion,
542
+ credentials: sesCredentials
543
+ }));
544
+
545
+ if (!ResolveIOServer.getSESMail()) {
546
+ this._mailerCustom = nodemailer.createTransport({
547
+ host: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server
548
+ port: ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP
549
+ secure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely
550
+ auth: {
551
+ user: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],
552
+ pass: ResolveIOServer.getServerConfig()['MAIL_PASSWORD']
553
+ },
554
+ tls: {
555
+ ciphers: 'SSLv3'
556
+ }
557
+ });
558
+ }
559
+
560
+ setInterval(async () => {
561
+ let flag = await Flags.findOne({type: 'Enable Debug'});
562
+
563
+ if (flag && flag.value) {
564
+ this._enableDebug = true;
565
+ }
566
+ else {
567
+ this._enableDebug = false;
568
+ }
569
+
570
+ if (this._enableDebug) {
571
+ console.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);
572
+ console.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);
573
+ console.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);
574
+ console.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);
575
+ }
576
+
577
+ this._debugcallMethodHits = 0;
578
+ this._debugCallMethodHits = 0;
579
+ this._debugCallMethodCronJobHits = 0;
580
+ this._debugSendQueueHits = 0;
581
+ }, 60000);
582
+
583
+ if (!this._isWorkersEnabled || this._isWorkerInstance) {
584
+ this.setupEmailWatcher();
585
+ }
586
+ }
587
+
588
+ private markReady(): void {
589
+ if (this._ready) {
590
+ return;
591
+ }
592
+ this._ready = true;
593
+ this._readyEmitter.emit('ready');
594
+ this._readyEmitter.removeAllListeners('ready');
595
+ this._readyEmitter.removeAllListeners('readyError');
596
+ }
597
+
598
+ private markReadyFailure(error: any): void {
599
+ if (this._ready) {
600
+ return;
601
+ }
602
+ this._readyError = error;
603
+ this._readyEmitter.emit('readyError', error);
604
+ this._readyEmitter.removeAllListeners('ready');
605
+ this._readyEmitter.removeAllListeners('readyError');
606
+ }
607
+
608
+ public onReady(callback: () => void): () => void {
609
+ if (this._ready) {
610
+ callback();
611
+ return () => {};
612
+ }
613
+ if (this._readyError) {
614
+ return () => {};
615
+ }
616
+
617
+ const handleReady = () => {
618
+ callback();
619
+ };
620
+
621
+ this._readyEmitter.once('ready', handleReady);
622
+
623
+ return () => {
624
+ this._readyEmitter.removeListener('ready', handleReady);
625
+ };
626
+ }
627
+
628
+ private async waitForReadyEvent(): Promise<void> {
629
+ await once(this._readyEmitter, 'ready');
630
+ }
631
+
632
+ private async waitForReadyError(): Promise<void> {
633
+ const [error] = await once(this._readyEmitter, 'readyError');
634
+ throw error || new Error('MethodManager failed to initialize');
635
+ }
636
+
637
+ private async waitForReadyTimeout(timeoutMs: number): Promise<void> {
638
+ await delay(timeoutMs);
639
+ throw new Error('MethodManager ready timeout');
640
+ }
641
+
642
+ public isReady(): boolean {
643
+ return this._ready;
644
+ }
645
+
646
+ public getReadyError(): any {
647
+ return this._readyError;
648
+ }
649
+
650
+ public async waitUntilReady(timeoutMs: number = 30000): Promise<void> {
651
+ if (this._ready) {
652
+ return;
653
+ }
654
+ if (this._readyError) {
655
+ throw this._readyError;
656
+ }
657
+ if (!timeoutMs || timeoutMs <= 0) {
658
+ await Promise.race([
659
+ this.waitForReadyEvent(),
660
+ this.waitForReadyError()
661
+ ]);
662
+ return;
663
+ }
664
+ await Promise.race([
665
+ this.waitForReadyEvent(),
666
+ this.waitForReadyError(),
667
+ this.waitForReadyTimeout(timeoutMs)
668
+ ]);
669
+ }
670
+
671
+ public getMethod(methodName: string): MethodAllModel {
672
+ return this._methods[methodName];
673
+ }
674
+
675
+ // Add methods to private methods object
676
+ public methods(method: MethodModel) {
677
+ this._methods = Object.assign(this._methods, method);
678
+ }
679
+
680
+ private async reportMethodError(
681
+ subject: string,
682
+ correlationId: string,
683
+ context: Record<string, any> | string,
684
+ meta: Record<string, any>,
685
+ stack?: string
686
+ ) {
687
+ const metadata = Object.assign({}, meta || {});
688
+ if (correlationId && !metadata.correlationId) {
689
+ metadata.correlationId = correlationId;
690
+ }
691
+
692
+ await ErrorReporter.report({
693
+ sourceApp: 'method-manager',
694
+ message: subject,
695
+ environment: this.serverConfig?.ROOT_URL,
696
+ clientSlug: ResolveIOServer.getClientName(),
697
+ clientName: this.serverConfig?.CLIENT_NAME,
698
+ severity: 'error',
699
+ stack,
700
+ context,
701
+ metadata,
702
+ correlationId
703
+ });
704
+ }
705
+
706
+ public async callMethodCron(method: string, ...methodData: any[]) {
707
+ this._debugCallMethodCronJobHits += 1;
708
+
709
+ const existingCorrelationId = getCorrelationId();
710
+ const correlationId = existingCorrelationId || objectIdHexString();
711
+
712
+ const execute = async () => {
713
+ const cronMethod = this._methods[method];
714
+
715
+ if (!cronMethod) {
716
+ console.log('No Method: ' + method);
717
+
718
+ await this.reportMethodError(
719
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
720
+ correlationId,
721
+ { message: 'No Method registered for cron execution', method },
722
+ { context: 'callMethodCron', method }
723
+ );
724
+
725
+ throw new Error('No Method: ' + method);
726
+ }
727
+
728
+ if ((methodData.length > 1 || methodData[0]) && !cronMethod.skipValidation) {
729
+ if (!cronMethod.check) {
730
+ console.error(new Date(), 'No Check Function For Cron Method ' + method);
731
+
732
+ await this.reportMethodError(
733
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
734
+ correlationId,
735
+ { message: 'Missing check function for cron method', method },
736
+ { context: 'callMethodCron-validation', method }
737
+ );
738
+
739
+ throw new Error('No Check Function For Cron Method ' + method);
740
+ }
741
+ else if (!cronMethod.check._schema) {
742
+ console.error(new Date(), 'No Check Schema For Cron Method ' + method);
743
+
744
+ await this.reportMethodError(
745
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
746
+ correlationId,
747
+ { message: 'Missing check schema for cron method', method },
748
+ { context: 'callMethodCron-validation', method }
749
+ );
750
+
751
+ throw new Error('No Check Schema For Cron Method ' + method);
752
+ }
753
+ else {
754
+ const valObj = {};
755
+ const valKeys = Object.keys(cronMethod.check._schema);
756
+
757
+ const rootKeys = valKeys.filter(a => !a.includes('.'));
758
+
759
+ for (let i = 0; i < methodData.length; i++) {
760
+ valObj[rootKeys[i]] = methodData[i];
761
+ }
762
+
763
+ try {
764
+ cronMethod.check.validate(valObj);
765
+ }
766
+ catch (err) {
767
+ console.error(new Date(), 'Error in Cron Method Check (' + method + ')', err);
768
+
769
+ const { error: normalizedError, correlationId: resolvedCorrelationId } = ensureErrorWithCorrelation(err, correlationId);
770
+
771
+ await this.reportMethodError(
772
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
773
+ resolvedCorrelationId,
774
+ {
775
+ message: 'Match error on cron method',
776
+ method,
777
+ data: valObj,
778
+ validationError: normalizedError
779
+ },
780
+ { context: 'callMethodCron-validation-error', method },
781
+ normalizedError.stack
782
+ );
783
+ normalizedError.message = `${new Date().toISOString()} - Error in Cron Method Check (${method}): ${normalizedError.message}`;
784
+
785
+ throw normalizedError;
786
+ }
787
+ }
788
+ }
789
+
790
+ const monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);
791
+
792
+ try {
793
+ const res = await cronMethod.function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData);
794
+ return res;
795
+ }
796
+ catch (err) {
797
+ const { error: normalizedError, correlationId: resolvedCorrelationId } = ensureErrorWithCorrelation(err, correlationId);
798
+
799
+ await this.reportMethodError(
800
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
801
+ resolvedCorrelationId,
802
+ {
803
+ message: 'Error detected during cron method execution',
804
+ method,
805
+ data: methodData,
806
+ error: normalizedError
807
+ },
808
+ { context: 'callMethodCron-execution', method },
809
+ normalizedError.stack
810
+ );
811
+
812
+ normalizedError.message = `${new Date().toISOString()} - Error in Cron Method (${method}): ${normalizedError.message}`;
813
+
814
+ throw normalizedError;
815
+ }
816
+ finally {
817
+ await this._monitorManagerFunction.finishMonitorFunction(monitor);
818
+ }
819
+ };
820
+
821
+ return await runWithCorrelationContext(correlationId, execute);
822
+ }
823
+
824
+ // Call/run method internal (No Emit on Socket)
825
+ public async callMethod(methodName: string, ...methodData: any[]): Promise<any> {
826
+ this._debugcallMethodHits += 1;
827
+
828
+ const existingCorrelationId = getCorrelationId();
829
+ const correlationId = existingCorrelationId || objectIdHexString();
830
+
831
+ return await runWithCorrelationContext(correlationId, async () => await this.callMethodInternal(correlationId, methodName, methodData));
832
+ }
833
+
834
+ private async callMethodInternal(correlationId: string, methodName: string, methodData: any[]): Promise<any> {
835
+ const method = this.getMethod(methodName);
836
+
837
+ if (!method) {
838
+ console.log('No Method: ' + methodName);
839
+ throw new Error(`No Method: ${methodName}`);
840
+ }
841
+
842
+ const shouldTrackTextMetric = this.shouldTrackTextMessageMetric(methodName);
843
+ const textMetricProvider = shouldTrackTextMetric ? this.getTextMessageProvider() : undefined;
844
+
845
+ let releaseLocalConcurrency = await this.acquireLocalConcurrency(methodName, method.maxConcurrency);
846
+
847
+ try {
848
+ if ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !method.skipValidation) {
849
+ if (!method.check) {
850
+ console.error(new Date(), 'No Check Function For Method ' + methodName);
851
+ throw new Error(`No Check Function For Method: ${methodName}`);
852
+ }
853
+ else if (!method.check._schema) {
854
+ console.error(new Date(), 'No Check Schema For Method ' + methodName);
855
+ throw new Error(`No Check Schema For Method: ${methodName}`);
856
+ }
857
+ }
858
+
859
+ if (shouldWriteCallMethodLog(methodName, method)) {
860
+ if (
861
+ ResolveIOServer.shouldWriteLogsOffline()
862
+ ) {
863
+ ResolveIOServer.getLocalLogManager().writeLog({
864
+ type: 'log',
865
+ data: {
866
+ _id: objectIdHexString(),
867
+ createdAt: new Date(),
868
+ type: 'callMethod',
869
+ collection: '',
870
+ id_document: '',
871
+ payload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',
872
+ method: methodName,
873
+ id_user: this['id_user'] || '',
874
+ user: this['user'] || '',
875
+ messageId: 0,
876
+ route: '',
877
+ instance_index: process.env.NODE_APP_INSTANCE || '0',
878
+ correlationId
879
+ }
880
+ });
881
+ }
882
+ else {
883
+ await Logs.insertOne({
884
+ _id: objectIdHexString(),
885
+ type: 'callMethod',
886
+ collection: '',
887
+ id_document: '',
888
+ payload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',
889
+ method: methodName,
890
+ id_user: this['id_user'] || '',
891
+ user: this['user'] || '',
892
+ messageId: 0,
893
+ route: '',
894
+ client: 'ResolveIO',
895
+ instance: ResolveIOServer.getInstanceHost(),
896
+ instance_index: process.env.NODE_APP_INSTANCE || '0',
897
+ correlationId
898
+ })
899
+ };
900
+ }
901
+
902
+ const methodCallback = typeof(methodData[methodData.length - 1]) === 'function' ? methodData[methodData.length - 1] : null;
903
+ const functionMethodData = methodCallback ? methodData.slice(0, -1) : methodData;
904
+
905
+ const session = ResolveIOServer.getMongoManager().getSession();
906
+ const shouldStartTransaction = !method.bypassSession &&
907
+ !session &&
908
+ ![
909
+ 'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE
910
+ 'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORK WITH COUNTS
911
+ 'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION
912
+ ].includes(methodName) &&
913
+ !methodName.startsWith('monitor-') &&
914
+ !methodName.startsWith('log');
915
+
916
+ const executeWithExistingSession = async () => {
917
+ // console.log(new Date(), 'Calling Method - Existing Session', methodName);
918
+ let monitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);
919
+
920
+ try {
921
+ let res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);
922
+
923
+ if (methodCallback) {
924
+ methodCallback(null, res);
925
+ }
926
+
927
+ if (shouldTrackTextMetric) {
928
+ try {
929
+ await recordTextMessageMetric({
930
+ status: 'sent',
931
+ provider: textMetricProvider,
932
+ metadata: {
933
+ method: methodName
934
+ }
935
+ });
936
+ }
937
+ catch (error) {
938
+ console.error('Error recording text message metric:', error);
939
+ }
940
+ }
941
+
942
+ return res;
943
+ }
944
+ catch (err) {
945
+ if (err.code === 112 || err.codeName === 'WriteConflict' || err.code === 251 || err.codeName === 'NoSuchTransaction') {
946
+ throw err; // Write error, retry
947
+ }
948
+
949
+ const { error: normalizedError, correlationId: resolvedCorrelationId } = ensureErrorWithCorrelation(err, correlationId);
950
+
951
+ console.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - Existing Session', methodName, {
952
+ code: normalizedError.code,
953
+ codeName: normalizedError.codeName,
954
+ message: normalizedError.message,
955
+ stack: normalizedError.stack,
956
+ correlationId: resolvedCorrelationId
957
+ }], null, 2));
958
+
959
+ await this.reportMethodError(
960
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
961
+ resolvedCorrelationId,
962
+ {
963
+ message: 'Error detected during method execution (existing session)',
964
+ method: methodName,
965
+ data: methodData,
966
+ error: normalizedError
967
+ },
968
+ { context: 'callMethod-existing-session', methodName },
969
+ normalizedError.stack
970
+ );
971
+ normalizedError.message = `${new Date().toISOString()} - Error in Method (${methodName}) - Existing Session: ${normalizedError.message}`;
972
+
973
+ if (methodCallback) {
974
+ methodCallback(normalizedError, null);
975
+ }
976
+
977
+ if (shouldTrackTextMetric) {
978
+ try {
979
+ await recordTextMessageMetric({
980
+ status: 'failed',
981
+ provider: textMetricProvider,
982
+ metadata: {
983
+ method: methodName
984
+ }
985
+ });
986
+ }
987
+ catch (error) {
988
+ console.error('Error recording text message metric:', error);
989
+ }
990
+ }
991
+
992
+ if (!process.env.IS_WORKER_INSTANCE) {
993
+ await this.callMethod(
994
+ 'insertErrorLog',
995
+ `Error in Method: ${methodName}`,
996
+ {
997
+ method: methodName,
998
+ methodData,
999
+ error: {
1000
+ message: normalizedError.message,
1001
+ stack: normalizedError.stack,
1002
+ code: normalizedError.code,
1003
+ codeName: normalizedError.codeName
1004
+ },
1005
+ correlationId: resolvedCorrelationId
1006
+ }
1007
+ );
1008
+ }
1009
+
1010
+ throw normalizedError;
1011
+ }
1012
+ finally {
1013
+ await this._monitorManagerFunction.finishMonitorFunction(monitor);
1014
+ }
1015
+ };
1016
+
1017
+ if (shouldStartTransaction) {
1018
+ let monitor = null;
1019
+
1020
+ return ResolveIOServer.getMongoManager().oneTimeTransaction(async () => {
1021
+ // console.log(new Date(), 'Calling Method - New Session', methodName);
1022
+
1023
+ monitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);
1024
+
1025
+ try {
1026
+ let res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);
1027
+
1028
+ if (methodCallback) {
1029
+ methodCallback(null, res);
1030
+ }
1031
+
1032
+ if (shouldTrackTextMetric) {
1033
+ try {
1034
+ await recordTextMessageMetric({
1035
+ status: 'sent',
1036
+ provider: textMetricProvider,
1037
+ metadata: {
1038
+ method: methodName
1039
+ }
1040
+ });
1041
+ }
1042
+ catch (error) {
1043
+ console.error('Error recording text message metric:', error);
1044
+ }
1045
+ }
1046
+
1047
+ return res;
1048
+ }
1049
+ catch (err) {
1050
+ if (err.code === 112 || err.codeName === 'WriteConflict' || err.code === 251 || err.codeName === 'NoSuchTransaction') {
1051
+ throw err; // Write error, retry
1052
+ }
1053
+
1054
+ const { error: normalizedError, correlationId: resolvedCorrelationId } = ensureErrorWithCorrelation(err, correlationId);
1055
+
1056
+ console.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - New Session', methodName, {
1057
+ code: normalizedError.code,
1058
+ codeName: normalizedError.codeName,
1059
+ message: normalizedError.message,
1060
+ stack: normalizedError.stack,
1061
+ correlationId: resolvedCorrelationId
1062
+ }], null, 2));
1063
+
1064
+ await this.reportMethodError(
1065
+ 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
1066
+ resolvedCorrelationId,
1067
+ {
1068
+ message: 'Error detected during method execution (new session)',
1069
+ method: methodName,
1070
+ data: methodData,
1071
+ error: normalizedError
1072
+ },
1073
+ { context: 'callMethod-new-session', methodName },
1074
+ normalizedError.stack
1075
+ );
1076
+ normalizedError.message = `${new Date().toISOString()} - Error in Method With Session (${methodName}) - New Session: ${normalizedError.message}`;
1077
+
1078
+ if (methodCallback) {
1079
+ methodCallback(normalizedError, null);
1080
+ }
1081
+
1082
+ if (shouldTrackTextMetric) {
1083
+ try {
1084
+ await recordTextMessageMetric({
1085
+ status: 'failed',
1086
+ provider: textMetricProvider,
1087
+ metadata: {
1088
+ method: methodName
1089
+ }
1090
+ });
1091
+ }
1092
+ catch (error) {
1093
+ console.error('Error recording text message metric:', error);
1094
+ }
1095
+ }
1096
+
1097
+ if (!process.env.IS_WORKER_INSTANCE) {
1098
+ await this.callMethod(
1099
+ 'insertErrorLog',
1100
+ `Error in Method: ${methodName}`,
1101
+ {
1102
+ method: methodName,
1103
+ methodData,
1104
+ error: {
1105
+ message: normalizedError.message,
1106
+ stack: normalizedError.stack,
1107
+ code: normalizedError.code,
1108
+ codeName: normalizedError.codeName
1109
+ },
1110
+ correlationId: resolvedCorrelationId
1111
+ }
1112
+ );
1113
+ }
1114
+
1115
+ throw normalizedError;
1116
+ }
1117
+ finally {
1118
+ await this._monitorManagerFunction.finishMonitorFunction(monitor);
1119
+ }
1120
+ });
1121
+ }
1122
+ else if (method.bypassSession && session) {
1123
+ return ResolveIOServer.getMongoManager().runWithoutSession(async () => await executeWithExistingSession());
1124
+ }
1125
+ else {
1126
+ return executeWithExistingSession();
1127
+ }
1128
+ }
1129
+ finally {
1130
+ releaseLocalConcurrency();
1131
+ }
1132
+ }
1133
+
1134
+ private async acquireLocalConcurrency(methodName: string, maxConcurrency?: number): Promise<() => void> {
1135
+ if (!maxConcurrency || maxConcurrency < 1) {
1136
+ return () => {};
1137
+ }
1138
+
1139
+ let current = this._localActiveCounts.get(methodName) || 0;
1140
+
1141
+ if (current < maxConcurrency) {
1142
+ this._localActiveCounts.set(methodName, current + 1);
1143
+ return this.createLocalRelease(methodName);
1144
+ }
1145
+
1146
+ // eslint-disable-next-line no-restricted-syntax
1147
+ return new Promise((resolve) => {
1148
+ let queue = this._localWaitQueues.get(methodName);
1149
+
1150
+ if (!queue) {
1151
+ queue = [];
1152
+ this._localWaitQueues.set(methodName, queue);
1153
+ }
1154
+
1155
+ queue.push(() => {
1156
+ let curr = this._localActiveCounts.get(methodName) || 0;
1157
+ this._localActiveCounts.set(methodName, curr + 1);
1158
+ resolve(this.createLocalRelease(methodName));
1159
+ });
1160
+ });
1161
+ }
1162
+
1163
+ private createLocalRelease(methodName: string): () => void {
1164
+ let released = false;
1165
+
1166
+ return () => {
1167
+ if (released) {
1168
+ return;
1169
+ }
1170
+
1171
+ released = true;
1172
+
1173
+ let current = this._localActiveCounts.get(methodName) || 0;
1174
+ this._localActiveCounts.set(methodName, current > 0 ? current - 1 : 0);
1175
+
1176
+ let queue = this._localWaitQueues.get(methodName);
1177
+
1178
+ if (queue && queue.length) {
1179
+ let next = queue.shift();
1180
+
1181
+ if (next) {
1182
+ next();
1183
+ }
1184
+ }
1185
+ };
1186
+ }
1187
+
1188
+ setupEmailWatcher() {
1189
+ const changeStream = EmailHistories.watchCollection([]);
1190
+
1191
+ changeStream.on('change', async (change) => {
1192
+ if (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {
1193
+ this.emailQueue.add(change.fullDocument._id.toString());
1194
+ await this.tryProcessEmail();
1195
+ }
1196
+ else if (change.operationType === 'update' || change.operationType === 'replace') {
1197
+ const updatedEmail = change.fullDocument;
1198
+ if (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {
1199
+ this.emailQueue.delete(updatedEmail._id.toString());
1200
+ }
1201
+ }
1202
+ })
1203
+ .on('error', async err => {
1204
+ console.error('Email history changestream error', err);
1205
+ await changeStream.close();
1206
+ })
1207
+ .on('close', () => {
1208
+ this.setupEmailWatcher();
1209
+ });
1210
+ }
1211
+
1212
+ async loadPendingEmails() {
1213
+ // Load any pending emails on startup
1214
+ const pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});
1215
+ for (const email of pendingEmails) {
1216
+ this.emailQueue.add(email._id.toString());
1217
+ }
1218
+ // Try to process emails
1219
+ await this.tryProcessEmail();
1220
+ }
1221
+
1222
+ async tryProcessEmail() {
1223
+ if (this.isEmailProcessing || this.emailQueue.size === 0) {
1224
+ return;
1225
+ }
1226
+
1227
+ this.isEmailProcessing = true;
1228
+
1229
+ try {
1230
+ while (this.emailQueue.size > 0) {
1231
+ const emailId = this.emailQueue.values().next().value;
1232
+ this.emailQueue.delete(emailId);
1233
+
1234
+ const pendingEmail = await EmailHistories.findOne(
1235
+ {
1236
+ _id: emailId,
1237
+ status: 'pending',
1238
+ }
1239
+ );
1240
+
1241
+ if (!pendingEmail) {
1242
+ continue;
1243
+ }
1244
+
1245
+ let queuedAt: Date;
1246
+ if (pendingEmail.date instanceof Date) {
1247
+ queuedAt = pendingEmail.date;
1248
+ }
1249
+ else if (pendingEmail.createdAt instanceof Date) {
1250
+ queuedAt = pendingEmail.createdAt;
1251
+ }
1252
+ else {
1253
+ queuedAt = new Date();
1254
+ }
1255
+
1256
+ const timeSinceQueued = Date.now() - queuedAt.getTime();
1257
+ const remainingDelay = this._emailProcessingDelayMs - timeSinceQueued;
1258
+
1259
+ if (remainingDelay > 0) {
1260
+ // eslint-disable-next-line no-restricted-syntax
1261
+ await new Promise(resolve => setTimeout(resolve, remainingDelay));
1262
+ }
1263
+
1264
+ const emailHistory = await EmailHistories.findOneAndUpdate(
1265
+ {
1266
+ _id: emailId,
1267
+ status: 'pending',
1268
+ },
1269
+ {
1270
+ $set: { status: 'processing', processingAt: new Date() },
1271
+ }
1272
+ );
1273
+
1274
+ if (!emailHistory) {
1275
+ continue;
1276
+ }
1277
+
1278
+ // Fetch and process attachments
1279
+ if (emailHistory.attachments && emailHistory.attachments.length > 0) {
1280
+ const validAttachments: any[] = [];
1281
+ let attachmentError = false;
1282
+
1283
+ for (const att of emailHistory.attachments) {
1284
+ if (att.path && att.path.startsWith('http')) {
1285
+ try {
1286
+ const response = await fetch(att.path);
1287
+ if (!response.ok) {
1288
+ attachmentError = true;
1289
+ continue;
1290
+ }
1291
+ const arrayBuffer = await response.arrayBuffer();
1292
+ const buffer = Buffer.from(arrayBuffer);
1293
+
1294
+ // Check the size of the attachment
1295
+ const maxSize = 20 * 1024 * 1024; // 20MB in bytes
1296
+ if (buffer.length <= maxSize) {
1297
+ // Attachment is within size limits, include it
1298
+ att.content = buffer;
1299
+ delete att.path;
1300
+ validAttachments.push(att);
1301
+ }
1302
+ }
1303
+ catch (err) {
1304
+ console.error('Failed to fetch attachment:', err);
1305
+ attachmentError = true;
1306
+ }
1307
+ }
1308
+ else {
1309
+ validAttachments.push(att);
1310
+ }
1311
+ }
1312
+
1313
+ emailHistory.attachments = validAttachments;
1314
+ if (attachmentError) {
1315
+ emailHistory.text =
1316
+ (typeof emailHistory.text === 'string' ? emailHistory.text : '') +
1317
+ '\n\nCould not load attachments.';
1318
+ emailHistory.html =
1319
+ (typeof emailHistory.html === 'string' ? emailHistory.html : '') +
1320
+ '<p>Could not load attachments.</p>';
1321
+ }
1322
+ }
1323
+
1324
+ // Prepare email options
1325
+ const mailOptions: any = {
1326
+ replyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),
1327
+ from: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,
1328
+ to: emailHistory.email,
1329
+ subject:
1330
+ (ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/dev\./) ||
1331
+ ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/www\.dev\./)
1332
+ ? '(DEV SERVER) - '
1333
+ : '') + emailHistory.subject,
1334
+ text: typeof emailHistory.text === 'string' ? emailHistory.text : '',
1335
+ html: typeof emailHistory.html === 'string' ? emailHistory.html : '',
1336
+ attachments: emailHistory.attachments || [],
1337
+ headers: emailHistory.headers || undefined,
1338
+ force_ses: emailHistory.force_ses
1339
+ };
1340
+
1341
+ // Process attachments before sending
1342
+ if (mailOptions.attachments && mailOptions.attachments.length > 0) {
1343
+ mailOptions.attachments = mailOptions.attachments.map((att) => {
1344
+ const newAtt = { ...att };
1345
+ // Handle attachments stored as BinData or Buffer
1346
+ if (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {
1347
+ // Convert MongoDB's Binary data to Buffer
1348
+ if (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {
1349
+ newAtt.content = Buffer.from(newAtt.content.buffer);
1350
+ }
1351
+ else {
1352
+ // Handle other types if necessary
1353
+ newAtt.content = Buffer.from(newAtt.content);
1354
+ }
1355
+ }
1356
+ // Handle attachments stored as Base64 strings
1357
+ else if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {
1358
+ newAtt.content = Buffer.from(newAtt.content, 'base64');
1359
+ delete newAtt.encoding;
1360
+ }
1361
+ // Ensure the content is a Buffer
1362
+ else if (typeof newAtt.content === 'string') {
1363
+ newAtt.content = Buffer.from(newAtt.content);
1364
+ }
1365
+ return newAtt;
1366
+ });
1367
+ }
1368
+
1369
+ // Send the email
1370
+ const emailProvider = (!mailOptions.force_ses && this._mailerCustom) ? 'custom' : 'ses';
1371
+ (!mailOptions.force_ses && this._mailerCustom ? this._mailerCustom : this._mailerSES).sendMail(mailOptions, async err => {
1372
+ const metricStatus = err ? 'failed' : 'sent';
1373
+
1374
+ try {
1375
+ if (err) {
1376
+ console.error('Failed to send email:', err);
1377
+ await this.finalizeEmailHistoryStorage(
1378
+ emailHistory,
1379
+ 'failed',
1380
+ typeof err === 'string' ? err : this.safeStringify(err)
1381
+ );
1382
+ }
1383
+ else {
1384
+ if (emailHistory.email === 'dev@resolveio.com') {
1385
+ await EmailHistories.deleteOne({ _id: emailHistory._id });
1386
+ }
1387
+ else {
1388
+ await this.finalizeEmailHistoryStorage(emailHistory, 'completed');
1389
+ }
1390
+ }
1391
+ }
1392
+ catch (error) {
1393
+ console.error('Error in sendMail callback:', error);
1394
+ await this.finalizeEmailHistoryStorage(
1395
+ emailHistory,
1396
+ 'failed',
1397
+ typeof error === 'string' ? error : this.safeStringify(error)
1398
+ );
1399
+ }
1400
+ finally {
1401
+ try {
1402
+ await recordEmailMetric({
1403
+ status: metricStatus,
1404
+ provider: emailProvider,
1405
+ metadata: {
1406
+ method: 'sendEmail'
1407
+ }
1408
+ });
1409
+ }
1410
+ catch (error) {
1411
+ console.error('Error recording email metric:', error);
1412
+ }
1413
+ }
1414
+ });
1415
+
1416
+ // Wait for at least one second before sending the next email
1417
+ // eslint-disable-next-line no-restricted-syntax
1418
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1419
+ }
1420
+ }
1421
+ catch (err) {
1422
+ console.error('Error processing email queue:', err);
1423
+ }
1424
+ finally {
1425
+ this.isEmailProcessing = false;
1426
+ // Check if new emails arrived while processing
1427
+ if (this.emailQueue.size > 0) {
1428
+ await this.tryProcessEmail();
1429
+ }
1430
+ }
1431
+ }
1432
+
1433
+ private shouldTrackTextMessageMetric(methodName: string): boolean {
1434
+ const normalized = String(methodName || '').trim().toLowerCase();
1435
+ if (!normalized) {
1436
+ return false;
1437
+ }
1438
+
1439
+ return normalized.startsWith('sendsms') || normalized.startsWith('sendtext');
1440
+ }
1441
+
1442
+ private getTextMessageProvider(): string | undefined {
1443
+ const provider = this.serverConfig?.['SMS_PROVIDER'] || '';
1444
+ if (typeof provider === 'string' && provider.trim().length) {
1445
+ return provider.trim().toLowerCase();
1446
+ }
1447
+
1448
+ if (this.serverConfig?.['TWILIO_SID'] || this.serverConfig?.['TWILIO_AUTH_TOKEN']) {
1449
+ return 'twilio';
1450
+ }
1451
+
1452
+ return undefined;
1453
+ }
1454
+
1455
+ safeStringify(obj)
1456
+ {
1457
+ try
1458
+ {
1459
+ return JSON.stringify(obj, this.getCircularReplacer());
1460
+ }
1461
+ catch (e)
1462
+ {
1463
+ return `Error in JSON stringifying: ${e.message}`;
1464
+ }
1465
+ }
1466
+
1467
+ getCircularReplacer()
1468
+ {
1469
+ const seen = new WeakSet();
1470
+ return (key, value) =>
1471
+ {
1472
+ if (typeof value === "object" && value !== null)
1473
+ {
1474
+ if (seen.has(value))
1475
+ {
1476
+ return "[Circular]";
1477
+ }
1478
+ seen.add(value);
1479
+ }
1480
+ return value;
1481
+ };
1482
+ }
1483
+
1484
+ private async finalizeEmailHistoryStorage(
1485
+ emailHistory: EmailHistoryModel,
1486
+ status: 'completed' | 'failed',
1487
+ error?: string
1488
+ ): Promise<void> {
1489
+ const setValues: Record<string, any> = {
1490
+ status,
1491
+ text: truncateTextForHistory(emailHistory.text, EMAIL_HISTORY_TEXT_MAX_CHARS),
1492
+ html: truncateTextForHistory(emailHistory.html, EMAIL_HISTORY_HTML_MAX_CHARS),
1493
+ attachments: sanitizeAttachmentsForHistory(emailHistory.attachments),
1494
+ completedAt: new Date()
1495
+ };
1496
+
1497
+ const sanitizedOccurrences = sanitizeOccurrencesForHistory(emailHistory.occurrences);
1498
+ if (sanitizedOccurrences) {
1499
+ setValues.occurrences = sanitizedOccurrences;
1500
+ }
1501
+
1502
+ if (status === 'failed') {
1503
+ setValues.error = truncateTextForHistory(error || '', EMAIL_HISTORY_ERROR_MAX_CHARS);
1504
+ }
1505
+ else {
1506
+ setValues.error = '';
1507
+ }
1508
+
1509
+ await EmailHistories.updateOne(
1510
+ { _id: emailHistory._id },
1511
+ {
1512
+ $set: setValues
1513
+ }
1514
+ );
1515
+ }
1516
+
1517
+ private async tryMergeEmailOccurrence(
1518
+ email: string,
1519
+ subject: string,
1520
+ correlationId: string,
1521
+ occurrence: EmailHistoryOccurrence,
1522
+ meta?: Record<string, any>
1523
+ ): Promise<EmailHistoryModel | null> {
1524
+ const existing = await EmailHistories.findOne(
1525
+ {
1526
+ email,
1527
+ correlationId,
1528
+ status: 'pending'
1529
+ },
1530
+ { sort: { date: 1 } }
1531
+ );
1532
+
1533
+ if (!existing) {
1534
+ return null;
1535
+ }
1536
+
1537
+ const normalizedOccurrences: EmailHistoryOccurrence[] = Array.isArray(existing.occurrences) && existing.occurrences.length
1538
+ ? existing.occurrences.map((item: EmailHistoryOccurrence) => ({
1539
+ _id: item._id || objectIdHexString(),
1540
+ createdAt: item.createdAt instanceof Date ? item.createdAt : new Date(item.createdAt),
1541
+ subject: item.subject || existing.subject || '',
1542
+ text: item.text,
1543
+ html: item.html,
1544
+ meta: item.meta
1545
+ }))
1546
+ : [createEmailOccurrence(
1547
+ existing.subject || '',
1548
+ typeof existing.text === 'string' ? existing.text : undefined,
1549
+ typeof existing.html === 'string' ? existing.html : undefined,
1550
+ existing.meta
1551
+ )];
1552
+
1553
+ normalizedOccurrences.push(occurrence);
1554
+
1555
+ const { text: aggregatedText, html: aggregatedHtml } = formatGroupedEmailContent(correlationId, normalizedOccurrences);
1556
+
1557
+ const updated = await EmailHistories.findOneAndUpdate(
1558
+ {
1559
+ _id: existing._id,
1560
+ status: 'pending'
1561
+ },
1562
+ {
1563
+ $set: {
1564
+ subject,
1565
+ text: aggregatedText,
1566
+ html: aggregatedHtml,
1567
+ occurrences: normalizedOccurrences,
1568
+ meta: meta || existing.meta,
1569
+ updatedAt: new Date()
1570
+ }
1571
+ },
1572
+ { returnDocument: 'after' }
1573
+ );
1574
+
1575
+ return updated || null;
1576
+ }
1577
+
1578
+ private async waitForEmailCompletion(emailHistory: EmailHistoryModel, options?: SendEmailOptions): Promise<EmailHistoryModel> {
1579
+ const timeoutMs = Math.max(1000, Number(options?.waitForCompletionTimeoutMs) || 30000);
1580
+ const pollMs = Math.max(100, Number(options?.waitForCompletionPollMs) || 250);
1581
+ const deadline = Date.now() + timeoutMs;
1582
+
1583
+ while (Date.now() <= deadline) {
1584
+ const latest = await EmailHistories.findOne({_id: emailHistory._id}, {
1585
+ projection: {
1586
+ status: 1,
1587
+ error: 1,
1588
+ date: 1,
1589
+ id_user: 1,
1590
+ user: 1,
1591
+ email: 1,
1592
+ subject: 1,
1593
+ text: 1,
1594
+ html: 1,
1595
+ attachments: 1,
1596
+ send_from: 1,
1597
+ reply_to: 1,
1598
+ force_ses: 1,
1599
+ headers: 1,
1600
+ correlationId: 1,
1601
+ meta: 1,
1602
+ occurrences: 1,
1603
+ processingAt: 1,
1604
+ completedAt: 1
1605
+ }
1606
+ });
1607
+
1608
+ if (!latest) {
1609
+ return {
1610
+ ...emailHistory,
1611
+ status: 'completed',
1612
+ error: '',
1613
+ completedAt: new Date()
1614
+ };
1615
+ }
1616
+
1617
+ if (latest.status === 'completed') {
1618
+ return latest;
1619
+ }
1620
+
1621
+ if (latest.status === 'failed') {
1622
+ throw new Error(latest.error || `Email failed to send: ${latest.subject}`);
1623
+ }
1624
+
1625
+ // eslint-disable-next-line no-restricted-syntax
1626
+ await new Promise(resolve => setTimeout(resolve, pollMs));
1627
+ }
1628
+
1629
+ throw new Error(`Email send timed out waiting for completion: ${emailHistory.subject}`);
1630
+ }
1631
+
1632
+ public async sendEmail(
1633
+ sendTo: string,
1634
+ subject: string,
1635
+ text?: string | null,
1636
+ html?: string | null,
1637
+ attachments?: any[] | null,
1638
+ send_from?: string | null,
1639
+ reply_to?: string | null,
1640
+ force_ses = false,
1641
+ local_override = false,
1642
+ options?: SendEmailOptions
1643
+ ) {
1644
+ // Modify sendTo in development environments
1645
+ if (
1646
+ (ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/dev\./) ||
1647
+ ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/www\.dev\./) ||
1648
+ ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&
1649
+ !sendTo.match(/\@resolveio\.com/)
1650
+ ) {
1651
+ sendTo = 'dev@resolveio.com';
1652
+ }
1653
+
1654
+ const normalizedSubject = subject || '';
1655
+ const correlationId = options?.correlationId;
1656
+ const finalSubject = appendCorrelationIdToSubject(normalizedSubject, correlationId);
1657
+ const groupByCorrelationId = !!correlationId;
1658
+ const normalizedText = typeof text === 'string' ? text : '';
1659
+ const normalizedHtml = typeof html === 'string' ? html : '';
1660
+ const occurrence = groupByCorrelationId
1661
+ ? createEmailOccurrence(normalizedSubject, normalizedText, normalizedHtml, options?.meta)
1662
+ : null;
1663
+ let allowGrouping = groupByCorrelationId;
1664
+
1665
+ if (sendTo) {
1666
+ if (
1667
+ ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||
1668
+ local_override
1669
+ ) {
1670
+ let normalizedAttachments: any[] = [];
1671
+ if (Array.isArray(attachments)) {
1672
+ normalizedAttachments = attachments.slice();
1673
+ }
1674
+ else if (attachments) {
1675
+ normalizedAttachments = [attachments];
1676
+ }
1677
+
1678
+ normalizedAttachments = normalizedAttachments.map(att => {
1679
+ const newAtt = { ...att };
1680
+ if (Buffer.isBuffer(newAtt.content)) {
1681
+ newAtt.content = newAtt.content.toString('base64');
1682
+ newAtt.encoding = 'base64';
1683
+ }
1684
+ return newAtt;
1685
+ });
1686
+
1687
+ if (normalizedAttachments.length > 0) {
1688
+ allowGrouping = false;
1689
+ }
1690
+
1691
+ if (allowGrouping && occurrence && correlationId) {
1692
+ const merged = await this.tryMergeEmailOccurrence(sendTo, finalSubject, correlationId, occurrence, options?.meta);
1693
+ if (merged) {
1694
+ return merged;
1695
+ }
1696
+ }
1697
+
1698
+ const emailHistory: EmailHistoryModel = {
1699
+ _id: objectIdHexString(),
1700
+ __v: 0,
1701
+ date: new Date(),
1702
+ id_user: this['id_user'] || '',
1703
+ user: this['user'] || '',
1704
+ email: sendTo,
1705
+ subject: finalSubject,
1706
+ text: normalizedText,
1707
+ html: normalizedHtml,
1708
+ attachments: normalizedAttachments,
1709
+ send_from: send_from || '',
1710
+ reply_to: reply_to || '',
1711
+ status: 'pending',
1712
+ error: '',
1713
+ force_ses,
1714
+ headers: options?.headers
1715
+ };
1716
+
1717
+ if (allowGrouping && occurrence && correlationId) {
1718
+ const { text: aggregatedText, html: aggregatedHtml } = formatGroupedEmailContent(correlationId, [occurrence]);
1719
+ emailHistory.text = aggregatedText;
1720
+ emailHistory.html = aggregatedHtml;
1721
+ emailHistory.occurrences = [occurrence];
1722
+ emailHistory.correlationId = correlationId;
1723
+ if (options?.meta) {
1724
+ emailHistory.meta = options.meta;
1725
+ }
1726
+ }
1727
+ else {
1728
+ if (correlationId) {
1729
+ emailHistory.correlationId = correlationId;
1730
+ }
1731
+ if (options?.meta) {
1732
+ emailHistory.meta = options.meta;
1733
+ }
1734
+ }
1735
+
1736
+ try {
1737
+ let history = await EmailHistories.insertOne(emailHistory);
1738
+ if (options?.waitForCompletion) {
1739
+ return await this.waitForEmailCompletion(history, options);
1740
+ }
1741
+ return history;
1742
+ }
1743
+ catch (err) {
1744
+ console.error('Failed to queue email:', err);
1745
+ err.message = `Failed to queue email: ${err.message}`;
1746
+ throw err;
1747
+ }
1748
+ }
1749
+ else {
1750
+ console.log(
1751
+ 'Send email',
1752
+ sendTo,
1753
+ finalSubject,
1754
+ normalizedText,
1755
+ normalizedHtml,
1756
+ attachments,
1757
+ send_from,
1758
+ force_ses,
1759
+ correlationId
1760
+ );
1761
+
1762
+ return true;
1763
+ }
1764
+ }
1765
+ else {
1766
+ return true;
1767
+ }
1768
+ }
1769
+
1770
+ public getAWS(): AWS {
1771
+ return this._aws;
1772
+ }
1773
+
1774
+ public readFile(fileName) {
1775
+ if (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {
1776
+ try {
1777
+ return fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');
1778
+ }
1779
+ catch (err) {
1780
+ err.message = `Error in readFile: ${err.message}`;
1781
+ throw err;
1782
+ }
1783
+ }
1784
+ else {
1785
+ if (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {
1786
+ try {
1787
+ return fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');
1788
+ }
1789
+ catch (err) {
1790
+ err.message = `Error in readFile: ${err.message}`;
1791
+ throw err;
1792
+ }
1793
+ }
1794
+ }
1795
+
1796
+ throw new Error ('Error in readFile: File Not Found');
1797
+ }
1798
+
1799
+ public readImage(fileName) {
1800
+ if (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {
1801
+ try {
1802
+ return fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');
1803
+ }
1804
+ catch (err) {
1805
+ err.message = `Error in readImage: ${err.message}`;
1806
+ throw err;
1807
+ }
1808
+ }
1809
+ else {
1810
+ if (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {
1811
+ try {
1812
+ return fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');
1813
+ }
1814
+ catch (err) {
1815
+ err.message = `Error in readImage: ${err.message}`;
1816
+ throw err;
1817
+ }
1818
+ }
1819
+ }
1820
+
1821
+ throw new Error ('Error in readImage: File Not Found');
1822
+ }
1823
+
1824
+ public getEnableDebug() {
1825
+ return this._enableDebug;
1826
+ }
1827
+ }