@resolveio/server-lib 22.3.221 → 22.3.223

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 (745) 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-run.collection.d.ts +3 -0
  20. package/collections/ai-run.collection.js +170 -0
  21. package/collections/ai-run.collection.js.map +1 -0
  22. package/collections/ai-terminal-conversation.collection.d.ts +2 -0
  23. package/collections/ai-terminal-conversation.collection.js +140 -0
  24. package/collections/ai-terminal-conversation.collection.js.map +1 -0
  25. package/collections/ai-terminal-issue-report.collection.d.ts +2 -0
  26. package/collections/ai-terminal-issue-report.collection.js +148 -0
  27. package/collections/ai-terminal-issue-report.collection.js.map +1 -0
  28. package/collections/ai-terminal-message.collection.d.ts +2 -0
  29. package/collections/ai-terminal-message.collection.js +121 -0
  30. package/collections/ai-terminal-message.collection.js.map +1 -0
  31. package/collections/app-setting.collection.d.ts +3 -0
  32. package/collections/app-setting.collection.js +103 -0
  33. package/collections/app-setting.collection.js.map +1 -0
  34. package/collections/app-status.collection.d.ts +3 -0
  35. package/collections/app-status.collection.js +57 -0
  36. package/collections/app-status.collection.js.map +1 -0
  37. package/collections/communication-metric.collection.d.ts +2 -0
  38. package/collections/communication-metric.collection.js +133 -0
  39. package/collections/communication-metric.collection.js.map +1 -0
  40. package/collections/counter.collection.d.ts +3 -0
  41. package/collections/counter.collection.js +56 -0
  42. package/collections/counter.collection.js.map +1 -0
  43. package/collections/cron-job-history.collection.d.ts +3 -0
  44. package/collections/cron-job-history.collection.js +137 -0
  45. package/collections/cron-job-history.collection.js.map +1 -0
  46. package/collections/cron-job.collection.d.ts +3 -0
  47. package/collections/cron-job.collection.js +92 -0
  48. package/collections/cron-job.collection.js.map +1 -0
  49. package/collections/customer-notification.collection.d.ts +3 -0
  50. package/collections/customer-notification.collection.js +130 -0
  51. package/collections/customer-notification.collection.js.map +1 -0
  52. package/collections/customer-portal-password.collection.d.ts +3 -0
  53. package/collections/customer-portal-password.collection.js +75 -0
  54. package/collections/customer-portal-password.collection.js.map +1 -0
  55. package/collections/email-history.collection.d.ts +3 -0
  56. package/collections/email-history.collection.js +134 -0
  57. package/collections/email-history.collection.js.map +1 -0
  58. package/collections/email-verified.collection.d.ts +3 -0
  59. package/collections/email-verified.collection.js +62 -0
  60. package/collections/email-verified.collection.js.map +1 -0
  61. package/collections/file.collection.d.ts +3 -0
  62. package/collections/file.collection.js +74 -0
  63. package/collections/file.collection.js.map +1 -0
  64. package/collections/flag-update.collection.d.ts +3 -0
  65. package/collections/flag-update.collection.js +57 -0
  66. package/collections/flag-update.collection.js.map +1 -0
  67. package/collections/flag.collection.d.ts +3 -0
  68. package/collections/flag.collection.js +57 -0
  69. package/collections/flag.collection.js.map +1 -0
  70. package/collections/log-method-latency.collection.d.ts +3 -0
  71. package/collections/log-method-latency.collection.js +77 -0
  72. package/collections/log-method-latency.collection.js.map +1 -0
  73. package/collections/log-subscription.collection.d.ts +3 -0
  74. package/collections/log-subscription.collection.js +80 -0
  75. package/collections/log-subscription.collection.js.map +1 -0
  76. package/collections/log.collection.d.ts +3 -0
  77. package/collections/log.collection.js +93 -0
  78. package/collections/log.collection.js.map +1 -0
  79. package/collections/logged-in-users.collection.d.ts +3 -0
  80. package/collections/logged-in-users.collection.js +67 -0
  81. package/collections/logged-in-users.collection.js.map +1 -0
  82. package/collections/monitor-cpu.collection.d.ts +3 -0
  83. package/collections/monitor-cpu.collection.js +65 -0
  84. package/collections/monitor-cpu.collection.js.map +1 -0
  85. package/collections/monitor-function.collection.d.ts +3 -0
  86. package/collections/monitor-function.collection.js +74 -0
  87. package/collections/monitor-function.collection.js.map +1 -0
  88. package/collections/monitor-memory.collection.d.ts +3 -0
  89. package/collections/monitor-memory.collection.js +77 -0
  90. package/collections/monitor-memory.collection.js.map +1 -0
  91. package/collections/monitor-mongo.collection.d.ts +3 -0
  92. package/collections/monitor-mongo.collection.js +71 -0
  93. package/collections/monitor-mongo.collection.js.map +1 -0
  94. package/collections/notification.collection.d.ts +3 -0
  95. package/collections/notification.collection.js +57 -0
  96. package/collections/notification.collection.js.map +1 -0
  97. package/collections/openai-usage-ledger.collection.d.ts +2 -0
  98. package/collections/openai-usage-ledger.collection.js +188 -0
  99. package/collections/openai-usage-ledger.collection.js.map +1 -0
  100. package/collections/report-builder-dashboard-builder.collection.d.ts +3 -0
  101. package/collections/report-builder-dashboard-builder.collection.js +109 -0
  102. package/collections/report-builder-dashboard-builder.collection.js.map +1 -0
  103. package/collections/report-builder-library.collection.d.ts +3 -0
  104. package/collections/report-builder-library.collection.js +87 -0
  105. package/collections/report-builder-library.collection.js.map +1 -0
  106. package/collections/report-builder-report.collection.d.ts +4 -0
  107. package/collections/report-builder-report.collection.js +184 -0
  108. package/collections/report-builder-report.collection.js.map +1 -0
  109. package/collections/user-group.collection.d.ts +4 -0
  110. package/collections/user-group.collection.js +89 -0
  111. package/collections/user-group.collection.js.map +1 -0
  112. package/collections/user-guide.collection.d.ts +3 -0
  113. package/collections/user-guide.collection.js +57 -0
  114. package/collections/user-guide.collection.js.map +1 -0
  115. package/collections/user.collection.d.ts +4 -0
  116. package/collections/user.collection.js +180 -0
  117. package/collections/user.collection.js.map +1 -0
  118. package/cron/cron.d.ts +14 -0
  119. package/cron/cron.js +216 -0
  120. package/cron/cron.js.map +1 -0
  121. package/fixtures/cron-jobs.d.ts +1 -0
  122. package/fixtures/cron-jobs.js +150 -0
  123. package/fixtures/cron-jobs.js.map +1 -0
  124. package/fixtures/init.d.ts +1 -0
  125. package/fixtures/init.js +91 -0
  126. package/fixtures/init.js.map +1 -0
  127. package/http/auth.d.ts +2 -0
  128. package/http/auth.js +951 -0
  129. package/http/auth.js.map +1 -0
  130. package/http/health.d.ts +1 -0
  131. package/http/health.js +11 -0
  132. package/http/health.js.map +1 -0
  133. package/http/home.d.ts +1 -0
  134. package/http/home.js +134 -0
  135. package/http/home.js.map +1 -0
  136. package/http/slow-query-publication.d.ts +2 -0
  137. package/http/slow-query-publication.js +99 -0
  138. package/http/slow-query-publication.js.map +1 -0
  139. package/index.d.ts +1 -0
  140. package/index.js +19 -0
  141. package/index.js.map +1 -0
  142. package/managers/ai-assistant-codex-manager.manager.d.ts +67 -0
  143. package/managers/ai-assistant-codex-manager.manager.js +1113 -0
  144. package/managers/ai-assistant-codex-manager.manager.js.map +1 -0
  145. package/managers/ai-run-evidence.manager.d.ts +36 -0
  146. package/managers/ai-run-evidence.manager.js +377 -0
  147. package/managers/ai-run-evidence.manager.js.map +1 -0
  148. package/managers/communication-metric.manager.d.ts +16 -0
  149. package/managers/communication-metric.manager.js +134 -0
  150. package/managers/communication-metric.manager.js.map +1 -0
  151. package/managers/cron.manager.d.ts +20 -0
  152. package/managers/cron.manager.js +534 -0
  153. package/managers/cron.manager.js.map +1 -0
  154. package/managers/customer-notification-content.manager.d.ts +55 -0
  155. package/managers/customer-notification-content.manager.js +158 -0
  156. package/managers/customer-notification-content.manager.js.map +1 -0
  157. package/managers/diagnostic-manager-bootstrap.d.ts +9 -0
  158. package/managers/diagnostic-manager-bootstrap.js +260 -0
  159. package/managers/diagnostic-manager-bootstrap.js.map +1 -0
  160. package/managers/error-auto-fix.manager.d.ts +149 -0
  161. package/managers/error-auto-fix.manager.js +3064 -0
  162. package/managers/error-auto-fix.manager.js.map +1 -0
  163. package/managers/local-log.manager.d.ts +18 -0
  164. package/managers/local-log.manager.js +88 -0
  165. package/managers/local-log.manager.js.map +1 -0
  166. package/managers/method.manager.d.ts +84 -0
  167. package/managers/method.manager.js +1964 -0
  168. package/managers/method.manager.js.map +1 -0
  169. package/managers/mongo.manager.d.ts +224 -0
  170. package/managers/mongo.manager.js +5000 -0
  171. package/managers/mongo.manager.js.map +1 -0
  172. package/managers/monitor.manager.d.ts +70 -0
  173. package/managers/monitor.manager.js +550 -0
  174. package/managers/monitor.manager.js.map +1 -0
  175. package/managers/openai-usage-ledger.manager.d.ts +30 -0
  176. package/managers/openai-usage-ledger.manager.js +142 -0
  177. package/managers/openai-usage-ledger.manager.js.map +1 -0
  178. package/managers/slow-query-verifier.manager.d.ts +144 -0
  179. package/managers/slow-query-verifier.manager.js +3857 -0
  180. package/managers/slow-query-verifier.manager.js.map +1 -0
  181. package/managers/slow-query.manager.d.ts +28 -0
  182. package/managers/slow-query.manager.js +468 -0
  183. package/managers/slow-query.manager.js.map +1 -0
  184. package/managers/subscription.manager.d.ts +169 -0
  185. package/managers/subscription.manager.js +3434 -0
  186. package/managers/subscription.manager.js.map +1 -0
  187. package/managers/websocket.manager.d.ts +73 -0
  188. package/managers/websocket.manager.js +673 -0
  189. package/managers/websocket.manager.js.map +1 -0
  190. package/managers/worker-dispatcher.manager.d.ts +120 -0
  191. package/managers/worker-dispatcher.manager.js +1266 -0
  192. package/managers/worker-dispatcher.manager.js.map +1 -0
  193. package/managers/worker-server.manager.d.ts +35 -0
  194. package/managers/worker-server.manager.js +582 -0
  195. package/managers/worker-server.manager.js.map +1 -0
  196. package/methods/accounts.d.ts +2 -0
  197. package/methods/accounts.js +624 -0
  198. package/methods/accounts.js.map +1 -0
  199. package/methods/ai-terminal.d.ts +458 -0
  200. package/methods/ai-terminal.js +27991 -0
  201. package/methods/ai-terminal.js.map +1 -0
  202. package/methods/app-settings.d.ts +2 -0
  203. package/methods/app-settings.js +169 -0
  204. package/methods/app-settings.js.map +1 -0
  205. package/methods/aws.d.ts +2 -0
  206. package/methods/aws.js +877 -0
  207. package/methods/aws.js.map +1 -0
  208. package/methods/collections.d.ts +2 -0
  209. package/methods/collections.js +719 -0
  210. package/methods/collections.js.map +1 -0
  211. package/methods/counters.d.ts +2 -0
  212. package/methods/counters.js +113 -0
  213. package/methods/counters.js.map +1 -0
  214. package/methods/cron-jobs.d.ts +2 -0
  215. package/methods/cron-jobs.js +2475 -0
  216. package/methods/cron-jobs.js.map +1 -0
  217. package/methods/customer-notifications.d.ts +2 -0
  218. package/methods/customer-notifications.js +528 -0
  219. package/methods/customer-notifications.js.map +1 -0
  220. package/methods/diagnostics.d.ts +2 -0
  221. package/methods/diagnostics.js +703 -0
  222. package/methods/diagnostics.js.map +1 -0
  223. package/methods/flag-updates.d.ts +2 -0
  224. package/methods/flag-updates.js +8 -0
  225. package/methods/flag-updates.js.map +1 -0
  226. package/methods/flags.d.ts +2 -0
  227. package/methods/flags.js +8 -0
  228. package/methods/flags.js.map +1 -0
  229. package/methods/logs.d.ts +2 -0
  230. package/methods/logs.js +751 -0
  231. package/methods/logs.js.map +1 -0
  232. package/methods/mongo-explorer.d.ts +2 -0
  233. package/methods/mongo-explorer.js +1808 -0
  234. package/methods/mongo-explorer.js.map +1 -0
  235. package/methods/monitor.d.ts +2 -0
  236. package/methods/monitor.js +543 -0
  237. package/methods/monitor.js.map +1 -0
  238. package/methods/pdf.d.ts +2 -0
  239. package/methods/pdf.js +1216 -0
  240. package/methods/pdf.js.map +1 -0
  241. package/methods/publications.d.ts +1 -0
  242. package/methods/publications.js +183 -0
  243. package/methods/publications.js.map +1 -0
  244. package/methods/report-builder.d.ts +2 -0
  245. package/methods/report-builder.js +3094 -0
  246. package/methods/report-builder.js.map +1 -0
  247. package/methods/support.d.ts +2 -0
  248. package/methods/support.js +430 -0
  249. package/methods/support.js.map +1 -0
  250. package/models/ai-run.model.d.ts +19 -0
  251. package/models/ai-run.model.js +4 -0
  252. package/models/ai-run.model.js.map +1 -0
  253. package/models/ai-terminal-conversation.model.d.ts +17 -0
  254. package/models/ai-terminal-conversation.model.js +4 -0
  255. package/models/ai-terminal-conversation.model.js.map +1 -0
  256. package/models/ai-terminal-issue-report.model.d.ts +19 -0
  257. package/models/ai-terminal-issue-report.model.js +4 -0
  258. package/models/ai-terminal-issue-report.model.js.map +1 -0
  259. package/models/ai-terminal-message.model.d.ts +22 -0
  260. package/models/ai-terminal-message.model.js +4 -0
  261. package/models/ai-terminal-message.model.js.map +1 -0
  262. package/models/app-setting.model.d.ts +16 -0
  263. package/models/app-setting.model.js +4 -0
  264. package/models/app-setting.model.js.map +1 -0
  265. package/{src/models/app-status.model.ts → models/app-status.model.d.ts} +2 -3
  266. package/models/app-status.model.js +4 -0
  267. package/models/app-status.model.js.map +1 -0
  268. package/{src/models/billing-logged-in-users.model.ts → models/billing-logged-in-users.model.d.ts} +4 -5
  269. package/models/billing-logged-in-users.model.js +4 -0
  270. package/models/billing-logged-in-users.model.js.map +1 -0
  271. package/models/collection-document.model.d.ts +21 -0
  272. package/models/collection-document.model.js +4 -0
  273. package/models/collection-document.model.js.map +1 -0
  274. package/models/communication-metric.model.d.ts +20 -0
  275. package/models/communication-metric.model.js +4 -0
  276. package/models/communication-metric.model.js.map +1 -0
  277. package/{src/models/counter.model.ts → models/counter.model.d.ts} +3 -4
  278. package/models/counter.model.js +4 -0
  279. package/models/counter.model.js.map +1 -0
  280. package/models/cron-job-history.model.d.ts +15 -0
  281. package/models/cron-job-history.model.js +4 -0
  282. package/models/cron-job-history.model.js.map +1 -0
  283. package/models/cron-job.model.d.ts +14 -0
  284. package/models/cron-job.model.js +4 -0
  285. package/models/cron-job.model.js.map +1 -0
  286. package/models/customer-notification.model.d.ts +26 -0
  287. package/models/customer-notification.model.js +4 -0
  288. package/models/customer-notification.model.js.map +1 -0
  289. package/models/customer-portal-password.model.d.ts +11 -0
  290. package/models/customer-portal-password.model.js +4 -0
  291. package/models/customer-portal-password.model.js.map +1 -0
  292. package/models/dialog.model.d.ts +23 -0
  293. package/models/dialog.model.js +4 -0
  294. package/models/dialog.model.js.map +1 -0
  295. package/models/email-history.model.d.ts +32 -0
  296. package/{src/models/email-history.model.ts → models/email-history.model.js} +4 -36
  297. package/models/email-history.model.js.map +1 -0
  298. package/{src/models/email-verified.model.ts → models/email-verified.model.d.ts} +5 -6
  299. package/models/email-verified.model.js +4 -0
  300. package/models/email-verified.model.js.map +1 -0
  301. package/{src/models/file.model.ts → models/file.model.d.ts} +7 -8
  302. package/models/file.model.js +4 -0
  303. package/models/file.model.js.map +1 -0
  304. package/{src/models/flag-update.model.ts → models/flag-update.model.d.ts} +3 -4
  305. package/models/flag-update.model.js +4 -0
  306. package/models/flag-update.model.js.map +1 -0
  307. package/{src/models/flag.model.ts → models/flag.model.d.ts} +3 -4
  308. package/models/flag.model.js +4 -0
  309. package/models/flag.model.js.map +1 -0
  310. package/models/log-method-latency.model.d.ts +10 -0
  311. package/models/log-method-latency.model.js +4 -0
  312. package/models/log-method-latency.model.js.map +1 -0
  313. package/{src/models/log-subscription.model.ts → models/log-subscription.model.d.ts} +9 -11
  314. package/models/log-subscription.model.js +4 -0
  315. package/models/log-subscription.model.js.map +1 -0
  316. package/models/log.model.d.ts +17 -0
  317. package/models/log.model.js +4 -0
  318. package/models/log.model.js.map +1 -0
  319. package/{src/models/logged-in-users.model.ts → models/logged-in-users.model.d.ts} +5 -6
  320. package/models/logged-in-users.model.js +4 -0
  321. package/models/logged-in-users.model.js.map +1 -0
  322. package/{src/models/method-response.model.ts → models/method-response.model.d.ts} +6 -7
  323. package/models/method-response.model.js +4 -0
  324. package/models/method-response.model.js.map +1 -0
  325. package/models/method.model.d.ts +26 -0
  326. package/models/method.model.js +4 -0
  327. package/models/method.model.js.map +1 -0
  328. package/{src/models/monitor-cpu.model.ts → models/monitor-cpu.model.d.ts} +7 -9
  329. package/models/monitor-cpu.model.js +4 -0
  330. package/models/monitor-cpu.model.js.map +1 -0
  331. package/models/monitor-function.model.d.ts +14 -0
  332. package/models/monitor-function.model.js +4 -0
  333. package/models/monitor-function.model.js.map +1 -0
  334. package/models/monitor-memory.model.d.ts +15 -0
  335. package/models/monitor-memory.model.js +4 -0
  336. package/models/monitor-memory.model.js.map +1 -0
  337. package/models/monitor-mongo.model.d.ts +13 -0
  338. package/models/monitor-mongo.model.js +4 -0
  339. package/models/monitor-mongo.model.js.map +1 -0
  340. package/{src/models/notification.model.ts → models/notification.model.d.ts} +4 -6
  341. package/models/notification.model.js +4 -0
  342. package/models/notification.model.js.map +1 -0
  343. package/models/openai-usage-ledger.model.d.ts +30 -0
  344. package/models/openai-usage-ledger.model.js +4 -0
  345. package/models/openai-usage-ledger.model.js.map +1 -0
  346. package/models/pagination.model.d.ts +11 -0
  347. package/models/pagination.model.js +28 -0
  348. package/models/pagination.model.js.map +1 -0
  349. package/models/permission.model.d.ts +12 -0
  350. package/models/permission.model.js +4 -0
  351. package/models/permission.model.js.map +1 -0
  352. package/models/report-builder-dashboard-builder.model.d.ts +25 -0
  353. package/models/report-builder-dashboard-builder.model.js +4 -0
  354. package/models/report-builder-dashboard-builder.model.js.map +1 -0
  355. package/models/report-builder-library.model.d.ts +17 -0
  356. package/models/report-builder-library.model.js +4 -0
  357. package/models/report-builder-library.model.js.map +1 -0
  358. package/models/report-builder-report.model.d.ts +121 -0
  359. package/models/report-builder-report.model.js +4 -0
  360. package/models/report-builder-report.model.js.map +1 -0
  361. package/models/report-builder.model.d.ts +61 -0
  362. package/models/report-builder.model.js +4 -0
  363. package/models/report-builder.model.js.map +1 -0
  364. package/models/select-data-label.model.d.ts +9 -0
  365. package/models/select-data-label.model.js +4 -0
  366. package/models/select-data-label.model.js.map +1 -0
  367. package/models/server-message.model.d.ts +32 -0
  368. package/models/server-message.model.js +4 -0
  369. package/models/server-message.model.js.map +1 -0
  370. package/models/slow-query-report.model.d.ts +23 -0
  371. package/models/slow-query-report.model.js +4 -0
  372. package/models/slow-query-report.model.js.map +1 -0
  373. package/models/subscription.model.d.ts +31 -0
  374. package/models/subscription.model.js +4 -0
  375. package/models/subscription.model.js.map +1 -0
  376. package/models/support-ticket.model.d.ts +87 -0
  377. package/models/support-ticket.model.js +4 -0
  378. package/models/support-ticket.model.js.map +1 -0
  379. package/models/user-group.model.d.ts +20 -0
  380. package/models/user-group.model.js +4 -0
  381. package/models/user-group.model.js.map +1 -0
  382. package/{src/models/user-guide.model.ts → models/user-guide.model.d.ts} +4 -5
  383. package/models/user-guide.model.js +4 -0
  384. package/models/user-guide.model.js.map +1 -0
  385. package/models/user.model.d.ts +84 -0
  386. package/models/user.model.js +4 -0
  387. package/models/user.model.js.map +1 -0
  388. package/package.json +1 -1
  389. package/private/images/ResolveIO.png +0 -0
  390. package/public_api.js +127 -0
  391. package/public_api.js.map +1 -0
  392. package/publications/ai-terminal.d.ts +1 -0
  393. package/publications/ai-terminal.js +122 -0
  394. package/publications/ai-terminal.js.map +1 -0
  395. package/publications/app-settings.d.ts +2 -0
  396. package/publications/app-settings.js +28 -0
  397. package/publications/app-settings.js.map +1 -0
  398. package/publications/app-status.d.ts +2 -0
  399. package/publications/app-status.js +16 -0
  400. package/publications/app-status.js.map +1 -0
  401. package/publications/cron-jobs.d.ts +2 -0
  402. package/publications/cron-jobs.js +88 -0
  403. package/publications/cron-jobs.js.map +1 -0
  404. package/publications/customer-notifications.d.ts +2 -0
  405. package/publications/customer-notifications.js +161 -0
  406. package/publications/customer-notifications.js.map +1 -0
  407. package/publications/files.d.ts +2 -0
  408. package/publications/files.js +36 -0
  409. package/publications/files.js.map +1 -0
  410. package/publications/flags-update.d.ts +2 -0
  411. package/publications/flags-update.js +22 -0
  412. package/publications/flags-update.js.map +1 -0
  413. package/publications/flags.d.ts +2 -0
  414. package/publications/flags.js +22 -0
  415. package/publications/flags.js.map +1 -0
  416. package/publications/logs.d.ts +2 -0
  417. package/publications/logs.js +164 -0
  418. package/publications/logs.js.map +1 -0
  419. package/publications/notifications.d.ts +2 -0
  420. package/publications/notifications.js +16 -0
  421. package/publications/notifications.js.map +1 -0
  422. package/publications/report-builder-dashboard-builders.d.ts +2 -0
  423. package/publications/report-builder-dashboard-builders.js +42 -0
  424. package/publications/report-builder-dashboard-builders.js.map +1 -0
  425. package/publications/report-builder-libraries.d.ts +2 -0
  426. package/publications/report-builder-libraries.js +90 -0
  427. package/publications/report-builder-libraries.js.map +1 -0
  428. package/publications/report-builder-reports.d.ts +2 -0
  429. package/publications/report-builder-reports.js +50 -0
  430. package/publications/report-builder-reports.js.map +1 -0
  431. package/publications/super-admin.d.ts +2 -0
  432. package/publications/super-admin.js +16 -0
  433. package/publications/super-admin.js.map +1 -0
  434. package/publications/user-groups.d.ts +1 -0
  435. package/publications/user-groups.js +16 -0
  436. package/publications/user-groups.js.map +1 -0
  437. package/publications/user-guides.d.ts +1 -0
  438. package/publications/user-guides.js +16 -0
  439. package/publications/user-guides.js.map +1 -0
  440. package/resolveio-server-app.d.ts +70 -0
  441. package/resolveio-server-app.js +801 -0
  442. package/resolveio-server-app.js.map +1 -0
  443. package/server-app.d.ts +228 -0
  444. package/server-app.js +3566 -0
  445. package/server-app.js.map +1 -0
  446. package/services/codex-client.d.ts +128 -0
  447. package/services/codex-client.js +1629 -0
  448. package/services/codex-client.js.map +1 -0
  449. package/services/openai-client.d.ts +46 -0
  450. package/services/openai-client.js +318 -0
  451. package/services/openai-client.js.map +1 -0
  452. package/types/error-report.d.ts +25 -0
  453. package/types/error-report.js +4 -0
  454. package/types/error-report.js.map +1 -0
  455. package/types/slow-query-report.d.ts +27 -0
  456. package/types/slow-query-report.js +6 -0
  457. package/types/slow-query-report.js.map +1 -0
  458. package/util/ai-qa-policy.d.ts +124 -0
  459. package/util/ai-qa-policy.js +736 -0
  460. package/util/ai-qa-policy.js.map +1 -0
  461. package/util/ai-run-evidence-adapters.d.ts +109 -0
  462. package/util/ai-run-evidence-adapters.js +7234 -0
  463. package/util/ai-run-evidence-adapters.js.map +1 -0
  464. package/util/ai-run-evidence-dashboard.d.ts +88 -0
  465. package/util/ai-run-evidence-dashboard.js +343 -0
  466. package/util/ai-run-evidence-dashboard.js.map +1 -0
  467. package/util/ai-run-evidence-eval.d.ts +86 -0
  468. package/util/ai-run-evidence-eval.js +1018 -0
  469. package/util/ai-run-evidence-eval.js.map +1 -0
  470. package/util/ai-run-evidence.d.ts +244 -0
  471. package/util/ai-run-evidence.js +1096 -0
  472. package/util/ai-run-evidence.js.map +1 -0
  473. package/util/ai-runner-artifacts.d.ts +82 -0
  474. package/util/ai-runner-artifacts.js +713 -0
  475. package/util/ai-runner-artifacts.js.map +1 -0
  476. package/util/ai-runner-manager-autopilot.d.ts +210 -0
  477. package/util/ai-runner-manager-autopilot.js +642 -0
  478. package/util/ai-runner-manager-autopilot.js.map +1 -0
  479. package/util/ai-runner-manager-policy.d.ts +807 -0
  480. package/util/ai-runner-manager-policy.js +3501 -0
  481. package/util/ai-runner-manager-policy.js.map +1 -0
  482. package/util/ai-runner-qa-auth.d.ts +5 -0
  483. package/util/ai-runner-qa-auth.js +839 -0
  484. package/util/ai-runner-qa-auth.js.map +1 -0
  485. package/util/ai-runner-qa-tools.d.ts +26 -0
  486. package/util/ai-runner-qa-tools.js +3520 -0
  487. package/util/ai-runner-qa-tools.js.map +1 -0
  488. package/util/aicoder-runner-v6.d.ts +426 -0
  489. package/util/aicoder-runner-v6.js +2464 -0
  490. package/util/aicoder-runner-v6.js.map +1 -0
  491. package/util/common.d.ts +31 -0
  492. package/util/common.js +683 -0
  493. package/util/common.js.map +1 -0
  494. package/util/customer-portal-password.d.ts +13 -0
  495. package/util/customer-portal-password.js +209 -0
  496. package/util/customer-portal-password.js.map +1 -0
  497. package/util/error-reporter.d.ts +52 -0
  498. package/util/error-reporter.js +326 -0
  499. package/util/error-reporter.js.map +1 -0
  500. package/util/error-tracking.d.ts +13 -0
  501. package/util/error-tracking.js +120 -0
  502. package/util/error-tracking.js.map +1 -0
  503. package/util/openai-usage-cost.d.ts +6 -0
  504. package/util/openai-usage-cost.js +103 -0
  505. package/util/openai-usage-cost.js.map +1 -0
  506. package/util/report-builder-unwinds.d.ts +15 -0
  507. package/util/report-builder-unwinds.js +156 -0
  508. package/util/report-builder-unwinds.js.map +1 -0
  509. package/util/runner-process-janitor.d.ts +27 -0
  510. package/util/runner-process-janitor.js +208 -0
  511. package/util/runner-process-janitor.js.map +1 -0
  512. package/util/schema-report-builder.d.ts +6 -0
  513. package/util/schema-report-builder.js +481 -0
  514. package/util/schema-report-builder.js.map +1 -0
  515. package/util/slow-query-reporter.d.ts +28 -0
  516. package/util/slow-query-reporter.js +226 -0
  517. package/util/slow-query-reporter.js.map +1 -0
  518. package/util/subscription-dependency-context.d.ts +34 -0
  519. package/util/subscription-dependency-context.js +1283 -0
  520. package/util/subscription-dependency-context.js.map +1 -0
  521. package/util/support-runner-v5.d.ts +1426 -0
  522. package/util/support-runner-v5.js +7647 -0
  523. package/util/support-runner-v5.js.map +1 -0
  524. package/util/tokenizer.d.ts +5 -0
  525. package/util/tokenizer.js +41 -0
  526. package/util/tokenizer.js.map +1 -0
  527. package/workers/codex-runner.worker.d.ts +1 -0
  528. package/workers/codex-runner.worker.js +192 -0
  529. package/workers/codex-runner.worker.js.map +1 -0
  530. package/.nodemon.json +0 -5
  531. package/.vscode/settings.json +0 -21
  532. package/AGENTS.md +0 -195
  533. package/README.md +0 -22
  534. package/build_package.sh +0 -5
  535. package/compileDTS.pl +0 -64
  536. package/docs/ai-assistant-nightly-eval.md +0 -65
  537. package/docs/ai-assistant-preflight-checklist.md +0 -23
  538. package/docs/ai-assistant-report-builder-bridge-playbook.md +0 -115
  539. package/eslint-plugin-custom/index.js +0 -7
  540. package/eslint-plugin-custom/rules/no-filter-zero-index.js +0 -44
  541. package/eslint.config.js +0 -103
  542. package/gulpfile.js +0 -216
  543. package/methodAndPublicationListGenerator.py +0 -375
  544. package/mongodbensurers.js +0 -2
  545. package/mongostop.js +0 -3
  546. package/scripts/cleanup-bypassed-callmethod-logs.js +0 -616
  547. package/settings.development.json +0 -25
  548. package/settings.development.redacted.json +0 -25
  549. package/src/.env +0 -12
  550. package/src/ai/assistant-core-heuristics.ts +0 -379
  551. package/src/ai/resolveio-platform-intelligence-memory-corpus.ts +0 -185
  552. package/src/ai/resolveio-platform-intelligence-memory.ts +0 -325
  553. package/src/ai/resolveio-platform-intelligence.ts +0 -462
  554. package/src/client-server-app.ts +0 -12
  555. package/src/collections/ai-run.collection.ts +0 -117
  556. package/src/collections/ai-terminal-conversation.collection.ts +0 -91
  557. package/src/collections/ai-terminal-issue-report.collection.ts +0 -99
  558. package/src/collections/ai-terminal-message.collection.ts +0 -77
  559. package/src/collections/app-setting.collection.ts +0 -104
  560. package/src/collections/app-status.collection.ts +0 -58
  561. package/src/collections/communication-metric.collection.ts +0 -84
  562. package/src/collections/counter.collection.ts +0 -56
  563. package/src/collections/cron-job-history.collection.ts +0 -94
  564. package/src/collections/cron-job.collection.ts +0 -92
  565. package/src/collections/customer-notification.collection.ts +0 -131
  566. package/src/collections/customer-portal-password.collection.ts +0 -76
  567. package/src/collections/email-history.collection.ts +0 -134
  568. package/src/collections/email-verified.collection.ts +0 -62
  569. package/src/collections/file.collection.ts +0 -74
  570. package/src/collections/flag-update.collection.ts +0 -57
  571. package/src/collections/flag.collection.ts +0 -57
  572. package/src/collections/log-method-latency.collection.ts +0 -77
  573. package/src/collections/log-subscription.collection.ts +0 -80
  574. package/src/collections/log.collection.ts +0 -93
  575. package/src/collections/logged-in-users.collection.ts +0 -67
  576. package/src/collections/monitor-cpu.collection.ts +0 -65
  577. package/src/collections/monitor-function.collection.ts +0 -74
  578. package/src/collections/monitor-memory.collection.ts +0 -77
  579. package/src/collections/monitor-mongo.collection.ts +0 -71
  580. package/src/collections/notification.collection.ts +0 -57
  581. package/src/collections/openai-usage-ledger.collection.ts +0 -131
  582. package/src/collections/report-builder-dashboard-builder.collection.ts +0 -109
  583. package/src/collections/report-builder-library.collection.ts +0 -89
  584. package/src/collections/report-builder-report.collection.ts +0 -184
  585. package/src/collections/user-group.collection.ts +0 -89
  586. package/src/collections/user-guide.collection.ts +0 -57
  587. package/src/collections/user.collection.ts +0 -181
  588. package/src/cron/cron.ts +0 -117
  589. package/src/fixtures/cron-jobs.ts +0 -95
  590. package/src/fixtures/init.ts +0 -35
  591. package/src/http/auth.ts +0 -818
  592. package/src/http/health.ts +0 -7
  593. package/src/http/home.ts +0 -90
  594. package/src/http/slow-query-publication.ts +0 -49
  595. package/src/index.ts +0 -1
  596. package/src/managers/ai-assistant-codex-manager.manager.ts +0 -1131
  597. package/src/managers/ai-run-evidence.manager.ts +0 -264
  598. package/src/managers/communication-metric.manager.ts +0 -82
  599. package/src/managers/cron.manager.ts +0 -333
  600. package/src/managers/customer-notification-content.manager.ts +0 -236
  601. package/src/managers/diagnostic-manager-bootstrap.ts +0 -165
  602. package/src/managers/error-auto-fix.manager.ts +0 -2767
  603. package/src/managers/local-log.manager.ts +0 -113
  604. package/src/managers/method.manager.ts +0 -1857
  605. package/src/managers/mongo.manager.ts +0 -4575
  606. package/src/managers/monitor.manager.ts +0 -507
  607. package/src/managers/openai-usage-ledger.manager.ts +0 -112
  608. package/src/managers/slow-query-verifier.manager.ts +0 -3590
  609. package/src/managers/slow-query.manager.ts +0 -519
  610. package/src/managers/subscription.manager.ts +0 -3128
  611. package/src/managers/websocket.manager.ts +0 -746
  612. package/src/managers/worker-dispatcher.manager.ts +0 -1360
  613. package/src/managers/worker-server.manager.ts +0 -536
  614. package/src/methods/accounts.ts +0 -532
  615. package/src/methods/ai-terminal.ts +0 -29070
  616. package/src/methods/app-settings.ts +0 -114
  617. package/src/methods/aws.ts +0 -649
  618. package/src/methods/collections.ts +0 -641
  619. package/src/methods/counters.ts +0 -69
  620. package/src/methods/cron-jobs.ts +0 -2614
  621. package/src/methods/customer-notifications.ts +0 -458
  622. package/src/methods/diagnostics.ts +0 -616
  623. package/src/methods/flag-updates.ts +0 -7
  624. package/src/methods/flags.ts +0 -7
  625. package/src/methods/logs.ts +0 -657
  626. package/src/methods/mongo-explorer.ts +0 -1880
  627. package/src/methods/monitor.ts +0 -540
  628. package/src/methods/pdf.ts +0 -1236
  629. package/src/methods/publications.ts +0 -129
  630. package/src/methods/report-builder.ts +0 -3300
  631. package/src/methods/support.ts +0 -335
  632. package/src/models/ai-run.model.ts +0 -27
  633. package/src/models/ai-terminal-conversation.model.ts +0 -19
  634. package/src/models/ai-terminal-issue-report.model.ts +0 -21
  635. package/src/models/ai-terminal-message.model.ts +0 -24
  636. package/src/models/app-setting.model.ts +0 -17
  637. package/src/models/collection-document.model.ts +0 -24
  638. package/src/models/communication-metric.model.ts +0 -23
  639. package/src/models/cron-job-history.model.ts +0 -16
  640. package/src/models/cron-job.model.ts +0 -15
  641. package/src/models/customer-notification.model.ts +0 -28
  642. package/src/models/customer-portal-password.model.ts +0 -12
  643. package/src/models/dialog.model.ts +0 -25
  644. package/src/models/log-method-latency.model.ts +0 -11
  645. package/src/models/log.model.ts +0 -19
  646. package/src/models/method.model.ts +0 -25
  647. package/src/models/monitor-function.model.ts +0 -16
  648. package/src/models/monitor-memory.model.ts +0 -17
  649. package/src/models/monitor-mongo.model.ts +0 -15
  650. package/src/models/openai-usage-ledger.model.ts +0 -56
  651. package/src/models/pagination.model.ts +0 -35
  652. package/src/models/permission.model.ts +0 -14
  653. package/src/models/report-builder-dashboard-builder.model.ts +0 -29
  654. package/src/models/report-builder-library.model.ts +0 -20
  655. package/src/models/report-builder-report.model.ts +0 -136
  656. package/src/models/report-builder.model.ts +0 -68
  657. package/src/models/select-data-label.model.ts +0 -9
  658. package/src/models/server-message.model.ts +0 -31
  659. package/src/models/slow-query-report.model.ts +0 -23
  660. package/src/models/subscription.model.ts +0 -73
  661. package/src/models/support-ticket.model.ts +0 -104
  662. package/src/models/user-group.model.ts +0 -24
  663. package/src/models/user.model.ts +0 -96
  664. package/src/private/images/ResolveIO.png +0 -0
  665. package/src/publications/ai-terminal.ts +0 -73
  666. package/src/publications/app-settings.ts +0 -25
  667. package/src/publications/app-status.ts +0 -13
  668. package/src/publications/cron-jobs.ts +0 -40
  669. package/src/publications/customer-notifications.ts +0 -101
  670. package/src/publications/files.ts +0 -33
  671. package/src/publications/flags-update.ts +0 -19
  672. package/src/publications/flags.ts +0 -19
  673. package/src/publications/logs.ts +0 -163
  674. package/src/publications/notifications.ts +0 -13
  675. package/src/publications/report-builder-dashboard-builders.ts +0 -39
  676. package/src/publications/report-builder-libraries.ts +0 -41
  677. package/src/publications/report-builder-reports.ts +0 -47
  678. package/src/publications/super-admin.ts +0 -13
  679. package/src/publications/user-groups.ts +0 -12
  680. package/src/publications/user-guides.ts +0 -12
  681. package/src/resolveio-server-app.ts +0 -617
  682. package/src/server-app.ts +0 -3354
  683. package/src/services/codex-client.ts +0 -1231
  684. package/src/services/openai-client.ts +0 -265
  685. package/src/types/error-report.ts +0 -26
  686. package/src/types/js-tiktoken.d.ts +0 -11
  687. package/src/types/slow-query-report.ts +0 -28
  688. package/src/util/ai-qa-policy.ts +0 -925
  689. package/src/util/ai-run-evidence-adapters.ts +0 -8347
  690. package/src/util/ai-run-evidence-dashboard.ts +0 -323
  691. package/src/util/ai-run-evidence-eval.ts +0 -1057
  692. package/src/util/ai-run-evidence.ts +0 -1430
  693. package/src/util/ai-runner-artifacts.ts +0 -586
  694. package/src/util/ai-runner-manager-autopilot.ts +0 -961
  695. package/src/util/ai-runner-manager-policy.ts +0 -5011
  696. package/src/util/ai-runner-qa-auth.ts +0 -838
  697. package/src/util/ai-runner-qa-tools.ts +0 -3536
  698. package/src/util/aicoder-runner-v6.ts +0 -3121
  699. package/src/util/common.ts +0 -649
  700. package/src/util/customer-portal-password.ts +0 -183
  701. package/src/util/error-reporter.ts +0 -332
  702. package/src/util/error-tracking.ts +0 -79
  703. package/src/util/openai-usage-cost.ts +0 -114
  704. package/src/util/report-builder-unwinds.ts +0 -180
  705. package/src/util/runner-process-janitor.ts +0 -219
  706. package/src/util/schema-report-builder.ts +0 -448
  707. package/src/util/slow-query-reporter.ts +0 -216
  708. package/src/util/subscription-dependency-context.ts +0 -1096
  709. package/src/util/support-runner-v5.ts +0 -10040
  710. package/src/util/tokenizer.ts +0 -38
  711. package/src/workers/codex-runner.worker.ts +0 -142
  712. package/start_server.sh +0 -5
  713. package/tests/ai-assistant-corpus-build.ts +0 -484
  714. package/tests/ai-assistant-corpus-replay-e2e.ts +0 -774
  715. package/tests/ai-assistant-data-parity-e2e.ts +0 -1989
  716. package/tests/ai-assistant-eval-triage.ts +0 -831
  717. package/tests/ai-assistant-openai-e2e.ts +0 -1061
  718. package/tests/ai-assistant-openai-git-e2e.ts +0 -155
  719. package/tests/ai-assistant-preflight-matrix.ts +0 -215
  720. package/tests/ai-assistant-routing-eval.test.ts +0 -585
  721. package/tests/ai-assistant-snf-live-eval.ts +0 -975
  722. package/tests/ai-assistant-utils.test.ts +0 -4834
  723. package/tests/ai-manager-autopilot-snapshot.test.ts +0 -193
  724. package/tests/ai-manager-recovery-checkpoint.test.ts +0 -1383
  725. package/tests/ai-run-eval.test.ts +0 -132
  726. package/tests/ai-run-evidence.test.ts +0 -3773
  727. package/tests/ai-runner-contract.test.ts +0 -515
  728. package/tests/aicoder-runner-v6.test.ts +0 -822
  729. package/tests/error-reporter.test.ts +0 -145
  730. package/tests/method-publication-generator.test.ts +0 -46
  731. package/tests/report-builder-linking.test.ts +0 -79
  732. package/tests/resolveio-platform-intelligence.test.ts +0 -352
  733. package/tests/server-app-cron-owner.test.ts +0 -127
  734. package/tests/subscription-connect-race.test.ts +0 -158
  735. package/tests/subscription-dependency-context.test.ts +0 -324
  736. package/tests/subscription-manager-collection-tracking.test.ts +0 -86
  737. package/tests/subscription-manager-invalidation.test.ts +0 -86
  738. package/tests/support-runner-v5.test.ts +0 -3201
  739. package/tsconfig.json +0 -34
  740. /package/{src/private → private}/email-templates/enrollment.html +0 -0
  741. /package/{src/private → private}/email-templates/forgot-password.html +0 -0
  742. /package/{src/private → private}/email-templates/support-ticket-deleted.html +0 -0
  743. /package/{src/private → private}/email-templates/support-ticket-modified.html +0 -0
  744. /package/{src/private → private}/email-templates/support-ticket.html +0 -0
  745. /package/{src/public_api.ts → public_api.d.ts} +0 -0
