@resolveio/server-lib 22.3.62 → 22.3.63

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