@@ -0,0 +1,1808 @@
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 __values = (this && this.__values) || function(o) {
66
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
67
+ if (m) return m.call(o);
68
+ if (o && typeof o.length === "number") return {
69
+ next: function () {
70
+ if (o && i >= o.length) o = void 0;
71
+ return { value: o && o[i++], done: !o };
72
+ }
73
+ };
74
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
75
+ };
76
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
77
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
78
+ if (ar || !(i in from)) {
79
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
80
+ ar[i] = from[i];
81
+ }
82
+ }
83
+ return to.concat(ar || Array.prototype.slice.call(from));
84
+ };
85
+ Object.defineProperty(exports, "__esModule", { value: true });
86
+ exports.loadMongoExplorerMethods = loadMongoExplorerMethods;
87
+ var simpl_schema_1 = require("simpl-schema");
88
+ var user_collection_1 = require("../collections/user.collection");
89
+ var openai_usage_ledger_manager_1 = require("../managers/openai-usage-ledger.manager");
90
+ var resolveio_server_app_1 = require("../resolveio-server-app");
91
+ var codex_client_1 = require("../services/codex-client");
92
+ var common_1 = require("../util/common");
93
+ var tokenizer_1 = require("../util/tokenizer");
94
+ var DEFAULT_LIMIT = 100;
95
+ var MAX_LIMIT = 2000;
96
+ var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
97
+ var MAX_REVIEW_STRING_LENGTH = 500;
98
+ var MAX_REVIEW_ARRAY_ITEMS = 10;
99
+ var MAX_REVIEW_OBJECT_KEYS = 40;
100
+ var MAX_REVIEW_DEPTH = 4;
101
+ var MAX_REVIEW_LIST_ITEMS = 6;
102
+ var MAX_REVIEW_CHANGED_FIELDS = 60;
103
+ var DEFAULT_RISK_REVIEW_TIMEOUT_MS = 30000;
104
+ var DEFAULT_RISK_REVIEW_MAX_TOKENS = 700;
105
+ var SENSITIVE_REVIEW_FIELD_REGEX = /(password|secret|token|api[_-]?key|salt|hash|email|phone|address|ssn|services|roles)/i;
106
+ var DEFAULT_AI_SUGGEST_TIMEOUT_MS = 60000;
107
+ var DEFAULT_AI_SUGGEST_MAX_TOKENS = 1000;
108
+ var MAX_AI_SUGGEST_FIELDS = 700;
109
+ var MAX_AI_SUGGEST_COLLECTIONS = 800;
110
+ var MAX_AI_SUGGEST_RESULTS = 500;
111
+ var RESTRICTED_AGGREGATE_STAGES = new Set(['$out', '$merge']);
112
+ function parseMongoExplorerWriteUsers() {
113
+ var raw = typeof process.env.MONGO_EXPLORER_WRITE_USERS === 'string' ? process.env.MONGO_EXPLORER_WRITE_USERS.trim() : '';
114
+ if (!raw) {
115
+ return [];
116
+ }
117
+ try {
118
+ var parsed = JSON.parse(raw);
119
+ if (Array.isArray(parsed)) {
120
+ return parsed.map(function (value) { return String(value); }).filter(function (value) { return value.trim().length; });
121
+ }
122
+ if (typeof parsed === 'string') {
123
+ return [parsed.trim()].filter(Boolean);
124
+ }
125
+ }
126
+ catch (_a) {
127
+ // Fall back to comma-separated list.
128
+ }
129
+ return raw
130
+ .split(',')
131
+ .map(function (value) { return value.trim(); })
132
+ .filter(Boolean);
133
+ }
134
+ function normalizeExplorerMode(mode) {
135
+ var normalizedMode = String(mode || '').trim().toLowerCase();
136
+ if (normalizedMode === 'resolveio') {
137
+ return 'resolveio';
138
+ }
139
+ return 'aicoder';
140
+ }
141
+ function allowUnschemaizedWrites() {
142
+ return process.env.MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE === 'true';
143
+ }
144
+ function resolveDatabaseName(database) {
145
+ var _a, _b;
146
+ var defaultDb = ((_a = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _a === void 0 ? void 0 : _a.DATABASE) || '';
147
+ var dbName = typeof database === 'string' && database.trim().length ? database.trim() : defaultDb;
148
+ if (!dbName) {
149
+ throw new Error('Mongo Explorer: Database is required');
150
+ }
151
+ var allowedDatabases = ((_b = resolveio_server_app_1.ResolveIOServer.getMongoManager()) === null || _b === void 0 ? void 0 : _b.getWatchedDatabases()) || [];
152
+ if (allowedDatabases.length && !allowedDatabases.includes(dbName)) {
153
+ throw new Error('Mongo Explorer: Database access denied');
154
+ }
155
+ return dbName;
156
+ }
157
+ function resolveDatabase(database) {
158
+ var dbName = resolveDatabaseName(database);
159
+ return resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
160
+ }
161
+ function resolveCollectionHandle(database, collection) {
162
+ var _a, _b;
163
+ var mainDb = ((_a = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _a === void 0 ? void 0 : _a.DATABASE) || '';
164
+ var isMainDb = database === mainDb;
165
+ var managerCollection = isMainDb ? (_b = resolveio_server_app_1.ResolveIOServer.getMongoManager()) === null || _b === void 0 ? void 0 : _b.collection(collection) : null;
166
+ var db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(database);
167
+ return {
168
+ managerCollection: managerCollection,
169
+ dbCollection: db.collection(collection)
170
+ };
171
+ }
172
+ function getSchemaDefinition(collectionRef) {
173
+ if (!collectionRef || !collectionRef.simplschema || typeof collectionRef.simplschema.schema !== 'function') {
174
+ return {};
175
+ }
176
+ var schema = collectionRef.simplschema.schema();
177
+ return schema && typeof schema === 'object' ? schema : {};
178
+ }
179
+ function getSchemaTypeName(definition) {
180
+ var _a, _b;
181
+ var typeDefs = (_a = definition === null || definition === void 0 ? void 0 : definition.type) === null || _a === void 0 ? void 0 : _a.definitions;
182
+ if (!Array.isArray(typeDefs) || !typeDefs.length) {
183
+ return 'Any';
184
+ }
185
+ var firstType = (_b = typeDefs[0]) === null || _b === void 0 ? void 0 : _b.type;
186
+ if (!firstType) {
187
+ return 'Any';
188
+ }
189
+ if (firstType === String) {
190
+ return 'String';
191
+ }
192
+ if (firstType === Number) {
193
+ return 'Number';
194
+ }
195
+ if (firstType === Boolean) {
196
+ return 'Boolean';
197
+ }
198
+ if (firstType === Date) {
199
+ return 'Date';
200
+ }
201
+ if (firstType === Object) {
202
+ return 'Object';
203
+ }
204
+ if (firstType === Array) {
205
+ return 'Array';
206
+ }
207
+ var typeName = firstType.name || String(firstType);
208
+ if (typeName === 'Integer') {
209
+ return 'Number';
210
+ }
211
+ return typeName;
212
+ }
213
+ function toLabel(path) {
214
+ var last = path.split('.').pop() || path;
215
+ return last
216
+ .replace(/\$/g, '')
217
+ .replace(/_/g, ' ')
218
+ .replace(/\s+/g, ' ')
219
+ .trim();
220
+ }
221
+ function isProtectedFieldSegment(segment) {
222
+ if (!segment) {
223
+ return false;
224
+ }
225
+ if (segment === '_id') {
226
+ return true;
227
+ }
228
+ var normalizedSegment = segment.replace(/\[\d+\]/g, '');
229
+ return normalizedSegment.toLowerCase().startsWith('id_');
230
+ }
231
+ function isProtectedFieldPath(path) {
232
+ var segments = String(path || '').split('.').filter(Boolean);
233
+ return segments.some(function (segment) { return isProtectedFieldSegment(segment); });
234
+ }
235
+ function safeStringify(value) {
236
+ try {
237
+ return JSON.stringify(value);
238
+ }
239
+ catch (_a) {
240
+ return String(value);
241
+ }
242
+ }
243
+ function collectProtectedFieldPaths(value, prefix, out) {
244
+ if (prefix === void 0) { prefix = ''; }
245
+ if (out === void 0) { out = {}; }
246
+ if (Array.isArray(value)) {
247
+ value.forEach(function (item, index) {
248
+ var nextPrefix = prefix ? "".concat(prefix, "[").concat(index, "]") : "[".concat(index, "]");
249
+ collectProtectedFieldPaths(item, nextPrefix, out);
250
+ });
251
+ return out;
252
+ }
253
+ if (!value || typeof value !== 'object') {
254
+ return out;
255
+ }
256
+ Object.keys(value).forEach(function (key) {
257
+ var nextPrefix = prefix ? "".concat(prefix, ".").concat(key) : key;
258
+ if (isProtectedFieldSegment(key)) {
259
+ out[nextPrefix] = value[key];
260
+ }
261
+ collectProtectedFieldPaths(value[key], nextPrefix, out);
262
+ });
263
+ return out;
264
+ }
265
+ function ensureProtectedFieldsUnchanged(originalDoc, updatedDoc) {
266
+ var originalProtected = collectProtectedFieldPaths(originalDoc || {});
267
+ var updatedProtected = collectProtectedFieldPaths(updatedDoc || {});
268
+ var violations = [];
269
+ Object.keys(originalProtected).forEach(function (path) {
270
+ if (!Object.prototype.hasOwnProperty.call(updatedProtected, path)) {
271
+ violations.push(path);
272
+ return;
273
+ }
274
+ var originalValue = safeStringify(originalProtected[path]);
275
+ var updatedValue = safeStringify(updatedProtected[path]);
276
+ if (originalValue !== updatedValue) {
277
+ violations.push(path);
278
+ }
279
+ });
280
+ Object.keys(updatedProtected).forEach(function (path) {
281
+ if (!Object.prototype.hasOwnProperty.call(originalProtected, path)) {
282
+ violations.push(path);
283
+ }
284
+ });
285
+ if (violations.length) {
286
+ var preview = violations.slice(0, 4).join(', ');
287
+ throw new Error("Mongo Explorer: Protected fields cannot be edited (".concat(preview).concat(violations.length > 4 ? ', ...' : '', ")"));
288
+ }
289
+ }
290
+ function coerceDateValue(value) {
291
+ if (value instanceof Date) {
292
+ return value;
293
+ }
294
+ if (typeof value !== 'string' || !ISO_DATE_REGEX.test(value)) {
295
+ return value;
296
+ }
297
+ var parsed = new Date(value);
298
+ return Number.isNaN(parsed.getTime()) ? value : parsed;
299
+ }
300
+ function coerceDatePath(target, segments) {
301
+ if (!target || !segments.length) {
302
+ return;
303
+ }
304
+ var _a = __read(segments), segment = _a[0], rest = _a.slice(1);
305
+ if (segment === '$') {
306
+ if (Array.isArray(target)) {
307
+ target.forEach(function (item) { return coerceDatePath(item, rest); });
308
+ }
309
+ return;
310
+ }
311
+ if (!Object.prototype.hasOwnProperty.call(target, segment)) {
312
+ return;
313
+ }
314
+ if (rest.length === 0) {
315
+ var updatedValue = coerceDateValue(target[segment]);
316
+ if (updatedValue !== target[segment]) {
317
+ target[segment] = updatedValue;
318
+ }
319
+ return;
320
+ }
321
+ coerceDatePath(target[segment], rest);
322
+ }
323
+ function coerceDateFields(collectionRef, doc) {
324
+ if (!collectionRef || !collectionRef.simplschema || !doc) {
325
+ return;
326
+ }
327
+ var schema = getSchemaDefinition(collectionRef);
328
+ Object.keys(schema).forEach(function (schemaKey) {
329
+ var _a;
330
+ var definition = schema[schemaKey];
331
+ var typeDefs = (_a = definition === null || definition === void 0 ? void 0 : definition.type) === null || _a === void 0 ? void 0 : _a.definitions;
332
+ if (!Array.isArray(typeDefs) || !typeDefs.some(function (typeDef) { return typeDef.type === Date; })) {
333
+ return;
334
+ }
335
+ coerceDatePath(doc, schemaKey.split('.'));
336
+ });
337
+ }
338
+ function normalizeFindOptions(options) {
339
+ var normalized = options || {};
340
+ var projection = normalized.projection && Object.keys(normalized.projection).length ? normalized.projection : undefined;
341
+ var sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
342
+ var limit = typeof normalized.limit === 'number' ? Math.min(Math.max(normalized.limit, 0), MAX_LIMIT) : DEFAULT_LIMIT;
343
+ var skip = typeof normalized.skip === 'number' ? Math.max(normalized.skip, 0) : 0;
344
+ return {
345
+ findOptions: {
346
+ projection: projection,
347
+ sort: sort,
348
+ limit: limit,
349
+ skip: skip
350
+ },
351
+ includeTotal: normalized.includeTotal === true
352
+ };
353
+ }
354
+ function userHasView(user, view) {
355
+ var _a, _b, _c;
356
+ if (!user || !view) {
357
+ return false;
358
+ }
359
+ if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
360
+ return true;
361
+ }
362
+ var groups = Array.isArray((_b = user.roles) === null || _b === void 0 ? void 0 : _b.groups) ? user.roles.groups : [];
363
+ var miscs = Array.isArray((_c = user.roles) === null || _c === void 0 ? void 0 : _c.miscs) ? user.roles.miscs : [];
364
+ if (groups.some(function (group) { return Array.isArray(group.views) && group.views.some(function (v) { return v.startsWith(view); }); })) {
365
+ return true;
366
+ }
367
+ if (miscs.some(function (v) { return v.startsWith(view); })) {
368
+ return true;
369
+ }
370
+ if (groups.some(function (group) { return group.name === view; })) {
371
+ return true;
372
+ }
373
+ return false;
374
+ }
375
+ function ensureWriteAccess(context, permissionView, mode) {
376
+ return __awaiter(this, void 0, void 0, function () {
377
+ var idUser, user, normalizedMode, allowedUsers, username_1, email_1, id_1, isAllowed, normalizedPermission;
378
+ var _a;
379
+ return __generator(this, function (_b) {
380
+ switch (_b.label) {
381
+ case 0:
382
+ idUser = context === null || context === void 0 ? void 0 : context.id_user;
383
+ if (!idUser) {
384
+ throw new Error('Mongo Explorer: Unauthorized');
385
+ }
386
+ return [4 /*yield*/, user_collection_1.Users.findOne({ _id: idUser })];
387
+ case 1:
388
+ user = _b.sent();
389
+ if (!user) {
390
+ throw new Error('Mongo Explorer: Unauthorized');
391
+ }
392
+ if (user.readonly) {
393
+ throw new Error('Mongo Explorer: Readonly user');
394
+ }
395
+ normalizedMode = normalizeExplorerMode(mode);
396
+ if (normalizedMode === 'resolveio') {
397
+ throw new Error('Mongo Explorer: ResolveIO mode is read only');
398
+ }
399
+ allowedUsers = parseMongoExplorerWriteUsers();
400
+ if (allowedUsers.length) {
401
+ username_1 = String(user.username || '').trim().toLowerCase();
402
+ email_1 = String(user.email || '').trim().toLowerCase();
403
+ id_1 = String(user._id || '').trim();
404
+ isAllowed = allowedUsers.some(function (entry) {
405
+ var normalized = String(entry || '').trim().toLowerCase();
406
+ if (!normalized) {
407
+ return false;
408
+ }
409
+ return normalized === username_1 || (email_1 && normalized === email_1) || (id_1 && entry === id_1);
410
+ });
411
+ if (!isAllowed) {
412
+ throw new Error('Mongo Explorer: Write access denied');
413
+ }
414
+ }
415
+ if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
416
+ return [2 /*return*/];
417
+ }
418
+ normalizedPermission = typeof permissionView === 'string' ? permissionView.trim() : '';
419
+ if (!normalizedPermission) {
420
+ return [2 /*return*/];
421
+ }
422
+ if (userHasView(user, normalizedPermission)) {
423
+ return [2 /*return*/];
424
+ }
425
+ throw new Error('Mongo Explorer: Write access denied');
426
+ }
427
+ });
428
+ });
429
+ }
430
+ function buildDeleteSafetyCollections(collectionRef) {
431
+ var schema = getSchemaDefinition(collectionRef);
432
+ return Object.keys(schema).filter(function (path) { return isProtectedFieldPath(path) && path !== '_id'; });
433
+ }
434
+ function buildDeleteImpact(database, sourceCollection, docId) {
435
+ return __awaiter(this, void 0, void 0, function () {
436
+ var mainDb, mongoManager, collections, impacts, unresolved, collections_1, collections_1_1, collectionRef, collectionName, referencePaths, query, docs, _a, e_1_1;
437
+ var e_1, _b;
438
+ var _c;
439
+ return __generator(this, function (_d) {
440
+ switch (_d.label) {
441
+ case 0:
442
+ mainDb = ((_c = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _c === void 0 ? void 0 : _c.DATABASE) || '';
443
+ if (database !== mainDb) {
444
+ return [2 /*return*/, {
445
+ has_references: false,
446
+ unresolved: true,
447
+ collections: []
448
+ }];
449
+ }
450
+ mongoManager = resolveio_server_app_1.ResolveIOServer.getMongoManager();
451
+ collections = (mongoManager === null || mongoManager === void 0 ? void 0 : mongoManager.collections) ? mongoManager.collections() : [];
452
+ impacts = [];
453
+ unresolved = false;
454
+ _d.label = 1;
455
+ case 1:
456
+ _d.trys.push([1, 8, 9, 10]);
457
+ collections_1 = __values(collections), collections_1_1 = collections_1.next();
458
+ _d.label = 2;
459
+ case 2:
460
+ if (!!collections_1_1.done) return [3 /*break*/, 7];
461
+ collectionRef = collections_1_1.value;
462
+ collectionName = collectionRef === null || collectionRef === void 0 ? void 0 : collectionRef.collectionName;
463
+ if (!collectionName) {
464
+ return [3 /*break*/, 6];
465
+ }
466
+ if (collectionName === "".concat(sourceCollection, ".versions")) {
467
+ return [3 /*break*/, 6];
468
+ }
469
+ referencePaths = buildDeleteSafetyCollections(collectionRef);
470
+ if (!referencePaths.length) {
471
+ return [3 /*break*/, 6];
472
+ }
473
+ query = {
474
+ $or: referencePaths.map(function (path) {
475
+ var _a;
476
+ return (_a = {}, _a[path] = docId, _a);
477
+ })
478
+ };
479
+ _d.label = 3;
480
+ case 3:
481
+ _d.trys.push([3, 5, , 6]);
482
+ return [4 /*yield*/, collectionRef.find(query, { projection: { _id: 1 }, limit: 3 })];
483
+ case 4:
484
+ docs = _d.sent();
485
+ if (Array.isArray(docs) && docs.length) {
486
+ impacts.push({
487
+ collection: collectionName,
488
+ references: docs.length,
489
+ sample_ids: docs.map(function (doc) { return String((doc === null || doc === void 0 ? void 0 : doc._id) || ''); }).filter(Boolean)
490
+ });
491
+ }
492
+ return [3 /*break*/, 6];
493
+ case 5:
494
+ _a = _d.sent();
495
+ unresolved = true;
496
+ return [3 /*break*/, 6];
497
+ case 6:
498
+ collections_1_1 = collections_1.next();
499
+ return [3 /*break*/, 2];
500
+ case 7: return [3 /*break*/, 10];
501
+ case 8:
502
+ e_1_1 = _d.sent();
503
+ e_1 = { error: e_1_1 };
504
+ return [3 /*break*/, 10];
505
+ case 9:
506
+ try {
507
+ if (collections_1_1 && !collections_1_1.done && (_b = collections_1.return)) _b.call(collections_1);
508
+ }
509
+ finally { if (e_1) throw e_1.error; }
510
+ return [7 /*endfinally*/];
511
+ case 10: return [2 /*return*/, {
512
+ has_references: impacts.length > 0,
513
+ unresolved: unresolved,
514
+ collections: impacts.sort(function (a, b) { return a.collection.localeCompare(b.collection); })
515
+ }];
516
+ }
517
+ });
518
+ });
519
+ }
520
+ function normalizeOptionalString(value) {
521
+ if (typeof value === 'string') {
522
+ var trimmed = value.trim();
523
+ return trimmed.length ? trimmed : undefined;
524
+ }
525
+ if (value === null || value === undefined) {
526
+ return undefined;
527
+ }
528
+ var normalized = String(value).trim();
529
+ return normalized.length ? normalized : undefined;
530
+ }
531
+ function normalizePositiveNumber(value, fallback) {
532
+ var parsed = Number(value);
533
+ if (!Number.isFinite(parsed) || parsed <= 0) {
534
+ return fallback;
535
+ }
536
+ return parsed;
537
+ }
538
+ function parseBooleanValue(value, fallback) {
539
+ if (typeof value === 'boolean') {
540
+ return value;
541
+ }
542
+ var normalized = String(value || '').trim().toLowerCase();
543
+ if (!normalized.length) {
544
+ return fallback;
545
+ }
546
+ if (['1', 'true', 'yes', 'on'].includes(normalized)) {
547
+ return true;
548
+ }
549
+ if (['0', 'false', 'no', 'off'].includes(normalized)) {
550
+ return false;
551
+ }
552
+ return fallback;
553
+ }
554
+ function truncateForRiskReview(value, maxLength) {
555
+ if (maxLength === void 0) { maxLength = MAX_REVIEW_STRING_LENGTH; }
556
+ var normalized = String(value || '');
557
+ if (normalized.length <= maxLength) {
558
+ return normalized;
559
+ }
560
+ var diff = normalized.length - maxLength;
561
+ return "".concat(normalized.slice(0, maxLength), "...[+").concat(diff, " chars]");
562
+ }
563
+ function sanitizeForRiskReview(value, depth) {
564
+ if (depth === void 0) { depth = 0; }
565
+ if (value === null || value === undefined) {
566
+ return value;
567
+ }
568
+ if (depth > MAX_REVIEW_DEPTH) {
569
+ return '[Truncated depth]';
570
+ }
571
+ if (value instanceof Date) {
572
+ return value.toISOString();
573
+ }
574
+ if (typeof value === 'string') {
575
+ return truncateForRiskReview(value);
576
+ }
577
+ if (typeof value === 'number' || typeof value === 'boolean') {
578
+ return value;
579
+ }
580
+ if (Array.isArray(value)) {
581
+ var sanitized = value
582
+ .slice(0, MAX_REVIEW_ARRAY_ITEMS)
583
+ .map(function (item) { return sanitizeForRiskReview(item, depth + 1); });
584
+ if (value.length > MAX_REVIEW_ARRAY_ITEMS) {
585
+ sanitized.push("[".concat(value.length - MAX_REVIEW_ARRAY_ITEMS, " more item(s)]"));
586
+ }
587
+ return sanitized;
588
+ }
589
+ if (typeof value === 'object') {
590
+ var output_1 = {};
591
+ var keys = Object.keys(value);
592
+ var limitedKeys = keys.slice(0, MAX_REVIEW_OBJECT_KEYS);
593
+ limitedKeys.forEach(function (key) {
594
+ if (SENSITIVE_REVIEW_FIELD_REGEX.test(key)) {
595
+ output_1[key] = '[REDACTED]';
596
+ return;
597
+ }
598
+ output_1[key] = sanitizeForRiskReview(value[key], depth + 1);
599
+ });
600
+ if (keys.length > MAX_REVIEW_OBJECT_KEYS) {
601
+ output_1.__truncated_keys = keys.length - MAX_REVIEW_OBJECT_KEYS;
602
+ }
603
+ return output_1;
604
+ }
605
+ return truncateForRiskReview(String(value));
606
+ }
607
+ function pickChangedFields(beforeDocument, afterDocument) {
608
+ var e_2, _a;
609
+ if (!beforeDocument || typeof beforeDocument !== 'object' || !afterDocument || typeof afterDocument !== 'object') {
610
+ return [];
611
+ }
612
+ var changed = [];
613
+ var fieldNames = new Set(__spreadArray(__spreadArray([], __read(Object.keys(beforeDocument)), false), __read(Object.keys(afterDocument)), false));
614
+ try {
615
+ for (var fieldNames_1 = __values(fieldNames), fieldNames_1_1 = fieldNames_1.next(); !fieldNames_1_1.done; fieldNames_1_1 = fieldNames_1.next()) {
616
+ var field = fieldNames_1_1.value;
617
+ if (changed.length >= MAX_REVIEW_CHANGED_FIELDS) {
618
+ break;
619
+ }
620
+ var beforeValue = safeStringify(beforeDocument[field]);
621
+ var afterValue = safeStringify(afterDocument[field]);
622
+ if (beforeValue !== afterValue) {
623
+ changed.push(field);
624
+ }
625
+ }
626
+ }
627
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
628
+ finally {
629
+ try {
630
+ if (fieldNames_1_1 && !fieldNames_1_1.done && (_a = fieldNames_1.return)) _a.call(fieldNames_1);
631
+ }
632
+ finally { if (e_2) throw e_2.error; }
633
+ }
634
+ return changed;
635
+ }
636
+ function normalizeRiskLevel(value) {
637
+ var normalized = String(value || '').trim().toLowerCase();
638
+ if (normalized === 'low') {
639
+ return 'low';
640
+ }
641
+ if (normalized === 'medium') {
642
+ return 'medium';
643
+ }
644
+ if (normalized === 'high') {
645
+ return 'high';
646
+ }
647
+ if (normalized === 'critical') {
648
+ return 'critical';
649
+ }
650
+ return 'high';
651
+ }
652
+ function normalizeRiskList(value) {
653
+ if (!Array.isArray(value)) {
654
+ return [];
655
+ }
656
+ return value
657
+ .map(function (item) { return normalizeOptionalString(item); })
658
+ .filter(function (item) { return !!item; })
659
+ .slice(0, MAX_REVIEW_LIST_ITEMS)
660
+ .map(function (item) { return truncateForRiskReview(item, 220); });
661
+ }
662
+ function buildFallbackRiskReview(operation, summary, model) {
663
+ if (model === void 0) { model = ''; }
664
+ return {
665
+ operation: operation,
666
+ risk_level: 'high',
667
+ should_block: true,
668
+ summary: truncateForRiskReview(summary, 220),
669
+ reasons: [
670
+ 'AI review could not produce a reliable result.',
671
+ 'Proceed only with explicit approval and manual dependency checks.'
672
+ ],
673
+ suggested_checks: [
674
+ 'Confirm related records and id_* references before writing.',
675
+ 'Validate that schema-required fields and date values remain valid.'
676
+ ],
677
+ confidence: 0,
678
+ model: model || '',
679
+ request_id: '',
680
+ review_status: 'fallback',
681
+ reviewed_at: new Date().toISOString()
682
+ };
683
+ }
684
+ function buildDisabledRiskReview(operation) {
685
+ return {
686
+ operation: operation,
687
+ risk_level: 'low',
688
+ should_block: false,
689
+ summary: 'AI risk review is disabled by configuration.',
690
+ reasons: [],
691
+ suggested_checks: [],
692
+ confidence: 1,
693
+ model: '',
694
+ request_id: '',
695
+ review_status: 'disabled',
696
+ reviewed_at: new Date().toISOString()
697
+ };
698
+ }
699
+ function parseRiskReviewPayload(content) {
700
+ var normalized = String(content || '').trim();
701
+ if (!normalized.length) {
702
+ return {};
703
+ }
704
+ try {
705
+ return JSON.parse(normalized);
706
+ }
707
+ catch (_a) {
708
+ // Fall through and try to parse a JSON object embedded in plain text.
709
+ }
710
+ var start = normalized.indexOf('{');
711
+ var end = normalized.lastIndexOf('}');
712
+ if (start !== -1 && end > start) {
713
+ var candidate = normalized.slice(start, end + 1);
714
+ try {
715
+ return JSON.parse(candidate);
716
+ }
717
+ catch (_b) {
718
+ return {};
719
+ }
720
+ }
721
+ return {};
722
+ }
723
+ function normalizeRiskReview(operation, payload, model, requestId) {
724
+ var riskLevel = normalizeRiskLevel(payload === null || payload === void 0 ? void 0 : payload.risk_level);
725
+ var normalizedConfidence = Number(payload === null || payload === void 0 ? void 0 : payload.confidence);
726
+ var confidence = Number.isFinite(normalizedConfidence)
727
+ ? Math.max(0, Math.min(1, normalizedConfidence))
728
+ : 0.6;
729
+ var summary = normalizeOptionalString(payload === null || payload === void 0 ? void 0 : payload.summary)
730
+ || "AI review marked this operation as ".concat(riskLevel, " risk.");
731
+ var reasons = normalizeRiskList(payload === null || payload === void 0 ? void 0 : payload.reasons);
732
+ var suggestedChecks = normalizeRiskList(payload === null || payload === void 0 ? void 0 : payload.suggested_checks);
733
+ var shouldBlock = (payload === null || payload === void 0 ? void 0 : payload.should_block) === true || riskLevel === 'critical';
734
+ return {
735
+ operation: operation,
736
+ risk_level: riskLevel,
737
+ should_block: !!shouldBlock,
738
+ summary: truncateForRiskReview(summary, 220),
739
+ reasons: reasons,
740
+ suggested_checks: suggestedChecks,
741
+ confidence: confidence,
742
+ model: model || '',
743
+ request_id: requestId || '',
744
+ review_status: 'ok',
745
+ reviewed_at: new Date().toISOString()
746
+ };
747
+ }
748
+ function resolveRiskReviewSettings() {
749
+ var _a, _b, _c, _d, _e;
750
+ var serverConfig = resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
751
+ var enabled = parseBooleanValue((_a = serverConfig['MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW']) !== null && _a !== void 0 ? _a : process.env.MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW, true);
752
+ var model = normalizeOptionalString(serverConfig['MONGO_EXPLORER_RISK_REVIEW_MODEL']
753
+ || process.env.MONGO_EXPLORER_RISK_REVIEW_MODEL
754
+ || serverConfig['AI_ASSISTANT_CODEX_MODEL']
755
+ || process.env.AI_ASSISTANT_CODEX_MODEL
756
+ || serverConfig['AI_DASHBOARD_CODEX_MODEL']
757
+ || process.env.AI_DASHBOARD_CODEX_MODEL);
758
+ var fallbackModel = normalizeOptionalString(serverConfig['MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL']
759
+ || process.env.MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL
760
+ || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
761
+ || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL
762
+ || serverConfig['AI_DASHBOARD_CODEX_FALLBACK_MODEL']
763
+ || process.env.AI_DASHBOARD_CODEX_FALLBACK_MODEL);
764
+ var timeoutMs = normalizePositiveNumber((_b = serverConfig['MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS']) !== null && _b !== void 0 ? _b : process.env.MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS, DEFAULT_RISK_REVIEW_TIMEOUT_MS);
765
+ var maxTokens = normalizePositiveNumber((_c = serverConfig['MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS']) !== null && _c !== void 0 ? _c : process.env.MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS, DEFAULT_RISK_REVIEW_MAX_TOKENS);
766
+ var maxRetries = normalizePositiveNumber((_d = serverConfig['OPENAI_MAX_RETRIES']) !== null && _d !== void 0 ? _d : process.env.OPENAI_MAX_RETRIES, 1);
767
+ var retryDelayMs = normalizePositiveNumber((_e = serverConfig['OPENAI_RETRY_DELAY_MS']) !== null && _e !== void 0 ? _e : process.env.OPENAI_RETRY_DELAY_MS, 750);
768
+ var apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
769
+ var baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
770
+ return {
771
+ enabled: enabled,
772
+ apiKey: apiKey,
773
+ baseUrl: baseUrl,
774
+ model: model,
775
+ fallbackModel: fallbackModel,
776
+ timeoutMs: timeoutMs,
777
+ maxTokens: maxTokens,
778
+ maxRetries: maxRetries,
779
+ retryDelayMs: retryDelayMs
780
+ };
781
+ }
782
+ function buildCodexPrompt(systemPrompt, userPrompt) {
783
+ return "System:\n".concat(systemPrompt, "\n\nUser:\n").concat(userPrompt).trim();
784
+ }
785
+ function buildCodexClient(settings) {
786
+ var fallbackModels = [];
787
+ var fallback = normalizeOptionalString(settings.fallbackModel);
788
+ if (fallback && fallback !== settings.model) {
789
+ fallbackModels.push(fallback);
790
+ }
791
+ return new codex_client_1.CodexClient(__assign(__assign(__assign({ apiKey: settings.apiKey, baseUrl: settings.baseUrl }, (settings.model ? { model: settings.model } : {})), (fallbackModels.length ? { fallbackModel: fallbackModels[0], fallbackModels: fallbackModels } : {})), { maxRetries: (0, common_1.round)(settings.maxRetries || 0), retryDelayMs: (0, common_1.round)(settings.retryDelayMs || 0) }));
792
+ }
793
+ function estimateCodexUsage(messages, responseText, model) {
794
+ var inputTokens = (0, tokenizer_1.countChatTokens)(messages, model);
795
+ var outputTokens = (0, tokenizer_1.countTokens)(responseText || '', model);
796
+ return {
797
+ inputTokens: inputTokens,
798
+ outputTokens: outputTokens,
799
+ totalTokens: inputTokens + outputTokens
800
+ };
801
+ }
802
+ function buildRiskReviewPrompt(input) {
803
+ var payload = {
804
+ database: input.database,
805
+ collection: input.collection,
806
+ operation: input.operation,
807
+ mode: input.mode,
808
+ changed_fields: pickChangedFields(input.before_document, input.after_document),
809
+ delete_impact: sanitizeForRiskReview(input.delete_impact || null),
810
+ before_document: sanitizeForRiskReview(input.before_document || null),
811
+ after_document: sanitizeForRiskReview(input.after_document || null)
812
+ };
813
+ return [
814
+ 'Review this MongoDB write operation for runtime and data integrity risk.',
815
+ 'Focus on foreign-key style id_* dependencies, schema compatibility, destructive impact, and financial/operational record safety.',
816
+ 'Return JSON only.',
817
+ JSON.stringify(payload, null, 2)
818
+ ].join('\n');
819
+ }
820
+ function reviewOperationRisk(input) {
821
+ return __awaiter(this, void 0, void 0, function () {
822
+ var settings, client, systemPrompt, userPrompt, prompt, responseText, payload, err_1, detail;
823
+ return __generator(this, function (_a) {
824
+ switch (_a.label) {
825
+ case 0:
826
+ settings = resolveRiskReviewSettings();
827
+ if (!settings.enabled) {
828
+ return [2 /*return*/, buildDisabledRiskReview(input.operation)];
829
+ }
830
+ if (!settings.apiKey) {
831
+ return [2 /*return*/, buildFallbackRiskReview(input.operation, 'AI risk review unavailable: AI API key is missing.')];
832
+ }
833
+ client = buildCodexClient(settings);
834
+ systemPrompt = [
835
+ 'You are a MongoDB operation safety reviewer for a production SaaS application.',
836
+ 'Respond with a single JSON object only.',
837
+ 'Required keys:',
838
+ 'risk_level ("low" | "medium" | "high" | "critical"),',
839
+ 'should_block (boolean),',
840
+ 'summary (string),',
841
+ 'reasons (string[]),',
842
+ 'suggested_checks (string[]),',
843
+ 'confidence (number between 0 and 1).',
844
+ 'Keep summary concise (<= 220 chars).'
845
+ ].join(' ');
846
+ userPrompt = buildRiskReviewPrompt(input);
847
+ prompt = buildCodexPrompt(systemPrompt, userPrompt);
848
+ _a.label = 1;
849
+ case 1:
850
+ _a.trys.push([1, 3, , 4]);
851
+ return [4 /*yield*/, client.run(prompt, {
852
+ timeoutMs: (0, common_1.round)(settings.timeoutMs),
853
+ threadOptions: {
854
+ model: settings.model,
855
+ sandboxMode: 'read-only',
856
+ skipGitRepoCheck: true,
857
+ networkAccessEnabled: false,
858
+ webSearchMode: 'disabled',
859
+ webSearchEnabled: false,
860
+ approvalPolicy: 'never'
861
+ }
862
+ })];
863
+ case 2:
864
+ responseText = _a.sent();
865
+ payload = parseRiskReviewPayload(responseText);
866
+ return [2 /*return*/, normalizeRiskReview(input.operation, payload, settings.model, '')];
867
+ case 3:
868
+ err_1 = _a.sent();
869
+ detail = (err_1 === null || err_1 === void 0 ? void 0 : err_1.message) ? String(err_1.message) : 'Unknown AI review error';
870
+ return [2 /*return*/, buildFallbackRiskReview(input.operation, "AI risk review failed: ".concat(truncateForRiskReview(detail, 160)), settings.model)];
871
+ case 4: return [2 /*return*/];
872
+ }
873
+ });
874
+ });
875
+ }
876
+ function normalizeAiAction(value) {
877
+ var normalized = normalizeOptionalString(value) || '';
878
+ return normalized.toLowerCase() === 'aggregate' ? 'aggregate' : 'find';
879
+ }
880
+ function sanitizeAiCollections(raw) {
881
+ var values = [];
882
+ var seen = new Set();
883
+ (raw || []).forEach(function (entry) {
884
+ var normalized = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.collection) || (entry === null || entry === void 0 ? void 0 : entry.name) || entry);
885
+ if (!normalized) {
886
+ return;
887
+ }
888
+ var key = normalized.toLowerCase();
889
+ if (seen.has(key)) {
890
+ return;
891
+ }
892
+ seen.add(key);
893
+ values.push(normalized);
894
+ });
895
+ return values.slice(0, MAX_AI_SUGGEST_COLLECTIONS);
896
+ }
897
+ function sanitizeAiFields(raw, fallbackCollection) {
898
+ var fields = [];
899
+ var seen = new Set();
900
+ (raw || []).forEach(function (entry) {
901
+ var path = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.path) || (entry === null || entry === void 0 ? void 0 : entry.field_path) || (entry === null || entry === void 0 ? void 0 : entry.fieldPath));
902
+ if (!path) {
903
+ return;
904
+ }
905
+ var collection = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.collection) || (entry === null || entry === void 0 ? void 0 : entry.collection_name) || (entry === null || entry === void 0 ? void 0 : entry.collectionName)) || fallbackCollection || '';
906
+ var key = "".concat(collection.toLowerCase(), "::").concat(path.toLowerCase());
907
+ if (seen.has(key)) {
908
+ return;
909
+ }
910
+ seen.add(key);
911
+ fields.push({
912
+ path: path,
913
+ label: normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.label) || (entry === null || entry === void 0 ? void 0 : entry.field_path_name) || (entry === null || entry === void 0 ? void 0 : entry.fieldPathName)) || path,
914
+ type: normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.type) || (entry === null || entry === void 0 ? void 0 : entry.field_type) || (entry === null || entry === void 0 ? void 0 : entry.fieldType)) || 'Any',
915
+ collection: collection
916
+ });
917
+ });
918
+ return fields.slice(0, MAX_AI_SUGGEST_FIELDS);
919
+ }
920
+ function deriveAiFieldsFromCollection(database, collection) {
921
+ if (!collection) {
922
+ return [];
923
+ }
924
+ var managerCollection = resolveCollectionHandle(database, collection).managerCollection;
925
+ if (!managerCollection) {
926
+ return [];
927
+ }
928
+ var schema = getSchemaDefinition(managerCollection);
929
+ return Object.keys(schema)
930
+ .sort(function (a, b) { return a.localeCompare(b); })
931
+ .slice(0, MAX_AI_SUGGEST_FIELDS)
932
+ .map(function (path) {
933
+ var definition = schema[path];
934
+ return {
935
+ path: path,
936
+ label: toLabel(path),
937
+ type: getSchemaTypeName(definition),
938
+ collection: collection
939
+ };
940
+ });
941
+ }
942
+ function resolveCollectionFromList(value, collections, fallback) {
943
+ if (fallback === void 0) { fallback = ''; }
944
+ var normalized = normalizeOptionalString(value);
945
+ if (normalized) {
946
+ var matched = (collections || []).find(function (entry) { return entry.toLowerCase() === normalized.toLowerCase(); });
947
+ if (matched) {
948
+ return matched;
949
+ }
950
+ }
951
+ if (fallback) {
952
+ return fallback;
953
+ }
954
+ return (collections === null || collections === void 0 ? void 0 : collections[0]) || '';
955
+ }
956
+ function normalizeAiResultLimit(value, fallback) {
957
+ if (fallback === void 0) { fallback = 100; }
958
+ var fallbackValue = Math.min(Math.max(fallback, 1), MAX_AI_SUGGEST_RESULTS);
959
+ var parsed = Number(value);
960
+ if (!Number.isFinite(parsed) || parsed <= 0) {
961
+ return fallbackValue;
962
+ }
963
+ return Math.min(Math.max((0, common_1.round)(parsed), 1), MAX_AI_SUGGEST_RESULTS);
964
+ }
965
+ function normalizeAiSkip(value) {
966
+ var parsed = Number(value);
967
+ if (!Number.isFinite(parsed) || parsed < 0) {
968
+ return 0;
969
+ }
970
+ return Math.max(0, (0, common_1.round)(parsed));
971
+ }
972
+ function normalizeAiObject(value) {
973
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
974
+ return {};
975
+ }
976
+ return value;
977
+ }
978
+ function hasObjectKeys(value) {
979
+ return !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
980
+ }
981
+ function parseAiPlanPayload(content) {
982
+ var normalized = String(content || '').trim();
983
+ if (!normalized.length) {
984
+ return {};
985
+ }
986
+ try {
987
+ return JSON.parse(normalized);
988
+ }
989
+ catch (_a) {
990
+ // Fall through and parse embedded JSON object.
991
+ }
992
+ var start = normalized.indexOf('{');
993
+ var end = normalized.lastIndexOf('}');
994
+ if (start !== -1 && end > start) {
995
+ try {
996
+ return JSON.parse(normalized.slice(start, end + 1));
997
+ }
998
+ catch (_b) {
999
+ return {};
1000
+ }
1001
+ }
1002
+ return {};
1003
+ }
1004
+ function resolveMongoExplorerAiSettings() {
1005
+ var _a, _b, _c, _d;
1006
+ var serverConfig = resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
1007
+ var apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
1008
+ var baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
1009
+ var model = normalizeOptionalString(serverConfig['MONGO_EXPLORER_AI_MODEL']
1010
+ || process.env.MONGO_EXPLORER_AI_MODEL
1011
+ || serverConfig['AI_ASSISTANT_CODEX_MODEL']
1012
+ || process.env.AI_ASSISTANT_CODEX_MODEL);
1013
+ var fallbackModel = normalizeOptionalString(serverConfig['MONGO_EXPLORER_AI_FALLBACK_MODEL']
1014
+ || process.env.MONGO_EXPLORER_AI_FALLBACK_MODEL
1015
+ || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
1016
+ || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL);
1017
+ var timeoutMs = normalizePositiveNumber((_a = serverConfig['MONGO_EXPLORER_AI_TIMEOUT_MS']) !== null && _a !== void 0 ? _a : process.env.MONGO_EXPLORER_AI_TIMEOUT_MS, DEFAULT_AI_SUGGEST_TIMEOUT_MS);
1018
+ var maxTokens = normalizePositiveNumber((_b = serverConfig['MONGO_EXPLORER_AI_MAX_TOKENS']) !== null && _b !== void 0 ? _b : process.env.MONGO_EXPLORER_AI_MAX_TOKENS, DEFAULT_AI_SUGGEST_MAX_TOKENS);
1019
+ var maxRetries = normalizePositiveNumber((_c = serverConfig['OPENAI_MAX_RETRIES']) !== null && _c !== void 0 ? _c : process.env.OPENAI_MAX_RETRIES, 1);
1020
+ var retryDelayMs = normalizePositiveNumber((_d = serverConfig['OPENAI_RETRY_DELAY_MS']) !== null && _d !== void 0 ? _d : process.env.OPENAI_RETRY_DELAY_MS, 750);
1021
+ return {
1022
+ apiKey: apiKey,
1023
+ baseUrl: baseUrl,
1024
+ model: model,
1025
+ fallbackModel: fallbackModel,
1026
+ timeoutMs: timeoutMs,
1027
+ maxTokens: maxTokens,
1028
+ maxRetries: maxRetries,
1029
+ retryDelayMs: retryDelayMs
1030
+ };
1031
+ }
1032
+ function buildMongoExplorerAiSystemPrompt() {
1033
+ return [
1034
+ 'You are a MongoDB query planner for a read-only Mongo Explorer UI.',
1035
+ 'Return a single JSON object and nothing else.',
1036
+ 'Supported schema:',
1037
+ '{',
1038
+ ' "action": "find|aggregate",',
1039
+ ' "collection": "string",',
1040
+ ' "query": { ... },',
1041
+ ' "pipeline": [{ ... }],',
1042
+ ' "options": {',
1043
+ ' "projection": { "field": 1 },',
1044
+ ' "sort": { "field": -1 },',
1045
+ ' "limit": 100,',
1046
+ ' "skip": 0,',
1047
+ ' "includeTotal": true,',
1048
+ ' "allowDiskUse": true',
1049
+ ' },',
1050
+ ' "notes": "short summary"',
1051
+ '}',
1052
+ 'Rules:',
1053
+ '- Use only provided collection names and field paths.',
1054
+ '- Read-only only. Never output write operations, update/delete commands, or aggregation stages $out/$merge.',
1055
+ '- Prefer action=find for direct lookups and simple filters.',
1056
+ '- Use action=aggregate for grouped totals, rankings, or trend buckets.',
1057
+ '- Keep options.limit between 1 and 500.',
1058
+ '- If request is ambiguous, use selected_collection and a conservative limit.'
1059
+ ].join('\n');
1060
+ }
1061
+ function buildMongoExplorerAiUserPrompt(input) {
1062
+ var payload = {
1063
+ request: input.prompt,
1064
+ selected_collection: input.selectedCollection || '',
1065
+ max_results: input.maxResults,
1066
+ available_collections: input.availableCollections || [],
1067
+ available_fields: input.availableFields || []
1068
+ };
1069
+ return JSON.stringify(payload);
1070
+ }
1071
+ function sanitizeAggregatePipeline(rawPipeline, limit) {
1072
+ var source = Array.isArray(rawPipeline) ? rawPipeline : [];
1073
+ var sanitized = [];
1074
+ var removedRestricted = false;
1075
+ source.forEach(function (stage) {
1076
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
1077
+ return;
1078
+ }
1079
+ var keys = Object.keys(stage);
1080
+ if (!keys.length) {
1081
+ return;
1082
+ }
1083
+ var stageName = keys[0];
1084
+ if (RESTRICTED_AGGREGATE_STAGES.has(String(stageName).toLowerCase())) {
1085
+ removedRestricted = true;
1086
+ return;
1087
+ }
1088
+ if (stageName === '$limit') {
1089
+ sanitized.push({ $limit: normalizeAiResultLimit(stage.$limit, limit) });
1090
+ return;
1091
+ }
1092
+ sanitized.push(stage);
1093
+ });
1094
+ if (!sanitized.some(function (stage) { return Object.keys(stage || {})[0] === '$limit'; })) {
1095
+ sanitized.push({ $limit: limit });
1096
+ }
1097
+ return {
1098
+ pipeline: sanitized,
1099
+ removedRestricted: removedRestricted
1100
+ };
1101
+ }
1102
+ function sanitizeFindOptions(raw, fallbackLimit) {
1103
+ var options = normalizeAiObject(raw);
1104
+ return {
1105
+ projection: hasObjectKeys(options.projection) ? options.projection : undefined,
1106
+ sort: hasObjectKeys(options.sort) ? options.sort : undefined,
1107
+ limit: normalizeAiResultLimit(options.limit, fallbackLimit),
1108
+ skip: normalizeAiSkip(options.skip),
1109
+ includeTotal: options.includeTotal === true
1110
+ };
1111
+ }
1112
+ function buildMongoExplorerAiNotes(rawNotes, action, collection, rowCount, total, removedRestricted) {
1113
+ var notes = [];
1114
+ var base = normalizeOptionalString(rawNotes);
1115
+ if (base) {
1116
+ notes.push(base);
1117
+ }
1118
+ var actionLabel = action === 'aggregate' ? 'aggregate pipeline' : 'query';
1119
+ if (typeof total === 'number' && total >= 0) {
1120
+ notes.push("Applied ".concat(actionLabel, " on ").concat(collection, ". Loaded ").concat(rowCount, " of ").concat(total, " rows."));
1121
+ }
1122
+ else {
1123
+ notes.push("Applied ".concat(actionLabel, " on ").concat(collection, ". Loaded ").concat(rowCount, " rows."));
1124
+ }
1125
+ if (removedRestricted) {
1126
+ notes.push('Removed restricted write stages from the generated pipeline.');
1127
+ }
1128
+ return notes.join(' ').trim();
1129
+ }
1130
+ function resolveUsageClientId(idClientInput, idUser) {
1131
+ return __awaiter(this, void 0, void 0, function () {
1132
+ var normalized, user, _a;
1133
+ var _b, _c;
1134
+ return __generator(this, function (_d) {
1135
+ switch (_d.label) {
1136
+ case 0:
1137
+ normalized = normalizeOptionalString(idClientInput);
1138
+ if (normalized) {
1139
+ return [2 /*return*/, normalized];
1140
+ }
1141
+ if (!idUser) {
1142
+ return [2 /*return*/, ''];
1143
+ }
1144
+ _d.label = 1;
1145
+ case 1:
1146
+ _d.trys.push([1, 3, , 4]);
1147
+ return [4 /*yield*/, user_collection_1.Users.findById(idUser)];
1148
+ case 2:
1149
+ user = _d.sent();
1150
+ return [2 /*return*/, normalizeOptionalString(((_b = user === null || user === void 0 ? void 0 : user.other) === null || _b === void 0 ? void 0 : _b.id_client) || ((_c = user === null || user === void 0 ? void 0 : user.other) === null || _c === void 0 ? void 0 : _c.idClient)) || ''];
1151
+ case 3:
1152
+ _a = _d.sent();
1153
+ return [2 /*return*/, ''];
1154
+ case 4: return [2 /*return*/];
1155
+ }
1156
+ });
1157
+ });
1158
+ }
1159
+ function executeMongoExplorerAi(payload, context) {
1160
+ return __awaiter(this, void 0, void 0, function () {
1161
+ var input, prompt, database, db, availableCollections, listed, selectedCollection, availableFields, settings, maxResults, client, messages, responseText, parsed, action, collection, plan, removedRestrictedStages, optionsRaw, aggregateLimit, pipelineResult, aggregateOptions, aggregateRows, rows, query, options, findOptions, rows, total, _a, usage, idClient;
1162
+ var _b;
1163
+ return __generator(this, function (_c) {
1164
+ switch (_c.label) {
1165
+ case 0:
1166
+ input = payload || {};
1167
+ prompt = normalizeOptionalString(input.prompt);
1168
+ if (!prompt) {
1169
+ throw new Error('Prompt is required.');
1170
+ }
1171
+ database = resolveDatabaseName(input.database);
1172
+ db = resolveDatabase(database);
1173
+ availableCollections = sanitizeAiCollections(input.available_collections || []);
1174
+ if (!!availableCollections.length) return [3 /*break*/, 2];
1175
+ return [4 /*yield*/, db.listCollections().toArray()];
1176
+ case 1:
1177
+ listed = _c.sent();
1178
+ availableCollections = listed
1179
+ .map(function (collection) { return normalizeOptionalString(collection === null || collection === void 0 ? void 0 : collection.name); })
1180
+ .filter(function (collection) { return !!collection; })
1181
+ .slice(0, MAX_AI_SUGGEST_COLLECTIONS);
1182
+ _c.label = 2;
1183
+ case 2:
1184
+ if (!availableCollections.length) {
1185
+ throw new Error('Mongo Explorer AI assistant: no collections available.');
1186
+ }
1187
+ selectedCollection = resolveCollectionFromList(input.selected_collection, availableCollections, availableCollections[0]);
1188
+ availableFields = sanitizeAiFields(input.available_fields || [], selectedCollection);
1189
+ if (!availableFields.length && selectedCollection) {
1190
+ availableFields = deriveAiFieldsFromCollection(database, selectedCollection);
1191
+ }
1192
+ settings = resolveMongoExplorerAiSettings();
1193
+ if (!settings.apiKey) {
1194
+ throw new Error('AI API key missing. Add an AI API key to server config.');
1195
+ }
1196
+ maxResults = normalizeAiResultLimit(input.max_results, 100);
1197
+ client = buildCodexClient(settings);
1198
+ messages = [
1199
+ { role: 'system', content: buildMongoExplorerAiSystemPrompt() },
1200
+ {
1201
+ role: 'user',
1202
+ content: buildMongoExplorerAiUserPrompt({
1203
+ prompt: prompt,
1204
+ selectedCollection: selectedCollection,
1205
+ availableCollections: availableCollections,
1206
+ availableFields: availableFields,
1207
+ maxResults: maxResults
1208
+ })
1209
+ }
1210
+ ];
1211
+ return [4 /*yield*/, client.run(buildCodexPrompt(messages[0].content, messages[1].content), {
1212
+ timeoutMs: (0, common_1.round)(settings.timeoutMs),
1213
+ threadOptions: {
1214
+ model: settings.model,
1215
+ sandboxMode: 'read-only',
1216
+ skipGitRepoCheck: true,
1217
+ networkAccessEnabled: false,
1218
+ webSearchMode: 'disabled',
1219
+ webSearchEnabled: false,
1220
+ approvalPolicy: 'never'
1221
+ }
1222
+ })];
1223
+ case 3:
1224
+ responseText = _c.sent();
1225
+ parsed = parseAiPlanPayload(responseText);
1226
+ action = normalizeAiAction((parsed === null || parsed === void 0 ? void 0 : parsed.action) || (Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.pipeline) ? 'aggregate' : 'find'));
1227
+ collection = resolveCollectionFromList((parsed === null || parsed === void 0 ? void 0 : parsed.collection) || (parsed === null || parsed === void 0 ? void 0 : parsed.collection_name), availableCollections, selectedCollection || availableCollections[0]);
1228
+ if (!collection) {
1229
+ throw new Error('Mongo Explorer AI assistant could not resolve a collection.');
1230
+ }
1231
+ plan = {
1232
+ action: action,
1233
+ collection: collection,
1234
+ options: {}
1235
+ };
1236
+ removedRestrictedStages = false;
1237
+ if (!(action === 'aggregate')) return [3 /*break*/, 5];
1238
+ optionsRaw = normalizeAiObject(parsed === null || parsed === void 0 ? void 0 : parsed.options);
1239
+ aggregateLimit = normalizeAiResultLimit((_b = optionsRaw.limit) !== null && _b !== void 0 ? _b : parsed === null || parsed === void 0 ? void 0 : parsed.limit, maxResults);
1240
+ pipelineResult = sanitizeAggregatePipeline(parsed === null || parsed === void 0 ? void 0 : parsed.pipeline, aggregateLimit);
1241
+ removedRestrictedStages = pipelineResult.removedRestricted;
1242
+ aggregateOptions = {
1243
+ allowDiskUse: optionsRaw.allowDiskUse === true
1244
+ };
1245
+ return [4 /*yield*/, db.collection(collection).aggregate(pipelineResult.pipeline, aggregateOptions).toArray()];
1246
+ case 4:
1247
+ aggregateRows = _c.sent();
1248
+ rows = (aggregateRows || []).slice(0, aggregateLimit);
1249
+ plan = {
1250
+ action: action,
1251
+ collection: collection,
1252
+ pipeline: pipelineResult.pipeline,
1253
+ options: {
1254
+ allowDiskUse: aggregateOptions.allowDiskUse,
1255
+ limit: aggregateLimit
1256
+ },
1257
+ documents: rows,
1258
+ total: null
1259
+ };
1260
+ return [3 /*break*/, 10];
1261
+ case 5:
1262
+ query = normalizeAiObject(parsed === null || parsed === void 0 ? void 0 : parsed.query);
1263
+ options = sanitizeFindOptions(parsed === null || parsed === void 0 ? void 0 : parsed.options, maxResults);
1264
+ findOptions = {
1265
+ limit: options.limit,
1266
+ skip: options.skip
1267
+ };
1268
+ if (options.projection) {
1269
+ findOptions.projection = options.projection;
1270
+ }
1271
+ if (options.sort) {
1272
+ findOptions.sort = options.sort;
1273
+ }
1274
+ return [4 /*yield*/, db.collection(collection).find(query, findOptions).toArray()];
1275
+ case 6:
1276
+ rows = _c.sent();
1277
+ if (!options.includeTotal) return [3 /*break*/, 8];
1278
+ return [4 /*yield*/, db.collection(collection).countDocuments(query)];
1279
+ case 7:
1280
+ _a = _c.sent();
1281
+ return [3 /*break*/, 9];
1282
+ case 8:
1283
+ _a = null;
1284
+ _c.label = 9;
1285
+ case 9:
1286
+ total = _a;
1287
+ plan = {
1288
+ action: action,
1289
+ collection: collection,
1290
+ query: query,
1291
+ options: __assign(__assign(__assign({}, (options.projection ? { projection: options.projection } : {})), (options.sort ? { sort: options.sort } : {})), { limit: options.limit, skip: options.skip, includeTotal: options.includeTotal }),
1292
+ documents: rows,
1293
+ total: total
1294
+ };
1295
+ _c.label = 10;
1296
+ case 10:
1297
+ plan.notes = buildMongoExplorerAiNotes(parsed === null || parsed === void 0 ? void 0 : parsed.notes, plan.action, plan.collection, Array.isArray(plan.documents) ? plan.documents.length : 0, typeof plan.total === 'number' ? plan.total : null, removedRestrictedStages);
1298
+ usage = estimateCodexUsage(messages, responseText, settings.model);
1299
+ return [4 /*yield*/, resolveUsageClientId(input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
1300
+ case 11:
1301
+ idClient = _c.sent();
1302
+ if (!usage.totalTokens) return [3 /*break*/, 13];
1303
+ return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
1304
+ id_client: idClient || '',
1305
+ model: settings.model || 'unknown',
1306
+ input_tokens: usage.inputTokens || 0,
1307
+ output_tokens: usage.outputTokens || 0,
1308
+ total_tokens: usage.totalTokens || 0,
1309
+ category: 'mongo-explorer-ai',
1310
+ id_request: ''
1311
+ })];
1312
+ case 12:
1313
+ _c.sent();
1314
+ _c.label = 13;
1315
+ case 13: return [2 /*return*/, {
1316
+ notes: plan.notes,
1317
+ plan: plan,
1318
+ model: settings.model,
1319
+ usage: {
1320
+ input_tokens: usage.inputTokens || 0,
1321
+ output_tokens: usage.outputTokens || 0,
1322
+ total_tokens: usage.totalTokens || 0
1323
+ }
1324
+ }];
1325
+ }
1326
+ });
1327
+ });
1328
+ }
1329
+ function loadMongoExplorerMethods(methodManager) {
1330
+ methodManager.methods({
1331
+ mongoExplorerAiSuggest: {
1332
+ check: new simpl_schema_1.default({
1333
+ payload: {
1334
+ type: Object,
1335
+ blackbox: true
1336
+ }
1337
+ }),
1338
+ function: function (payload) {
1339
+ return __awaiter(this, void 0, void 0, function () {
1340
+ return __generator(this, function (_a) {
1341
+ return [2 /*return*/, executeMongoExplorerAi(payload || {}, this)];
1342
+ });
1343
+ });
1344
+ }
1345
+ },
1346
+ mongoExplorerListCollections: {
1347
+ check: new simpl_schema_1.default({
1348
+ database: {
1349
+ type: String,
1350
+ optional: true
1351
+ }
1352
+ }),
1353
+ function: function (database) {
1354
+ return __awaiter(this, void 0, void 0, function () {
1355
+ var db, collections;
1356
+ return __generator(this, function (_a) {
1357
+ switch (_a.label) {
1358
+ case 0:
1359
+ db = resolveDatabase(database);
1360
+ return [4 /*yield*/, db.listCollections().toArray()];
1361
+ case 1:
1362
+ collections = _a.sent();
1363
+ return [2 /*return*/, collections
1364
+ .map(function (col) { return ({
1365
+ name: col.name,
1366
+ type: col.type || 'collection'
1367
+ }); })
1368
+ .sort(function (a, b) { return a.name.localeCompare(b.name); })];
1369
+ }
1370
+ });
1371
+ });
1372
+ }
1373
+ },
1374
+ mongoExplorerFind: {
1375
+ bypassSession: true,
1376
+ check: new simpl_schema_1.default({
1377
+ database: {
1378
+ type: String,
1379
+ optional: true
1380
+ },
1381
+ collection: {
1382
+ type: String
1383
+ },
1384
+ query: {
1385
+ type: Object,
1386
+ blackbox: true,
1387
+ optional: true
1388
+ },
1389
+ options: {
1390
+ type: Object,
1391
+ blackbox: true,
1392
+ optional: true
1393
+ }
1394
+ }),
1395
+ function: function (database_1, collection_1) {
1396
+ return __awaiter(this, arguments, void 0, function (database, collection, query, options) {
1397
+ var db, normalized, documents, total;
1398
+ if (query === void 0) { query = {}; }
1399
+ return __generator(this, function (_a) {
1400
+ switch (_a.label) {
1401
+ case 0:
1402
+ db = resolveDatabase(database);
1403
+ normalized = normalizeFindOptions(options);
1404
+ return [4 /*yield*/, db.collection(collection).find(query || {}, normalized.findOptions).toArray()];
1405
+ case 1:
1406
+ documents = _a.sent();
1407
+ total = null;
1408
+ if (!normalized.includeTotal) return [3 /*break*/, 3];
1409
+ return [4 /*yield*/, db.collection(collection).countDocuments(query || {})];
1410
+ case 2:
1411
+ total = _a.sent();
1412
+ _a.label = 3;
1413
+ case 3: return [2 /*return*/, {
1414
+ documents: documents,
1415
+ total: total
1416
+ }];
1417
+ }
1418
+ });
1419
+ });
1420
+ }
1421
+ },
1422
+ mongoExplorerGetCollectionSchema: {
1423
+ check: new simpl_schema_1.default({
1424
+ database: {
1425
+ type: String,
1426
+ optional: true
1427
+ },
1428
+ collection: {
1429
+ type: String
1430
+ }
1431
+ }),
1432
+ function: function (database, collection) {
1433
+ var dbName = resolveDatabaseName(database);
1434
+ var managerCollection = resolveCollectionHandle(dbName, collection).managerCollection;
1435
+ if (!managerCollection) {
1436
+ return Promise.resolve({
1437
+ collection: collection,
1438
+ has_schema: false,
1439
+ fields: []
1440
+ });
1441
+ }
1442
+ var schema = getSchemaDefinition(managerCollection);
1443
+ var fields = Object.keys(schema)
1444
+ .sort(function (a, b) { return a.localeCompare(b); })
1445
+ .map(function (path) {
1446
+ var definition = schema[path];
1447
+ return {
1448
+ path: path,
1449
+ label: toLabel(path),
1450
+ type: getSchemaTypeName(definition),
1451
+ optional: (definition === null || definition === void 0 ? void 0 : definition.optional) === true,
1452
+ protected: isProtectedFieldPath(path),
1453
+ depth: path.split('.').filter(function (segment) { return segment !== '$'; }).length - 1
1454
+ };
1455
+ });
1456
+ return Promise.resolve({
1457
+ collection: collection,
1458
+ has_schema: true,
1459
+ fields: fields
1460
+ });
1461
+ }
1462
+ },
1463
+ mongoExplorerAggregate: {
1464
+ bypassSession: true,
1465
+ check: new simpl_schema_1.default({
1466
+ database: {
1467
+ type: String,
1468
+ optional: true
1469
+ },
1470
+ collection: {
1471
+ type: String
1472
+ },
1473
+ pipeline: {
1474
+ type: Array
1475
+ },
1476
+ 'pipeline.$': {
1477
+ type: Object,
1478
+ blackbox: true
1479
+ },
1480
+ options: {
1481
+ type: Object,
1482
+ optional: true,
1483
+ blackbox: true
1484
+ }
1485
+ }),
1486
+ function: function (database_1, collection_1, pipeline_1) {
1487
+ return __awaiter(this, arguments, void 0, function (database, collection, pipeline, options) {
1488
+ var db;
1489
+ if (options === void 0) { options = {}; }
1490
+ return __generator(this, function (_a) {
1491
+ db = resolveDatabase(database);
1492
+ return [2 /*return*/, db.collection(collection).aggregate(pipeline || [], options || undefined).toArray()];
1493
+ });
1494
+ });
1495
+ }
1496
+ },
1497
+ mongoExplorerCommand: {
1498
+ check: new simpl_schema_1.default({
1499
+ database: {
1500
+ type: String,
1501
+ optional: true
1502
+ },
1503
+ command: {
1504
+ type: Object,
1505
+ blackbox: true
1506
+ },
1507
+ permissionView: {
1508
+ type: String,
1509
+ optional: true
1510
+ },
1511
+ mode: {
1512
+ type: String,
1513
+ optional: true
1514
+ }
1515
+ }),
1516
+ function: function (database, command, permissionView, mode) {
1517
+ return __awaiter(this, void 0, void 0, function () {
1518
+ var db;
1519
+ return __generator(this, function (_a) {
1520
+ switch (_a.label) {
1521
+ case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1522
+ case 1:
1523
+ _a.sent();
1524
+ db = resolveDatabase(database);
1525
+ return [2 /*return*/, db.command(command)];
1526
+ }
1527
+ });
1528
+ });
1529
+ }
1530
+ },
1531
+ mongoExplorerInsertDocument: {
1532
+ check: new simpl_schema_1.default({
1533
+ database: {
1534
+ type: String,
1535
+ optional: true
1536
+ },
1537
+ collection: {
1538
+ type: String
1539
+ },
1540
+ document: {
1541
+ type: Object,
1542
+ blackbox: true
1543
+ },
1544
+ permissionView: {
1545
+ type: String,
1546
+ optional: true
1547
+ },
1548
+ mode: {
1549
+ type: String,
1550
+ optional: true
1551
+ }
1552
+ }),
1553
+ function: function (database, collection, document, permissionView, mode) {
1554
+ return __awaiter(this, void 0, void 0, function () {
1555
+ var dbName, _a, managerCollection, dbCollection;
1556
+ return __generator(this, function (_b) {
1557
+ switch (_b.label) {
1558
+ case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1559
+ case 1:
1560
+ _b.sent();
1561
+ dbName = resolveDatabaseName(database);
1562
+ _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1563
+ if (!document || typeof document !== 'object') {
1564
+ throw new Error('Mongo Explorer: Document is required');
1565
+ }
1566
+ if (!managerCollection && !allowUnschemaizedWrites()) {
1567
+ throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1568
+ }
1569
+ if (!document._id) {
1570
+ document._id = (0, common_1.objectIdHexString)();
1571
+ }
1572
+ if (document.__v === undefined) {
1573
+ document.__v = 0;
1574
+ }
1575
+ if (!managerCollection) return [3 /*break*/, 3];
1576
+ coerceDateFields(managerCollection, document);
1577
+ return [4 /*yield*/, managerCollection.insertOne(document)];
1578
+ case 2:
1579
+ _b.sent();
1580
+ return [3 /*break*/, 5];
1581
+ case 3: return [4 /*yield*/, dbCollection.insertOne(document)];
1582
+ case 4:
1583
+ _b.sent();
1584
+ _b.label = 5;
1585
+ case 5: return [2 /*return*/, document._id];
1586
+ }
1587
+ });
1588
+ });
1589
+ }
1590
+ },
1591
+ mongoExplorerReplaceDocument: {
1592
+ check: new simpl_schema_1.default({
1593
+ database: {
1594
+ type: String,
1595
+ optional: true
1596
+ },
1597
+ collection: {
1598
+ type: String
1599
+ },
1600
+ document: {
1601
+ type: Object,
1602
+ blackbox: true
1603
+ },
1604
+ permissionView: {
1605
+ type: String,
1606
+ optional: true
1607
+ },
1608
+ mode: {
1609
+ type: String,
1610
+ optional: true
1611
+ }
1612
+ }),
1613
+ function: function (database, collection, document, permissionView, mode) {
1614
+ return __awaiter(this, void 0, void 0, function () {
1615
+ var dbName, _a, managerCollection, dbCollection, currentDoc, _b;
1616
+ return __generator(this, function (_c) {
1617
+ switch (_c.label) {
1618
+ case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1619
+ case 1:
1620
+ _c.sent();
1621
+ dbName = resolveDatabaseName(database);
1622
+ _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1623
+ if (!document || typeof document !== 'object' || !document._id) {
1624
+ throw new Error('Mongo Explorer: Document with _id is required');
1625
+ }
1626
+ if (!managerCollection) return [3 /*break*/, 3];
1627
+ return [4 /*yield*/, managerCollection.findOne({ _id: document._id })];
1628
+ case 2:
1629
+ _b = _c.sent();
1630
+ return [3 /*break*/, 5];
1631
+ case 3: return [4 /*yield*/, dbCollection.findOne({ _id: document._id })];
1632
+ case 4:
1633
+ _b = _c.sent();
1634
+ _c.label = 5;
1635
+ case 5:
1636
+ currentDoc = _b;
1637
+ if (!currentDoc) {
1638
+ throw new Error('Mongo Explorer: Document not found');
1639
+ }
1640
+ ensureProtectedFieldsUnchanged(currentDoc, document);
1641
+ if (!managerCollection && !allowUnschemaizedWrites()) {
1642
+ throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1643
+ }
1644
+ if (!managerCollection) return [3 /*break*/, 7];
1645
+ coerceDateFields(managerCollection, document);
1646
+ return [4 /*yield*/, managerCollection.replaceOne({ _id: document._id }, document)];
1647
+ case 6:
1648
+ _c.sent();
1649
+ return [3 /*break*/, 9];
1650
+ case 7: return [4 /*yield*/, dbCollection.replaceOne({ _id: document._id }, document)];
1651
+ case 8:
1652
+ _c.sent();
1653
+ _c.label = 9;
1654
+ case 9: return [2 /*return*/, true];
1655
+ }
1656
+ });
1657
+ });
1658
+ }
1659
+ },
1660
+ mongoExplorerReviewOperationRisk: {
1661
+ check: new simpl_schema_1.default({
1662
+ database: {
1663
+ type: String,
1664
+ optional: true
1665
+ },
1666
+ collection: {
1667
+ type: String
1668
+ },
1669
+ operation: {
1670
+ type: String,
1671
+ allowedValues: ['insert', 'replace', 'delete', 'command']
1672
+ },
1673
+ before_document: {
1674
+ type: Object,
1675
+ blackbox: true,
1676
+ optional: true
1677
+ },
1678
+ after_document: {
1679
+ type: Object,
1680
+ blackbox: true,
1681
+ optional: true
1682
+ },
1683
+ delete_impact: {
1684
+ type: Object,
1685
+ blackbox: true,
1686
+ optional: true
1687
+ },
1688
+ permissionView: {
1689
+ type: String,
1690
+ optional: true
1691
+ },
1692
+ mode: {
1693
+ type: String,
1694
+ optional: true
1695
+ }
1696
+ }),
1697
+ function: function (database, collection, operation, before_document, after_document, delete_impact, permissionView, mode) {
1698
+ return __awaiter(this, void 0, void 0, function () {
1699
+ var dbName;
1700
+ return __generator(this, function (_a) {
1701
+ switch (_a.label) {
1702
+ case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1703
+ case 1:
1704
+ _a.sent();
1705
+ dbName = resolveDatabaseName(database);
1706
+ return [2 /*return*/, reviewOperationRisk({
1707
+ database: dbName,
1708
+ collection: collection,
1709
+ operation: operation,
1710
+ mode: normalizeExplorerMode(mode),
1711
+ before_document: before_document,
1712
+ after_document: after_document,
1713
+ delete_impact: delete_impact
1714
+ })];
1715
+ }
1716
+ });
1717
+ });
1718
+ }
1719
+ },
1720
+ mongoExplorerDeleteDocument: {
1721
+ check: new simpl_schema_1.default({
1722
+ database: {
1723
+ type: String,
1724
+ optional: true
1725
+ },
1726
+ collection: {
1727
+ type: String
1728
+ },
1729
+ doc_id: {
1730
+ type: String
1731
+ },
1732
+ permissionView: {
1733
+ type: String,
1734
+ optional: true
1735
+ },
1736
+ force: {
1737
+ type: Boolean,
1738
+ optional: true
1739
+ },
1740
+ mode: {
1741
+ type: String,
1742
+ optional: true
1743
+ }
1744
+ }),
1745
+ function: function (database_1, collection_1, doc_id_1, permissionView_1) {
1746
+ return __awaiter(this, arguments, void 0, function (database, collection, doc_id, permissionView, force, mode) {
1747
+ var dbName, impact, collectionPreview, _a, managerCollection, dbCollection, deleteFilter;
1748
+ if (force === void 0) { force = false; }
1749
+ return __generator(this, function (_b) {
1750
+ switch (_b.label) {
1751
+ case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1752
+ case 1:
1753
+ _b.sent();
1754
+ dbName = resolveDatabaseName(database);
1755
+ return [4 /*yield*/, buildDeleteImpact(dbName, collection, doc_id)];
1756
+ case 2:
1757
+ impact = _b.sent();
1758
+ if (!force && (impact.unresolved || impact.has_references)) {
1759
+ collectionPreview = impact.collections.slice(0, 3).map(function (item) { return item.collection; }).join(', ');
1760
+ if (impact.unresolved) {
1761
+ throw new Error('Mongo Explorer: Delete blocked because dependency checks could not complete. Use force delete after review.');
1762
+ }
1763
+ throw new Error("Mongo Explorer: Delete blocked. Document is referenced by ".concat(collectionPreview).concat(impact.collections.length > 3 ? ', ...' : ''));
1764
+ }
1765
+ _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1766
+ deleteFilter = { _id: doc_id };
1767
+ if (!managerCollection) return [3 /*break*/, 4];
1768
+ return [4 /*yield*/, managerCollection.deleteOne(deleteFilter)];
1769
+ case 3:
1770
+ _b.sent();
1771
+ return [3 /*break*/, 6];
1772
+ case 4: return [4 /*yield*/, dbCollection.deleteOne(deleteFilter)];
1773
+ case 5:
1774
+ _b.sent();
1775
+ _b.label = 6;
1776
+ case 6: return [2 /*return*/, true];
1777
+ }
1778
+ });
1779
+ });
1780
+ }
1781
+ },
1782
+ mongoExplorerDeleteImpact: {
1783
+ check: new simpl_schema_1.default({
1784
+ database: {
1785
+ type: String,
1786
+ optional: true
1787
+ },
1788
+ collection: {
1789
+ type: String
1790
+ },
1791
+ doc_id: {
1792
+ type: String
1793
+ }
1794
+ }),
1795
+ function: function (database, collection, doc_id) {
1796
+ return __awaiter(this, void 0, void 0, function () {
1797
+ var dbName;
1798
+ return __generator(this, function (_a) {
1799
+ dbName = resolveDatabaseName(database);
1800
+ return [2 /*return*/, buildDeleteImpact(dbName, collection, doc_id)];
1801
+ });
1802
+ });
1803
+ }
1804
+ }
1805
+ });
1806
+ }
1807
+
1808
+ //# sourceMappingURL=mongo-explorer.js.map