openloops 0.1.6 → 0.1.8

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 (368) hide show
  1. package/dist/common/clients/llm-client.d.ts +1 -1
  2. package/dist/common/core/base.app.d.ts +4 -4
  3. package/dist/common/core/base.entity.d.ts +1 -1
  4. package/dist/common/core/base.use-case.d.ts +2 -2
  5. package/dist/common/helpers/index.d.ts +0 -6
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +7 -18
  8. package/dist/index.mjs +7 -0
  9. package/dist/services/agent/core/agent-loop.d.ts +7 -7
  10. package/dist/services/agent/core/agent.d.ts +6 -6
  11. package/dist/services/agent/loops/plan-execute/plan-execute-loop.d.ts +1 -1
  12. package/dist/services/agent/modules/chats/entities/agent-action.entity.d.ts +2 -2
  13. package/dist/services/agent/modules/chats/entities/agent-task.entity.d.ts +2 -2
  14. package/dist/services/agent/modules/chats/entities/chat-message.entity.d.ts +1 -1
  15. package/dist/services/agent/modules/chats/entities/chat.entity.d.ts +2 -2
  16. package/dist/services/agent/modules/chats/lambdas/create-chat/create-chat.use-case.d.ts +1 -1
  17. package/dist/services/agent/modules/chats/lambdas/delete-chat/delete-chat.use-case.d.ts +1 -1
  18. package/dist/services/agent/modules/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.d.ts +1 -1
  19. package/dist/services/agent/modules/chats/lambdas/interrupt-execution/interrupt-execution.use-case.d.ts +1 -1
  20. package/dist/services/agent/modules/chats/lambdas/list-chats-by-props/list-chats-by-props.use-case.d.ts +2 -2
  21. package/dist/services/agent/modules/chats/lambdas/list-chats-by-user/list-chats-by-user.use-case.d.ts +2 -2
  22. package/dist/services/agent/modules/chats/lambdas/update-chat/update-chat.use-case.d.ts +1 -1
  23. package/dist/services/agent/modules/chats/repositories/chat.repository.d.ts +1 -1
  24. package/dist/services/agent/modules/llmcalls/entities/llmcall.entity.d.ts +1 -1
  25. package/dist/services/agent/modules/llmcalls/lambdas/create-llmcall/create-llmcall.use-case.d.ts +1 -1
  26. package/dist/services/agent/modules/llmcalls/lambdas/delete-llmcall/delete-llmcall.use-case.d.ts +1 -1
  27. package/dist/services/agent/modules/llmcalls/lambdas/get-llm-usage/get-llm-usage.use-case.d.ts +1 -1
  28. package/dist/services/agent/modules/llmcalls/lambdas/get-llmcall-by-id/get-llmcall-by-id.use-case.d.ts +1 -1
  29. package/dist/services/agent/modules/llmcalls/lambdas/list-llmcalls-by-props/list-llmcalls-by-props.use-case.d.ts +2 -2
  30. package/dist/services/agent/modules/llmcalls/lambdas/update-llmcall/update-llmcall.use-case.d.ts +1 -1
  31. package/dist/services/agent/modules/llmcalls/repositories/llmcall.repository.d.ts +1 -1
  32. package/dist/services/agent/modules/mcp-servers/entities/mcpserver.entity.d.ts +1 -1
  33. package/dist/services/agent/modules/mcp-servers/lambdas/create-mcpserver/create-mcpserver.use-case.d.ts +1 -1
  34. package/dist/services/agent/modules/mcp-servers/lambdas/delete-mcpserver/delete-mcpserver.use-case.d.ts +1 -1
  35. package/dist/services/agent/modules/mcp-servers/lambdas/get-mcpserver-by-id/get-mcpserver-by-id.use-case.d.ts +1 -1
  36. package/dist/services/agent/modules/mcp-servers/lambdas/list-mcpservers-by-user/list-mcpservers-by-user.use-case.d.ts +2 -2
  37. package/dist/services/agent/modules/mcp-servers/lambdas/update-mcpserver/update-mcpserver.use-case.d.ts +1 -1
  38. package/dist/services/agent/modules/mcp-servers/repositories/mcpserver.repository.d.ts +1 -1
  39. package/dist/services/agent/skills/skill-runner.d.ts +3 -3
  40. package/dist/services/agent/skills/skill.d.ts +3 -3
  41. package/dist/services/agent/tools/tool.d.ts +1 -1
  42. package/dist/services/app/core/current-user.d.ts +1 -1
  43. package/dist/services/app/modules/authentication/lambdas/login/login.use-case.d.ts +4 -4
  44. package/dist/services/app/modules/users/entities/user.entity.d.ts +1 -1
  45. package/dist/services/app/modules/users/lambdas/create-user/create-user.use-case.d.ts +1 -1
  46. package/dist/services/app/modules/users/lambdas/delete-user/delete-user.use-case.d.ts +1 -1
  47. package/dist/services/app/modules/users/lambdas/get-user-by-id/get-user-by-id.use-case.d.ts +1 -1
  48. package/dist/services/app/modules/users/lambdas/list-users-by-props/list-users-by-props.use-case.d.ts +2 -2
  49. package/dist/services/app/modules/users/lambdas/update-user/update-user.use-case.d.ts +1 -1
  50. package/dist/services/app/modules/users/repositories/user.repository.d.ts +1 -1
  51. package/package.json +7 -8
  52. package/dist/common/clients/index.js +0 -20
  53. package/dist/common/clients/index.js.map +0 -1
  54. package/dist/common/clients/llm-client.js +0 -118
  55. package/dist/common/clients/llm-client.js.map +0 -1
  56. package/dist/common/clients/sentry-client.js +0 -91
  57. package/dist/common/clients/sentry-client.js.map +0 -1
  58. package/dist/common/clients/serper-client.js +0 -46
  59. package/dist/common/clients/serper-client.js.map +0 -1
  60. package/dist/common/core/base.app.js +0 -35
  61. package/dist/common/core/base.app.js.map +0 -1
  62. package/dist/common/core/base.entity.js +0 -210
  63. package/dist/common/core/base.entity.js.map +0 -1
  64. package/dist/common/core/base.use-case.js +0 -8
  65. package/dist/common/core/base.use-case.js.map +0 -1
  66. package/dist/common/core/index.js +0 -3
  67. package/dist/common/core/index.js.map +0 -1
  68. package/dist/common/core/utils/delete-empty-fields.js +0 -46
  69. package/dist/common/core/utils/delete-empty-fields.js.map +0 -1
  70. package/dist/common/core/utils/flatten-object.js +0 -23
  71. package/dist/common/core/utils/flatten-object.js.map +0 -1
  72. package/dist/common/core/utils/index.js +0 -20
  73. package/dist/common/core/utils/index.js.map +0 -1
  74. package/dist/common/core/utils/is-plain-object.js +0 -10
  75. package/dist/common/core/utils/is-plain-object.js.map +0 -1
  76. package/dist/common/decorators/admin-only/admin-only.js +0 -30
  77. package/dist/common/decorators/admin-only/admin-only.js.map +0 -1
  78. package/dist/common/decorators/admin-only/index.js +0 -18
  79. package/dist/common/decorators/admin-only/index.js.map +0 -1
  80. package/dist/common/decorators/index.js +0 -20
  81. package/dist/common/decorators/index.js.map +0 -1
  82. package/dist/common/decorators/mask-in-logs/index.js +0 -18
  83. package/dist/common/decorators/mask-in-logs/index.js.map +0 -1
  84. package/dist/common/decorators/mask-in-logs/mask-in-logs.js +0 -32
  85. package/dist/common/decorators/mask-in-logs/mask-in-logs.js.map +0 -1
  86. package/dist/common/decorators/owner-only/index.js +0 -18
  87. package/dist/common/decorators/owner-only/index.js.map +0 -1
  88. package/dist/common/decorators/owner-only/owner-only.js +0 -30
  89. package/dist/common/decorators/owner-only/owner-only.js.map +0 -1
  90. package/dist/common/error/http-error.js +0 -15
  91. package/dist/common/error/http-error.js.map +0 -1
  92. package/dist/common/error/index.js +0 -19
  93. package/dist/common/error/index.js.map +0 -1
  94. package/dist/common/error/reportError.js +0 -30
  95. package/dist/common/error/reportError.js.map +0 -1
  96. package/dist/common/helpers/countries-db.d.ts +0 -2718
  97. package/dist/common/helpers/countries-db.js +0 -2722
  98. package/dist/common/helpers/countries-db.js.map +0 -1
  99. package/dist/common/helpers/currencies-db.d.ts +0 -470
  100. package/dist/common/helpers/currencies-db.js +0 -474
  101. package/dist/common/helpers/currencies-db.js.map +0 -1
  102. package/dist/common/helpers/extract-json-from-text.js +0 -45
  103. package/dist/common/helpers/extract-json-from-text.js.map +0 -1
  104. package/dist/common/helpers/get-country-data-from-country-code.d.ts +0 -16
  105. package/dist/common/helpers/get-country-data-from-country-code.js +0 -14
  106. package/dist/common/helpers/get-country-data-from-country-code.js.map +0 -1
  107. package/dist/common/helpers/get-country-from-timezone.d.ts +0 -1
  108. package/dist/common/helpers/get-country-from-timezone.js +0 -14
  109. package/dist/common/helpers/get-country-from-timezone.js.map +0 -1
  110. package/dist/common/helpers/get-country-name-from-country-code.d.ts +0 -1
  111. package/dist/common/helpers/get-country-name-from-country-code.js +0 -17
  112. package/dist/common/helpers/get-country-name-from-country-code.js.map +0 -1
  113. package/dist/common/helpers/get-currency-data.d.ts +0 -13
  114. package/dist/common/helpers/get-currency-data.js +0 -48
  115. package/dist/common/helpers/get-currency-data.js.map +0 -1
  116. package/dist/common/helpers/get-language-from-language-code.d.ts +0 -5
  117. package/dist/common/helpers/get-language-from-language-code.js +0 -23
  118. package/dist/common/helpers/get-language-from-language-code.js.map +0 -1
  119. package/dist/common/helpers/get-timezone-offset.d.ts +0 -1
  120. package/dist/common/helpers/get-timezone-offset.js +0 -12
  121. package/dist/common/helpers/get-timezone-offset.js.map +0 -1
  122. package/dist/common/helpers/index.js +0 -25
  123. package/dist/common/helpers/index.js.map +0 -1
  124. package/dist/common/helpers/sanitize-string.js +0 -16
  125. package/dist/common/helpers/sanitize-string.js.map +0 -1
  126. package/dist/common/logger/index.js +0 -18
  127. package/dist/common/logger/index.js.map +0 -1
  128. package/dist/common/logger/pino.js +0 -39
  129. package/dist/common/logger/pino.js.map +0 -1
  130. package/dist/common/repositories/index.js +0 -19
  131. package/dist/common/repositories/index.js.map +0 -1
  132. package/dist/common/repositories/mongo-db.client.js +0 -59
  133. package/dist/common/repositories/mongo-db.client.js.map +0 -1
  134. package/dist/common/repositories/mongo-db.repository.js +0 -210
  135. package/dist/common/repositories/mongo-db.repository.js.map +0 -1
  136. package/dist/common/utils/secret-manager.js +0 -77
  137. package/dist/common/utils/secret-manager.js.map +0 -1
  138. package/dist/index.js.map +0 -1
  139. package/dist/services/agent/core/agent-loop.js +0 -7
  140. package/dist/services/agent/core/agent-loop.js.map +0 -1
  141. package/dist/services/agent/core/agent-state.js +0 -72
  142. package/dist/services/agent/core/agent-state.js.map +0 -1
  143. package/dist/services/agent/core/agent.js +0 -351
  144. package/dist/services/agent/core/agent.js.map +0 -1
  145. package/dist/services/agent/core/index.js +0 -20
  146. package/dist/services/agent/core/index.js.map +0 -1
  147. package/dist/services/agent/loops/index.js +0 -19
  148. package/dist/services/agent/loops/index.js.map +0 -1
  149. package/dist/services/agent/loops/plan-execute/index.js +0 -18
  150. package/dist/services/agent/loops/plan-execute/index.js.map +0 -1
  151. package/dist/services/agent/loops/plan-execute/plan-execute-loop.js +0 -228
  152. package/dist/services/agent/loops/plan-execute/plan-execute-loop.js.map +0 -1
  153. package/dist/services/agent/loops/shared/index.js +0 -18
  154. package/dist/services/agent/loops/shared/index.js.map +0 -1
  155. package/dist/services/agent/loops/shared/skills/action-planner.js +0 -44
  156. package/dist/services/agent/loops/shared/skills/action-planner.js.map +0 -1
  157. package/dist/services/agent/loops/shared/skills/confirmation-gate.js +0 -30
  158. package/dist/services/agent/loops/shared/skills/confirmation-gate.js.map +0 -1
  159. package/dist/services/agent/loops/shared/skills/fast-responder.js +0 -46
  160. package/dist/services/agent/loops/shared/skills/fast-responder.js.map +0 -1
  161. package/dist/services/agent/loops/shared/skills/final-responder.js +0 -34
  162. package/dist/services/agent/loops/shared/skills/final-responder.js.map +0 -1
  163. package/dist/services/agent/loops/shared/skills/index.js +0 -23
  164. package/dist/services/agent/loops/shared/skills/index.js.map +0 -1
  165. package/dist/services/agent/loops/shared/skills/state-observer.js +0 -34
  166. package/dist/services/agent/loops/shared/skills/state-observer.js.map +0 -1
  167. package/dist/services/agent/loops/shared/skills/strategy-engine.js +0 -37
  168. package/dist/services/agent/loops/shared/skills/strategy-engine.js.map +0 -1
  169. package/dist/services/agent/modules/chats/entities/agent-action.entity.js +0 -117
  170. package/dist/services/agent/modules/chats/entities/agent-action.entity.js.map +0 -1
  171. package/dist/services/agent/modules/chats/entities/agent-task.entity.js +0 -200
  172. package/dist/services/agent/modules/chats/entities/agent-task.entity.js.map +0 -1
  173. package/dist/services/agent/modules/chats/entities/chat-context.entity.js +0 -46
  174. package/dist/services/agent/modules/chats/entities/chat-context.entity.js.map +0 -1
  175. package/dist/services/agent/modules/chats/entities/chat-message.entity.js +0 -34
  176. package/dist/services/agent/modules/chats/entities/chat-message.entity.js.map +0 -1
  177. package/dist/services/agent/modules/chats/entities/chat-settings.entity.js +0 -36
  178. package/dist/services/agent/modules/chats/entities/chat-settings.entity.js.map +0 -1
  179. package/dist/services/agent/modules/chats/entities/chat.entity.js +0 -135
  180. package/dist/services/agent/modules/chats/entities/chat.entity.js.map +0 -1
  181. package/dist/services/agent/modules/chats/entities/index.js +0 -18
  182. package/dist/services/agent/modules/chats/entities/index.js.map +0 -1
  183. package/dist/services/agent/modules/chats/lambdas/create-chat/create-chat.use-case.js +0 -37
  184. package/dist/services/agent/modules/chats/lambdas/create-chat/create-chat.use-case.js.map +0 -1
  185. package/dist/services/agent/modules/chats/lambdas/create-chat/index.js +0 -18
  186. package/dist/services/agent/modules/chats/lambdas/create-chat/index.js.map +0 -1
  187. package/dist/services/agent/modules/chats/lambdas/delete-chat/delete-chat.use-case.js +0 -44
  188. package/dist/services/agent/modules/chats/lambdas/delete-chat/delete-chat.use-case.js.map +0 -1
  189. package/dist/services/agent/modules/chats/lambdas/delete-chat/index.js +0 -18
  190. package/dist/services/agent/modules/chats/lambdas/delete-chat/index.js.map +0 -1
  191. package/dist/services/agent/modules/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.js +0 -33
  192. package/dist/services/agent/modules/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.js.map +0 -1
  193. package/dist/services/agent/modules/chats/lambdas/get-chat-by-id/index.js +0 -18
  194. package/dist/services/agent/modules/chats/lambdas/get-chat-by-id/index.js.map +0 -1
  195. package/dist/services/agent/modules/chats/lambdas/interrupt-execution/index.js +0 -18
  196. package/dist/services/agent/modules/chats/lambdas/interrupt-execution/index.js.map +0 -1
  197. package/dist/services/agent/modules/chats/lambdas/interrupt-execution/interrupt-execution.use-case.js +0 -45
  198. package/dist/services/agent/modules/chats/lambdas/interrupt-execution/interrupt-execution.use-case.js.map +0 -1
  199. package/dist/services/agent/modules/chats/lambdas/list-chats-by-props/index.js +0 -18
  200. package/dist/services/agent/modules/chats/lambdas/list-chats-by-props/index.js.map +0 -1
  201. package/dist/services/agent/modules/chats/lambdas/list-chats-by-props/list-chats-by-props.use-case.js +0 -33
  202. package/dist/services/agent/modules/chats/lambdas/list-chats-by-props/list-chats-by-props.use-case.js.map +0 -1
  203. package/dist/services/agent/modules/chats/lambdas/list-chats-by-user/index.js +0 -18
  204. package/dist/services/agent/modules/chats/lambdas/list-chats-by-user/index.js.map +0 -1
  205. package/dist/services/agent/modules/chats/lambdas/list-chats-by-user/list-chats-by-user.use-case.js +0 -40
  206. package/dist/services/agent/modules/chats/lambdas/list-chats-by-user/list-chats-by-user.use-case.js.map +0 -1
  207. package/dist/services/agent/modules/chats/lambdas/update-chat/index.js +0 -18
  208. package/dist/services/agent/modules/chats/lambdas/update-chat/index.js.map +0 -1
  209. package/dist/services/agent/modules/chats/lambdas/update-chat/update-chat.use-case.js +0 -45
  210. package/dist/services/agent/modules/chats/lambdas/update-chat/update-chat.use-case.js.map +0 -1
  211. package/dist/services/agent/modules/chats/repositories/chat.repository.js +0 -43
  212. package/dist/services/agent/modules/chats/repositories/chat.repository.js.map +0 -1
  213. package/dist/services/agent/modules/chats/repositories/index.js +0 -18
  214. package/dist/services/agent/modules/chats/repositories/index.js.map +0 -1
  215. package/dist/services/agent/modules/llmcalls/entities/index.js +0 -18
  216. package/dist/services/agent/modules/llmcalls/entities/index.js.map +0 -1
  217. package/dist/services/agent/modules/llmcalls/entities/llmcall.entity.js +0 -42
  218. package/dist/services/agent/modules/llmcalls/entities/llmcall.entity.js.map +0 -1
  219. package/dist/services/agent/modules/llmcalls/lambdas/create-llmcall/create-llmcall.use-case.js +0 -37
  220. package/dist/services/agent/modules/llmcalls/lambdas/create-llmcall/create-llmcall.use-case.js.map +0 -1
  221. package/dist/services/agent/modules/llmcalls/lambdas/create-llmcall/index.js +0 -18
  222. package/dist/services/agent/modules/llmcalls/lambdas/create-llmcall/index.js.map +0 -1
  223. package/dist/services/agent/modules/llmcalls/lambdas/delete-llmcall/delete-llmcall.use-case.js +0 -44
  224. package/dist/services/agent/modules/llmcalls/lambdas/delete-llmcall/delete-llmcall.use-case.js.map +0 -1
  225. package/dist/services/agent/modules/llmcalls/lambdas/delete-llmcall/index.js +0 -18
  226. package/dist/services/agent/modules/llmcalls/lambdas/delete-llmcall/index.js.map +0 -1
  227. package/dist/services/agent/modules/llmcalls/lambdas/get-llm-usage/get-llm-usage.use-case.js +0 -104
  228. package/dist/services/agent/modules/llmcalls/lambdas/get-llm-usage/get-llm-usage.use-case.js.map +0 -1
  229. package/dist/services/agent/modules/llmcalls/lambdas/get-llm-usage/index.js +0 -18
  230. package/dist/services/agent/modules/llmcalls/lambdas/get-llm-usage/index.js.map +0 -1
  231. package/dist/services/agent/modules/llmcalls/lambdas/get-llmcall-by-id/get-llmcall-by-id.use-case.js +0 -33
  232. package/dist/services/agent/modules/llmcalls/lambdas/get-llmcall-by-id/get-llmcall-by-id.use-case.js.map +0 -1
  233. package/dist/services/agent/modules/llmcalls/lambdas/get-llmcall-by-id/index.js +0 -18
  234. package/dist/services/agent/modules/llmcalls/lambdas/get-llmcall-by-id/index.js.map +0 -1
  235. package/dist/services/agent/modules/llmcalls/lambdas/list-llmcalls-by-props/index.js +0 -18
  236. package/dist/services/agent/modules/llmcalls/lambdas/list-llmcalls-by-props/index.js.map +0 -1
  237. package/dist/services/agent/modules/llmcalls/lambdas/list-llmcalls-by-props/list-llmcalls-by-props.use-case.js +0 -33
  238. package/dist/services/agent/modules/llmcalls/lambdas/list-llmcalls-by-props/list-llmcalls-by-props.use-case.js.map +0 -1
  239. package/dist/services/agent/modules/llmcalls/lambdas/update-llmcall/index.js +0 -18
  240. package/dist/services/agent/modules/llmcalls/lambdas/update-llmcall/index.js.map +0 -1
  241. package/dist/services/agent/modules/llmcalls/lambdas/update-llmcall/update-llmcall.use-case.js +0 -43
  242. package/dist/services/agent/modules/llmcalls/lambdas/update-llmcall/update-llmcall.use-case.js.map +0 -1
  243. package/dist/services/agent/modules/llmcalls/repositories/index.js +0 -18
  244. package/dist/services/agent/modules/llmcalls/repositories/index.js.map +0 -1
  245. package/dist/services/agent/modules/llmcalls/repositories/llmcall.repository.js +0 -43
  246. package/dist/services/agent/modules/llmcalls/repositories/llmcall.repository.js.map +0 -1
  247. package/dist/services/agent/modules/mcp-servers/entities/index.js +0 -18
  248. package/dist/services/agent/modules/mcp-servers/entities/index.js.map +0 -1
  249. package/dist/services/agent/modules/mcp-servers/entities/mcpserver.entity.js +0 -53
  250. package/dist/services/agent/modules/mcp-servers/entities/mcpserver.entity.js.map +0 -1
  251. package/dist/services/agent/modules/mcp-servers/lambdas/create-mcpserver/create-mcpserver.use-case.js +0 -37
  252. package/dist/services/agent/modules/mcp-servers/lambdas/create-mcpserver/create-mcpserver.use-case.js.map +0 -1
  253. package/dist/services/agent/modules/mcp-servers/lambdas/create-mcpserver/index.js +0 -18
  254. package/dist/services/agent/modules/mcp-servers/lambdas/create-mcpserver/index.js.map +0 -1
  255. package/dist/services/agent/modules/mcp-servers/lambdas/delete-mcpserver/delete-mcpserver.use-case.js +0 -44
  256. package/dist/services/agent/modules/mcp-servers/lambdas/delete-mcpserver/delete-mcpserver.use-case.js.map +0 -1
  257. package/dist/services/agent/modules/mcp-servers/lambdas/delete-mcpserver/index.js +0 -18
  258. package/dist/services/agent/modules/mcp-servers/lambdas/delete-mcpserver/index.js.map +0 -1
  259. package/dist/services/agent/modules/mcp-servers/lambdas/get-mcpserver-by-id/get-mcpserver-by-id.use-case.js +0 -33
  260. package/dist/services/agent/modules/mcp-servers/lambdas/get-mcpserver-by-id/get-mcpserver-by-id.use-case.js.map +0 -1
  261. package/dist/services/agent/modules/mcp-servers/lambdas/get-mcpserver-by-id/index.js +0 -18
  262. package/dist/services/agent/modules/mcp-servers/lambdas/get-mcpserver-by-id/index.js.map +0 -1
  263. package/dist/services/agent/modules/mcp-servers/lambdas/list-mcpservers-by-user/index.js +0 -18
  264. package/dist/services/agent/modules/mcp-servers/lambdas/list-mcpservers-by-user/index.js.map +0 -1
  265. package/dist/services/agent/modules/mcp-servers/lambdas/list-mcpservers-by-user/list-mcpservers-by-user.use-case.js +0 -40
  266. package/dist/services/agent/modules/mcp-servers/lambdas/list-mcpservers-by-user/list-mcpservers-by-user.use-case.js.map +0 -1
  267. package/dist/services/agent/modules/mcp-servers/lambdas/update-mcpserver/index.js +0 -18
  268. package/dist/services/agent/modules/mcp-servers/lambdas/update-mcpserver/index.js.map +0 -1
  269. package/dist/services/agent/modules/mcp-servers/lambdas/update-mcpserver/update-mcpserver.use-case.js +0 -42
  270. package/dist/services/agent/modules/mcp-servers/lambdas/update-mcpserver/update-mcpserver.use-case.js.map +0 -1
  271. package/dist/services/agent/modules/mcp-servers/repositories/index.js +0 -18
  272. package/dist/services/agent/modules/mcp-servers/repositories/index.js.map +0 -1
  273. package/dist/services/agent/modules/mcp-servers/repositories/mcpserver.repository.js +0 -43
  274. package/dist/services/agent/modules/mcp-servers/repositories/mcpserver.repository.js.map +0 -1
  275. package/dist/services/agent/skills/index.js +0 -19
  276. package/dist/services/agent/skills/index.js.map +0 -1
  277. package/dist/services/agent/skills/shared/index.js +0 -18
  278. package/dist/services/agent/skills/shared/index.js.map +0 -1
  279. package/dist/services/agent/skills/shared/shared-rules.js +0 -8
  280. package/dist/services/agent/skills/shared/shared-rules.js.map +0 -1
  281. package/dist/services/agent/skills/skill-runner.js +0 -105
  282. package/dist/services/agent/skills/skill-runner.js.map +0 -1
  283. package/dist/services/agent/skills/skill.js +0 -110
  284. package/dist/services/agent/skills/skill.js.map +0 -1
  285. package/dist/services/agent/tools/core/call-ai/call-ai.skill.js +0 -31
  286. package/dist/services/agent/tools/core/call-ai/call-ai.skill.js.map +0 -1
  287. package/dist/services/agent/tools/core/call-ai/call-ai.tool.js +0 -47
  288. package/dist/services/agent/tools/core/call-ai/call-ai.tool.js.map +0 -1
  289. package/dist/services/agent/tools/core/call-ai/index.js +0 -18
  290. package/dist/services/agent/tools/core/call-ai/index.js.map +0 -1
  291. package/dist/services/agent/tools/core/index.js +0 -19
  292. package/dist/services/agent/tools/core/index.js.map +0 -1
  293. package/dist/services/agent/tools/core/web-search/index.js +0 -18
  294. package/dist/services/agent/tools/core/web-search/index.js.map +0 -1
  295. package/dist/services/agent/tools/core/web-search/web-search.tool.js +0 -29
  296. package/dist/services/agent/tools/core/web-search/web-search.tool.js.map +0 -1
  297. package/dist/services/agent/tools/index.js +0 -19
  298. package/dist/services/agent/tools/index.js.map +0 -1
  299. package/dist/services/agent/tools/tool.js +0 -35
  300. package/dist/services/agent/tools/tool.js.map +0 -1
  301. package/dist/services/agent/utils/rank-tools-by-keywords.js +0 -43
  302. package/dist/services/agent/utils/rank-tools-by-keywords.js.map +0 -1
  303. package/dist/services/app/core/app.js +0 -38
  304. package/dist/services/app/core/app.js.map +0 -1
  305. package/dist/services/app/core/current-session.js +0 -95
  306. package/dist/services/app/core/current-session.js.map +0 -1
  307. package/dist/services/app/core/current-user.js +0 -61
  308. package/dist/services/app/core/current-user.js.map +0 -1
  309. package/dist/services/app/core/index.js +0 -20
  310. package/dist/services/app/core/index.js.map +0 -1
  311. package/dist/services/app/modules/authentication/lambdas/login/index.js +0 -18
  312. package/dist/services/app/modules/authentication/lambdas/login/index.js.map +0 -1
  313. package/dist/services/app/modules/authentication/lambdas/login/login.use-case.js +0 -64
  314. package/dist/services/app/modules/authentication/lambdas/login/login.use-case.js.map +0 -1
  315. package/dist/services/app/modules/users/entities/index.js +0 -18
  316. package/dist/services/app/modules/users/entities/index.js.map +0 -1
  317. package/dist/services/app/modules/users/entities/user-acquisition.js +0 -34
  318. package/dist/services/app/modules/users/entities/user-acquisition.js.map +0 -1
  319. package/dist/services/app/modules/users/entities/user-country.js +0 -22
  320. package/dist/services/app/modules/users/entities/user-country.js.map +0 -1
  321. package/dist/services/app/modules/users/entities/user-currency.js +0 -22
  322. package/dist/services/app/modules/users/entities/user-currency.js.map +0 -1
  323. package/dist/services/app/modules/users/entities/user-email.value-object.js +0 -22
  324. package/dist/services/app/modules/users/entities/user-email.value-object.js.map +0 -1
  325. package/dist/services/app/modules/users/entities/user-language.js +0 -22
  326. package/dist/services/app/modules/users/entities/user-language.js.map +0 -1
  327. package/dist/services/app/modules/users/entities/user-marketing.js +0 -32
  328. package/dist/services/app/modules/users/entities/user-marketing.js.map +0 -1
  329. package/dist/services/app/modules/users/entities/user-notification-preferences.js +0 -19
  330. package/dist/services/app/modules/users/entities/user-notification-preferences.js.map +0 -1
  331. package/dist/services/app/modules/users/entities/user-password.value-object.js +0 -28
  332. package/dist/services/app/modules/users/entities/user-password.value-object.js.map +0 -1
  333. package/dist/services/app/modules/users/entities/user-permissions.js +0 -37
  334. package/dist/services/app/modules/users/entities/user-permissions.js.map +0 -1
  335. package/dist/services/app/modules/users/entities/user-preferences.js +0 -40
  336. package/dist/services/app/modules/users/entities/user-preferences.js.map +0 -1
  337. package/dist/services/app/modules/users/entities/user-report-preferences.js +0 -29
  338. package/dist/services/app/modules/users/entities/user-report-preferences.js.map +0 -1
  339. package/dist/services/app/modules/users/entities/user-report-schedule.js +0 -19
  340. package/dist/services/app/modules/users/entities/user-report-schedule.js.map +0 -1
  341. package/dist/services/app/modules/users/entities/user-timezone.js +0 -22
  342. package/dist/services/app/modules/users/entities/user-timezone.js.map +0 -1
  343. package/dist/services/app/modules/users/entities/user.entity.js +0 -100
  344. package/dist/services/app/modules/users/entities/user.entity.js.map +0 -1
  345. package/dist/services/app/modules/users/lambdas/create-user/create-user.use-case.js +0 -41
  346. package/dist/services/app/modules/users/lambdas/create-user/create-user.use-case.js.map +0 -1
  347. package/dist/services/app/modules/users/lambdas/create-user/index.js +0 -18
  348. package/dist/services/app/modules/users/lambdas/create-user/index.js.map +0 -1
  349. package/dist/services/app/modules/users/lambdas/delete-user/delete-user.use-case.js +0 -44
  350. package/dist/services/app/modules/users/lambdas/delete-user/delete-user.use-case.js.map +0 -1
  351. package/dist/services/app/modules/users/lambdas/delete-user/index.js +0 -18
  352. package/dist/services/app/modules/users/lambdas/delete-user/index.js.map +0 -1
  353. package/dist/services/app/modules/users/lambdas/get-user-by-id/get-user-by-id.use-case.js +0 -33
  354. package/dist/services/app/modules/users/lambdas/get-user-by-id/get-user-by-id.use-case.js.map +0 -1
  355. package/dist/services/app/modules/users/lambdas/get-user-by-id/index.js +0 -18
  356. package/dist/services/app/modules/users/lambdas/get-user-by-id/index.js.map +0 -1
  357. package/dist/services/app/modules/users/lambdas/list-users-by-props/index.js +0 -18
  358. package/dist/services/app/modules/users/lambdas/list-users-by-props/index.js.map +0 -1
  359. package/dist/services/app/modules/users/lambdas/list-users-by-props/list-users-by-props.use-case.js +0 -33
  360. package/dist/services/app/modules/users/lambdas/list-users-by-props/list-users-by-props.use-case.js.map +0 -1
  361. package/dist/services/app/modules/users/lambdas/update-user/index.js +0 -18
  362. package/dist/services/app/modules/users/lambdas/update-user/index.js.map +0 -1
  363. package/dist/services/app/modules/users/lambdas/update-user/update-user.use-case.js +0 -43
  364. package/dist/services/app/modules/users/lambdas/update-user/update-user.use-case.js.map +0 -1
  365. package/dist/services/app/modules/users/repositories/index.js +0 -18
  366. package/dist/services/app/modules/users/repositories/index.js.map +0 -1
  367. package/dist/services/app/modules/users/repositories/user.repository.js +0 -60
  368. package/dist/services/app/modules/users/repositories/user.repository.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import 'reflect-metadata';
2
2
  import type { KnownProvider, Message, AssistantMessage } from '@mariozechner/pi-ai';
3
- import { CurrentUser } from '../../services/app/core/index.js';
3
+ import { CurrentUser } from '@services/app/core';
4
4
  export declare class LLMClient {
5
5
  private readonly logger;
6
6
  private readonly langfuse;
@@ -1,9 +1,9 @@
1
- import { Logger } from '../logger/index.js';
2
- import { HttpError, HttpErrorProps } from '../error/index.js';
3
- import { CurrentSessionProps } from '../../services/app/core/current-session.js';
1
+ import { Logger } from '@common/logger';
2
+ import { HttpError, HttpErrorProps } from '@common/error';
3
+ import { CurrentSessionProps } from '@services/app/core/current-session';
4
4
  export declare abstract class BaseApp {
5
5
  logger: Logger;
6
- secretManager: import("../utils/secret-manager.js").SecretManager;
6
+ secretManager: import("@common/utils/secret-manager").SecretManager;
7
7
  reportError: (error: Error | HttpError | string, details?: object) => Promise<void>;
8
8
  onCatch(error: Error): Promise<void>;
9
9
  throwHttpError(error: HttpErrorProps): void;
@@ -1,6 +1,6 @@
1
1
  import 'reflect-metadata';
2
2
  import { ObjectId } from 'bson';
3
- import { CurrentUser } from '../../services/app/core/index.js';
3
+ import { CurrentUser } from '@services/app/core';
4
4
  export interface BaseEntityProps {
5
5
  _id?: string | ObjectId;
6
6
  __v?: number;
@@ -1,5 +1,5 @@
1
- import { CurrentUser, CurrentSession } from '../../services/app/core/index.js';
2
- import { HttpError } from '../error/index.js';
1
+ import { CurrentUser, CurrentSession } from '@services/app/core';
2
+ import { HttpError } from '@common/error';
3
3
  import { BaseApp } from './base.app';
4
4
  export interface BaseUseCaseParams {
5
5
  currentUser?: CurrentUser;
@@ -1,8 +1,2 @@
1
1
  export * from './extract-json-from-text';
2
- export * from './get-country-data-from-country-code';
3
- export * from './get-country-from-timezone';
4
- export * from './get-country-name-from-country-code';
5
- export * from './get-currency-data';
6
- export * from './get-language-from-language-code';
7
- export * from './get-timezone-offset';
8
2
  export * from './sanitize-string';
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './services/agent/core/index.js';
1
+ export * from '@services/agent/core';
package/dist/index.js CHANGED
@@ -1,18 +1,7 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./services/agent/core/index.js"), exports);
18
- //# sourceMappingURL=index.js.map
1
+ "use strict";var Rr=Object.create;var It=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Lr=Object.getOwnPropertyNames;var Ur=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var Mr=(r,t)=>{for(var e in t)It(r,e,{get:t[e],enumerable:!0})},Ae=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Lr(t))!$r.call(r,s)&&s!==e&&It(r,s,{get:()=>t[s],enumerable:!(n=Te(t,s))||n.enumerable});return r};var rt=(r,t,e)=>(e=r!=null?Rr(Ur(r)):{},Ae(t||!r||!r.__esModule?It(e,"default",{value:r,enumerable:!0}):e,r)),Dr=r=>Ae(It({},"__esModule",{value:!0}),r),A=(r,t,e,n)=>{for(var s=n>1?void 0:n?Te(t,e):t,i=r.length-1,o;i>=0;i--)(o=r[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&It(t,e,s),s};var kn={};Mr(kn,{AGENT_ERROR_CODES:()=>xr,Agent:()=>Ee,AgentLoop:()=>ne,AgentState:()=>nt,AgentStatus:()=>se});module.exports=Dr(kn);var ne=class{};var se=(i=>(i.IDLE="idle",i.FAILED="failed",i.PROCESSING="processing",i.AWAITING_USER_INPUT="awaiting_user_input",i.AWAITING_USER_CONFIRMATION="awaiting_user_confirmation",i))(se||{}),nt=class r{constructor(t,e,n,s,i,o){this.status=t;this.language=e;this.lastError=n;this.activeTaskId=s;this.stopRequested=i;this.currentActivity=o}status;language;lastError;activeTaskId;stopRequested;currentActivity;static fromJSON(t={}){return new r(t.status,t.language,t.lastError,t.activeTaskId,t.stopRequested,t.currentActivity)}toJSON(){return{currentActivity:this.currentActivity,language:this.language,status:this.status,activeTaskId:this.activeTaskId,lastError:this.lastError,stopRequested:this.stopRequested}}setLanguage(t){t&&(this.language=t)}setCurrentActivity(t){this.currentActivity=t}setStatus(t){this.status=t}setActiveTaskId(t){this.activeTaskId=t}setLastError(t){this.lastError=t}setStopRequested(t=!0){this.stopRequested=t}interruptExecution(){this.stopRequested=!0}cleanContext(){this.currentActivity="",this.language="en",this.status="idle",this.activeTaskId=void 0,this.lastError=void 0,this.stopRequested=!1}};var Xa=require("reflect-metadata"),Y=require("tsyringe");var zn=require("dotenv/config"),ie=rt(require("pino")),Be=rt(require("pino-pretty")),kr=(0,Be.default)({colorize:!0}),v=class{IS_LOCAL=process.env.IS_LOCAL==="true"||process.env.NODE_ENV==="development";logger=this.IS_LOCAL?(0,ie.default)({level:"debug"},kr):(0,ie.default)({level:"info"});log(t,e,n){typeof e=="string"&&(n=e,e=void 0),this.logger[t](e??{},n||"")}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}debug(t,e){this.log("debug",t,e)}error(t,e){this.log("error",t,e)}fatal(t,e){this.log("fatal",t,e)}},D=new v;var ar=require("tsyringe");var X=class{statusCode;errorMessage;errorDetails;constructor(t){this.statusCode=t.statusCode,this.errorMessage=t.errorMessage,this.errorDetails=t.errorDetails}};var q=rt(require("@sentry/node"));var Yn=require("dotenv/config"),Ce=rt(require("cryptr"));var oe=class r{static instance;cache=new Map;cryptr;static getInstance(){return r.instance||(r.instance=new r),r.instance}static encrypt(t){if(!t)throw new Error("[Secret manager] Value to encrypt cannot be empty");return`ENC:${r.getInstance().cryptr.encrypt(t)}`}constructor(){if(!process.env.SSUID)throw new Error("[Secret manager] SSUID environment variable is not set");this.cryptr=new Ce.default(process.env.SSUID,{pbkdf2Iterations:1e3,saltLength:16})}get(t){let e=process.hrtime.bigint();if(this.cache.has(t)){let i=this.cache.get(t);return this.logElapsed(t,e,!0),i}let n=this.getEnvVar(t),s=this.decryptEnvVar(n);return this.cache.set(t,s),this.logElapsed(t,e,!1),s}getEnvVar(t){let e=process.env[t];if(!e)throw new Error(`[Secret manager] Environment variable ${t} is not set`);return e}decryptEnvVar(t){if(!t)throw new Error("[Secret manager] Encrypted value cannot be empty");if(!this.isStringEncrypted(t))return D.debug("[Secret Manager] Value is not encrypted"),t;let e=t.replace(/^ENC:/,"");return this.cryptr.decrypt(e)}isStringEncrypted(t){return t?t.startsWith("ENC:"):!1}logElapsed(t,e,n){let s=process.hrtime.bigint(),i=Number(s-e)/1e6,o=n?" (cached)":"";D.debug(`[Secret Manager] GET: ${t} | ${i.toFixed(3)} ms${o}`)}},U=oe.getInstance();var ae=class r{static instance;enabled;static getInstance(){return r.instance||(r.instance=new r),r.instance}constructor(){let t=this.resolveDsn();if(this.enabled=!!t,!t){D.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");return}q.init({dsn:t,environment:process.env.NODE_ENV||"production",tracesSampleRate:0}),D.debug("[Sentry Client] Sentry client initialized")}async captureError(t,e){if(this.enabled){q.withScope(n=>{e&&n.setExtras(e),q.captureException(t)});try{await q.flush(2e3),D.debug("[Sentry Client] Error reported to Sentry successfully")}catch(n){D.error(n,"[Sentry Client] Failed to flush Sentry events")}}}setUser(t){this.enabled&&q.setUser({id:t})}resolveDsn(){try{return U.get("SENTRY_DSN")}catch{return}}},xe=ae.getInstance();var st=async(r,t)=>{r=typeof r=="string"?new Error(r):r;let e=(r instanceof X?r?.errorMessage:r?.message)||"Unknown error",n=(r instanceof X?r?.errorDetails:r?.stack)||"No stack trace available",s=r instanceof X?r?.statusCode:500;D.debug({error:t,message:e},"[Report Error] Reporting new error");let i=process.env.IS_LOCAL==="true"||process.env.NODE_ENV==="development";try{!i&&await xe.captureError(r,{statusCode:s,errorMessage:e,errorDetails:n,...t})}catch(o){D.error({error:o},"[Report Error] Failed to report error to Sentry")}};var Dt=class{logger=new v;secretManager=U;reportError=st;async onCatch(t){throw await st(t),t}throwHttpError(t){throw new X(t)}throwError401(t){this.throwHttpError({statusCode:401,errorMessage:"{{invalid_token}}: {{not_authenticated_error_details}}",errorDetails:JSON.stringify(t??{})})}throwError403(t){this.throwHttpError({statusCode:403,errorMessage:"{{forbidden_error}}: {{forbidden_error_details}}",errorDetails:JSON.stringify(t??{})})}};var _=class extends Dt{};var Ys=require("reflect-metadata");var Je=require("crypto"),vr=(()=>{let r=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>r.call(t)})();function Ve(r){return vr(r)==="Uint8Array"}function jr(r){return typeof r=="object"&&r!=null&&Symbol.toStringTag in r&&(r[Symbol.toStringTag]==="ArrayBuffer"||r[Symbol.toStringTag]==="SharedArrayBuffer")}function Fr(r){return r instanceof RegExp||Object.prototype.toString.call(r)==="[object RegExp]"}function qe(r){return typeof r=="object"&&r!=null&&Symbol.toStringTag in r&&r[Symbol.toStringTag]==="Map"}function zr(r){return r instanceof Date||Object.prototype.toString.call(r)==="[object Date]"}function k(r,t){return JSON.stringify(r,(e,n)=>typeof n=="bigint"?{$numberLong:`${n}`}:qe(n)?Object.fromEntries(n):n)}function Jr(r){if(r!=null&&typeof r=="object"&&"stylize"in r&&typeof r.stylize=="function")return r.stylize}var pe=6,He=Symbol.for("@@mdb.bson.version"),de=2147483647,me=-2147483648,Ye=Math.pow(2,63)-1,Ge=-Math.pow(2,63),Vr=Math.pow(2,53),qr=-Math.pow(2,53);var We=4,ps=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127}),c=class extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,e){super(t,e)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}},ge=class extends c{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${pe}.x.x`)}},kt=class extends c{get name(){return"BSONRuntimeError"}constructor(t){super(t)}},H=class extends c{get name(){return"BSONOffsetError"}constructor(t,e,n){super(`${t}. offset: ${e}`,n),this.offset=e}},Pe,_e;function Ke(r,t,e,n){if(n){Pe??=new TextDecoder("utf8",{fatal:!0});try{return Pe.decode(r.subarray(t,e))}catch(s){throw new c("Invalid UTF-8 string in BSON document",{cause:s})}}return _e??=new TextDecoder("utf8",{fatal:!1}),_e.decode(r.subarray(t,e))}function Ze(r,t,e){if(r.length===0)return"";let n=e-t;if(n===0)return"";if(n>20)return null;if(n===1&&r[t]<128)return String.fromCharCode(r[t]);if(n===2&&r[t]<128&&r[t+1]<128)return String.fromCharCode(r[t])+String.fromCharCode(r[t+1]);if(n===3&&r[t]<128&&r[t+1]<128&&r[t+2]<128)return String.fromCharCode(r[t])+String.fromCharCode(r[t+1])+String.fromCharCode(r[t+2]);let s=[];for(let i=t;i<e;i++){let o=r[i];if(o>127)return null;s.push(o)}return String.fromCharCode(...s)}function Hr(r,t,e){if(t.length===0)return 0;if(t.length>25||r.length-e<t.length)return null;for(let n=0,s=e;n<t.length;n++,s++){let i=t.charCodeAt(n);if(i>127)return null;r[s]=i}return t.length}var tt={toLocalBufferType(r){if(Buffer.isBuffer(r))return r;if(ArrayBuffer.isView(r))return Buffer.from(r.buffer,r.byteOffset,r.byteLength);let t=r?.[Symbol.toStringTag]??Object.prototype.toString.call(r);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(r);throw new c("Cannot create Buffer from the passed potentialBuffer.")},allocate(r){return Buffer.alloc(r)},allocateUnsafe(r){return Buffer.allocUnsafe(r)},equals(r,t){return tt.toLocalBufferType(r).equals(t)},fromNumberArray(r){return Buffer.from(r)},fromBase64(r){return Buffer.from(r,"base64")},toBase64(r){return tt.toLocalBufferType(r).toString("base64")},fromISO88591(r){return Buffer.from(r,"binary")},toISO88591(r){return tt.toLocalBufferType(r).toString("binary")},fromHex(r){return Buffer.from(r,"hex")},toHex(r){return tt.toLocalBufferType(r).toString("hex")},toUTF8(r,t,e,n){let s=e-t<=20?Ze(r,t,e):null;if(s!=null)return s;let i=tt.toLocalBufferType(r).toString("utf8",t,e);if(n){for(let o=0;o<i.length;o++)if(i.charCodeAt(o)===65533){Ke(r,t,e,!0);break}}return i},utf8ByteLength(r){return Buffer.byteLength(r,"utf8")},encodeUTF8Into(r,t,e){let n=Hr(r,t,e);return n??tt.toLocalBufferType(r).write(t,e,void 0,"utf8")},randomBytes:Je.randomBytes,swap32(r){return tt.toLocalBufferType(r).swap32()}};function Yr(){let{navigator:r}=globalThis;return typeof r=="object"&&r.product==="ReactNative"}function Gr(r){if(r<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${r}`);return Bt.fromNumberArray(Array.from({length:r},()=>Math.floor(Math.random()*256)))}var Wr=(()=>{let{crypto:r}=globalThis;if(r!=null&&typeof r.getRandomValues=="function")return t=>r.getRandomValues(Bt.allocate(t));if(Yr()){let{console:t}=globalThis;t?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Gr})(),Re=/(\d|[a-f])/i,Bt={toLocalBufferType(r){let t=r?.[Symbol.toStringTag]??Object.prototype.toString.call(r);if(t==="Uint8Array")return r;if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(r);throw new c("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(r){if(typeof r!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(r)}`);return new Uint8Array(r)},allocateUnsafe(r){return Bt.allocate(r)},equals(r,t){if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0},fromNumberArray(r){return Uint8Array.from(r)},fromBase64(r){return Uint8Array.from(atob(r),t=>t.charCodeAt(0))},toBase64(r){return btoa(Bt.toISO88591(r))},fromISO88591(r){return Uint8Array.from(r,t=>t.charCodeAt(0)&255)},toISO88591(r){return Array.from(Uint16Array.from(r),t=>String.fromCharCode(t)).join("")},fromHex(r){let t=r.length%2===0?r:r.slice(0,r.length-1),e=[];for(let n=0;n<t.length;n+=2){let s=t[n],i=t[n+1];if(!Re.test(s)||!Re.test(i))break;let o=Number.parseInt(`${s}${i}`,16);e.push(o)}return Uint8Array.from(e)},toHex(r){return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(r,t,e,n){let s=e-t<=20?Ze(r,t,e):null;return s??Ke(r,t,e,n)},utf8ByteLength(r){return new TextEncoder().encode(r).byteLength},encodeUTF8Into(r,t,e){let n=new TextEncoder().encode(t);return r.set(n,e),n.byteLength},randomBytes:Wr,swap32(r){if(r.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<r.length;t+=4){let e=r[t],n=r[t+1],s=r[t+2],i=r[t+3];r[t]=i,r[t+1]=s,r[t+2]=n,r[t+3]=e}return r}},Kr=typeof Buffer=="function"&&Buffer.prototype?._isBuffer!==!0,d=Kr?tt:Bt,$=class{get[He](){return pe}[Symbol.for("nodejs.util.inspect.custom")](t,e,n){return this.inspect(t,e,n)}},ft=new Float64Array(1),O=new Uint8Array(ft.buffer,0,8);ft[0]=-1;var ce=O[7]===0,ot={isBigEndian:ce,getNonnegativeInt32LE(r,t){if(r[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24},getInt32LE(r,t){return r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24},getUint32LE(r,t){return r[t]+r[t+1]*256+r[t+2]*65536+r[t+3]*16777216},getUint32BE(r,t){return r[t+3]+r[t+2]*256+r[t+1]*65536+r[t]*16777216},getBigInt64LE(r,t){let e=BigInt(r[t+4]+r[t+5]*256+r[t+6]*65536+(r[t+7]<<24)),n=BigInt(r[t]+r[t+1]*256+r[t+2]*65536+r[t+3]*16777216);return(e<<BigInt(32))+n},getFloat64LE:ce?(r,t)=>(O[7]=r[t],O[6]=r[t+1],O[5]=r[t+2],O[4]=r[t+3],O[3]=r[t+4],O[2]=r[t+5],O[1]=r[t+6],O[0]=r[t+7],ft[0]):(r,t)=>(O[0]=r[t],O[1]=r[t+1],O[2]=r[t+2],O[3]=r[t+3],O[4]=r[t+4],O[5]=r[t+5],O[6]=r[t+6],O[7]=r[t+7],ft[0]),setInt32BE(r,t,e){return r[t+3]=e,e>>>=8,r[t+2]=e,e>>>=8,r[t+1]=e,e>>>=8,r[t]=e,4},setInt32LE(r,t,e){return r[t]=e,e>>>=8,r[t+1]=e,e>>>=8,r[t+2]=e,e>>>=8,r[t+3]=e,4},setBigInt64LE(r,t,e){let n=BigInt(4294967295),s=Number(e&n);r[t]=s,s>>=8,r[t+1]=s,s>>=8,r[t+2]=s,s>>=8,r[t+3]=s;let i=Number(e>>BigInt(32)&n);return r[t+4]=i,i>>=8,r[t+5]=i,i>>=8,r[t+6]=i,i>>=8,r[t+7]=i,8},setFloat64LE:ce?(r,t,e)=>(ft[0]=e,r[t]=O[7],r[t+1]=O[6],r[t+2]=O[5],r[t+3]=O[4],r[t+4]=O[3],r[t+5]=O[2],r[t+6]=O[1],r[t+7]=O[0],8):(r,t,e)=>(ft[0]=e,r[t]=O[0],r[t+1]=O[1],r[t+2]=O[2],r[t+3]=O[3],r[t+4]=O[4],r[t+5]=O[5],r[t+6]=O[6],r[t+7]=O[7],8)},B=class r extends ${get _bsontype(){return"Binary"}constructor(t,e){if(super(),t!=null&&typeof t=="string"&&!ArrayBuffer.isView(t)&&!jr(t)&&!Array.isArray(t))throw new c("Binary can only be constructed from Uint8Array or number[]");this.sub_type=e??r.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=d.allocate(r.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(t)?d.fromNumberArray(t):d.toLocalBufferType(t),this.position=this.buffer.byteLength)}put(t){if(typeof t=="string"&&t.length!==1)throw new c("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new c("only accepts single character Uint8Array or Array");let e;if(typeof t=="string"?e=t.charCodeAt(0):typeof t=="number"?e=t:e=t[0],e<0||e>255)throw new c("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=e;else{let n=d.allocate(r.BUFFER_SIZE+this.buffer.length);n.set(this.buffer,0),this.buffer=n,this.buffer[this.position++]=e}}write(t,e){if(e=typeof e=="number"?e:this.position,this.buffer.byteLength<e+t.length){let n=d.allocate(this.buffer.byteLength+t.length);n.set(this.buffer,0),this.buffer=n}if(ArrayBuffer.isView(t))this.buffer.set(d.toLocalBufferType(t),e),this.position=e+t.byteLength>this.position?e+t.length:this.position;else if(typeof t=="string")throw new c("input cannot be string")}read(t,e){e=e&&e>0?e:this.position;let n=t+e;return this.buffer.subarray(t,n>this.position?this.position:n)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return d.toBase64(this.buffer.subarray(0,this.position))}toString(t){return t==="hex"?d.toHex(this.buffer.subarray(0,this.position)):t==="base64"?d.toBase64(this.buffer.subarray(0,this.position)):t==="utf8"||t==="utf-8"?d.toUTF8(this.buffer,0,this.position,!1):d.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(t){t=t||{},this.sub_type===r.SUBTYPE_VECTOR&&Q(this);let e=d.toBase64(this.buffer),n=Number(this.sub_type).toString(16);return t.legacy?{$binary:e,$type:n.length===1?"0"+n:n}:{$binary:{base64:e,subType:n.length===1?"0"+n:n}}}toUUID(){if(this.sub_type===r.SUBTYPE_UUID)return new At(this.buffer.subarray(0,this.position));throw new c(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${r.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(t,e){return new r(d.fromHex(t),e)}static createFromBase64(t,e){return new r(d.fromBase64(t),e)}static fromExtendedJSON(t,e){e=e||{};let n,s;if("$binary"in t?e.legacy&&typeof t.$binary=="string"&&"$type"in t?(s=t.$type?parseInt(t.$type,16):0,n=d.fromBase64(t.$binary)):typeof t.$binary!="string"&&(s=t.$binary.subType?parseInt(t.$binary.subType,16):0,n=d.fromBase64(t.$binary.base64)):"$uuid"in t&&(s=4,n=At.bytesFromString(t.$uuid)),!n)throw new c(`Unexpected Binary Extended JSON format ${JSON.stringify(t)}`);return s===We?new At(n):new r(n,s)}inspect(t,e,n){n??=k;let s=d.toBase64(this.buffer.subarray(0,this.position)),i=n(s,e),o=n(this.sub_type,e);return`Binary.createFromBase64(${i}, ${o})`}toInt8Array(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.Int8)throw new c("Binary datatype field is not Int8");return Q(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.Float32)throw new c("Binary datatype field is not Float32");Q(this);let t=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return ot.isBigEndian&&d.swap32(t),new Float32Array(t.buffer)}toPackedBits(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.PackedBit)throw new c("Binary datatype field is not packed bit");return Q(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.PackedBit)throw new c("Binary datatype field is not packed bit");Q(this);let e=(this.length()-2)*8-this.buffer[1],n=new Int8Array(e);for(let s=0;s<n.length;s++){let i=s/8|0,o=this.buffer[i+2],a=7-s%8,u=o>>a&1;n[s]=u}return n}static fromInt8Array(t){let e=d.allocate(t.byteLength+2);e[0]=r.VECTOR_TYPE.Int8,e[1]=0;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e.set(n,2);let s=new this(e,this.SUBTYPE_VECTOR);return Q(s),s}static fromFloat32Array(t){let e=d.allocate(t.byteLength+2);e[0]=r.VECTOR_TYPE.Float32,e[1]=0;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e.set(n,2),ot.isBigEndian&&d.swap32(new Uint8Array(e.buffer,2));let s=new this(e,this.SUBTYPE_VECTOR);return Q(s),s}static fromPackedBits(t,e=0){let n=d.allocate(t.byteLength+2);n[0]=r.VECTOR_TYPE.PackedBit,n[1]=e,n.set(t,2);let s=new this(n,this.SUBTYPE_VECTOR);return Q(s),s}static fromBits(t){let e=t.length+7>>>3,n=new Uint8Array(e+2);n[0]=r.VECTOR_TYPE.PackedBit;let s=t.length%8;n[1]=s===0?0:8-s;for(let i=0;i<t.length;i++){let o=i>>>3,a=t[i];if(a!==0&&a!==1)throw new c(`Invalid bit value at ${i}: must be 0 or 1, found ${t[i]}`);if(a===0)continue;let u=7-i%8;n[o+2]|=a<<u}return new this(n,r.SUBTYPE_VECTOR)}};B.BSON_BINARY_SUBTYPE_DEFAULT=0;B.BUFFER_SIZE=256;B.SUBTYPE_DEFAULT=0;B.SUBTYPE_FUNCTION=1;B.SUBTYPE_BYTE_ARRAY=2;B.SUBTYPE_UUID_OLD=3;B.SUBTYPE_UUID=4;B.SUBTYPE_MD5=5;B.SUBTYPE_ENCRYPTED=6;B.SUBTYPE_COLUMN=7;B.SUBTYPE_SENSITIVE=8;B.SUBTYPE_VECTOR=9;B.SUBTYPE_USER_DEFINED=128;B.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function Q(r){if(r.sub_type!==B.SUBTYPE_VECTOR)return;let t=r.position,e=r.buffer[0],n=r.buffer[1];if((e===B.VECTOR_TYPE.Float32||e===B.VECTOR_TYPE.Int8)&&n!==0)throw new c("Invalid Vector: padding must be zero for int8 and float32 vectors");if(e===B.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new c("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(e===B.VECTOR_TYPE.PackedBit&&n!==0&&t===2)throw new c("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(e===B.VECTOR_TYPE.PackedBit&&n>7)throw new c(`Invalid Vector: padding must be a value between 0 and 7. found: ${n}`)}var le=16,Zr=/^[0-9A-F]{32}$/i,Xr=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,At=class r extends B{constructor(t){let e;if(t==null)e=r.generate();else if(t instanceof r)e=d.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===le)e=d.toLocalBufferType(t);else if(typeof t=="string")e=r.bytesFromString(t);else throw new c("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(e,We)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[d.toHex(this.buffer.subarray(0,4)),d.toHex(this.buffer.subarray(4,6)),d.toHex(this.buffer.subarray(6,8)),d.toHex(this.buffer.subarray(8,10)),d.toHex(this.buffer.subarray(10,16))].join("-"):d.toHex(this.buffer)}toString(t){return t==="hex"?d.toHex(this.id):t==="base64"?d.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof r)return d.equals(t.id,this.id);try{return d.equals(new r(t).id,this.id)}catch{return!1}}toBinary(){return new B(this.id,B.SUBTYPE_UUID)}static generate(){let t=d.randomBytes(le);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?r.isValidUUIDString(t):Ve(t)?t.byteLength===le:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){let e=r.bytesFromString(t);return new r(e)}static createFromBase64(t){return new r(d.fromBase64(t))}static bytesFromString(t){if(!r.isValidUUIDString(t))throw new c("UUID string representation must be 32 hex digits or canonical hyphenated representation");return d.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return Zr.test(t)||Xr.test(t)}inspect(t,e,n){return n??=k,`new UUID(${n(this.toHexString(),e)})`}},Ct=class r extends ${get _bsontype(){return"Code"}constructor(t,e){super(),this.code=t.toString(),this.scope=e??null}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(t){return new r(t.$code,t.$scope)}inspect(t,e,n){n??=k;let s=n(this.code,e),i=s.includes(`
2
+ `);this.scope!=null&&(s+=`,${i?`
3
+ `:" "}${n(this.scope,e)}`);let o=i&&this.scope===null;return`new Code(${i?`
4
+ `:""}${s}${o?`
5
+ `:""})`}};function Qr(r){return r!=null&&typeof r=="object"&&"$id"in r&&r.$id!=null&&"$ref"in r&&typeof r.$ref=="string"&&(!("$db"in r)||"$db"in r&&typeof r.$db=="string")}var pt=class r extends ${get _bsontype(){return"DBRef"}constructor(t,e,n,s){super();let i=t.split(".");i.length===2&&(n=i.shift(),t=i.shift()),this.collection=t,this.oid=e,this.db=n,this.fields=s||{}}get namespace(){return this.collection}set namespace(t){this.collection=t}toJSON(){let t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t}toExtendedJSON(t){t=t||{};let e={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(e.$db=this.db),e=Object.assign(e,this.fields)),e}static fromExtendedJSON(t){let e=Object.assign({},t);return delete e.$ref,delete e.$id,delete e.$db,new r(t.$ref,t.$id,t.$db,e)}inspect(t,e,n){n??=k;let s=[n(this.namespace,e),n(this.oid,e),...this.db?[n(this.db,e)]:[],...Object.keys(this.fields).length>0?[n(this.fields,e)]:[]];return s[1]=n===k?`new ObjectId(${s[1]})`:s[1],`new DBRef(${s.join(", ")})`}};function Xe(r){if(r==="")return r;let t=0,e=r[t]==="-",n=r[t]==="+";(n||e)&&(t+=1);let s=!1;for(;t<r.length&&r[t]==="0";++t)s=!0;return s?`${e?"-":""}${r.length===t?"0":r.slice(t)}`:n?r.slice(1):r}function tn(r,t){t=t??10;let e="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,t);return new RegExp(`[^-+${e}]`,"i").test(r)?!1:r}var j;try{j=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var Le=65536,en=1<<24,gt=Le*Le,Qe=gt*gt,rn=Qe/2,Ue={},$e={},nn=20,sn=/^(\+?0|(\+|-)?[1-9][0-9]*)$/,l=class r extends ${get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(t=0,e,n){super();let s=typeof e=="boolean"?e:!!n,i=typeof e=="number"?e:0,o=typeof t=="string"?r.fromString(t,s):typeof t=="bigint"?r.fromBigInt(t,s):{low:t|0,high:i|0,unsigned:s};this.low=o.low,this.high=o.high,this.unsigned=o.unsigned}static fromBits(t,e,n){return new r(t,e,n)}static fromInt(t,e){let n,s,i;return e?(t>>>=0,(i=0<=t&&t<256)&&(s=$e[t],s)?s:(n=r.fromBits(t,(t|0)<0?-1:0,!0),i&&($e[t]=n),n)):(t|=0,(i=-128<=t&&t<128)&&(s=Ue[t],s)?s:(n=r.fromBits(t,t<0?-1:0,!1),i&&(Ue[t]=n),n))}static fromNumber(t,e){if(isNaN(t))return e?r.UZERO:r.ZERO;if(e){if(t<0)return r.UZERO;if(t>=Qe)return r.MAX_UNSIGNED_VALUE}else{if(t<=-9223372036854776e3)return r.MIN_VALUE;if(t+1>=rn)return r.MAX_VALUE}return t<0?r.fromNumber(-t,e).neg():r.fromBits(t%gt|0,t/gt|0,e)}static fromBigInt(t,e){let n=BigInt(4294967295),s=BigInt(32);return new r(Number(t&n),Number(t>>s&n),e)}static _fromString(t,e,n){if(t.length===0)throw new c("empty string");if(n<2||36<n)throw new c("radix");let s;if((s=t.indexOf("-"))>0)throw new c("interior hyphen");if(s===0)return r._fromString(t.substring(1),e,n).neg();let i=r.fromNumber(Math.pow(n,8)),o=r.ZERO;for(let a=0;a<t.length;a+=8){let u=Math.min(8,t.length-a),p=parseInt(t.substring(a,a+u),n);if(u<8){let f=r.fromNumber(Math.pow(n,u));o=o.mul(f).add(r.fromNumber(p))}else o=o.mul(i),o=o.add(r.fromNumber(p))}return o.unsigned=e,o}static fromStringStrict(t,e,n){let s=!1;if(typeof e=="number"?(n=e,e=!1):s=!!e,n??=10,t.trim()!==t)throw new c(`Input: '${t}' contains leading and/or trailing whitespace`);if(!tn(t,n))throw new c(`Input: '${t}' contains invalid characters for radix: ${n}`);let i=Xe(t),o=r._fromString(i,s,n);if(o.toString(n).toLowerCase()!==i.toLowerCase())throw new c(`Input: ${t} is not representable as ${o.unsigned?"an unsigned":"a signed"} 64-bit Long ${n!=null?`with radix: ${n}`:""}`);return o}static fromString(t,e,n){let s=!1;return typeof e=="number"?(n=e,e=!1):s=!!e,n??=10,t==="NaN"&&n<24||(t==="Infinity"||t==="+Infinity"||t==="-Infinity")&&n<35?r.ZERO:r._fromString(t,s,n)}static fromBytes(t,e,n){return n?r.fromBytesLE(t,e):r.fromBytesBE(t,e)}static fromBytesLE(t,e){return new r(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)}static fromBytesBE(t,e){return new r(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}static isLong(t){return t!=null&&typeof t=="object"&&"__isLong__"in t&&t.__isLong__===!0}static fromValue(t,e){return typeof t=="number"?r.fromNumber(t,e):typeof t=="string"?r.fromString(t,e):r.fromBits(t.low,t.high,typeof e=="boolean"?e:t.unsigned)}add(t){r.isLong(t)||(t=r.fromValue(t));let e=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,a=t.high&65535,u=t.low>>>16,p=t.low&65535,f=0,h=0,m=0,b=0;return b+=i+p,m+=b>>>16,b&=65535,m+=s+u,h+=m>>>16,m&=65535,h+=n+a,f+=h>>>16,h&=65535,f+=e+o,f&=65535,r.fromBits(m<<16|b,f<<16|h,this.unsigned)}and(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low&t.low,this.high&t.high,this.unsigned)}compare(t){if(r.isLong(t)||(t=r.fromValue(t)),this.eq(t))return 0;let e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1}comp(t){return this.compare(t)}divide(t){if(r.isLong(t)||(t=r.fromValue(t)),t.isZero())throw new c("division by zero");if(j){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;let i=(this.unsigned?j.div_u:j.div_s)(this.low,this.high,t.low,t.high);return r.fromBits(i,j.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?r.UZERO:r.ZERO;let e,n,s;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return r.UZERO;if(t.gt(this.shru(1)))return r.UONE;s=r.UZERO}else{if(this.eq(r.MIN_VALUE))return t.eq(r.ONE)||t.eq(r.NEG_ONE)?r.MIN_VALUE:t.eq(r.MIN_VALUE)?r.ONE:(e=this.shr(1).div(t).shl(1),e.eq(r.ZERO)?t.isNegative()?r.ONE:r.NEG_ONE:(n=this.sub(t.mul(e)),s=e.add(n.div(t)),s));if(t.eq(r.MIN_VALUE))return this.unsigned?r.UZERO:r.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=r.ZERO}for(n=this;n.gte(t);){e=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));let i=Math.ceil(Math.log(e)/Math.LN2),o=i<=48?1:Math.pow(2,i-48),a=r.fromNumber(e),u=a.mul(t);for(;u.isNegative()||u.gt(n);)e-=o,a=r.fromNumber(e,this.unsigned),u=a.mul(t);a.isZero()&&(a=r.ONE),s=s.add(a),n=n.sub(u)}return s}div(t){return this.divide(t)}equals(t){return r.isLong(t)||(t=r.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low}eq(t){return this.equals(t)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(r.MIN_VALUE)?64:this.neg().getNumBitsAbs();let t=this.high!==0?this.high:this.low,e;for(e=31;e>0&&(t&1<<e)===0;e--);return this.high!==0?e+33:e+1}greaterThan(t){return this.comp(t)>0}gt(t){return this.greaterThan(t)}greaterThanOrEqual(t){return this.comp(t)>=0}gte(t){return this.greaterThanOrEqual(t)}ge(t){return this.greaterThanOrEqual(t)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(t){return this.comp(t)<0}lt(t){return this.lessThan(t)}lessThanOrEqual(t){return this.comp(t)<=0}lte(t){return this.lessThanOrEqual(t)}modulo(t){if(r.isLong(t)||(t=r.fromValue(t)),j){let e=(this.unsigned?j.rem_u:j.rem_s)(this.low,this.high,t.low,t.high);return r.fromBits(e,j.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))}mod(t){return this.modulo(t)}rem(t){return this.modulo(t)}multiply(t){if(this.isZero())return r.ZERO;if(r.isLong(t)||(t=r.fromValue(t)),j){let x=j.mul(this.low,this.high,t.low,t.high);return r.fromBits(x,j.get_high(),this.unsigned)}if(t.isZero())return r.ZERO;if(this.eq(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.eq(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(r.TWO_PWR_24)&&t.lt(r.TWO_PWR_24))return r.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);let e=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,a=t.high&65535,u=t.low>>>16,p=t.low&65535,f=0,h=0,m=0,b=0;return b+=i*p,m+=b>>>16,b&=65535,m+=s*p,h+=m>>>16,m&=65535,m+=i*u,h+=m>>>16,m&=65535,h+=n*p,f+=h>>>16,h&=65535,h+=s*u,f+=h>>>16,h&=65535,h+=i*a,f+=h>>>16,h&=65535,f+=e*p+n*u+s*a+i*o,f&=65535,r.fromBits(m<<16|b,f<<16|h,this.unsigned)}mul(t){return this.multiply(t)}negate(){return!this.unsigned&&this.eq(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)}neg(){return this.negate()}not(){return r.fromBits(~this.low,~this.high,this.unsigned)}notEquals(t){return!this.equals(t)}neq(t){return this.notEquals(t)}ne(t){return this.notEquals(t)}or(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low|t.low,this.high|t.high,this.unsigned)}shiftLeft(t){return r.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?r.fromBits(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):r.fromBits(0,this.low<<t-32,this.unsigned)}shl(t){return this.shiftLeft(t)}shiftRight(t){return r.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?r.fromBits(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):r.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)}shr(t){return this.shiftRight(t)}shiftRightUnsigned(t){if(r.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;{let e=this.high;if(t<32){let n=this.low;return r.fromBits(n>>>t|e<<32-t,e>>>t,this.unsigned)}else return t===32?r.fromBits(e,0,this.unsigned):r.fromBits(e>>>t-32,0,this.unsigned)}}shr_u(t){return this.shiftRightUnsigned(t)}shru(t){return this.shiftRightUnsigned(t)}subtract(t){return r.isLong(t)||(t=r.fromValue(t)),this.add(t.neg())}sub(t){return this.subtract(t)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){return this.unsigned?(this.high>>>0)*gt+(this.low>>>0):this.high*gt+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(t){return t?this.toBytesLE():this.toBytesBE()}toBytesLE(){let t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]}toBytesBE(){let t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]}toSigned(){return this.unsigned?r.fromBits(this.low,this.high,!1):this}toString(t){if(t=t||10,t<2||36<t)throw new c("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(r.MIN_VALUE)){let i=r.fromNumber(t),o=this.div(i),a=o.mul(i).sub(this);return o.toString(t)+a.toInt().toString(t)}else return"-"+this.neg().toString(t);let e=r.fromNumber(Math.pow(t,6),this.unsigned),n=this,s="";for(;;){let i=n.div(e),a=(n.sub(i.mul(e)).toInt()>>>0).toString(t);if(n=i,n.isZero())return a+s;for(;a.length<6;)a="0"+a;s=""+a+s}}toUnsigned(){return this.unsigned?this:r.fromBits(this.low,this.high,!0)}xor(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low^t.low,this.high^t.high,this.unsigned)}eqz(){return this.isZero()}le(t){return this.lessThanOrEqual(t)}toExtendedJSON(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}}static fromExtendedJSON(t,e){let{useBigInt64:n=!1,relaxed:s=!0}={...e};if(t.$numberLong.length>nn)throw new c("$numberLong string is too long");if(!sn.test(t.$numberLong))throw new c(`$numberLong string "${t.$numberLong}" is in an invalid format`);if(n){let o=BigInt(t.$numberLong);return BigInt.asIntN(64,o)}let i=r.fromString(t.$numberLong);return s?i.toNumber():i}inspect(t,e,n){n??=k;let s=n(this.toString(),e),i=this.unsigned?`, ${n(this.unsigned,e)}`:"";return`new Long(${s}${i})`}};l.TWO_PWR_24=l.fromInt(en);l.MAX_UNSIGNED_VALUE=l.fromBits(-1,-1,!0);l.ZERO=l.fromInt(0);l.UZERO=l.fromInt(0,!0);l.ONE=l.fromInt(1);l.UONE=l.fromInt(1,!0);l.NEG_ONE=l.fromInt(-1);l.MAX_VALUE=l.fromBits(-1,2147483647,!1);l.MIN_VALUE=l.fromBits(0,-2147483648,!1);var on=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,an=/^(\+|-)?(Infinity|inf)$/i,cn=/^(\+|-)?NaN$/i,ht=6111,Et=-6176,Me=6176,De=34,ue=d.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),ke=d.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),ve=d.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),ln=/^([-+])?(\d+)?$/,un=31,je=16383,hn=30,fn=31;function Fe(r){return!isNaN(parseInt(r,10))}function gn(r){let t=l.fromNumber(1e9),e=l.fromNumber(0);if(!r.parts[0]&&!r.parts[1]&&!r.parts[2]&&!r.parts[3])return{quotient:r,rem:e};for(let n=0;n<=3;n++)e=e.shiftLeft(32),e=e.add(new l(r.parts[n],0)),r.parts[n]=e.div(t).low,e=e.modulo(t);return{quotient:r,rem:e}}function pn(r,t){if(!r&&!t)return{high:l.fromNumber(0),low:l.fromNumber(0)};let e=r.shiftRightUnsigned(32),n=new l(r.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new l(t.getLowBits(),0),o=e.multiply(s),a=e.multiply(i),u=n.multiply(s),p=n.multiply(i);return o=o.add(a.shiftRightUnsigned(32)),a=new l(a.getLowBits(),0).add(u).add(p.shiftRightUnsigned(32)),o=o.add(a.shiftRightUnsigned(32)),p=a.shiftLeft(32).add(new l(p.getLowBits(),0)),{high:o,low:p}}function dn(r,t){let e=r.high>>>0,n=t.high>>>0;if(e<n)return!0;if(e===n){let s=r.low>>>0,i=t.low>>>0;if(s<i)return!0}return!1}function z(r,t){throw new c(`"${r}" is not a valid Decimal128 string - ${t}`)}var vt=class r extends ${get _bsontype(){return"Decimal128"}constructor(t){if(super(),typeof t=="string")this.bytes=r.fromString(t).bytes;else if(t instanceof Uint8Array||Ve(t)){if(t.byteLength!==16)throw new c("Decimal128 must take a Buffer of 16 bytes");this.bytes=t}else throw new c("Decimal128 must take a Buffer or string")}static fromString(t){return r._fromString(t,{allowRounding:!1})}static fromStringWithRounding(t){return r._fromString(t,{allowRounding:!0})}static _fromString(t,e){let n=!1,s=!1,i=!1,o=!1,a=0,u=0,p=0,f=0,h=0,m=[0],b=0,x=0,y=0,w=0,S=new l(0,0),E=new l(0,0),F=0,g=0;if(t.length>=7e3)throw new c(""+t+" not a valid Decimal128 string");let L=t.match(on),Pr=t.match(an),_r=t.match(cn);if(!L&&!Pr&&!_r||t.length===0)throw new c(""+t+" not a valid Decimal128 string");if(L){let T=L[2],lt=L[4],ut=L[5],M=L[6];lt&&M===void 0&&z(t,"missing exponent power"),lt&&T===void 0&&z(t,"missing exponent base"),lt===void 0&&(ut||M)&&z(t,"missing e before exponent")}if((t[g]==="+"||t[g]==="-")&&(s=!0,n=t[g++]==="-"),!Fe(t[g])&&t[g]!=="."){if(t[g]==="i"||t[g]==="I")return new r(n?ke:ve);if(t[g]==="N")return new r(ue)}for(;Fe(t[g])||t[g]===".";){if(t[g]==="."){i&&z(t,"contains multiple periods"),i=!0,g=g+1;continue}b<De&&(t[g]!=="0"||o)&&(o||(h=u),o=!0,m[x++]=parseInt(t[g],10),b=b+1),o&&(p=p+1),i&&(f=f+1),u=u+1,g=g+1}if(i&&!u)throw new c(""+t+" not a valid Decimal128 string");if(t[g]==="e"||t[g]==="E"){let T=t.substr(++g).match(ln);if(!T||!T[2])return new r(ue);w=parseInt(T[0],10),g=g+T[0].length}if(t[g])return new r(ue);if(!b)m[0]=0,p=1,b=1,a=0;else if(y=b-1,a=p,a!==1)for(;t[h+a-1+Number(s)+Number(i)]==="0";)a=a-1;for(w<=f&&f>w+16384?w=Et:w=w-f;w>ht;){if(y=y+1,y>=De){if(a===0){w=ht;break}z(t,"overflow")}w=w-1}if(e.allowRounding){for(;w<Et||b<p;){if(y===0&&a<b){w=Et,a=0;break}if(b<p?p=p-1:y=y-1,w<ht)w=w+1;else{if(m.join("").match(/^0+$/)){w=ht;break}z(t,"overflow")}}if(y+1<a){let T=u;i&&(h=h+1,T=T+1),s&&(h=h+1,T=T+1);let lt=parseInt(t[h+y+1],10),ut=0;if(lt>=5&&(ut=1,lt===5)){ut=m[y]%2===1?1:0;for(let M=h+y+2;M<T;M++)if(parseInt(t[M],10)){ut=1;break}}if(ut){let M=y;for(;M>=0&&++m[M]>9;M--)if(m[M]=0,M===0)if(w<ht)w=w+1,m[M]=1;else return new r(n?ke:ve)}}}else{for(;w<Et||b<p;){if(y===0){if(a===0){w=Et;break}z(t,"exponent underflow")}b<p?(t[p-1+Number(s)+Number(i)]!=="0"&&a!==0&&z(t,"inexact rounding"),p=p-1):(m[y]!==0&&z(t,"inexact rounding"),y=y-1),w<ht?w=w+1:z(t,"overflow")}y+1<a&&(i&&(h=h+1),s&&(h=h+1),parseInt(t[h+y+1],10)!==0&&z(t,"inexact rounding"))}if(S=l.fromNumber(0),E=l.fromNumber(0),a===0)S=l.fromNumber(0),E=l.fromNumber(0);else if(y<17){let T=0;for(E=l.fromNumber(m[T++]),S=new l(0,0);T<=y;T++)E=E.multiply(l.fromNumber(10)),E=E.add(l.fromNumber(m[T]))}else{let T=0;for(S=l.fromNumber(m[T++]);T<=y-17;T++)S=S.multiply(l.fromNumber(10)),S=S.add(l.fromNumber(m[T]));for(E=l.fromNumber(m[T++]);T<=y;T++)E=E.multiply(l.fromNumber(10)),E=E.add(l.fromNumber(m[T]))}let G=pn(S,l.fromString("100000000000000000"));G.low=G.low.add(E),dn(G.low,E)&&(G.high=G.high.add(l.fromNumber(1))),F=w+Me;let I={low:l.fromNumber(0),high:l.fromNumber(0)};G.high.shiftRightUnsigned(49).and(l.fromNumber(1)).equals(l.fromNumber(1))?(I.high=I.high.or(l.fromNumber(3).shiftLeft(61)),I.high=I.high.or(l.fromNumber(F).and(l.fromNumber(16383).shiftLeft(47))),I.high=I.high.or(G.high.and(l.fromNumber(0x7fffffffffff)))):(I.high=I.high.or(l.fromNumber(F&16383).shiftLeft(49)),I.high=I.high.or(G.high.and(l.fromNumber(562949953421311)))),I.low=G.low,n&&(I.high=I.high.or(l.fromString("9223372036854775808")));let P=d.allocateUnsafe(16);return g=0,P[g++]=I.low.low&255,P[g++]=I.low.low>>8&255,P[g++]=I.low.low>>16&255,P[g++]=I.low.low>>24&255,P[g++]=I.low.high&255,P[g++]=I.low.high>>8&255,P[g++]=I.low.high>>16&255,P[g++]=I.low.high>>24&255,P[g++]=I.high.low&255,P[g++]=I.high.low>>8&255,P[g++]=I.high.low>>16&255,P[g++]=I.high.low>>24&255,P[g++]=I.high.high&255,P[g++]=I.high.high>>8&255,P[g++]=I.high.high>>16&255,P[g++]=I.high.high>>24&255,new r(P)}toString(){let t,e=0,n=new Array(36);for(let g=0;g<n.length;g++)n[g]=0;let s=0,i=!1,o,a={parts:[0,0,0,0]},u,p,f=[];s=0;let h=this.bytes,m=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,b=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,x=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,y=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24;s=0,{low:new l(m,b),high:new l(x,y)}.high.lessThan(l.ZERO)&&f.push("-");let S=y>>26&un;if(S>>3===3){if(S===hn)return f.join("")+"Infinity";if(S===fn)return"NaN";t=y>>15&je,o=8+(y>>14&1)}else o=y>>14&7,t=y>>17&je;let E=t-Me;if(a.parts[0]=(y&16383)+((o&15)<<14),a.parts[1]=x,a.parts[2]=b,a.parts[3]=m,a.parts[0]===0&&a.parts[1]===0&&a.parts[2]===0&&a.parts[3]===0)i=!0;else for(p=3;p>=0;p--){let g=0,L=gn(a);if(a=L.quotient,g=L.rem.low,!!g)for(u=8;u>=0;u--)n[p*9+u]=g%10,g=Math.floor(g/10)}if(i)e=1,n[s]=0;else for(e=36;!n[s];)e=e-1,s=s+1;let F=e-1+E;if(F>=34||F<=-7||E>0){if(e>34)return f.push("0"),E>0?f.push(`E+${E}`):E<0&&f.push(`E${E}`),f.join("");f.push(`${n[s++]}`),e=e-1,e&&f.push(".");for(let g=0;g<e;g++)f.push(`${n[s++]}`);f.push("E"),F>0?f.push(`+${F}`):f.push(`${F}`)}else if(E>=0)for(let g=0;g<e;g++)f.push(`${n[s++]}`);else{let g=e+E;if(g>0)for(let L=0;L<g;L++)f.push(`${n[s++]}`);else f.push("0");for(f.push(".");g++<0;)f.push("0");for(let L=0;L<e-Math.max(g-1,0);L++)f.push(`${n[s++]}`)}return f.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(t){return r.fromString(t.$numberDecimal)}inspect(t,e,n){return n??=k,`new Decimal128(${n(this.toString(),e)})`}},xt=class r extends ${get _bsontype(){return"Double"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t}static fromString(t){let e=Number(t);if(t==="NaN")return new r(NaN);if(t==="Infinity")return new r(1/0);if(t==="-Infinity")return new r(-1/0);if(!Number.isFinite(e))throw new c(`Input: ${t} is not representable as a Double`);if(t.trim()!==t)throw new c(`Input: '${t}' contains whitespace`);if(t==="")throw new c("Input is an empty string");if(/[^-0-9.+eE]/.test(t))throw new c(`Input: '${t}' is not in decimal or exponential notation`);return new r(e)}valueOf(){return this.value}toJSON(){return this.value}toString(t){return this.value.toString(t)}toExtendedJSON(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-0.0"}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(t,e){let n=parseFloat(t.$numberDouble);return e&&e.relaxed?n:new r(n)}inspect(t,e,n){return n??=k,`new Double(${n(this.value,e)})`}},Pt=class r extends ${get _bsontype(){return"Int32"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t|0}static fromString(t){let e=Xe(t),n=Number(t);if(de<n)throw new c(`Input: '${t}' is larger than the maximum value for Int32`);if(me>n)throw new c(`Input: '${t}' is smaller than the minimum value for Int32`);if(Number.isSafeInteger(n)){if(n.toString()!==e)throw new c(`Input: '${t}' is not a valid Int32 string`)}else throw new c(`Input: '${t}' is not a safe integer`);return new r(n)}valueOf(){return this.value}toString(t){return this.value.toString(t)}toJSON(){return this.value}toExtendedJSON(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}}static fromExtendedJSON(t,e){return e&&e.relaxed?parseInt(t.$numberInt,10):new r(t.$numberInt)}inspect(t,e,n){return n??=k,`new Int32(${n(this.value,e)})`}},jt=class r extends ${get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new r}inspect(){return"new MaxKey()"}},Ft=class r extends ${get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new r}inspect(){return"new MinKey()"}},it=null,Tt=new WeakMap,K=class r extends ${get _bsontype(){return"ObjectId"}constructor(t){super();let e;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new c("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?e=d.fromHex(t.toHexString()):e=t.id}else e=t;if(e==null||typeof e=="number")this.buffer=r.generate(typeof e=="number"?e:void 0);else if(ArrayBuffer.isView(e)&&e.byteLength===12)this.buffer=d.toLocalBufferType(e);else if(typeof e=="string")if(r.validateHexString(e))this.buffer=d.fromHex(e),r.cacheHexString&&Tt.set(this,e);else throw new c("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new c("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(t){this.buffer=t,r.cacheHexString&&Tt.set(this,d.toHex(t))}static validateHexString(t){if(t?.length!==24)return!1;for(let e=0;e<24;e++){let n=t.charCodeAt(e);if(!(n>=48&&n<=57||n>=97&&n<=102||n>=65&&n<=70))return!1}return!0}toHexString(){if(r.cacheHexString){let e=Tt.get(this);if(e)return e}let t=d.toHex(this.id);return r.cacheHexString&&Tt.set(this,t),t}static getInc(){return r.index=(r.index+1)%16777215}static generate(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));let e=r.getInc(),n=d.allocateUnsafe(12);return ot.setInt32BE(n,0,t),it===null&&(it=d.randomBytes(5)),n[4]=it[0],n[5]=it[1],n[6]=it[2],n[7]=it[3],n[8]=it[4],n[11]=e&255,n[10]=e>>8&255,n[9]=e>>16&255,n}toString(t){return t==="base64"?d.toBase64(this.id):t==="hex"?this.toHexString():this.toHexString()}toJSON(){return this.toHexString()}static is(t){return t!=null&&typeof t=="object"&&"_bsontype"in t&&t._bsontype==="ObjectId"}equals(t){if(t==null)return!1;if(r.is(t))return this.buffer[11]===t.buffer[11]&&d.equals(this.buffer,t.buffer);if(typeof t=="string")return t.toLowerCase()===this.toHexString();if(typeof t=="object"&&typeof t.toHexString=="function"){let e=t.toHexString(),n=this.toHexString();return typeof e=="string"&&e.toLowerCase()===n}return!1}getTimestamp(){let t=new Date,e=ot.getUint32BE(this.buffer,0);return t.setTime(Math.floor(e)*1e3),t}static createPk(){return new r}serializeInto(t,e){return t[e]=this.buffer[0],t[e+1]=this.buffer[1],t[e+2]=this.buffer[2],t[e+3]=this.buffer[3],t[e+4]=this.buffer[4],t[e+5]=this.buffer[5],t[e+6]=this.buffer[6],t[e+7]=this.buffer[7],t[e+8]=this.buffer[8],t[e+9]=this.buffer[9],t[e+10]=this.buffer[10],t[e+11]=this.buffer[11],12}static createFromTime(t){let e=d.allocate(12);for(let n=11;n>=4;n--)e[n]=0;return ot.setInt32BE(e,0,t),new r(e)}static createFromHexString(t){if(t?.length!==24)throw new c("hex string must be 24 characters");return new r(d.fromHex(t))}static createFromBase64(t){if(t?.length!==16)throw new c("base64 string must be 16 characters");return new r(d.fromBase64(t))}static isValid(t){if(t==null)return!1;if(typeof t=="string")return r.validateHexString(t);try{return new r(t),!0}catch{return!1}}toExtendedJSON(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}}static fromExtendedJSON(t){return new r(t.$oid)}isCached(){return r.cacheHexString&&Tt.has(this)}inspect(t,e,n){return n??=k,`new ObjectId(${n(this.toHexString(),e)})`}};K.index=Math.floor(Math.random()*16777215);function mn(r){return r.split("").sort().join("")}var dt=class r extends ${get _bsontype(){return"BSONRegExp"}constructor(t,e){if(super(),this.pattern=t,this.options=mn(e??""),this.pattern.indexOf("\0")!==-1)throw new c(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\0")!==-1)throw new c(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let n=0;n<this.options.length;n++)if(!(this.options[n]==="i"||this.options[n]==="m"||this.options[n]==="x"||this.options[n]==="l"||this.options[n]==="s"||this.options[n]==="u"))throw new c(`The regular expression option [${this.options[n]}] is not supported`)}static parseOptions(t){return t?t.split("").sort().join(""):""}toExtendedJSON(t){return t=t||{},t.legacy?{$regex:this.pattern,$options:this.options}:{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(t){if("$regex"in t)if(typeof t.$regex!="string"){if(t.$regex._bsontype==="BSONRegExp")return t}else return new r(t.$regex,r.parseOptions(t.$options));if("$regularExpression"in t)return new r(t.$regularExpression.pattern,r.parseOptions(t.$regularExpression.options));throw new c(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(t)}`)}inspect(t,e,n){let s=Jr(e)??(a=>a);n??=k;let i=s(n(this.pattern),"regexp"),o=s(n(this.options),"regexp");return`new BSONRegExp(${i}, ${o})`}},zt=class r extends ${get _bsontype(){return"BSONSymbol"}constructor(t){super(),this.value=t}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(t){return new r(t.$symbol)}inspect(t,e,n){return n??=k,`new BSONSymbol(${n(this.value,e)})`}},yn=l,_t=class r extends yn{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(t){if(t==null)super(0,0,!0);else if(typeof t=="bigint")super(t,!0);else if(l.isLong(t))super(t.low,t.high,!0);else if(typeof t=="object"&&"t"in t&&"i"in t){if(typeof t.t!="number"&&(typeof t.t!="object"||t.t._bsontype!=="Int32"))throw new c("Timestamp constructed from { t, i } must provide t as a number");if(typeof t.i!="number"&&(typeof t.i!="object"||t.i._bsontype!=="Int32"))throw new c("Timestamp constructed from { t, i } must provide i as a number");let e=Number(t.t),n=Number(t.i);if(e<0||Number.isNaN(e))throw new c("Timestamp constructed from { t, i } must provide a positive t");if(n<0||Number.isNaN(n))throw new c("Timestamp constructed from { t, i } must provide a positive i");if(e>4294967295)throw new c("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(n>4294967295)throw new c("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(n,e,!0)}else throw new c("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(t){return new r(l.fromInt(t,!0))}static fromNumber(t){return new r(l.fromNumber(t,!0))}static fromBits(t,e){return new r({i:t,t:e})}static fromString(t,e){return new r(l.fromString(t,!0,e))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(t){let e=l.isLong(t.$timestamp.i)?t.$timestamp.i.getLowBitsUnsigned():t.$timestamp.i,n=l.isLong(t.$timestamp.t)?t.$timestamp.t.getLowBitsUnsigned():t.$timestamp.t;return new r({t:n,i:e})}inspect(t,e,n){n??=k;let s=n(this.t,e),i=n(this.i,e);return`new Timestamp({ t: ${s}, i: ${i} })`}};_t.MAX_VALUE=l.MAX_UNSIGNED_VALUE;var ds=l.fromNumber(Vr),ms=l.fromNumber(qr);function wn(r){return r!=null&&typeof r=="object"&&"_bsontype"in r&&typeof r._bsontype=="string"}var bn={$oid:K,$binary:B,$uuid:B,$symbol:zt,$numberInt:Pt,$numberDecimal:vt,$numberDouble:xt,$numberLong:l,$minKey:Ft,$maxKey:jt,$regex:dt,$regularExpression:dt,$timestamp:_t};function tr(r,t={}){if(typeof r=="number"){let n=r<=de&&r>=me,s=r<=Ye&&r>=Ge;if(t.relaxed||t.legacy)return r;if(Number.isInteger(r)&&!Object.is(r,-0)){if(n)return new Pt(r);if(s)return t.useBigInt64?BigInt(r):l.fromNumber(r)}return new xt(r)}if(r==null||typeof r!="object")return r;if(r.$undefined)return null;let e=Object.keys(r).filter(n=>n.startsWith("$")&&r[n]!=null);for(let n=0;n<e.length;n++){let s=bn[e[n]];if(s)return s.fromExtendedJSON(r,t)}if(r.$date!=null){let n=r.$date,s=new Date;if(t.legacy)if(typeof n=="number")s.setTime(n);else if(typeof n=="string")s.setTime(Date.parse(n));else if(typeof n=="bigint")s.setTime(Number(n));else throw new kt(`Unrecognized type for EJSON date: ${typeof n}`);else if(typeof n=="string")s.setTime(Date.parse(n));else if(l.isLong(n))s.setTime(n.toNumber());else if(typeof n=="number"&&t.relaxed)s.setTime(n);else if(typeof n=="bigint")s.setTime(Number(n));else throw new kt(`Unrecognized type for EJSON date: ${typeof n}`);return s}if(r.$code!=null){let n=Object.assign({},r);return r.$scope&&(n.$scope=tr(r.$scope)),Ct.fromExtendedJSON(r)}if(Qr(r)||r.$dbPointer){let n=r.$ref?r:r.$dbPointer;if(n instanceof pt)return n;let s=Object.keys(n).filter(o=>o.startsWith("$")),i=!0;if(s.forEach(o=>{["$ref","$id","$db"].indexOf(o)===-1&&(i=!1)}),i)return pt.fromExtendedJSON(n)}return r}function Sn(r,t){return r.map((e,n)=>{t.seenObjects.push({propertyName:`index ${n}`,obj:null});try{return W(e,t)}finally{t.seenObjects.pop()}})}function ze(r){let t=r.toISOString();return r.getUTCMilliseconds()!==0?t:t.slice(0,-5)+"Z"}function W(r,t){if(r instanceof Map||qe(r)){let e=Object.create(null);for(let[n,s]of r){if(typeof n!="string")throw new c("Can only serialize maps with string keys");e[n]=s}return W(e,t)}if((typeof r=="object"||typeof r=="function")&&r!==null){let e=t.seenObjects.findIndex(n=>n.obj===r);if(e!==-1){let n=t.seenObjects.map(f=>f.propertyName),s=n.slice(0,e).map(f=>`${f} -> `).join(""),i=n[e],o=" -> "+n.slice(e+1,n.length-1).map(f=>`${f} -> `).join(""),a=n[n.length-1],u=" ".repeat(s.length+i.length/2),p="-".repeat(o.length+(i.length+a.length)/2-1);throw new c(`Converting circular structure to EJSON:
6
+ ${s}${i}${o}${a}
7
+ ${u}\\${p}/`)}t.seenObjects[t.seenObjects.length-1].obj=r}if(Array.isArray(r))return Sn(r,t);if(r===void 0)return null;if(r instanceof Date||zr(r)){let e=r.getTime(),n=e>-1&&e<2534023188e5;return t.legacy?t.relaxed&&n?{$date:r.getTime()}:{$date:ze(r)}:t.relaxed&&n?{$date:ze(r)}:{$date:{$numberLong:r.getTime().toString()}}}if(typeof r=="number"&&(!t.relaxed||!isFinite(r))){if(Number.isInteger(r)&&!Object.is(r,-0)){if(r>=me&&r<=de)return{$numberInt:r.toString()};if(r>=Ge&&r<=Ye)return{$numberLong:r.toString()}}return{$numberDouble:Object.is(r,-0)?"-0.0":r.toString()}}if(typeof r=="bigint")return t.relaxed?Number(BigInt.asIntN(64,r)):{$numberLong:BigInt.asIntN(64,r).toString()};if(r instanceof RegExp||Fr(r)){let e=r.flags;if(e===void 0){let s=r.toString().match(/[gimuy]*$/);s&&(e=s[0])}return new dt(r.source,e).toExtendedJSON(t)}return r!=null&&typeof r=="object"?Nn(r,t):r}var On={Binary:r=>new B(r.value(),r.sub_type),Code:r=>new Ct(r.code,r.scope),DBRef:r=>new pt(r.collection||r.namespace,r.oid,r.db,r.fields),Decimal128:r=>new vt(r.bytes),Double:r=>new xt(r.value),Int32:r=>new Pt(r.value),Long:r=>l.fromBits(r.low!=null?r.low:r.low_,r.low!=null?r.high:r.high_,r.low!=null?r.unsigned:r.unsigned_),MaxKey:()=>new jt,MinKey:()=>new Ft,ObjectId:r=>new K(r),BSONRegExp:r=>new dt(r.pattern,r.options),BSONSymbol:r=>new zt(r.value),Timestamp:r=>_t.fromBits(r.low,r.high)};function Nn(r,t){if(r==null||typeof r!="object")throw new c("not an object instance");let e=r._bsontype;if(typeof e>"u"){let n={};for(let s of Object.keys(r)){t.seenObjects.push({propertyName:s,obj:null});try{let i=W(r[s],t);s==="__proto__"?Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):n[s]=i}finally{t.seenObjects.pop()}}return n}else{if(r!=null&&typeof r=="object"&&typeof r._bsontype=="string"&&r[He]!==pe)throw new ge;if(wn(r)){let n=r;if(typeof n.toExtendedJSON!="function"){let s=On[r._bsontype];if(!s)throw new c("Unrecognized or invalid _bsontype: "+r._bsontype);n=s(n)}return e==="Code"&&n.scope?n=new Ct(n.code,W(n.scope,t)):e==="DBRef"&&n.oid&&(n=new pt(W(n.collection,t),W(n.oid,t),W(n.db,t),W(n.fields,t))),n.toExtendedJSON(t)}else throw new c("_bsontype must be a string, but was: "+typeof e)}}function er(r,t){let e={useBigInt64:t?.useBigInt64??!1,relaxed:t?.relaxed??!0,legacy:t?.legacy??!1};return JSON.parse(r,(n,s)=>{if(n.indexOf("\0")!==-1)throw new c(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(n)}`);return tr(s,e)})}function rr(r,t,e,n){e!=null&&typeof e=="object"&&(n=e,e=0),t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t,t=void 0,e=0);let s=Object.assign({relaxed:!0,legacy:!1},n,{seenObjects:[{propertyName:"(root)",obj:null}]}),i=W(r,s);return JSON.stringify(i,t,e)}function In(r,t){return t=t||{},JSON.parse(rr(r,t))}function En(r,t){return t=t||{},er(JSON.stringify(r),t)}var Rt=Object.create(null);Rt.parse=er;Rt.stringify=rr;Rt.serialize=In;Rt.deserialize=En;Object.freeze(Rt);var C={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function he(r,t){try{return ot.getNonnegativeInt32LE(r,t)}catch(e){throw new H("BSON size cannot be negative",t,{cause:e})}}function fe(r,t){let e=t;for(;r[e]!==0;e++);if(e===r.length-1)throw new H("Null terminator not found",t);return e}function Tn(r,t=0){if(t??=0,r.length<5)throw new H(`Input must be at least 5 bytes, got ${r.length} bytes`,t);let e=he(r,t);if(e>r.length-t)throw new H(`Parsed documentSize (${e} bytes) does not match input length (${r.length} bytes)`,t);if(r[t+e-1]!==0)throw new H("BSON documents must end in 0x00",t+e);let n=[],s=t+4;for(;s<=e+t;){let i=r[s];if(s+=1,i===0){if(s-t!==e)throw new H("Invalid 0x00 type byte",s);break}let o=s,a=fe(r,s)-o;s+=a+1;let u;if(i===C.double||i===C.long||i===C.date||i===C.timestamp)u=8;else if(i===C.int)u=4;else if(i===C.objectId)u=12;else if(i===C.decimal)u=16;else if(i===C.bool)u=1;else if(i===C.null||i===C.undefined||i===C.maxKey||i===C.minKey)u=0;else if(i===C.regex)u=fe(r,fe(r,s)+1)+1-s;else if(i===C.object||i===C.array||i===C.javascriptWithScope)u=he(r,s);else if(i===C.string||i===C.binData||i===C.dbPointer||i===C.javascript||i===C.symbol)u=he(r,s)+4,i===C.binData&&(u+=1),i===C.dbPointer&&(u+=12);else throw new H(`Invalid 0x${i.toString(16).padStart(2,"0")} type byte`,s);if(u>e)throw new H("value reports length larger than document",s);n.push([i,o,a,s,u]),s+=u}return n}var Jt=Object.create(null);Jt.parseToElements=Tn;Jt.ByteUtils=d;Jt.NumberUtils=ot;Object.freeze(Jt);var An=1024*1024*17,ys=d.allocate(An);function Z(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}function ye(r){if(Array.isArray(r))return r.map(ye);if(Z(r)){let t={};for(let e of Object.keys(r))t[e]=ye(r[e]);return t}return r}function we(r){let t=n=>{if(Array.isArray(n)){n.forEach(t);return}Z(n)&&Object.keys(n).forEach(s=>{let i=n[s];Array.isArray(i)?t(i):Z(i)?(t(i),Object.keys(i).length===0&&delete n[s]):i==null&&delete n[s]})},e=ye(r);return t(e),e}function be(r,t="",e={}){if(!Z(r))return{};for(let n in r)if(r.hasOwnProperty(n)){let s=t?`${t}.${n}`:n,i=r[n];Z(i)?be(i,s,e):e[s]=i}return e}var Bn="maskInLogs";var Cn=(r,t)=>Reflect.getMetadata(Bn,r,t);function Vt(r){if(r&&Z(r)){let t={};for(let[e,n]of Object.entries(r))Cn(r,e)?t[e]="[HIDDEN]":Array.isArray(n)?t[e]=n.map(s=>Vt(s)):typeof n=="object"?t[e]=Vt(n):t[e]=n;return t}return r}var xn="adminOnly";function J(r,t){Reflect.defineMetadata(xn,!0,r,t)}var Pn="ownerOnly";function nr(r,t){Reflect.defineMetadata(Pn,!0,r,t)}function qt(r){if(!r)return{};let t=r.indexOf("{");if(t===-1)return{};let e=0,n=!1,s=!1;for(let i=t;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"?e++:o==="}"&&e--,e===0))try{return JSON.parse(r.substring(t,i+1))}catch{return{}}}return{}}var sr=rt(require("sanitize-html"));function ir(r=""){if(r)return(0,sr.default)(r,{allowedTags:[],allowedAttributes:{}})}var N=class N{_id;__v;ownerId;createdAt;createdBy;updatedAt;updatedBy;deletedAt;deletedBy;deletedReason;archivedAt;archivedBy;sharedWith;toUnset;static toObjectId(t){if(t){if(t instanceof K)return t;if(!K.isValid(t))throw new Error(`Invalid ObjectId: ${t}`);return new K(t)}}static toDate(t){if(!t)return;let e=new Date(t);if(isNaN(e.getTime()))throw new Error("{{value_must_be_a_date}}");return e}static toNumber(t){if(t!=null){if(typeof t!="number")throw new Error("{{value_must_be_a_number}}");return t}}static clean(t){return we(t)}constructor(t){this._id=N.toObjectId(t._id),this.__v=N.toNumber(t.__v),this.ownerId=N.toObjectId(t.ownerId),this.createdAt=N.toDate(t.createdAt),this.createdBy=N.toObjectId(t.createdBy),this.updatedAt=N.toDate(t.updatedAt),this.updatedBy=N.toObjectId(t.updatedBy),this.deletedAt=N.toDate(t.deletedAt),this.deletedBy=N.toObjectId(t.deletedBy),this.deletedReason=ir(t.deletedReason),this.archivedAt=N.toDate(t.archivedAt),this.archivedBy=N.toObjectId(t.archivedBy),this.sharedWith=t.sharedWith?.length?t.sharedWith.map(e=>N.toObjectId(e)):void 0}toJSON(){return{_id:this._id,__v:this.__v,ownerId:this.ownerId,createdAt:this.createdAt,createdBy:this.createdBy,updatedAt:this.updatedAt,updatedBy:this.updatedBy,deletedAt:this.deletedAt,deletedBy:this.deletedBy,deletedReason:this.deletedReason,archivedAt:this.archivedAt,archivedBy:this.archivedBy,sharedWith:this.sharedWith?.length?this.sharedWith.map(t=>t.toHexString()):void 0,toUnset:this.toUnset}}setDefaults(){}setId(t){this._id=N.toObjectId(t)}setOwner(t){t&&(this.ownerId=N.toObjectId(t.userId))}setCreatedBy(t){t&&(this.sanitize(t),this.createdAt=new Date,this.createdBy=N.toObjectId(t.userId),this.setDefaults())}setUpdatedBy(t){t&&(this.sanitize(t),this.updatedAt=new Date,this.updatedBy=N.toObjectId(t.userId))}setDeletedBy(t){t&&(this.sanitize(t),this.deletedAt=new Date,this.deletedBy=N.toObjectId(t.userId))}setArchivedBy(t){t&&(this.sanitize(t),this.archivedAt=new Date,this.archivedBy=N.toObjectId(t.userId))}toDocument(){return we(this.toJSON())}toFlatDocument(){let{toUnset:t,...e}=this.toDocument();return{...be(e),toUnset:t}}stringify(){return JSON.stringify(Vt(this),null,2)}unset(t){let e=Array.from(new Set(t.map(n=>String(n))));if(!e||!Array.isArray(e))return{};this.toUnset=e.reduce((n,s)=>(n[s]="",n),{}),t.forEach(n=>{delete this[n]})}sanitize(t){if(!t?.isAdmin())for(let e in this)Reflect.getMetadata("adminOnly",this.constructor.prototype,e)&&delete this[e]}};A([J],N.prototype,"__v",2),A([J],N.prototype,"ownerId",2),A([J],N.prototype,"createdAt",2),A([J],N.prototype,"createdBy",2),A([J],N.prototype,"updatedAt",2),A([J],N.prototype,"updatedBy",2),A([J],N.prototype,"deletedAt",2),A([J],N.prototype,"deletedBy",2),A([J],N.prototype,"archivedAt",2),A([J],N.prototype,"archivedBy",2),A([nr],N.prototype,"sharedWith",2);var R=N;var Ht=require("mongodb");var Lt=class r extends R{constructor(e,n,s){super(e);this.props=e;this.role=n;this.content=s}props;role;content;static factory(e){let n=e._id&&Ht.ObjectId.isValid(e._id)?new Ht.ObjectId(e._id):new Ht.ObjectId;return r.fromJSON({...e,_id:n})}static fromJSON(e){return new r(e,e.role,e.content)}toJSON(){return{...super.toJSON(),role:this.role,content:this.content}}};var Yt=class r{constructor(t,e,n,s){this.props=t;this.notifyOnCompletion=e;this.modelName=n;this.loopName=s}props;notifyOnCompletion;modelName;loopName;static fromJSON(t){return new r(t,t.notifyOnCompletion,t.modelName,t.loopName)}toJSON(){return{notifyOnCompletion:this.notifyOnCompletion,modelName:this.modelName,loopName:this.loopName}}setLoopName(t){this.loopName=t}setModelName(t){this.modelName=t}setNotifyOnCompletion(t){this.notifyOnCompletion=t}};var Ut=class r{constructor(t,e){this.props=t;this.items=e}props;items;MEMORY_CONTEXT_MAX_CHARS=1e4;static fromJSON(t){return new r(t,t.items)}get length(){return this.items?JSON.stringify(this.items).length:0}get allMeta(){return this.items?.map(t=>t.meta)}toJSON(){return{items:this.items}}addContext(t){this.items??=[],this.items.push(t)}selectContext(t){return this.items?.filter(e=>(t.taskId===void 0||e.taskId===t.taskId)&&(t.name===void 0||e.meta.name===t.name))}lastContext(t){let e=this.selectContext(t);return e?.[e.length-1]}compress(){}pruneContext(){}};var Wt=require("mongodb");var Gt=require("mongodb");var $t=class r extends R{constructor(e,n,s,i,o,a,u,p,f,h,m,b,x){super(e);this.props=e;this.name=n;this.stepId=s;this.args=i;this.dependsOn=o;this.status=a;this.output=u;this.error=p;this.reasoning=f;this.retries=h;this.author=m;this.startedAt=b;this.completedAt=x}props;name;stepId;args;dependsOn;status;output;error;reasoning;retries;author;startedAt;completedAt;static factory(e){let n=e._id&&Gt.ObjectId.isValid(e._id)?new Gt.ObjectId(e._id):new Gt.ObjectId;return r.fromJSON({...e,_id:n,status:e.status??"pending"})}static fromJSON(e){return new r(e,e.name,e.stepId,e.args,e.dependsOn,e.status,e.output,e.error,e.reasoning,e.retries,e.author,e.startedAt,e.completedAt)}toJSON(){return{...super.toJSON(),name:this.name,stepId:this.stepId,args:this.args,dependsOn:this.dependsOn,status:this.status,output:this.output,error:this.error,reasoning:this.reasoning,retries:this.retries,author:this.author,startedAt:this.startedAt,completedAt:this.completedAt}}get id(){return this._id.toString()}get isReady(){return this.status==="pending"}get isTerminal(){return this.status==="completed"||this.status==="failed"}dependenciesSatisfiedBy(e){return this.dependsOn?.length?this.dependsOn.every(n=>e.has(n)):!0}markRunning(){this.status="running",this.startedAt=new Date}markCompleted(e){this.status="completed",this.output=e,this.completedAt=new Date}markFailed(e){this.status="failed",this.error=e,this.completedAt=new Date}incrementRetries(){return this.retries=(this.retries??0)+1,this.retries}resetForRetry(){this.status="pending",this.error=void 0,this.startedAt=void 0,this.completedAt=void 0}async runTool(e,n,s){if(!e)return this.markFailed({message:`Tool "${this.name}" not found`}),this;this.markRunning();try{let i=await e.run({...n,...s});this.markCompleted(i?.data)}catch(i){this.markFailed({message:i?.message??String(i)})}return this}};var _n=/^\{\{step_([\w-]+)\.output\}\}$/,Rn=/\{\{step_([\w-]+)\.output\}\}/g,Ln=/^\{\{context\.([\w.-]+)\}\}$/,Un=/\{\{context\.([\w.-]+)\}\}/g;function or(r){return typeof r=="object"?JSON.stringify(r):String(r)}var Mt=class r extends R{constructor(e,n,s,i,o,a,u,p,f=[]){super(e);this.props=e;this.status=n;this.goal=s;this.nextNode=i;this.threadId=o;this.previousTaskId=a;this.summary=u;this.loopName=p;this.actions=f}props;status;goal;nextNode;threadId;previousTaskId;summary;loopName;actions;static factory(e){let n=e._id&&Wt.ObjectId.isValid(e._id)?new Wt.ObjectId(e._id):new Wt.ObjectId;return r.fromJSON({...e,_id:n,status:e.status??"in_progress"})}static fromJSON(e){return new r(e,e.status,e.goal,e.nextNode,e.threadId,e.previousTaskId,e.summary,e.loopName,e.actions?.map(n=>$t.factory(n))??[])}toJSON(){return{...super.toJSON(),status:this.status,goal:this.goal,nextNode:this.nextNode,threadId:this.threadId,previousTaskId:this.previousTaskId,summary:this.summary,loopName:this.loopName,actions:this.actions.map(e=>e.toJSON())}}get id(){return this._id.toString()}addAction(e){let n=$t.factory({name:e.name,stepId:e.stepId,args:e.args,dependsOn:e.dependsOn,reasoning:e.reasoning,author:e.author});return this.actions.push(n),n}getAction(e){return this.actions.find(n=>n.id===e||n.stepId===e)}findLastByName(e){return this.actions.slice().reverse().find(n=>n.name===e)}get readyActions(){let e=new Set(this.actions.filter(n=>n.status==="completed").flatMap(n=>[n.id,n.stepId].filter(Boolean)));return this.actions.filter(n=>n.isReady&&n.dependenciesSatisfiedBy(e))}get failedActions(){return this.actions.filter(e=>e.status==="failed")}get lastExecutedAction(){return this.actions.slice().reverse().find(e=>e.isTerminal)}setNextNode(e){this.nextNode=e}complete(e){this.status="completed",e&&(this.summary=e),this.nextNode=void 0}fail(){this.status="failed",this.nextNode=void 0}cancel(){this.status="cancelled",this.nextNode=void 0}pause(){(this.status==="in_progress"||this.status==="awaiting_user")&&(this.status="paused")}reopen(){this.status="in_progress",this.nextNode=void 0}resolveArgs(e,n){return this.resolveValue(e.args,n)}resolveValue(e,n){if(typeof e=="string"){let s=e.match(_n);if(s){let o=this.findActionByRef(s[1]);return o?.output!==void 0?o.output:e}let i=e.match(Ln);if(i){let o=this.readContextValue(i[1],n);return o!==void 0?o:e}return e.replace(Rn,(o,a)=>{let u=this.findActionByRef(a);return u?.output!==void 0?or(u.output):""}).replace(Un,(o,a)=>{let u=this.readContextValue(a,n);return u!==void 0?or(u):""})}if(Array.isArray(e))return e.map(s=>this.resolveValue(s,n));if(e!==null&&typeof e=="object"){let s={};for(let i of Object.keys(e))s[i]=this.resolveValue(e[i],n);return s}return e}findActionByRef(e){return this.actions.find(n=>n.stepId===e||n.id===e)}readContextValue(e,n){return n.selectContext({taskId:this.id,name:e})?.[0]?.content}async runTool(e,n,s,i){let o=this.addAction(e);return this.executeToolAction(o,n,s,i)}async runReadyAction(e,n,s,i){let o=this.getAction(e);if(!o)throw new Error(`[AgentTask] Action "${e}" not found`);return this.executeToolAction(o,n,s,i)}async executeToolAction(e,n,s,i){let o=this.resolveArgs(e,s),a=await e.runTool(n,o,i);return a.status==="completed"&&a.name&&s.addContext({taskId:this.id,meta:{name:a.name,type:"tool_output",shortDescription:`Output of ${a.name}`},content:a.output}),a}};var V=class r extends R{constructor(e,n,s,i,o=Ut.fromJSON({}),a=[],u){super(e);this.props=e;this.state=n;this.settings=s;this.messages=i;this.context=o;this.tasks=a;this.traces=u}props;state;settings;messages;context;tasks;traces;static withDefaults(e){let n=new nt;return n.cleanContext(),r.fromJSON({state:n.toJSON(),settings:{loopName:e}})}static fromJSON(e){return new r(e,e.state&&nt.fromJSON(e.state),e.settings&&Yt.fromJSON(e.settings),e.messages?.map(n=>Lt.factory(n)),Ut.fromJSON(e.context??{}),e.tasks?.map(n=>Mt.fromJSON(n))??[],e.traces)}get lastAnswer(){return this.messages?.slice().reverse().find(e=>e.role==="assistant")?.content}get activeTask(){if(this.state?.activeTaskId)return this.tasks.find(e=>e.id===this.state?.activeTaskId)}toJSON(){return{...super.toJSON(),state:this.state?.toJSON(),settings:this.settings?.toJSON(),messages:this.messages?.map(e=>e.toJSON()),context:this.context.toJSON(),tasks:this.tasks.map(e=>e.toJSON()),traces:this.traces}}pushMessage(e){this.messages??=[],this.messages.push(Lt.factory(e))}lastHistoryMessages(e=6){return this.messages?.slice(-e,-1)}addTrace(e){this.traces??=[],this.traces.push({...e,taskId:e.taskId??this.activeTask?.id,timestamp:new Date})}setAgentState(e){this.state=nt.fromJSON(e)}getTask(e){return this.tasks.find(n=>n.id===e)}lastCompletedTask(){return this.tasks.slice().reverse().find(e=>e.status==="completed"&&e.loopName===this.settings?.loopName)}createTask(e,n){this.activeTask?.status==="in_progress"&&this.activeTask.pause();let s=n?.continuesFrom?this.getTask(n.continuesFrom):void 0,i=Mt.factory({goal:e,threadId:s?.threadId,previousTaskId:n?.continuesFrom,loopName:this.settings?.loopName});return i.threadId??=i.id,this.tasks.push(i),this.state?.setActiveTaskId(i.id),i}reopenTask(e){let n=this.getTask(e);if(n)return n.reopen(),this.state?.setActiveTaskId(n.id),n}completeTask(e,n){let s=e?this.getTask(e):this.activeTask;s?.complete(n),this.clearActiveTaskIdIfMatches(s)}failTask(e){let n=e?this.getTask(e):this.activeTask;n?.fail(),this.clearActiveTaskIdIfMatches(n)}cancelTask(e){let n=e?this.getTask(e):this.activeTask;n?.cancel(),this.clearActiveTaskIdIfMatches(n)}clearActiveTaskIdIfMatches(e){e?.id===this.state?.activeTaskId&&this.state?.setActiveTaskId(void 0)}switchLoop(e){this.settings?.loopName&&this.settings.loopName!==e&&(this.activeTask?.pause(),this.state?.setActiveTaskId(void 0)),this.settings?.setLoopName(e)}};var mt=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{payload:n,currentUser:s}=e,i=V.fromJSON({...n});return i.setCreatedBy(s),i.setOwner(s),{data:await this.chatRepository.create(i)}}};mt=A([(0,ar.autoInjectable)()],mt);var cr=require("tsyringe");var at=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{payload:n,id:s,currentUser:i}=e;if(!s)throw new Error("Id is required for updating Chat");if(!n||Object.keys(n).length===0)throw new Error("Payload is required for updating Chat");let o=V.fromJSON({...n,_id:s});o.setUpdatedBy(i);let a=await this.chatRepository.update(o);if(!a)throw new Error("Chat not found or update failed");return{data:a}}};at=A([(0,cr.autoInjectable)()],at);var lr=require("tsyringe"),ur=require("mongodb");var yt=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{options:n,currentUser:s}=e,{page:i=1,limit:o=10}=n||{};return{data:await this.chatRepository._.findMany({where:{ownerId:new ur.ObjectId(s?.userId)},options:{page:i,limit:o,sortBy:{updatedAt:-1}}})}}};yt=A([(0,lr.autoInjectable)()],yt);var hr=require("tsyringe"),fr=require("mongodb");var wt=class extends _{constructor(e){super();this.mcpServerRepository=e}mcpServerRepository;async execute(e){let{options:n,currentUser:s}=e,{page:i=1,limit:o=10}=n||{};return{data:await this.mcpServerRepository._.findMany({where:{ownerId:new fr.ObjectId(s?.userId)},options:{page:i,limit:o,sortBy:{updatedAt:-1}}})}}};wt=A([(0,hr.autoInjectable)()],wt);var gr=require("@modelcontextprotocol/sdk/client/index.js"),pr=require("@modelcontextprotocol/sdk/client/streamableHttp.js"),bt=class r extends R{constructor(e,n,s,i,o){super(e);this.props=e;this.name=n;this.url=s;this.type=i;this.headers=o}props;name;url;type;headers;mcpClient;static fromJSON(e){return new r(e,e.name||void 0,e.url||void 0,e.type||void 0,e.headers||void 0)}toJSON(){return{...super.toJSON(),name:this.name,url:this.url,type:this.type,headers:this.headers}}async connect(){if(!this.url)throw new Error(`[McpServer] "${this.name}" is missing a url`);if(this.type!=="http")throw new Error(`[McpServer] "${this.name}" has an unsupported type "${this.type}" \u2014 only "http" is allowed`);let e=new pr.StreamableHTTPClientTransport(new URL(this.url),{requestInit:{headers:this.headers??{}}}),n=new gr.Client({name:`open-loops-${this.name??"mcp"}`,version:"1.0.0"});return await n.connect(e),this.mcpClient=n,n}async disconnect(){await this.mcpClient?.close(),this.mcpClient=void 0}};var dr=require("tsyringe");var St=class extends _{constructor(e){super();this.mcpServerRepository=e}mcpServerRepository;async execute(e){let{payload:n,currentUser:s}=e,i=bt.fromJSON({...n});i.setCreatedBy(s),i.setOwner(s);let o=await this.mcpServerRepository.create(i);return{data:i.toJSON()}}};St=A([(0,dr.autoInjectable)()],St);var wr=require("tsyringe");var Ne=require("mongodb");var mr=require("mongodb");var Oe=class{client;logger=D;isConnected=!1;constructor(t,e){if(!t)throw new Error("[Mongo Client]: uri parameter is required");this.client=new mr.MongoClient(t,{...e,connectTimeoutMS:5e3,serverSelectionTimeoutMS:5e3}),this.logger.info("[Mongo Client] Client initialized")}async connect(){if(!this.client)throw new Error("[Mongo Client]: Client is not initialized");this.isConnected||(await this.client.connect(),this.isConnected=!0,this.logger.info("[Mongo Client]: Connected to MongoDB"))}async close(t){await this.client.close(t||!1),this.isConnected=!1}async db(t,e){try{await this.connect()}catch(n){throw this.logger.error("[Mongo Client]: Error connecting to MongoDB"),await st(`Error connecting to MongoDB: ${n.message}`,{error:n}),n}return this.client.db(t,e)}},Se=new Map;function yr(r="OPENLOOPS_DB_URI"){if(!Se.has(r)){let t=U.get(r);t&&Se.set(r,new Oe(t,{}))}return Se.get(r)}var $n=10,Kt=class{database;collection;dbClient;_where={deletedAt:null,archivedAt:null};report=st;constructor(t){let{database:e,collection:n,envvar:s}=t||{};if(!e)throw new Error("[Mongo Repository] Database name is required");if(!n)throw new Error("[Mongo Repository] Collection name is required");if(this.dbClient=yr(s),!this.dbClient)throw new Error("[Mongo Repository] Database client not found");this.database=e,this.collection=n}parseId(t){return typeof t=="string"&&Ne.ObjectId.isValid(t)?new Ne.ObjectId(t):void 0}cleanInput(t){return t?.replace(/[{}[\]()\/\\]/g,"")}clampLimit(t){let e=Number(t);return!Number.isFinite(e)||e<=0?$n:e}async findOne({where:t,select:e,options:n}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).findOne({...t,...this._where},{...e?{projection:e}:{},...n})}catch(s){throw await this.report(s),s}}async findMany({where:t,select:e,options:n}){try{let i=(await this.dbClient.db(this.database)).collection(this.collection),{page:o=1,limit:a=10}=n||{},u=this.clampLimit(a),p=+o>0?(+o-1)*u:0;return await i.find({...t,...this._where},{projection:e}).sort(n?.sortBy||{_id:-1}).skip(p).limit(u).toArray()}catch(s){throw await this.report(s),s}}async findAll({where:t,select:e}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).find({...t,...this._where},{projection:e}).toArray()}catch(n){throw await this.report(n),n}}async createOne({payload:t}){if(!t||Object.keys(t).length===0)throw new Error("[Mongo Repository] Payload is required for createOne operation");try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{insertedId:s}=await n.insertOne({...t,__v:1});return s}catch(e){throw await this.report(e),e}}async createMany({payload:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{insertedIds:s}=await n.insertMany(t);return s}catch(e){throw await this.report(e),e}}async updateOne({where:t,payload:e,options:n}){if(!t||Object.keys(t).length===0)throw new Error("[Mongo Repository] Where is required for updateOne operation");if(!e||Object.keys(e).length===0)throw new Error("[Mongo Repository] Payload is required for updateOne operation");try{let i=(await this.dbClient.db(this.database)).collection(this.collection),{_id:o,__v:a,createdAt:u,createdBy:p,toUnset:f,...h}=e,m={...h?{$set:h}:{},...f?{$unset:f}:{}};return await i.findOneAndUpdate({...t,...this._where},{$inc:{__v:1},...m},{returnDocument:"after"})}catch(s){throw await this.report(s),s}}async updateMany({where:t,payload:e}){try{return(await(await this.dbClient.db(this.database)).collection(this.collection).updateMany({...t,...this._where},{$set:e})).modifiedCount}catch(n){throw await this.report(n),n}}async deleteOne({where:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{deletedCount:s}=await n.deleteOne({...t});return s}catch(e){throw await this.report(e),e}}async deleteMany({where:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{deletedCount:s}=await n.deleteMany({...t});return s}catch(e){throw await this.report(e),e}}async count({where:t,options:e}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).countDocuments({...t,...e?.includeDeleted?{}:this._where})}catch(n){throw await this.report(n),n}}async aggregate(t){try{return await(await this.dbClient.db(this.database)).collection(this.collection).aggregate(t).toArray()}catch(e){throw await this.report(e),e}}async distinct(t,e){try{return await(await this.dbClient.db(this.database)).collection(this.collection).distinct(t,{...e,...this._where})}catch(n){throw await this.report(n),n}}};var ct=class{_=new Kt({database:U.get("OPENLOOPS_DB_NAME"),collection:"chats"});async create(t){let e=await this._.createOne({payload:t.toDocument()});return e&&t.setId(e),t}async update(t){return await this._.updateOne({where:{_id:t._id},payload:t.toFlatDocument()})}async findById(t,e){return await this._.findOne({where:{_id:this._.parseId(t)},select:e})}async deleteById(t){return await this._.deleteOne({where:{_id:this._.parseId(t)}})}async findByProps(t,e){return await this._.findMany({where:t,options:e})}};ct=A([(0,wr.autoInjectable)()],ct);var br=require("tsyringe");var Ot=class extends _{constructor(e){super();this.llmCallRepository=e}llmCallRepository;async execute(e){let{filters:n,currentUser:s}=e,{sessionId:i,messageId:o,fromDate:a,toDate:u}=n,p=s?.userId;if(!p)return{data:{}};let f=s?.timezoneOffset,h=new Date,m=new Date(h.getFullYear(),h.getMonth(),1),b=new Date(h.getFullYear(),h.getMonth()+1,0,23,59,59,999),x=a||m,y=u||b,w=[{$match:{ownerId:this.llmCallRepository._.parseId(p),...i?{sessionId:this.llmCallRepository._.parseId(i)}:{},...o?{answerId:this.llmCallRepository._.parseId(o)}:{}}},{$addFields:{fromDateUTC:{$cond:{if:{$and:[x,{$ne:[x,null]}]},then:{$dateSubtract:{startDate:new Date(x),unit:"minute",amount:f||0}},else:null}},toDateUTC:{$cond:{if:{$and:[y,{$ne:[y,null]}]},then:{$dateSubtract:{startDate:new Date(y),unit:"minute",amount:f||0}},else:null}}}},{$match:{$expr:{$and:[{$gte:["$createdAt","$fromDateUTC"]},{$lte:["$createdAt","$toDateUTC"]}]}}},{$group:{_id:"$ownerId",totalTokens:{$sum:"$response.usage.totalTokens"}}}];return{data:{...(await this.llmCallRepository._.aggregate(w))[0],tokensLimit:5e6}}}};Ot=A([(0,br.autoInjectable)()],Ot);var et=class r{name;description;destructive;parameters;handler;constructor(t){this.name=t.name,this.description=t.description,this.destructive=t.destructive??!1,this.parameters=t.parameters,this.handler=t.handler}async run(...t){return this.handler(...t)}static fromMcp(t,e,n){return new r({name:`${n.namespace}__${t.name}`,description:t.description??"",destructive:t.annotations?.destructiveHint??!1,parameters:t.inputSchema,handler:async(s={})=>{let{currentUser:i,sessionId:o,answerId:a,...u}=s;return{data:await e.callTool({name:t.name,arguments:u})}}})}};var Sr=rt(require("axios"));var Zt=class{logger=new v;async searchOnGoogle(t){let{query:e,type:n,page:s,num:i,countryCode:o,languageCode:a}=t,u=U.get("SERPER_API_KEY"),p={q:e,type:n,page:s,num:i,...o?{gl:o}:{},...a?{hl:a}:{},engine:"google"},f={method:"post",maxBodyLength:1/0,url:"https://google.serper.dev/search",headers:{"X-API-KEY":u,"Content-Type":"application/json"},data:p};try{this.logger.debug({...p},"[Serper Client] Searching on internet...");let{data:h}=await Sr.default.request(f);return this.logger.debug({...h},"[Serper Client] Search results"),h}catch(h){this.logger.error(h)}}};var Xt=new et({name:"web_search",description:"Search on web",destructive:!1,parameters:{type:"object",properties:{query:{type:"string",description:"search query"}},required:["query"]},handler:async r=>{if(!r)throw new Error("[web_search] params is required");let{currentUser:t,sessionId:e,answerId:n,...s}=r;return{data:await new Zt().searchOnGoogle(s)}}});var Er=require("tsyringe");var Ea=require("reflect-metadata"),Nr=require("tsyringe"),Ir=require("langfuse");var Or=require("tsyringe");var Qt=class r extends R{constructor(e,n,s,i,o,a){super(e);this.props=e;this.taskName=n;this.answerId=s;this.sessionId=i;this.costInUsd=o;this.response=a}props;taskName;answerId;sessionId;costInUsd;response;static fromJSON(e){return new r(e,e.taskName||void 0,R.toObjectId(e.answerId),R.toObjectId(e.sessionId),e.costInUsd?Number(e.costInUsd):void 0,e.response||void 0)}toJSON(){return{...super.toJSON(),taskName:this.taskName,answerId:this.answerId,sessionId:this.sessionId,costInUsd:this.costInUsd,response:this.response}}setResponse(e){this.response=e}setTaskName(e){this.taskName=e}};var Nt=class extends _{constructor(e){super();this.llmCallRepository=e}llmCallRepository;async execute(e){let{payload:n,currentUser:s}=e,i=Qt.fromJSON({...n});i.setCreatedBy(s),i.setOwner(s);let o=await this.llmCallRepository.create(i);return{data:i.toJSON()}}};Nt=A([(0,Or.autoInjectable)()],Nt);var te=class{logger=new v;langfuse;constructor(){process.env.OPENAI_API_KEY=U.get("OPENAI_API_KEY"),this.langfuse=new Ir.Langfuse({publicKey:U.get("LANGFUSE_PUBLIC_KEY"),secretKey:U.get("LANGFUSE_SECRET_KEY"),baseUrl:process.env.LANGFUSE_BASE_URL})}async complete(t){let{getModel:e,complete:n}=await import("@mariozechner/pi-ai"),{taskName:s,sessionId:i,answerId:o,currentUser:a,systemPrompt:u,messages:p,provider:f="openai",modelName:h="gpt-4o-mini",temperature:m=.7}=t??{},b=e(f,h),x={systemPrompt:u,messages:p};this.logger.debug({taskName:s,context:{...x,messages:this.formatMessagesForLog(p)}},"[LLM Service] context");let w=this.langfuse.trace({sessionId:i,name:s,userId:a?.userId,metadata:{taskName:s,email:a?.email,sessionId:i}}).generation({name:"llm-completion",model:h,modelParameters:{temperature:m,provider:f},input:x});try{let S=await n(b,x,{temperature:m});return w.end({output:S,usage:S.usage?{promptTokens:S.usage.input,completionTokens:S.usage.output,totalTokens:S.usage.totalTokens}:void 0}),await this.langfuse.flushAsync(),this.logger.debug({taskName:s,response:{...S,content:this.formatContentForLog(S?.content)}},"[LLM Service] Response"),await this.postResponse({taskName:s,sessionId:i,answerId:o,currentUser:a,response:S}),S}catch(S){throw w.end({level:"ERROR",statusMessage:S.message}),await this.langfuse.flushAsync(),S}}async postResponse(t){let{taskName:e,sessionId:n,answerId:s,currentUser:i,response:o}=t??{};await Nr.container.resolve(Nt).execute({payload:{taskName:e,sessionId:n,answerId:s,response:o,costInUsd:o?.usage?.cost?.total},currentUser:i})}formatContentForLog(t){return t?.map(e=>{let n=e?.text,s=qt(n),i=Object.keys(s).length>0;return{...e,text:i?s:n}})}formatMessagesForLog(t){return t.map(e=>({...e,content:this.formatContentForLog(e?.content)??e?.content}))}};var ee=class{name;version;description;temperature;systemInstructions;constructor(t){this.name=t.name,this.version=t.version,this.description=t.description,this.temperature=t.temperature,this.systemInstructions=t.systemInstructions}async run(t){let{sessionId:e,answerId:n,userMessage:s,currentUser:i,currentSession:o,contextInjection:a={},input:u={},chat:p}=t;try{let f=Er.container.resolve(te),h=o?.location?.country,m=o?.currencyCode,b=new Date,x=o?.location?.timezone,y=x?b.toLocaleString("sv-SE",{timeZone:x}):void 0,w={SYSTEM_INSTRUCTIONS:{...this.systemInstructions},CONTEXT:{now_utc:new Date().toISOString(),now_local:y,timezone:o?.location?.timezone,day_of_week:new Date().toLocaleDateString("en-US",{weekday:"long"}),...p?.state?.language?{detected_language:p.state.language}:{},...i?{user_details:{first_name:i?.firstName,last_name:i?.lastName,preferred_language:i?.language,residence_country_code:i?.preferences?.country?.isoCode,preferred_currency_code:i?.preferences?.currency?.isoCode}}:{},...o?{session_details:{current_location:{country_code:h,currency_code:m,timezone_offset:o?.timezoneOffset},client_info:{platform:o?.device?.os,brand:o?.device?.brand,model:o?.device?.model}}}:{},...a},INPUT:{...s?{user_message:s}:{},...u}},S=await f.complete({sessionId:e,answerId:n,taskName:this.name,currentUser:i,messages:[{role:"user",timestamp:Date.now(),content:[{type:"text",text:JSON.stringify(w)}]}],temperature:this.temperature??.7}),E={...this.parseJsonResponse(S),responseId:S.responseId??"",costInUsd:S?.usage?.cost?.total};return p?.addTrace({node:this.name,reasoning:E?.reasoning}),E}catch(f){throw p?.addTrace({node:this.name,reasoning:`Failed: ${f?.message??f}`}),f}}parseJsonResponse(t){let e=t?.content??[],n=e[0]?.type==="text"?e[0].text:void 0;if(!n)throw new Error("LLM response text is empty or invalid");let s=qt(n);if(!s)throw new Error("Failed to extract JSON from LLM response");return s}};var Tr="FORMATTING: Present information in a clear, professional, and friendly manner. Use Markdown formatting (lists, bold text, code blocks) when appropriate to improve readability.",Ar="LATEX_FORMATTING: When outputting mathematical formulas or equations, use inline LaTeX with single dollar signs (e.g., $G_{\\mu\\nu}$) for inline expressions, and display block LaTeX (e.g., \\[ ... \\] or $$ ... $$) for standalone equations. Never wrap LaTeX inline symbols inside Markdown bold (**).",Br="CITATION_FORMATTING: Always includes source links in Markdown format whenever available or relevant.";var Ie=new ee({name:"call-ai",version:"1.0.0",description:"Executes custom AI analysis, summarization, extraction, or transformation tasks using dynamic agent-provided instructions and input context.",temperature:.3,systemInstructions:{instruction_set:{goal:"Execute the given task according to the specified instruction prompt, analyzing or processing the provided input to produce a clear, high-quality result.",role:"Flexible AI reasoning, analysis, summarization, and task execution engine",logic_rules:["INSTRUCTION_EXECUTION: Strictly follow the custom guidelines, criteria, and role instructions defined in 'systemPrompt'.","TASK_PROCESSING: Process the provided 'input_data' or context thoroughly, applying reasoning, extraction, or summarization as requested.","REASONING_LOG: Provide a concise, step-by-step logical justification of the proposed strategy in 'reasoning' strictly in English.",Tr,Ar,Br,"STRICT_OUTPUT: Return ONLY the JSON object matching response_schema."],response_schema:{result:"string",reasoning:"string"}}}});var re=new et({name:"call_ai",description:Ie.description??"",destructive:!1,parameters:{type:"object",properties:{instructions:{type:"string",description:"System instructions or guidelines to perform the analysis, extraction, or transformation task."},input_data:{type:"string",description:"The raw text, data, or context to be processed."},temperature:{type:"number",description:"Optional sampling temperature (0.0 to 1.0) to control creativity or precision."}},required:["instructions","input_data"]},handler:async r=>{let{payload:t,currentUser:e,sessionId:n,answerId:s}=r,{instructions:i,input_data:o}=t;if(!i)throw new Error("[call_ai_tool] Param instructions is required");if(!o)throw new Error("[call_ai_tool] Param input_data is required");return{data:await Ie.run({sessionId:n,answerId:s,input:o,contextInjection:{systemPrompt:i},currentUser:e})}}});function Mn(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cr(r,t,e=.1){let i=[];for(let o of t){let a=0,u=new Set,p=o.name.replace(/_/g," "),f=o.description||"";for(let{keyword:h,weight:m}of r){if(!h||m<=0)continue;let b=h.trim(),x=Mn(b),y=new RegExp(`\\b${x}\\b`,"gi"),w=(p.match(y)||[]).length,S=(f.match(y)||[]).length;if(w>0||S>0){u.add(b);let E=Math.sqrt(w)*2.5,F=Math.sqrt(S)*1,g=(E+F)*m;a+=g}}a>=e&&i.push({toolName:o.name,score:Number(a.toFixed(4)),matchedKeywords:Array.from(u),tool:o})}return i.sort((o,a)=>a.score-o.score)}var xr={NODE_NOT_FOUND:"AGENT_NODE_NOT_FOUND"},Dn=50,Ee=class r{updateChatUseCase=Y.container.resolve(at);chatRepository=Y.container.resolve(ct);logger=new v;_loop;_tools;_mcps=[];_preHooks=[];_postHooks=[];currentChat;currentUser;currentSession;currentMessage="";answerId="";stopLoop=!1;stopRequested=!1;pendingNextNode;static async getChat(t){return Y.container.resolve(ct).findById(t)}static async interruptExecution(t,e){let n=Y.container.resolve(at);new v().debug("[AGENT] Interrupt execution triggered"),await n.execute({id:t,payload:{state:{stopRequested:!0}},currentUser:e})}static async createChatSession(t,e){if(!t)throw new Error("[AGENT] CurrentUser is required to create a new chat");let n=Y.container.resolve(mt),s=V.withDefaults(e?.name),{data:i}=await n.execute({payload:s.toJSON(),currentUser:t});if(!i)throw new Error("[AGENT] There was an error creating the chat");return V.fromJSON(i)}static async listUserChats(t,e){let n=Y.container.resolve(yt),{page:s,limit:i}=t||{},{data:o}=await n.execute({options:{page:s,limit:i},currentUser:e});return o}static async getLLMUsage(t,e){let n=Y.container.resolve(Ot),{data:s}=await n.execute({filters:t,currentUser:e});return s}static async listUserMcpServers(t,e){let n=Y.container.resolve(wt),{page:s,limit:i}=t||{},{data:o}=await n.execute({options:{page:s,limit:i},currentUser:e});return o}static async createMcpServer(t,e){if(!e)throw new Error("[AGENT] CurrentUser is required to create a new mcp server");let n=Y.container.resolve(St),{data:s}=await n.execute({payload:t,currentUser:e});if(!s)throw new Error("[AGENT] There was an error creating the mcp server");return s}constructor(t){if(!t?.loop)throw new Error("[AGENT] An AgentLoop instance is required");this._loop=t.loop,this._tools=t.tools??[],this.currentChat=V.withDefaults(this._loop.name)}get tools(){return this._tools}get mcps(){return this._mcps}get notifyOnCompletion(){return this.currentChat?.settings?.notifyOnCompletion}get lastAssistantAnswer(){return this.currentChat.lastAnswer}async run(t,e,n){try{let{chatId:s,message:i}=t||{};if(this.logger.debug(t,"[AGENT] Agent started"),!i)throw new Error("[AGENT] Message is required");if(!e)throw new Error("[AGENT] CurrentUser is required");return this.stopLoop=!1,this.stopRequested=!1,this.pendingNextNode=void 0,this.currentUser=e,this.currentSession=n,this.currentMessage=i,this.answerId=new(require("mongodb")).ObjectId().toString(),await this.preRunner(s),await this.runLoop(),await this.postRunner(),{data:this.currentChat}}catch{this.currentChat.state?.setStatus("failed"),this.currentChat.state?.setCurrentActivity("stopped"),await this.saveChat(),await this.disconnectMcpServers()}}stopAgent(){this.stopLoop=!0}addTool(t){this._tools.push(t)}addHook(t,e){t==="pre_execution"&&this._preHooks.push(e),t==="post_execution"&&this._postHooks.push(e)}async preRunner(t){let e;if(t&&(e=await this.chatRepository?.findById(t)),e)this.logger.debug("[AGENT] Existing chat found"),this.currentChat=V.fromJSON(e),this.currentChat.state?.setStopRequested(!1),this.currentChat.switchLoop(this._loop.name);else{if(this.logger.debug("[AGENT] Not existing chat found"),!this.currentUser)throw new Error("[AGENT] CurrentUser params is required");this.currentChat=await r.createChatSession(this.currentUser,this._loop)}this.currentChat.pushMessage({role:"user",content:this.currentMessage}),this.currentChat.state?.setStatus("processing"),this.currentChat.state?.setCurrentActivity("Starting..."),await this.saveChat({resetStop:!0}),await this.loadMcpServers();for(let n of this._preHooks)await n()}async postRunner(){for(let t of this._postHooks)await t();this.currentChat.state?.setCurrentActivity("stopped"),await this.saveChat(),await this.disconnectMcpServers()}async loadMcpServers(){if(!this.currentUser)return;let t=await r.listUserMcpServers({},this.currentUser);for(let e of t??[]){let n=bt.fromJSON(e);try{let s=await n.connect(),{tools:i}=await s.listTools(),o=i.map(a=>et.fromMcp(a,s,{namespace:n.name??"mcp"}));this._tools.push(...o),this._mcps.push(n)}catch(s){this.logger.error({error:s,mcpServer:n.name},"[AGENT] Failed to connect MCP server")}}}async disconnectMcpServers(){for(let t of this._mcps)await t.disconnect().catch(e=>{this.logger.error({error:e,mcpServer:t.name},"[AGENT] Failed to disconnect MCP server")});this._mcps=[]}async saveChat(t){this.currentChat?._id&&(this.logger.debug("[AGENT] Updating chat..."),t?.resetStop||(this.logger.debug("[Agent] Removing stopRequested"),delete this.currentChat.state?.stopRequested),await this.updateChatUseCase?.execute({id:this.currentChat?._id.toString(),payload:this.currentChat.toJSON(),currentUser:this.currentUser}))}async checkInterruptionRequest(){let t=this.currentChat?._id?.toString(),e=t&&await this.chatRepository.findById(t,{state:1});e&&e.state?.stopRequested&&(this.stopRequested=!0)}async runLoop(){this.logger.info("[AGENT] Agent Loop started");let t=0;for(;!this.stopLoop&&t<Dn;){if(t++,await this.checkInterruptionRequest(),this.stopRequested){this.stopLoop=!0,this.currentChat.state?.setStatus("idle"),this.resetNextNode(),this.currentChat.state?.setStopRequested(!1);break}let n=this.currentChat.activeTask?.nextNode??this.pendingNextNode??this.resolveNodeName(this._loop.initialNode),s=n?this._loop.nodes[n]:void 0;if(!s){this.logger.error({nodeName:n,loop:this._loop.name},"[AGENT] Node not found in current loop"),this.currentChat.state?.setStatus("failed"),this.currentChat.state?.setLastError({code:xr.NODE_NOT_FOUND,message:`Node "${n}" is not implemented by loop "${this._loop.name}"`,isRetryable:!1,timestamp:new Date}),this.currentChat.addTrace({node:n??"",reasoning:"Node not found"}),this.stopLoop=!0;break}if(await s.call(this._loop,this.buildRunContext()),await this.saveChat(),!this.currentChat.state||this.currentChat.state?.status==="idle"||this.currentChat.state?.status==="failed"||this.currentChat.state?.status==="awaiting_user_input"||this.currentChat.state?.status==="awaiting_user_confirmation"){this.stopLoop=!0;break}}this.logger.info("[AGENT] Agent Loop stopped")}resetNextNode(){let t=this.resolveNodeName(this._loop.initialNode),e=this.currentChat.activeTask;e?e.setNextNode(t):this.pendingNextNode=t}resolveNodeName(t){return typeof t!="function"?t:Object.entries(this._loop.nodes).find(([,e])=>e===t)?.[0]}searchTools(t,e){this.logger.debug({opts:e},"[AGENT] Searching tools");let n=e?.page??1,s=e?.limit??5,i=Cr(t,this._tools);i.length<=5&&!i.some(a=>a.toolName===Xt.name)&&i.push({toolName:Xt.name,score:.1,matchedKeywords:[],tool:Xt}),i.length<=5&&!i.some(a=>a.toolName===re.name)&&i.push({toolName:re.name,score:.1,matchedKeywords:[],tool:re});let o=(n-1)*s;return i.slice(o,o+s)}buildRunContext(){let t=this.currentChat._id?.toString()??"";return{task:this.currentChat.activeTask,chat:this.currentChat,currentUser:this.currentUser,currentSession:this.currentSession,currentMessage:this.currentMessage,answerId:this.answerId,tools:this._tools,searchTools:this.searchTools.bind(this),baseParams:{currentUser:this.currentUser,sessionId:t,answerId:this.answerId},skillParams:{sessionId:t,answerId:this.answerId,userMessage:this.currentMessage,currentUser:this.currentUser,currentSession:this.currentSession,chat:this.currentChat},reply:e=>this.currentChat.pushMessage({_id:this.answerId,role:"assistant",content:e}),setNextNode:e=>{let n=this.resolveNodeName(e),s=this.currentChat.activeTask;s?s.setNextNode(n):this.pendingNextNode=n},logger:this.logger}}};0&&(module.exports={AGENT_ERROR_CODES,Agent,AgentLoop,AgentState,AgentStatus});
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ var or=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var cr=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var A=(r,t,e,n)=>{for(var s=n>1?void 0:n?ar(t,e):t,i=r.length-1,o;i>=0;i--)(o=r[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&or(t,e,s),s};var we=class{};var be=(i=>(i.IDLE="idle",i.FAILED="failed",i.PROCESSING="processing",i.AWAITING_USER_INPUT="awaiting_user_input",i.AWAITING_USER_CONFIRMATION="awaiting_user_confirmation",i))(be||{}),lt=class r{constructor(t,e,n,s,i,o){this.status=t;this.language=e;this.lastError=n;this.activeTaskId=s;this.stopRequested=i;this.currentActivity=o}status;language;lastError;activeTaskId;stopRequested;currentActivity;static fromJSON(t={}){return new r(t.status,t.language,t.lastError,t.activeTaskId,t.stopRequested,t.currentActivity)}toJSON(){return{currentActivity:this.currentActivity,language:this.language,status:this.status,activeTaskId:this.activeTaskId,lastError:this.lastError,stopRequested:this.stopRequested}}setLanguage(t){t&&(this.language=t)}setCurrentActivity(t){this.currentActivity=t}setStatus(t){this.status=t}setActiveTaskId(t){this.activeTaskId=t}setLastError(t){this.lastError=t}setStopRequested(t=!0){this.stopRequested=t}interruptExecution(){this.stopRequested=!0}cleanContext(){this.currentActivity="",this.language="en",this.status="idle",this.activeTaskId=void 0,this.lastError=void 0,this.stopRequested=!1}};import"reflect-metadata";import{container as Z}from"tsyringe";import"dotenv/config";import Se from"pino";import lr from"pino-pretty";var ur=lr({colorize:!0}),v=class{IS_LOCAL=process.env.IS_LOCAL==="true"||process.env.NODE_ENV==="development";logger=this.IS_LOCAL?Se({level:"debug"},ur):Se({level:"info"});log(t,e,n){typeof e=="string"&&(n=e,e=void 0),this.logger[t](e??{},n||"")}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}debug(t,e){this.log("debug",t,e)}error(t,e){this.log("error",t,e)}fatal(t,e){this.log("fatal",t,e)}},D=new v;import{autoInjectable as un}from"tsyringe";var X=class{statusCode;errorMessage;errorDetails;constructor(t){this.statusCode=t.statusCode,this.errorMessage=t.errorMessage,this.errorDetails=t.errorDetails}};import*as q from"@sentry/node";import"dotenv/config";import hr from"cryptr";var Xt=class r{static instance;cache=new Map;cryptr;static getInstance(){return r.instance||(r.instance=new r),r.instance}static encrypt(t){if(!t)throw new Error("[Secret manager] Value to encrypt cannot be empty");return`ENC:${r.getInstance().cryptr.encrypt(t)}`}constructor(){if(!process.env.SSUID)throw new Error("[Secret manager] SSUID environment variable is not set");this.cryptr=new hr(process.env.SSUID,{pbkdf2Iterations:1e3,saltLength:16})}get(t){let e=process.hrtime.bigint();if(this.cache.has(t)){let i=this.cache.get(t);return this.logElapsed(t,e,!0),i}let n=this.getEnvVar(t),s=this.decryptEnvVar(n);return this.cache.set(t,s),this.logElapsed(t,e,!1),s}getEnvVar(t){let e=process.env[t];if(!e)throw new Error(`[Secret manager] Environment variable ${t} is not set`);return e}decryptEnvVar(t){if(!t)throw new Error("[Secret manager] Encrypted value cannot be empty");if(!this.isStringEncrypted(t))return D.debug("[Secret Manager] Value is not encrypted"),t;let e=t.replace(/^ENC:/,"");return this.cryptr.decrypt(e)}isStringEncrypted(t){return t?t.startsWith("ENC:"):!1}logElapsed(t,e,n){let s=process.hrtime.bigint(),i=Number(s-e)/1e6,o=n?" (cached)":"";D.debug(`[Secret Manager] GET: ${t} | ${i.toFixed(3)} ms${o}`)}},U=Xt.getInstance();var Qt=class r{static instance;enabled;static getInstance(){return r.instance||(r.instance=new r),r.instance}constructor(){let t=this.resolveDsn();if(this.enabled=!!t,!t){D.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");return}q.init({dsn:t,environment:process.env.NODE_ENV||"production",tracesSampleRate:0}),D.debug("[Sentry Client] Sentry client initialized")}async captureError(t,e){if(this.enabled){q.withScope(n=>{e&&n.setExtras(e),q.captureException(t)});try{await q.flush(2e3),D.debug("[Sentry Client] Error reported to Sentry successfully")}catch(n){D.error(n,"[Sentry Client] Failed to flush Sentry events")}}}setUser(t){this.enabled&&q.setUser({id:t})}resolveDsn(){try{return U.get("SENTRY_DSN")}catch{return}}},Oe=Qt.getInstance();var rt=async(r,t)=>{r=typeof r=="string"?new Error(r):r;let e=(r instanceof X?r?.errorMessage:r?.message)||"Unknown error",n=(r instanceof X?r?.errorDetails:r?.stack)||"No stack trace available",s=r instanceof X?r?.statusCode:500;D.debug({error:t,message:e},"[Report Error] Reporting new error");let i=process.env.IS_LOCAL==="true"||process.env.NODE_ENV==="development";try{!i&&await Oe.captureError(r,{statusCode:s,errorMessage:e,errorDetails:n,...t})}catch(o){D.error({error:o},"[Report Error] Failed to report error to Sentry")}};var $t=class{logger=new v;secretManager=U;reportError=rt;async onCatch(t){throw await rt(t),t}throwHttpError(t){throw new X(t)}throwError401(t){this.throwHttpError({statusCode:401,errorMessage:"{{invalid_token}}: {{not_authenticated_error_details}}",errorDetails:JSON.stringify(t??{})})}throwError403(t){this.throwHttpError({statusCode:403,errorMessage:"{{forbidden_error}}: {{forbidden_error_details}}",errorDetails:JSON.stringify(t??{})})}};var _=class extends $t{};import"reflect-metadata";import{randomBytes as fr}from"crypto";var gr=(()=>{let r=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>r.call(t)})();function $e(r){return gr(r)==="Uint8Array"}function pr(r){return typeof r=="object"&&r!=null&&Symbol.toStringTag in r&&(r[Symbol.toStringTag]==="ArrayBuffer"||r[Symbol.toStringTag]==="SharedArrayBuffer")}function dr(r){return r instanceof RegExp||Object.prototype.toString.call(r)==="[object RegExp]"}function Me(r){return typeof r=="object"&&r!=null&&Symbol.toStringTag in r&&r[Symbol.toStringTag]==="Map"}function mr(r){return r instanceof Date||Object.prototype.toString.call(r)==="[object Date]"}function k(r,t){return JSON.stringify(r,(e,n)=>typeof n=="bigint"?{$numberLong:`${n}`}:Me(n)?Object.fromEntries(n):n)}function yr(r){if(r!=null&&typeof r=="object"&&"stylize"in r&&typeof r.stylize=="function")return r.stylize}var oe=6,De=Symbol.for("@@mdb.bson.version"),ae=2147483647,ce=-2147483648,ke=Math.pow(2,63)-1,ve=-Math.pow(2,63),wr=Math.pow(2,53),br=-Math.pow(2,53);var je=4,us=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127}),c=class extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,e){super(t,e)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}},ie=class extends c{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${oe}.x.x`)}},Mt=class extends c{get name(){return"BSONRuntimeError"}constructor(t){super(t)}},H=class extends c{get name(){return"BSONOffsetError"}constructor(t,e,n){super(`${t}. offset: ${e}`,n),this.offset=e}},Ne,Ie;function Fe(r,t,e,n){if(n){Ne??=new TextDecoder("utf8",{fatal:!0});try{return Ne.decode(r.subarray(t,e))}catch(s){throw new c("Invalid UTF-8 string in BSON document",{cause:s})}}return Ie??=new TextDecoder("utf8",{fatal:!1}),Ie.decode(r.subarray(t,e))}function ze(r,t,e){if(r.length===0)return"";let n=e-t;if(n===0)return"";if(n>20)return null;if(n===1&&r[t]<128)return String.fromCharCode(r[t]);if(n===2&&r[t]<128&&r[t+1]<128)return String.fromCharCode(r[t])+String.fromCharCode(r[t+1]);if(n===3&&r[t]<128&&r[t+1]<128&&r[t+2]<128)return String.fromCharCode(r[t])+String.fromCharCode(r[t+1])+String.fromCharCode(r[t+2]);let s=[];for(let i=t;i<e;i++){let o=r[i];if(o>127)return null;s.push(o)}return String.fromCharCode(...s)}function Sr(r,t,e){if(t.length===0)return 0;if(t.length>25||r.length-e<t.length)return null;for(let n=0,s=e;n<t.length;n++,s++){let i=t.charCodeAt(n);if(i>127)return null;r[s]=i}return t.length}var tt={toLocalBufferType(r){if(Buffer.isBuffer(r))return r;if(ArrayBuffer.isView(r))return Buffer.from(r.buffer,r.byteOffset,r.byteLength);let t=r?.[Symbol.toStringTag]??Object.prototype.toString.call(r);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(r);throw new c("Cannot create Buffer from the passed potentialBuffer.")},allocate(r){return Buffer.alloc(r)},allocateUnsafe(r){return Buffer.allocUnsafe(r)},equals(r,t){return tt.toLocalBufferType(r).equals(t)},fromNumberArray(r){return Buffer.from(r)},fromBase64(r){return Buffer.from(r,"base64")},toBase64(r){return tt.toLocalBufferType(r).toString("base64")},fromISO88591(r){return Buffer.from(r,"binary")},toISO88591(r){return tt.toLocalBufferType(r).toString("binary")},fromHex(r){return Buffer.from(r,"hex")},toHex(r){return tt.toLocalBufferType(r).toString("hex")},toUTF8(r,t,e,n){let s=e-t<=20?ze(r,t,e):null;if(s!=null)return s;let i=tt.toLocalBufferType(r).toString("utf8",t,e);if(n){for(let o=0;o<i.length;o++)if(i.charCodeAt(o)===65533){Fe(r,t,e,!0);break}}return i},utf8ByteLength(r){return Buffer.byteLength(r,"utf8")},encodeUTF8Into(r,t,e){let n=Sr(r,t,e);return n??tt.toLocalBufferType(r).write(t,e,void 0,"utf8")},randomBytes:fr,swap32(r){return tt.toLocalBufferType(r).swap32()}};function Or(){let{navigator:r}=globalThis;return typeof r=="object"&&r.product==="ReactNative"}function Nr(r){if(r<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${r}`);return Tt.fromNumberArray(Array.from({length:r},()=>Math.floor(Math.random()*256)))}var Ir=(()=>{let{crypto:r}=globalThis;if(r!=null&&typeof r.getRandomValues=="function")return t=>r.getRandomValues(Tt.allocate(t));if(Or()){let{console:t}=globalThis;t?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Nr})(),Ee=/(\d|[a-f])/i,Tt={toLocalBufferType(r){let t=r?.[Symbol.toStringTag]??Object.prototype.toString.call(r);if(t==="Uint8Array")return r;if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(r);throw new c("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(r){if(typeof r!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(r)}`);return new Uint8Array(r)},allocateUnsafe(r){return Tt.allocate(r)},equals(r,t){if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0},fromNumberArray(r){return Uint8Array.from(r)},fromBase64(r){return Uint8Array.from(atob(r),t=>t.charCodeAt(0))},toBase64(r){return btoa(Tt.toISO88591(r))},fromISO88591(r){return Uint8Array.from(r,t=>t.charCodeAt(0)&255)},toISO88591(r){return Array.from(Uint16Array.from(r),t=>String.fromCharCode(t)).join("")},fromHex(r){let t=r.length%2===0?r:r.slice(0,r.length-1),e=[];for(let n=0;n<t.length;n+=2){let s=t[n],i=t[n+1];if(!Ee.test(s)||!Ee.test(i))break;let o=Number.parseInt(`${s}${i}`,16);e.push(o)}return Uint8Array.from(e)},toHex(r){return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(r,t,e,n){let s=e-t<=20?ze(r,t,e):null;return s??Fe(r,t,e,n)},utf8ByteLength(r){return new TextEncoder().encode(r).byteLength},encodeUTF8Into(r,t,e){let n=new TextEncoder().encode(t);return r.set(n,e),n.byteLength},randomBytes:Ir,swap32(r){if(r.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<r.length;t+=4){let e=r[t],n=r[t+1],s=r[t+2],i=r[t+3];r[t]=i,r[t+1]=s,r[t+2]=n,r[t+3]=e}return r}},Er=typeof Buffer=="function"&&Buffer.prototype?._isBuffer!==!0,d=Er?tt:Tt,$=class{get[De](){return oe}[Symbol.for("nodejs.util.inspect.custom")](t,e,n){return this.inspect(t,e,n)}},ht=new Float64Array(1),O=new Uint8Array(ht.buffer,0,8);ht[0]=-1;var te=O[7]===0,st={isBigEndian:te,getNonnegativeInt32LE(r,t){if(r[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24},getInt32LE(r,t){return r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24},getUint32LE(r,t){return r[t]+r[t+1]*256+r[t+2]*65536+r[t+3]*16777216},getUint32BE(r,t){return r[t+3]+r[t+2]*256+r[t+1]*65536+r[t]*16777216},getBigInt64LE(r,t){let e=BigInt(r[t+4]+r[t+5]*256+r[t+6]*65536+(r[t+7]<<24)),n=BigInt(r[t]+r[t+1]*256+r[t+2]*65536+r[t+3]*16777216);return(e<<BigInt(32))+n},getFloat64LE:te?(r,t)=>(O[7]=r[t],O[6]=r[t+1],O[5]=r[t+2],O[4]=r[t+3],O[3]=r[t+4],O[2]=r[t+5],O[1]=r[t+6],O[0]=r[t+7],ht[0]):(r,t)=>(O[0]=r[t],O[1]=r[t+1],O[2]=r[t+2],O[3]=r[t+3],O[4]=r[t+4],O[5]=r[t+5],O[6]=r[t+6],O[7]=r[t+7],ht[0]),setInt32BE(r,t,e){return r[t+3]=e,e>>>=8,r[t+2]=e,e>>>=8,r[t+1]=e,e>>>=8,r[t]=e,4},setInt32LE(r,t,e){return r[t]=e,e>>>=8,r[t+1]=e,e>>>=8,r[t+2]=e,e>>>=8,r[t+3]=e,4},setBigInt64LE(r,t,e){let n=BigInt(4294967295),s=Number(e&n);r[t]=s,s>>=8,r[t+1]=s,s>>=8,r[t+2]=s,s>>=8,r[t+3]=s;let i=Number(e>>BigInt(32)&n);return r[t+4]=i,i>>=8,r[t+5]=i,i>>=8,r[t+6]=i,i>>=8,r[t+7]=i,8},setFloat64LE:te?(r,t,e)=>(ht[0]=e,r[t]=O[7],r[t+1]=O[6],r[t+2]=O[5],r[t+3]=O[4],r[t+4]=O[3],r[t+5]=O[2],r[t+6]=O[1],r[t+7]=O[0],8):(r,t,e)=>(ht[0]=e,r[t]=O[0],r[t+1]=O[1],r[t+2]=O[2],r[t+3]=O[3],r[t+4]=O[4],r[t+5]=O[5],r[t+6]=O[6],r[t+7]=O[7],8)},B=class r extends ${get _bsontype(){return"Binary"}constructor(t,e){if(super(),t!=null&&typeof t=="string"&&!ArrayBuffer.isView(t)&&!pr(t)&&!Array.isArray(t))throw new c("Binary can only be constructed from Uint8Array or number[]");this.sub_type=e??r.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=d.allocate(r.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(t)?d.fromNumberArray(t):d.toLocalBufferType(t),this.position=this.buffer.byteLength)}put(t){if(typeof t=="string"&&t.length!==1)throw new c("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new c("only accepts single character Uint8Array or Array");let e;if(typeof t=="string"?e=t.charCodeAt(0):typeof t=="number"?e=t:e=t[0],e<0||e>255)throw new c("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=e;else{let n=d.allocate(r.BUFFER_SIZE+this.buffer.length);n.set(this.buffer,0),this.buffer=n,this.buffer[this.position++]=e}}write(t,e){if(e=typeof e=="number"?e:this.position,this.buffer.byteLength<e+t.length){let n=d.allocate(this.buffer.byteLength+t.length);n.set(this.buffer,0),this.buffer=n}if(ArrayBuffer.isView(t))this.buffer.set(d.toLocalBufferType(t),e),this.position=e+t.byteLength>this.position?e+t.length:this.position;else if(typeof t=="string")throw new c("input cannot be string")}read(t,e){e=e&&e>0?e:this.position;let n=t+e;return this.buffer.subarray(t,n>this.position?this.position:n)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return d.toBase64(this.buffer.subarray(0,this.position))}toString(t){return t==="hex"?d.toHex(this.buffer.subarray(0,this.position)):t==="base64"?d.toBase64(this.buffer.subarray(0,this.position)):t==="utf8"||t==="utf-8"?d.toUTF8(this.buffer,0,this.position,!1):d.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(t){t=t||{},this.sub_type===r.SUBTYPE_VECTOR&&Q(this);let e=d.toBase64(this.buffer),n=Number(this.sub_type).toString(16);return t.legacy?{$binary:e,$type:n.length===1?"0"+n:n}:{$binary:{base64:e,subType:n.length===1?"0"+n:n}}}toUUID(){if(this.sub_type===r.SUBTYPE_UUID)return new Et(this.buffer.subarray(0,this.position));throw new c(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${r.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(t,e){return new r(d.fromHex(t),e)}static createFromBase64(t,e){return new r(d.fromBase64(t),e)}static fromExtendedJSON(t,e){e=e||{};let n,s;if("$binary"in t?e.legacy&&typeof t.$binary=="string"&&"$type"in t?(s=t.$type?parseInt(t.$type,16):0,n=d.fromBase64(t.$binary)):typeof t.$binary!="string"&&(s=t.$binary.subType?parseInt(t.$binary.subType,16):0,n=d.fromBase64(t.$binary.base64)):"$uuid"in t&&(s=4,n=Et.bytesFromString(t.$uuid)),!n)throw new c(`Unexpected Binary Extended JSON format ${JSON.stringify(t)}`);return s===je?new Et(n):new r(n,s)}inspect(t,e,n){n??=k;let s=d.toBase64(this.buffer.subarray(0,this.position)),i=n(s,e),o=n(this.sub_type,e);return`Binary.createFromBase64(${i}, ${o})`}toInt8Array(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.Int8)throw new c("Binary datatype field is not Int8");return Q(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.Float32)throw new c("Binary datatype field is not Float32");Q(this);let t=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return st.isBigEndian&&d.swap32(t),new Float32Array(t.buffer)}toPackedBits(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.PackedBit)throw new c("Binary datatype field is not packed bit");return Q(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==r.SUBTYPE_VECTOR)throw new c("Binary sub_type is not Vector");if(this.buffer[0]!==r.VECTOR_TYPE.PackedBit)throw new c("Binary datatype field is not packed bit");Q(this);let e=(this.length()-2)*8-this.buffer[1],n=new Int8Array(e);for(let s=0;s<n.length;s++){let i=s/8|0,o=this.buffer[i+2],a=7-s%8,u=o>>a&1;n[s]=u}return n}static fromInt8Array(t){let e=d.allocate(t.byteLength+2);e[0]=r.VECTOR_TYPE.Int8,e[1]=0;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e.set(n,2);let s=new this(e,this.SUBTYPE_VECTOR);return Q(s),s}static fromFloat32Array(t){let e=d.allocate(t.byteLength+2);e[0]=r.VECTOR_TYPE.Float32,e[1]=0;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e.set(n,2),st.isBigEndian&&d.swap32(new Uint8Array(e.buffer,2));let s=new this(e,this.SUBTYPE_VECTOR);return Q(s),s}static fromPackedBits(t,e=0){let n=d.allocate(t.byteLength+2);n[0]=r.VECTOR_TYPE.PackedBit,n[1]=e,n.set(t,2);let s=new this(n,this.SUBTYPE_VECTOR);return Q(s),s}static fromBits(t){let e=t.length+7>>>3,n=new Uint8Array(e+2);n[0]=r.VECTOR_TYPE.PackedBit;let s=t.length%8;n[1]=s===0?0:8-s;for(let i=0;i<t.length;i++){let o=i>>>3,a=t[i];if(a!==0&&a!==1)throw new c(`Invalid bit value at ${i}: must be 0 or 1, found ${t[i]}`);if(a===0)continue;let u=7-i%8;n[o+2]|=a<<u}return new this(n,r.SUBTYPE_VECTOR)}};B.BSON_BINARY_SUBTYPE_DEFAULT=0;B.BUFFER_SIZE=256;B.SUBTYPE_DEFAULT=0;B.SUBTYPE_FUNCTION=1;B.SUBTYPE_BYTE_ARRAY=2;B.SUBTYPE_UUID_OLD=3;B.SUBTYPE_UUID=4;B.SUBTYPE_MD5=5;B.SUBTYPE_ENCRYPTED=6;B.SUBTYPE_COLUMN=7;B.SUBTYPE_SENSITIVE=8;B.SUBTYPE_VECTOR=9;B.SUBTYPE_USER_DEFINED=128;B.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function Q(r){if(r.sub_type!==B.SUBTYPE_VECTOR)return;let t=r.position,e=r.buffer[0],n=r.buffer[1];if((e===B.VECTOR_TYPE.Float32||e===B.VECTOR_TYPE.Int8)&&n!==0)throw new c("Invalid Vector: padding must be zero for int8 and float32 vectors");if(e===B.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new c("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(e===B.VECTOR_TYPE.PackedBit&&n!==0&&t===2)throw new c("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(e===B.VECTOR_TYPE.PackedBit&&n>7)throw new c(`Invalid Vector: padding must be a value between 0 and 7. found: ${n}`)}var ee=16,Tr=/^[0-9A-F]{32}$/i,Ar=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,Et=class r extends B{constructor(t){let e;if(t==null)e=r.generate();else if(t instanceof r)e=d.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===ee)e=d.toLocalBufferType(t);else if(typeof t=="string")e=r.bytesFromString(t);else throw new c("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(e,je)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[d.toHex(this.buffer.subarray(0,4)),d.toHex(this.buffer.subarray(4,6)),d.toHex(this.buffer.subarray(6,8)),d.toHex(this.buffer.subarray(8,10)),d.toHex(this.buffer.subarray(10,16))].join("-"):d.toHex(this.buffer)}toString(t){return t==="hex"?d.toHex(this.id):t==="base64"?d.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof r)return d.equals(t.id,this.id);try{return d.equals(new r(t).id,this.id)}catch{return!1}}toBinary(){return new B(this.id,B.SUBTYPE_UUID)}static generate(){let t=d.randomBytes(ee);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?r.isValidUUIDString(t):$e(t)?t.byteLength===ee:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){let e=r.bytesFromString(t);return new r(e)}static createFromBase64(t){return new r(d.fromBase64(t))}static bytesFromString(t){if(!r.isValidUUIDString(t))throw new c("UUID string representation must be 32 hex digits or canonical hyphenated representation");return d.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return Tr.test(t)||Ar.test(t)}inspect(t,e,n){return n??=k,`new UUID(${n(this.toHexString(),e)})`}},At=class r extends ${get _bsontype(){return"Code"}constructor(t,e){super(),this.code=t.toString(),this.scope=e??null}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(t){return new r(t.$code,t.$scope)}inspect(t,e,n){n??=k;let s=n(this.code,e),i=s.includes(`
2
+ `);this.scope!=null&&(s+=`,${i?`
3
+ `:" "}${n(this.scope,e)}`);let o=i&&this.scope===null;return`new Code(${i?`
4
+ `:""}${s}${o?`
5
+ `:""})`}};function Br(r){return r!=null&&typeof r=="object"&&"$id"in r&&r.$id!=null&&"$ref"in r&&typeof r.$ref=="string"&&(!("$db"in r)||"$db"in r&&typeof r.$db=="string")}var gt=class r extends ${get _bsontype(){return"DBRef"}constructor(t,e,n,s){super();let i=t.split(".");i.length===2&&(n=i.shift(),t=i.shift()),this.collection=t,this.oid=e,this.db=n,this.fields=s||{}}get namespace(){return this.collection}set namespace(t){this.collection=t}toJSON(){let t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t}toExtendedJSON(t){t=t||{};let e={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(e.$db=this.db),e=Object.assign(e,this.fields)),e}static fromExtendedJSON(t){let e=Object.assign({},t);return delete e.$ref,delete e.$id,delete e.$db,new r(t.$ref,t.$id,t.$db,e)}inspect(t,e,n){n??=k;let s=[n(this.namespace,e),n(this.oid,e),...this.db?[n(this.db,e)]:[],...Object.keys(this.fields).length>0?[n(this.fields,e)]:[]];return s[1]=n===k?`new ObjectId(${s[1]})`:s[1],`new DBRef(${s.join(", ")})`}};function Je(r){if(r==="")return r;let t=0,e=r[t]==="-",n=r[t]==="+";(n||e)&&(t+=1);let s=!1;for(;t<r.length&&r[t]==="0";++t)s=!0;return s?`${e?"-":""}${r.length===t?"0":r.slice(t)}`:n?r.slice(1):r}function Cr(r,t){t=t??10;let e="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,t);return new RegExp(`[^-+${e}]`,"i").test(r)?!1:r}var j;try{j=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var Te=65536,xr=1<<24,ft=Te*Te,Ve=ft*ft,Pr=Ve/2,Ae={},Be={},_r=20,Rr=/^(\+?0|(\+|-)?[1-9][0-9]*)$/,l=class r extends ${get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(t=0,e,n){super();let s=typeof e=="boolean"?e:!!n,i=typeof e=="number"?e:0,o=typeof t=="string"?r.fromString(t,s):typeof t=="bigint"?r.fromBigInt(t,s):{low:t|0,high:i|0,unsigned:s};this.low=o.low,this.high=o.high,this.unsigned=o.unsigned}static fromBits(t,e,n){return new r(t,e,n)}static fromInt(t,e){let n,s,i;return e?(t>>>=0,(i=0<=t&&t<256)&&(s=Be[t],s)?s:(n=r.fromBits(t,(t|0)<0?-1:0,!0),i&&(Be[t]=n),n)):(t|=0,(i=-128<=t&&t<128)&&(s=Ae[t],s)?s:(n=r.fromBits(t,t<0?-1:0,!1),i&&(Ae[t]=n),n))}static fromNumber(t,e){if(isNaN(t))return e?r.UZERO:r.ZERO;if(e){if(t<0)return r.UZERO;if(t>=Ve)return r.MAX_UNSIGNED_VALUE}else{if(t<=-9223372036854776e3)return r.MIN_VALUE;if(t+1>=Pr)return r.MAX_VALUE}return t<0?r.fromNumber(-t,e).neg():r.fromBits(t%ft|0,t/ft|0,e)}static fromBigInt(t,e){let n=BigInt(4294967295),s=BigInt(32);return new r(Number(t&n),Number(t>>s&n),e)}static _fromString(t,e,n){if(t.length===0)throw new c("empty string");if(n<2||36<n)throw new c("radix");let s;if((s=t.indexOf("-"))>0)throw new c("interior hyphen");if(s===0)return r._fromString(t.substring(1),e,n).neg();let i=r.fromNumber(Math.pow(n,8)),o=r.ZERO;for(let a=0;a<t.length;a+=8){let u=Math.min(8,t.length-a),p=parseInt(t.substring(a,a+u),n);if(u<8){let f=r.fromNumber(Math.pow(n,u));o=o.mul(f).add(r.fromNumber(p))}else o=o.mul(i),o=o.add(r.fromNumber(p))}return o.unsigned=e,o}static fromStringStrict(t,e,n){let s=!1;if(typeof e=="number"?(n=e,e=!1):s=!!e,n??=10,t.trim()!==t)throw new c(`Input: '${t}' contains leading and/or trailing whitespace`);if(!Cr(t,n))throw new c(`Input: '${t}' contains invalid characters for radix: ${n}`);let i=Je(t),o=r._fromString(i,s,n);if(o.toString(n).toLowerCase()!==i.toLowerCase())throw new c(`Input: ${t} is not representable as ${o.unsigned?"an unsigned":"a signed"} 64-bit Long ${n!=null?`with radix: ${n}`:""}`);return o}static fromString(t,e,n){let s=!1;return typeof e=="number"?(n=e,e=!1):s=!!e,n??=10,t==="NaN"&&n<24||(t==="Infinity"||t==="+Infinity"||t==="-Infinity")&&n<35?r.ZERO:r._fromString(t,s,n)}static fromBytes(t,e,n){return n?r.fromBytesLE(t,e):r.fromBytesBE(t,e)}static fromBytesLE(t,e){return new r(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)}static fromBytesBE(t,e){return new r(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}static isLong(t){return t!=null&&typeof t=="object"&&"__isLong__"in t&&t.__isLong__===!0}static fromValue(t,e){return typeof t=="number"?r.fromNumber(t,e):typeof t=="string"?r.fromString(t,e):r.fromBits(t.low,t.high,typeof e=="boolean"?e:t.unsigned)}add(t){r.isLong(t)||(t=r.fromValue(t));let e=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,a=t.high&65535,u=t.low>>>16,p=t.low&65535,f=0,h=0,m=0,b=0;return b+=i+p,m+=b>>>16,b&=65535,m+=s+u,h+=m>>>16,m&=65535,h+=n+a,f+=h>>>16,h&=65535,f+=e+o,f&=65535,r.fromBits(m<<16|b,f<<16|h,this.unsigned)}and(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low&t.low,this.high&t.high,this.unsigned)}compare(t){if(r.isLong(t)||(t=r.fromValue(t)),this.eq(t))return 0;let e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1}comp(t){return this.compare(t)}divide(t){if(r.isLong(t)||(t=r.fromValue(t)),t.isZero())throw new c("division by zero");if(j){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;let i=(this.unsigned?j.div_u:j.div_s)(this.low,this.high,t.low,t.high);return r.fromBits(i,j.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?r.UZERO:r.ZERO;let e,n,s;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return r.UZERO;if(t.gt(this.shru(1)))return r.UONE;s=r.UZERO}else{if(this.eq(r.MIN_VALUE))return t.eq(r.ONE)||t.eq(r.NEG_ONE)?r.MIN_VALUE:t.eq(r.MIN_VALUE)?r.ONE:(e=this.shr(1).div(t).shl(1),e.eq(r.ZERO)?t.isNegative()?r.ONE:r.NEG_ONE:(n=this.sub(t.mul(e)),s=e.add(n.div(t)),s));if(t.eq(r.MIN_VALUE))return this.unsigned?r.UZERO:r.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=r.ZERO}for(n=this;n.gte(t);){e=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));let i=Math.ceil(Math.log(e)/Math.LN2),o=i<=48?1:Math.pow(2,i-48),a=r.fromNumber(e),u=a.mul(t);for(;u.isNegative()||u.gt(n);)e-=o,a=r.fromNumber(e,this.unsigned),u=a.mul(t);a.isZero()&&(a=r.ONE),s=s.add(a),n=n.sub(u)}return s}div(t){return this.divide(t)}equals(t){return r.isLong(t)||(t=r.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low}eq(t){return this.equals(t)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(r.MIN_VALUE)?64:this.neg().getNumBitsAbs();let t=this.high!==0?this.high:this.low,e;for(e=31;e>0&&(t&1<<e)===0;e--);return this.high!==0?e+33:e+1}greaterThan(t){return this.comp(t)>0}gt(t){return this.greaterThan(t)}greaterThanOrEqual(t){return this.comp(t)>=0}gte(t){return this.greaterThanOrEqual(t)}ge(t){return this.greaterThanOrEqual(t)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(t){return this.comp(t)<0}lt(t){return this.lessThan(t)}lessThanOrEqual(t){return this.comp(t)<=0}lte(t){return this.lessThanOrEqual(t)}modulo(t){if(r.isLong(t)||(t=r.fromValue(t)),j){let e=(this.unsigned?j.rem_u:j.rem_s)(this.low,this.high,t.low,t.high);return r.fromBits(e,j.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))}mod(t){return this.modulo(t)}rem(t){return this.modulo(t)}multiply(t){if(this.isZero())return r.ZERO;if(r.isLong(t)||(t=r.fromValue(t)),j){let x=j.mul(this.low,this.high,t.low,t.high);return r.fromBits(x,j.get_high(),this.unsigned)}if(t.isZero())return r.ZERO;if(this.eq(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.eq(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(r.TWO_PWR_24)&&t.lt(r.TWO_PWR_24))return r.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);let e=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,a=t.high&65535,u=t.low>>>16,p=t.low&65535,f=0,h=0,m=0,b=0;return b+=i*p,m+=b>>>16,b&=65535,m+=s*p,h+=m>>>16,m&=65535,m+=i*u,h+=m>>>16,m&=65535,h+=n*p,f+=h>>>16,h&=65535,h+=s*u,f+=h>>>16,h&=65535,h+=i*a,f+=h>>>16,h&=65535,f+=e*p+n*u+s*a+i*o,f&=65535,r.fromBits(m<<16|b,f<<16|h,this.unsigned)}mul(t){return this.multiply(t)}negate(){return!this.unsigned&&this.eq(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)}neg(){return this.negate()}not(){return r.fromBits(~this.low,~this.high,this.unsigned)}notEquals(t){return!this.equals(t)}neq(t){return this.notEquals(t)}ne(t){return this.notEquals(t)}or(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low|t.low,this.high|t.high,this.unsigned)}shiftLeft(t){return r.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?r.fromBits(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):r.fromBits(0,this.low<<t-32,this.unsigned)}shl(t){return this.shiftLeft(t)}shiftRight(t){return r.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?r.fromBits(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):r.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)}shr(t){return this.shiftRight(t)}shiftRightUnsigned(t){if(r.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;{let e=this.high;if(t<32){let n=this.low;return r.fromBits(n>>>t|e<<32-t,e>>>t,this.unsigned)}else return t===32?r.fromBits(e,0,this.unsigned):r.fromBits(e>>>t-32,0,this.unsigned)}}shr_u(t){return this.shiftRightUnsigned(t)}shru(t){return this.shiftRightUnsigned(t)}subtract(t){return r.isLong(t)||(t=r.fromValue(t)),this.add(t.neg())}sub(t){return this.subtract(t)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){return this.unsigned?(this.high>>>0)*ft+(this.low>>>0):this.high*ft+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(t){return t?this.toBytesLE():this.toBytesBE()}toBytesLE(){let t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]}toBytesBE(){let t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]}toSigned(){return this.unsigned?r.fromBits(this.low,this.high,!1):this}toString(t){if(t=t||10,t<2||36<t)throw new c("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(r.MIN_VALUE)){let i=r.fromNumber(t),o=this.div(i),a=o.mul(i).sub(this);return o.toString(t)+a.toInt().toString(t)}else return"-"+this.neg().toString(t);let e=r.fromNumber(Math.pow(t,6),this.unsigned),n=this,s="";for(;;){let i=n.div(e),a=(n.sub(i.mul(e)).toInt()>>>0).toString(t);if(n=i,n.isZero())return a+s;for(;a.length<6;)a="0"+a;s=""+a+s}}toUnsigned(){return this.unsigned?this:r.fromBits(this.low,this.high,!0)}xor(t){return r.isLong(t)||(t=r.fromValue(t)),r.fromBits(this.low^t.low,this.high^t.high,this.unsigned)}eqz(){return this.isZero()}le(t){return this.lessThanOrEqual(t)}toExtendedJSON(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}}static fromExtendedJSON(t,e){let{useBigInt64:n=!1,relaxed:s=!0}={...e};if(t.$numberLong.length>_r)throw new c("$numberLong string is too long");if(!Rr.test(t.$numberLong))throw new c(`$numberLong string "${t.$numberLong}" is in an invalid format`);if(n){let o=BigInt(t.$numberLong);return BigInt.asIntN(64,o)}let i=r.fromString(t.$numberLong);return s?i.toNumber():i}inspect(t,e,n){n??=k;let s=n(this.toString(),e),i=this.unsigned?`, ${n(this.unsigned,e)}`:"";return`new Long(${s}${i})`}};l.TWO_PWR_24=l.fromInt(xr);l.MAX_UNSIGNED_VALUE=l.fromBits(-1,-1,!0);l.ZERO=l.fromInt(0);l.UZERO=l.fromInt(0,!0);l.ONE=l.fromInt(1);l.UONE=l.fromInt(1,!0);l.NEG_ONE=l.fromInt(-1);l.MAX_VALUE=l.fromBits(-1,2147483647,!1);l.MIN_VALUE=l.fromBits(0,-2147483648,!1);var Lr=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Ur=/^(\+|-)?(Infinity|inf)$/i,$r=/^(\+|-)?NaN$/i,ut=6111,Nt=-6176,Ce=6176,xe=34,re=d.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Pe=d.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),_e=d.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Mr=/^([-+])?(\d+)?$/,Dr=31,Re=16383,kr=30,vr=31;function Le(r){return!isNaN(parseInt(r,10))}function jr(r){let t=l.fromNumber(1e9),e=l.fromNumber(0);if(!r.parts[0]&&!r.parts[1]&&!r.parts[2]&&!r.parts[3])return{quotient:r,rem:e};for(let n=0;n<=3;n++)e=e.shiftLeft(32),e=e.add(new l(r.parts[n],0)),r.parts[n]=e.div(t).low,e=e.modulo(t);return{quotient:r,rem:e}}function Fr(r,t){if(!r&&!t)return{high:l.fromNumber(0),low:l.fromNumber(0)};let e=r.shiftRightUnsigned(32),n=new l(r.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new l(t.getLowBits(),0),o=e.multiply(s),a=e.multiply(i),u=n.multiply(s),p=n.multiply(i);return o=o.add(a.shiftRightUnsigned(32)),a=new l(a.getLowBits(),0).add(u).add(p.shiftRightUnsigned(32)),o=o.add(a.shiftRightUnsigned(32)),p=a.shiftLeft(32).add(new l(p.getLowBits(),0)),{high:o,low:p}}function zr(r,t){let e=r.high>>>0,n=t.high>>>0;if(e<n)return!0;if(e===n){let s=r.low>>>0,i=t.low>>>0;if(s<i)return!0}return!1}function z(r,t){throw new c(`"${r}" is not a valid Decimal128 string - ${t}`)}var Dt=class r extends ${get _bsontype(){return"Decimal128"}constructor(t){if(super(),typeof t=="string")this.bytes=r.fromString(t).bytes;else if(t instanceof Uint8Array||$e(t)){if(t.byteLength!==16)throw new c("Decimal128 must take a Buffer of 16 bytes");this.bytes=t}else throw new c("Decimal128 must take a Buffer or string")}static fromString(t){return r._fromString(t,{allowRounding:!1})}static fromStringWithRounding(t){return r._fromString(t,{allowRounding:!0})}static _fromString(t,e){let n=!1,s=!1,i=!1,o=!1,a=0,u=0,p=0,f=0,h=0,m=[0],b=0,x=0,y=0,w=0,S=new l(0,0),E=new l(0,0),F=0,g=0;if(t.length>=7e3)throw new c(""+t+" not a valid Decimal128 string");let L=t.match(Lr),sr=t.match(Ur),ir=t.match($r);if(!L&&!sr&&!ir||t.length===0)throw new c(""+t+" not a valid Decimal128 string");if(L){let T=L[2],at=L[4],ct=L[5],M=L[6];at&&M===void 0&&z(t,"missing exponent power"),at&&T===void 0&&z(t,"missing exponent base"),at===void 0&&(ct||M)&&z(t,"missing e before exponent")}if((t[g]==="+"||t[g]==="-")&&(s=!0,n=t[g++]==="-"),!Le(t[g])&&t[g]!=="."){if(t[g]==="i"||t[g]==="I")return new r(n?Pe:_e);if(t[g]==="N")return new r(re)}for(;Le(t[g])||t[g]===".";){if(t[g]==="."){i&&z(t,"contains multiple periods"),i=!0,g=g+1;continue}b<xe&&(t[g]!=="0"||o)&&(o||(h=u),o=!0,m[x++]=parseInt(t[g],10),b=b+1),o&&(p=p+1),i&&(f=f+1),u=u+1,g=g+1}if(i&&!u)throw new c(""+t+" not a valid Decimal128 string");if(t[g]==="e"||t[g]==="E"){let T=t.substr(++g).match(Mr);if(!T||!T[2])return new r(re);w=parseInt(T[0],10),g=g+T[0].length}if(t[g])return new r(re);if(!b)m[0]=0,p=1,b=1,a=0;else if(y=b-1,a=p,a!==1)for(;t[h+a-1+Number(s)+Number(i)]==="0";)a=a-1;for(w<=f&&f>w+16384?w=Nt:w=w-f;w>ut;){if(y=y+1,y>=xe){if(a===0){w=ut;break}z(t,"overflow")}w=w-1}if(e.allowRounding){for(;w<Nt||b<p;){if(y===0&&a<b){w=Nt,a=0;break}if(b<p?p=p-1:y=y-1,w<ut)w=w+1;else{if(m.join("").match(/^0+$/)){w=ut;break}z(t,"overflow")}}if(y+1<a){let T=u;i&&(h=h+1,T=T+1),s&&(h=h+1,T=T+1);let at=parseInt(t[h+y+1],10),ct=0;if(at>=5&&(ct=1,at===5)){ct=m[y]%2===1?1:0;for(let M=h+y+2;M<T;M++)if(parseInt(t[M],10)){ct=1;break}}if(ct){let M=y;for(;M>=0&&++m[M]>9;M--)if(m[M]=0,M===0)if(w<ut)w=w+1,m[M]=1;else return new r(n?Pe:_e)}}}else{for(;w<Nt||b<p;){if(y===0){if(a===0){w=Nt;break}z(t,"exponent underflow")}b<p?(t[p-1+Number(s)+Number(i)]!=="0"&&a!==0&&z(t,"inexact rounding"),p=p-1):(m[y]!==0&&z(t,"inexact rounding"),y=y-1),w<ut?w=w+1:z(t,"overflow")}y+1<a&&(i&&(h=h+1),s&&(h=h+1),parseInt(t[h+y+1],10)!==0&&z(t,"inexact rounding"))}if(S=l.fromNumber(0),E=l.fromNumber(0),a===0)S=l.fromNumber(0),E=l.fromNumber(0);else if(y<17){let T=0;for(E=l.fromNumber(m[T++]),S=new l(0,0);T<=y;T++)E=E.multiply(l.fromNumber(10)),E=E.add(l.fromNumber(m[T]))}else{let T=0;for(S=l.fromNumber(m[T++]);T<=y-17;T++)S=S.multiply(l.fromNumber(10)),S=S.add(l.fromNumber(m[T]));for(E=l.fromNumber(m[T++]);T<=y;T++)E=E.multiply(l.fromNumber(10)),E=E.add(l.fromNumber(m[T]))}let Y=Fr(S,l.fromString("100000000000000000"));Y.low=Y.low.add(E),zr(Y.low,E)&&(Y.high=Y.high.add(l.fromNumber(1))),F=w+Ce;let I={low:l.fromNumber(0),high:l.fromNumber(0)};Y.high.shiftRightUnsigned(49).and(l.fromNumber(1)).equals(l.fromNumber(1))?(I.high=I.high.or(l.fromNumber(3).shiftLeft(61)),I.high=I.high.or(l.fromNumber(F).and(l.fromNumber(16383).shiftLeft(47))),I.high=I.high.or(Y.high.and(l.fromNumber(0x7fffffffffff)))):(I.high=I.high.or(l.fromNumber(F&16383).shiftLeft(49)),I.high=I.high.or(Y.high.and(l.fromNumber(562949953421311)))),I.low=Y.low,n&&(I.high=I.high.or(l.fromString("9223372036854775808")));let P=d.allocateUnsafe(16);return g=0,P[g++]=I.low.low&255,P[g++]=I.low.low>>8&255,P[g++]=I.low.low>>16&255,P[g++]=I.low.low>>24&255,P[g++]=I.low.high&255,P[g++]=I.low.high>>8&255,P[g++]=I.low.high>>16&255,P[g++]=I.low.high>>24&255,P[g++]=I.high.low&255,P[g++]=I.high.low>>8&255,P[g++]=I.high.low>>16&255,P[g++]=I.high.low>>24&255,P[g++]=I.high.high&255,P[g++]=I.high.high>>8&255,P[g++]=I.high.high>>16&255,P[g++]=I.high.high>>24&255,new r(P)}toString(){let t,e=0,n=new Array(36);for(let g=0;g<n.length;g++)n[g]=0;let s=0,i=!1,o,a={parts:[0,0,0,0]},u,p,f=[];s=0;let h=this.bytes,m=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,b=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,x=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24,y=h[s++]|h[s++]<<8|h[s++]<<16|h[s++]<<24;s=0,{low:new l(m,b),high:new l(x,y)}.high.lessThan(l.ZERO)&&f.push("-");let S=y>>26&Dr;if(S>>3===3){if(S===kr)return f.join("")+"Infinity";if(S===vr)return"NaN";t=y>>15&Re,o=8+(y>>14&1)}else o=y>>14&7,t=y>>17&Re;let E=t-Ce;if(a.parts[0]=(y&16383)+((o&15)<<14),a.parts[1]=x,a.parts[2]=b,a.parts[3]=m,a.parts[0]===0&&a.parts[1]===0&&a.parts[2]===0&&a.parts[3]===0)i=!0;else for(p=3;p>=0;p--){let g=0,L=jr(a);if(a=L.quotient,g=L.rem.low,!!g)for(u=8;u>=0;u--)n[p*9+u]=g%10,g=Math.floor(g/10)}if(i)e=1,n[s]=0;else for(e=36;!n[s];)e=e-1,s=s+1;let F=e-1+E;if(F>=34||F<=-7||E>0){if(e>34)return f.push("0"),E>0?f.push(`E+${E}`):E<0&&f.push(`E${E}`),f.join("");f.push(`${n[s++]}`),e=e-1,e&&f.push(".");for(let g=0;g<e;g++)f.push(`${n[s++]}`);f.push("E"),F>0?f.push(`+${F}`):f.push(`${F}`)}else if(E>=0)for(let g=0;g<e;g++)f.push(`${n[s++]}`);else{let g=e+E;if(g>0)for(let L=0;L<g;L++)f.push(`${n[s++]}`);else f.push("0");for(f.push(".");g++<0;)f.push("0");for(let L=0;L<e-Math.max(g-1,0);L++)f.push(`${n[s++]}`)}return f.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(t){return r.fromString(t.$numberDecimal)}inspect(t,e,n){return n??=k,`new Decimal128(${n(this.toString(),e)})`}},Bt=class r extends ${get _bsontype(){return"Double"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t}static fromString(t){let e=Number(t);if(t==="NaN")return new r(NaN);if(t==="Infinity")return new r(1/0);if(t==="-Infinity")return new r(-1/0);if(!Number.isFinite(e))throw new c(`Input: ${t} is not representable as a Double`);if(t.trim()!==t)throw new c(`Input: '${t}' contains whitespace`);if(t==="")throw new c("Input is an empty string");if(/[^-0-9.+eE]/.test(t))throw new c(`Input: '${t}' is not in decimal or exponential notation`);return new r(e)}valueOf(){return this.value}toJSON(){return this.value}toString(t){return this.value.toString(t)}toExtendedJSON(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-0.0"}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(t,e){let n=parseFloat(t.$numberDouble);return e&&e.relaxed?n:new r(n)}inspect(t,e,n){return n??=k,`new Double(${n(this.value,e)})`}},Ct=class r extends ${get _bsontype(){return"Int32"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t|0}static fromString(t){let e=Je(t),n=Number(t);if(ae<n)throw new c(`Input: '${t}' is larger than the maximum value for Int32`);if(ce>n)throw new c(`Input: '${t}' is smaller than the minimum value for Int32`);if(Number.isSafeInteger(n)){if(n.toString()!==e)throw new c(`Input: '${t}' is not a valid Int32 string`)}else throw new c(`Input: '${t}' is not a safe integer`);return new r(n)}valueOf(){return this.value}toString(t){return this.value.toString(t)}toJSON(){return this.value}toExtendedJSON(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}}static fromExtendedJSON(t,e){return e&&e.relaxed?parseInt(t.$numberInt,10):new r(t.$numberInt)}inspect(t,e,n){return n??=k,`new Int32(${n(this.value,e)})`}},kt=class r extends ${get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new r}inspect(){return"new MaxKey()"}},vt=class r extends ${get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new r}inspect(){return"new MinKey()"}},nt=null,It=new WeakMap,W=class r extends ${get _bsontype(){return"ObjectId"}constructor(t){super();let e;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new c("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?e=d.fromHex(t.toHexString()):e=t.id}else e=t;if(e==null||typeof e=="number")this.buffer=r.generate(typeof e=="number"?e:void 0);else if(ArrayBuffer.isView(e)&&e.byteLength===12)this.buffer=d.toLocalBufferType(e);else if(typeof e=="string")if(r.validateHexString(e))this.buffer=d.fromHex(e),r.cacheHexString&&It.set(this,e);else throw new c("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new c("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(t){this.buffer=t,r.cacheHexString&&It.set(this,d.toHex(t))}static validateHexString(t){if(t?.length!==24)return!1;for(let e=0;e<24;e++){let n=t.charCodeAt(e);if(!(n>=48&&n<=57||n>=97&&n<=102||n>=65&&n<=70))return!1}return!0}toHexString(){if(r.cacheHexString){let e=It.get(this);if(e)return e}let t=d.toHex(this.id);return r.cacheHexString&&It.set(this,t),t}static getInc(){return r.index=(r.index+1)%16777215}static generate(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));let e=r.getInc(),n=d.allocateUnsafe(12);return st.setInt32BE(n,0,t),nt===null&&(nt=d.randomBytes(5)),n[4]=nt[0],n[5]=nt[1],n[6]=nt[2],n[7]=nt[3],n[8]=nt[4],n[11]=e&255,n[10]=e>>8&255,n[9]=e>>16&255,n}toString(t){return t==="base64"?d.toBase64(this.id):t==="hex"?this.toHexString():this.toHexString()}toJSON(){return this.toHexString()}static is(t){return t!=null&&typeof t=="object"&&"_bsontype"in t&&t._bsontype==="ObjectId"}equals(t){if(t==null)return!1;if(r.is(t))return this.buffer[11]===t.buffer[11]&&d.equals(this.buffer,t.buffer);if(typeof t=="string")return t.toLowerCase()===this.toHexString();if(typeof t=="object"&&typeof t.toHexString=="function"){let e=t.toHexString(),n=this.toHexString();return typeof e=="string"&&e.toLowerCase()===n}return!1}getTimestamp(){let t=new Date,e=st.getUint32BE(this.buffer,0);return t.setTime(Math.floor(e)*1e3),t}static createPk(){return new r}serializeInto(t,e){return t[e]=this.buffer[0],t[e+1]=this.buffer[1],t[e+2]=this.buffer[2],t[e+3]=this.buffer[3],t[e+4]=this.buffer[4],t[e+5]=this.buffer[5],t[e+6]=this.buffer[6],t[e+7]=this.buffer[7],t[e+8]=this.buffer[8],t[e+9]=this.buffer[9],t[e+10]=this.buffer[10],t[e+11]=this.buffer[11],12}static createFromTime(t){let e=d.allocate(12);for(let n=11;n>=4;n--)e[n]=0;return st.setInt32BE(e,0,t),new r(e)}static createFromHexString(t){if(t?.length!==24)throw new c("hex string must be 24 characters");return new r(d.fromHex(t))}static createFromBase64(t){if(t?.length!==16)throw new c("base64 string must be 16 characters");return new r(d.fromBase64(t))}static isValid(t){if(t==null)return!1;if(typeof t=="string")return r.validateHexString(t);try{return new r(t),!0}catch{return!1}}toExtendedJSON(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}}static fromExtendedJSON(t){return new r(t.$oid)}isCached(){return r.cacheHexString&&It.has(this)}inspect(t,e,n){return n??=k,`new ObjectId(${n(this.toHexString(),e)})`}};W.index=Math.floor(Math.random()*16777215);function Jr(r){return r.split("").sort().join("")}var pt=class r extends ${get _bsontype(){return"BSONRegExp"}constructor(t,e){if(super(),this.pattern=t,this.options=Jr(e??""),this.pattern.indexOf("\0")!==-1)throw new c(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\0")!==-1)throw new c(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let n=0;n<this.options.length;n++)if(!(this.options[n]==="i"||this.options[n]==="m"||this.options[n]==="x"||this.options[n]==="l"||this.options[n]==="s"||this.options[n]==="u"))throw new c(`The regular expression option [${this.options[n]}] is not supported`)}static parseOptions(t){return t?t.split("").sort().join(""):""}toExtendedJSON(t){return t=t||{},t.legacy?{$regex:this.pattern,$options:this.options}:{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(t){if("$regex"in t)if(typeof t.$regex!="string"){if(t.$regex._bsontype==="BSONRegExp")return t}else return new r(t.$regex,r.parseOptions(t.$options));if("$regularExpression"in t)return new r(t.$regularExpression.pattern,r.parseOptions(t.$regularExpression.options));throw new c(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(t)}`)}inspect(t,e,n){let s=yr(e)??(a=>a);n??=k;let i=s(n(this.pattern),"regexp"),o=s(n(this.options),"regexp");return`new BSONRegExp(${i}, ${o})`}},jt=class r extends ${get _bsontype(){return"BSONSymbol"}constructor(t){super(),this.value=t}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(t){return new r(t.$symbol)}inspect(t,e,n){return n??=k,`new BSONSymbol(${n(this.value,e)})`}},Vr=l,xt=class r extends Vr{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(t){if(t==null)super(0,0,!0);else if(typeof t=="bigint")super(t,!0);else if(l.isLong(t))super(t.low,t.high,!0);else if(typeof t=="object"&&"t"in t&&"i"in t){if(typeof t.t!="number"&&(typeof t.t!="object"||t.t._bsontype!=="Int32"))throw new c("Timestamp constructed from { t, i } must provide t as a number");if(typeof t.i!="number"&&(typeof t.i!="object"||t.i._bsontype!=="Int32"))throw new c("Timestamp constructed from { t, i } must provide i as a number");let e=Number(t.t),n=Number(t.i);if(e<0||Number.isNaN(e))throw new c("Timestamp constructed from { t, i } must provide a positive t");if(n<0||Number.isNaN(n))throw new c("Timestamp constructed from { t, i } must provide a positive i");if(e>4294967295)throw new c("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(n>4294967295)throw new c("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(n,e,!0)}else throw new c("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(t){return new r(l.fromInt(t,!0))}static fromNumber(t){return new r(l.fromNumber(t,!0))}static fromBits(t,e){return new r({i:t,t:e})}static fromString(t,e){return new r(l.fromString(t,!0,e))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(t){let e=l.isLong(t.$timestamp.i)?t.$timestamp.i.getLowBitsUnsigned():t.$timestamp.i,n=l.isLong(t.$timestamp.t)?t.$timestamp.t.getLowBitsUnsigned():t.$timestamp.t;return new r({t:n,i:e})}inspect(t,e,n){n??=k;let s=n(this.t,e),i=n(this.i,e);return`new Timestamp({ t: ${s}, i: ${i} })`}};xt.MAX_VALUE=l.MAX_UNSIGNED_VALUE;var hs=l.fromNumber(wr),fs=l.fromNumber(br);function qr(r){return r!=null&&typeof r=="object"&&"_bsontype"in r&&typeof r._bsontype=="string"}var Hr={$oid:W,$binary:B,$uuid:B,$symbol:jt,$numberInt:Ct,$numberDecimal:Dt,$numberDouble:Bt,$numberLong:l,$minKey:vt,$maxKey:kt,$regex:pt,$regularExpression:pt,$timestamp:xt};function qe(r,t={}){if(typeof r=="number"){let n=r<=ae&&r>=ce,s=r<=ke&&r>=ve;if(t.relaxed||t.legacy)return r;if(Number.isInteger(r)&&!Object.is(r,-0)){if(n)return new Ct(r);if(s)return t.useBigInt64?BigInt(r):l.fromNumber(r)}return new Bt(r)}if(r==null||typeof r!="object")return r;if(r.$undefined)return null;let e=Object.keys(r).filter(n=>n.startsWith("$")&&r[n]!=null);for(let n=0;n<e.length;n++){let s=Hr[e[n]];if(s)return s.fromExtendedJSON(r,t)}if(r.$date!=null){let n=r.$date,s=new Date;if(t.legacy)if(typeof n=="number")s.setTime(n);else if(typeof n=="string")s.setTime(Date.parse(n));else if(typeof n=="bigint")s.setTime(Number(n));else throw new Mt(`Unrecognized type for EJSON date: ${typeof n}`);else if(typeof n=="string")s.setTime(Date.parse(n));else if(l.isLong(n))s.setTime(n.toNumber());else if(typeof n=="number"&&t.relaxed)s.setTime(n);else if(typeof n=="bigint")s.setTime(Number(n));else throw new Mt(`Unrecognized type for EJSON date: ${typeof n}`);return s}if(r.$code!=null){let n=Object.assign({},r);return r.$scope&&(n.$scope=qe(r.$scope)),At.fromExtendedJSON(r)}if(Br(r)||r.$dbPointer){let n=r.$ref?r:r.$dbPointer;if(n instanceof gt)return n;let s=Object.keys(n).filter(o=>o.startsWith("$")),i=!0;if(s.forEach(o=>{["$ref","$id","$db"].indexOf(o)===-1&&(i=!1)}),i)return gt.fromExtendedJSON(n)}return r}function Yr(r,t){return r.map((e,n)=>{t.seenObjects.push({propertyName:`index ${n}`,obj:null});try{return G(e,t)}finally{t.seenObjects.pop()}})}function Ue(r){let t=r.toISOString();return r.getUTCMilliseconds()!==0?t:t.slice(0,-5)+"Z"}function G(r,t){if(r instanceof Map||Me(r)){let e=Object.create(null);for(let[n,s]of r){if(typeof n!="string")throw new c("Can only serialize maps with string keys");e[n]=s}return G(e,t)}if((typeof r=="object"||typeof r=="function")&&r!==null){let e=t.seenObjects.findIndex(n=>n.obj===r);if(e!==-1){let n=t.seenObjects.map(f=>f.propertyName),s=n.slice(0,e).map(f=>`${f} -> `).join(""),i=n[e],o=" -> "+n.slice(e+1,n.length-1).map(f=>`${f} -> `).join(""),a=n[n.length-1],u=" ".repeat(s.length+i.length/2),p="-".repeat(o.length+(i.length+a.length)/2-1);throw new c(`Converting circular structure to EJSON:
6
+ ${s}${i}${o}${a}
7
+ ${u}\\${p}/`)}t.seenObjects[t.seenObjects.length-1].obj=r}if(Array.isArray(r))return Yr(r,t);if(r===void 0)return null;if(r instanceof Date||mr(r)){let e=r.getTime(),n=e>-1&&e<2534023188e5;return t.legacy?t.relaxed&&n?{$date:r.getTime()}:{$date:Ue(r)}:t.relaxed&&n?{$date:Ue(r)}:{$date:{$numberLong:r.getTime().toString()}}}if(typeof r=="number"&&(!t.relaxed||!isFinite(r))){if(Number.isInteger(r)&&!Object.is(r,-0)){if(r>=ce&&r<=ae)return{$numberInt:r.toString()};if(r>=ve&&r<=ke)return{$numberLong:r.toString()}}return{$numberDouble:Object.is(r,-0)?"-0.0":r.toString()}}if(typeof r=="bigint")return t.relaxed?Number(BigInt.asIntN(64,r)):{$numberLong:BigInt.asIntN(64,r).toString()};if(r instanceof RegExp||dr(r)){let e=r.flags;if(e===void 0){let s=r.toString().match(/[gimuy]*$/);s&&(e=s[0])}return new pt(r.source,e).toExtendedJSON(t)}return r!=null&&typeof r=="object"?Wr(r,t):r}var Gr={Binary:r=>new B(r.value(),r.sub_type),Code:r=>new At(r.code,r.scope),DBRef:r=>new gt(r.collection||r.namespace,r.oid,r.db,r.fields),Decimal128:r=>new Dt(r.bytes),Double:r=>new Bt(r.value),Int32:r=>new Ct(r.value),Long:r=>l.fromBits(r.low!=null?r.low:r.low_,r.low!=null?r.high:r.high_,r.low!=null?r.unsigned:r.unsigned_),MaxKey:()=>new kt,MinKey:()=>new vt,ObjectId:r=>new W(r),BSONRegExp:r=>new pt(r.pattern,r.options),BSONSymbol:r=>new jt(r.value),Timestamp:r=>xt.fromBits(r.low,r.high)};function Wr(r,t){if(r==null||typeof r!="object")throw new c("not an object instance");let e=r._bsontype;if(typeof e>"u"){let n={};for(let s of Object.keys(r)){t.seenObjects.push({propertyName:s,obj:null});try{let i=G(r[s],t);s==="__proto__"?Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):n[s]=i}finally{t.seenObjects.pop()}}return n}else{if(r!=null&&typeof r=="object"&&typeof r._bsontype=="string"&&r[De]!==oe)throw new ie;if(qr(r)){let n=r;if(typeof n.toExtendedJSON!="function"){let s=Gr[r._bsontype];if(!s)throw new c("Unrecognized or invalid _bsontype: "+r._bsontype);n=s(n)}return e==="Code"&&n.scope?n=new At(n.code,G(n.scope,t)):e==="DBRef"&&n.oid&&(n=new gt(G(n.collection,t),G(n.oid,t),G(n.db,t),G(n.fields,t))),n.toExtendedJSON(t)}else throw new c("_bsontype must be a string, but was: "+typeof e)}}function He(r,t){let e={useBigInt64:t?.useBigInt64??!1,relaxed:t?.relaxed??!0,legacy:t?.legacy??!1};return JSON.parse(r,(n,s)=>{if(n.indexOf("\0")!==-1)throw new c(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(n)}`);return qe(s,e)})}function Ye(r,t,e,n){e!=null&&typeof e=="object"&&(n=e,e=0),t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t,t=void 0,e=0);let s=Object.assign({relaxed:!0,legacy:!1},n,{seenObjects:[{propertyName:"(root)",obj:null}]}),i=G(r,s);return JSON.stringify(i,t,e)}function Kr(r,t){return t=t||{},JSON.parse(Ye(r,t))}function Zr(r,t){return t=t||{},He(JSON.stringify(r),t)}var Pt=Object.create(null);Pt.parse=He;Pt.stringify=Ye;Pt.serialize=Kr;Pt.deserialize=Zr;Object.freeze(Pt);var C={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ne(r,t){try{return st.getNonnegativeInt32LE(r,t)}catch(e){throw new H("BSON size cannot be negative",t,{cause:e})}}function se(r,t){let e=t;for(;r[e]!==0;e++);if(e===r.length-1)throw new H("Null terminator not found",t);return e}function Xr(r,t=0){if(t??=0,r.length<5)throw new H(`Input must be at least 5 bytes, got ${r.length} bytes`,t);let e=ne(r,t);if(e>r.length-t)throw new H(`Parsed documentSize (${e} bytes) does not match input length (${r.length} bytes)`,t);if(r[t+e-1]!==0)throw new H("BSON documents must end in 0x00",t+e);let n=[],s=t+4;for(;s<=e+t;){let i=r[s];if(s+=1,i===0){if(s-t!==e)throw new H("Invalid 0x00 type byte",s);break}let o=s,a=se(r,s)-o;s+=a+1;let u;if(i===C.double||i===C.long||i===C.date||i===C.timestamp)u=8;else if(i===C.int)u=4;else if(i===C.objectId)u=12;else if(i===C.decimal)u=16;else if(i===C.bool)u=1;else if(i===C.null||i===C.undefined||i===C.maxKey||i===C.minKey)u=0;else if(i===C.regex)u=se(r,se(r,s)+1)+1-s;else if(i===C.object||i===C.array||i===C.javascriptWithScope)u=ne(r,s);else if(i===C.string||i===C.binData||i===C.dbPointer||i===C.javascript||i===C.symbol)u=ne(r,s)+4,i===C.binData&&(u+=1),i===C.dbPointer&&(u+=12);else throw new H(`Invalid 0x${i.toString(16).padStart(2,"0")} type byte`,s);if(u>e)throw new H("value reports length larger than document",s);n.push([i,o,a,s,u]),s+=u}return n}var Ft=Object.create(null);Ft.parseToElements=Xr;Ft.ByteUtils=d;Ft.NumberUtils=st;Object.freeze(Ft);var Qr=1024*1024*17,gs=d.allocate(Qr);function K(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}function le(r){if(Array.isArray(r))return r.map(le);if(K(r)){let t={};for(let e of Object.keys(r))t[e]=le(r[e]);return t}return r}function ue(r){let t=n=>{if(Array.isArray(n)){n.forEach(t);return}K(n)&&Object.keys(n).forEach(s=>{let i=n[s];Array.isArray(i)?t(i):K(i)?(t(i),Object.keys(i).length===0&&delete n[s]):i==null&&delete n[s]})},e=le(r);return t(e),e}function he(r,t="",e={}){if(!K(r))return{};for(let n in r)if(r.hasOwnProperty(n)){let s=t?`${t}.${n}`:n,i=r[n];K(i)?he(i,s,e):e[s]=i}return e}var tn="maskInLogs";var en=(r,t)=>Reflect.getMetadata(tn,r,t);function zt(r){if(r&&K(r)){let t={};for(let[e,n]of Object.entries(r))en(r,e)?t[e]="[HIDDEN]":Array.isArray(n)?t[e]=n.map(s=>zt(s)):typeof n=="object"?t[e]=zt(n):t[e]=n;return t}return r}var rn="adminOnly";function J(r,t){Reflect.defineMetadata(rn,!0,r,t)}var nn="ownerOnly";function Ge(r,t){Reflect.defineMetadata(nn,!0,r,t)}function Jt(r){if(!r)return{};let t=r.indexOf("{");if(t===-1)return{};let e=0,n=!1,s=!1;for(let i=t;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"?e++:o==="}"&&e--,e===0))try{return JSON.parse(r.substring(t,i+1))}catch{return{}}}return{}}import sn from"sanitize-html";function We(r=""){if(r)return sn(r,{allowedTags:[],allowedAttributes:{}})}var N=class N{_id;__v;ownerId;createdAt;createdBy;updatedAt;updatedBy;deletedAt;deletedBy;deletedReason;archivedAt;archivedBy;sharedWith;toUnset;static toObjectId(t){if(t){if(t instanceof W)return t;if(!W.isValid(t))throw new Error(`Invalid ObjectId: ${t}`);return new W(t)}}static toDate(t){if(!t)return;let e=new Date(t);if(isNaN(e.getTime()))throw new Error("{{value_must_be_a_date}}");return e}static toNumber(t){if(t!=null){if(typeof t!="number")throw new Error("{{value_must_be_a_number}}");return t}}static clean(t){return ue(t)}constructor(t){this._id=N.toObjectId(t._id),this.__v=N.toNumber(t.__v),this.ownerId=N.toObjectId(t.ownerId),this.createdAt=N.toDate(t.createdAt),this.createdBy=N.toObjectId(t.createdBy),this.updatedAt=N.toDate(t.updatedAt),this.updatedBy=N.toObjectId(t.updatedBy),this.deletedAt=N.toDate(t.deletedAt),this.deletedBy=N.toObjectId(t.deletedBy),this.deletedReason=We(t.deletedReason),this.archivedAt=N.toDate(t.archivedAt),this.archivedBy=N.toObjectId(t.archivedBy),this.sharedWith=t.sharedWith?.length?t.sharedWith.map(e=>N.toObjectId(e)):void 0}toJSON(){return{_id:this._id,__v:this.__v,ownerId:this.ownerId,createdAt:this.createdAt,createdBy:this.createdBy,updatedAt:this.updatedAt,updatedBy:this.updatedBy,deletedAt:this.deletedAt,deletedBy:this.deletedBy,deletedReason:this.deletedReason,archivedAt:this.archivedAt,archivedBy:this.archivedBy,sharedWith:this.sharedWith?.length?this.sharedWith.map(t=>t.toHexString()):void 0,toUnset:this.toUnset}}setDefaults(){}setId(t){this._id=N.toObjectId(t)}setOwner(t){t&&(this.ownerId=N.toObjectId(t.userId))}setCreatedBy(t){t&&(this.sanitize(t),this.createdAt=new Date,this.createdBy=N.toObjectId(t.userId),this.setDefaults())}setUpdatedBy(t){t&&(this.sanitize(t),this.updatedAt=new Date,this.updatedBy=N.toObjectId(t.userId))}setDeletedBy(t){t&&(this.sanitize(t),this.deletedAt=new Date,this.deletedBy=N.toObjectId(t.userId))}setArchivedBy(t){t&&(this.sanitize(t),this.archivedAt=new Date,this.archivedBy=N.toObjectId(t.userId))}toDocument(){return ue(this.toJSON())}toFlatDocument(){let{toUnset:t,...e}=this.toDocument();return{...he(e),toUnset:t}}stringify(){return JSON.stringify(zt(this),null,2)}unset(t){let e=Array.from(new Set(t.map(n=>String(n))));if(!e||!Array.isArray(e))return{};this.toUnset=e.reduce((n,s)=>(n[s]="",n),{}),t.forEach(n=>{delete this[n]})}sanitize(t){if(!t?.isAdmin())for(let e in this)Reflect.getMetadata("adminOnly",this.constructor.prototype,e)&&delete this[e]}};A([J],N.prototype,"__v",2),A([J],N.prototype,"ownerId",2),A([J],N.prototype,"createdAt",2),A([J],N.prototype,"createdBy",2),A([J],N.prototype,"updatedAt",2),A([J],N.prototype,"updatedBy",2),A([J],N.prototype,"deletedAt",2),A([J],N.prototype,"deletedBy",2),A([J],N.prototype,"archivedAt",2),A([J],N.prototype,"archivedBy",2),A([Ge],N.prototype,"sharedWith",2);var R=N;import{ObjectId as fe}from"mongodb";var _t=class r extends R{constructor(e,n,s){super(e);this.props=e;this.role=n;this.content=s}props;role;content;static factory(e){let n=e._id&&fe.isValid(e._id)?new fe(e._id):new fe;return r.fromJSON({...e,_id:n})}static fromJSON(e){return new r(e,e.role,e.content)}toJSON(){return{...super.toJSON(),role:this.role,content:this.content}}};var Vt=class r{constructor(t,e,n,s){this.props=t;this.notifyOnCompletion=e;this.modelName=n;this.loopName=s}props;notifyOnCompletion;modelName;loopName;static fromJSON(t){return new r(t,t.notifyOnCompletion,t.modelName,t.loopName)}toJSON(){return{notifyOnCompletion:this.notifyOnCompletion,modelName:this.modelName,loopName:this.loopName}}setLoopName(t){this.loopName=t}setModelName(t){this.modelName=t}setNotifyOnCompletion(t){this.notifyOnCompletion=t}};var Rt=class r{constructor(t,e){this.props=t;this.items=e}props;items;MEMORY_CONTEXT_MAX_CHARS=1e4;static fromJSON(t){return new r(t,t.items)}get length(){return this.items?JSON.stringify(this.items).length:0}get allMeta(){return this.items?.map(t=>t.meta)}toJSON(){return{items:this.items}}addContext(t){this.items??=[],this.items.push(t)}selectContext(t){return this.items?.filter(e=>(t.taskId===void 0||e.taskId===t.taskId)&&(t.name===void 0||e.meta.name===t.name))}lastContext(t){let e=this.selectContext(t);return e?.[e.length-1]}compress(){}pruneContext(){}};import{ObjectId as pe}from"mongodb";import{ObjectId as ge}from"mongodb";var Lt=class r extends R{constructor(e,n,s,i,o,a,u,p,f,h,m,b,x){super(e);this.props=e;this.name=n;this.stepId=s;this.args=i;this.dependsOn=o;this.status=a;this.output=u;this.error=p;this.reasoning=f;this.retries=h;this.author=m;this.startedAt=b;this.completedAt=x}props;name;stepId;args;dependsOn;status;output;error;reasoning;retries;author;startedAt;completedAt;static factory(e){let n=e._id&&ge.isValid(e._id)?new ge(e._id):new ge;return r.fromJSON({...e,_id:n,status:e.status??"pending"})}static fromJSON(e){return new r(e,e.name,e.stepId,e.args,e.dependsOn,e.status,e.output,e.error,e.reasoning,e.retries,e.author,e.startedAt,e.completedAt)}toJSON(){return{...super.toJSON(),name:this.name,stepId:this.stepId,args:this.args,dependsOn:this.dependsOn,status:this.status,output:this.output,error:this.error,reasoning:this.reasoning,retries:this.retries,author:this.author,startedAt:this.startedAt,completedAt:this.completedAt}}get id(){return this._id.toString()}get isReady(){return this.status==="pending"}get isTerminal(){return this.status==="completed"||this.status==="failed"}dependenciesSatisfiedBy(e){return this.dependsOn?.length?this.dependsOn.every(n=>e.has(n)):!0}markRunning(){this.status="running",this.startedAt=new Date}markCompleted(e){this.status="completed",this.output=e,this.completedAt=new Date}markFailed(e){this.status="failed",this.error=e,this.completedAt=new Date}incrementRetries(){return this.retries=(this.retries??0)+1,this.retries}resetForRetry(){this.status="pending",this.error=void 0,this.startedAt=void 0,this.completedAt=void 0}async runTool(e,n,s){if(!e)return this.markFailed({message:`Tool "${this.name}" not found`}),this;this.markRunning();try{let i=await e.run({...n,...s});this.markCompleted(i?.data)}catch(i){this.markFailed({message:i?.message??String(i)})}return this}};var on=/^\{\{step_([\w-]+)\.output\}\}$/,an=/\{\{step_([\w-]+)\.output\}\}/g,cn=/^\{\{context\.([\w.-]+)\}\}$/,ln=/\{\{context\.([\w.-]+)\}\}/g;function Ke(r){return typeof r=="object"?JSON.stringify(r):String(r)}var Ut=class r extends R{constructor(e,n,s,i,o,a,u,p,f=[]){super(e);this.props=e;this.status=n;this.goal=s;this.nextNode=i;this.threadId=o;this.previousTaskId=a;this.summary=u;this.loopName=p;this.actions=f}props;status;goal;nextNode;threadId;previousTaskId;summary;loopName;actions;static factory(e){let n=e._id&&pe.isValid(e._id)?new pe(e._id):new pe;return r.fromJSON({...e,_id:n,status:e.status??"in_progress"})}static fromJSON(e){return new r(e,e.status,e.goal,e.nextNode,e.threadId,e.previousTaskId,e.summary,e.loopName,e.actions?.map(n=>Lt.factory(n))??[])}toJSON(){return{...super.toJSON(),status:this.status,goal:this.goal,nextNode:this.nextNode,threadId:this.threadId,previousTaskId:this.previousTaskId,summary:this.summary,loopName:this.loopName,actions:this.actions.map(e=>e.toJSON())}}get id(){return this._id.toString()}addAction(e){let n=Lt.factory({name:e.name,stepId:e.stepId,args:e.args,dependsOn:e.dependsOn,reasoning:e.reasoning,author:e.author});return this.actions.push(n),n}getAction(e){return this.actions.find(n=>n.id===e||n.stepId===e)}findLastByName(e){return this.actions.slice().reverse().find(n=>n.name===e)}get readyActions(){let e=new Set(this.actions.filter(n=>n.status==="completed").flatMap(n=>[n.id,n.stepId].filter(Boolean)));return this.actions.filter(n=>n.isReady&&n.dependenciesSatisfiedBy(e))}get failedActions(){return this.actions.filter(e=>e.status==="failed")}get lastExecutedAction(){return this.actions.slice().reverse().find(e=>e.isTerminal)}setNextNode(e){this.nextNode=e}complete(e){this.status="completed",e&&(this.summary=e),this.nextNode=void 0}fail(){this.status="failed",this.nextNode=void 0}cancel(){this.status="cancelled",this.nextNode=void 0}pause(){(this.status==="in_progress"||this.status==="awaiting_user")&&(this.status="paused")}reopen(){this.status="in_progress",this.nextNode=void 0}resolveArgs(e,n){return this.resolveValue(e.args,n)}resolveValue(e,n){if(typeof e=="string"){let s=e.match(on);if(s){let o=this.findActionByRef(s[1]);return o?.output!==void 0?o.output:e}let i=e.match(cn);if(i){let o=this.readContextValue(i[1],n);return o!==void 0?o:e}return e.replace(an,(o,a)=>{let u=this.findActionByRef(a);return u?.output!==void 0?Ke(u.output):""}).replace(ln,(o,a)=>{let u=this.readContextValue(a,n);return u!==void 0?Ke(u):""})}if(Array.isArray(e))return e.map(s=>this.resolveValue(s,n));if(e!==null&&typeof e=="object"){let s={};for(let i of Object.keys(e))s[i]=this.resolveValue(e[i],n);return s}return e}findActionByRef(e){return this.actions.find(n=>n.stepId===e||n.id===e)}readContextValue(e,n){return n.selectContext({taskId:this.id,name:e})?.[0]?.content}async runTool(e,n,s,i){let o=this.addAction(e);return this.executeToolAction(o,n,s,i)}async runReadyAction(e,n,s,i){let o=this.getAction(e);if(!o)throw new Error(`[AgentTask] Action "${e}" not found`);return this.executeToolAction(o,n,s,i)}async executeToolAction(e,n,s,i){let o=this.resolveArgs(e,s),a=await e.runTool(n,o,i);return a.status==="completed"&&a.name&&s.addContext({taskId:this.id,meta:{name:a.name,type:"tool_output",shortDescription:`Output of ${a.name}`},content:a.output}),a}};var V=class r extends R{constructor(e,n,s,i,o=Rt.fromJSON({}),a=[],u){super(e);this.props=e;this.state=n;this.settings=s;this.messages=i;this.context=o;this.tasks=a;this.traces=u}props;state;settings;messages;context;tasks;traces;static withDefaults(e){let n=new lt;return n.cleanContext(),r.fromJSON({state:n.toJSON(),settings:{loopName:e}})}static fromJSON(e){return new r(e,e.state&&lt.fromJSON(e.state),e.settings&&Vt.fromJSON(e.settings),e.messages?.map(n=>_t.factory(n)),Rt.fromJSON(e.context??{}),e.tasks?.map(n=>Ut.fromJSON(n))??[],e.traces)}get lastAnswer(){return this.messages?.slice().reverse().find(e=>e.role==="assistant")?.content}get activeTask(){if(this.state?.activeTaskId)return this.tasks.find(e=>e.id===this.state?.activeTaskId)}toJSON(){return{...super.toJSON(),state:this.state?.toJSON(),settings:this.settings?.toJSON(),messages:this.messages?.map(e=>e.toJSON()),context:this.context.toJSON(),tasks:this.tasks.map(e=>e.toJSON()),traces:this.traces}}pushMessage(e){this.messages??=[],this.messages.push(_t.factory(e))}lastHistoryMessages(e=6){return this.messages?.slice(-e,-1)}addTrace(e){this.traces??=[],this.traces.push({...e,taskId:e.taskId??this.activeTask?.id,timestamp:new Date})}setAgentState(e){this.state=lt.fromJSON(e)}getTask(e){return this.tasks.find(n=>n.id===e)}lastCompletedTask(){return this.tasks.slice().reverse().find(e=>e.status==="completed"&&e.loopName===this.settings?.loopName)}createTask(e,n){this.activeTask?.status==="in_progress"&&this.activeTask.pause();let s=n?.continuesFrom?this.getTask(n.continuesFrom):void 0,i=Ut.factory({goal:e,threadId:s?.threadId,previousTaskId:n?.continuesFrom,loopName:this.settings?.loopName});return i.threadId??=i.id,this.tasks.push(i),this.state?.setActiveTaskId(i.id),i}reopenTask(e){let n=this.getTask(e);if(n)return n.reopen(),this.state?.setActiveTaskId(n.id),n}completeTask(e,n){let s=e?this.getTask(e):this.activeTask;s?.complete(n),this.clearActiveTaskIdIfMatches(s)}failTask(e){let n=e?this.getTask(e):this.activeTask;n?.fail(),this.clearActiveTaskIdIfMatches(n)}cancelTask(e){let n=e?this.getTask(e):this.activeTask;n?.cancel(),this.clearActiveTaskIdIfMatches(n)}clearActiveTaskIdIfMatches(e){e?.id===this.state?.activeTaskId&&this.state?.setActiveTaskId(void 0)}switchLoop(e){this.settings?.loopName&&this.settings.loopName!==e&&(this.activeTask?.pause(),this.state?.setActiveTaskId(void 0)),this.settings?.setLoopName(e)}};var dt=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{payload:n,currentUser:s}=e,i=V.fromJSON({...n});return i.setCreatedBy(s),i.setOwner(s),{data:await this.chatRepository.create(i)}}};dt=A([un()],dt);import{autoInjectable as hn}from"tsyringe";var it=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{payload:n,id:s,currentUser:i}=e;if(!s)throw new Error("Id is required for updating Chat");if(!n||Object.keys(n).length===0)throw new Error("Payload is required for updating Chat");let o=V.fromJSON({...n,_id:s});o.setUpdatedBy(i);let a=await this.chatRepository.update(o);if(!a)throw new Error("Chat not found or update failed");return{data:a}}};it=A([hn()],it);import{autoInjectable as fn}from"tsyringe";import{ObjectId as gn}from"mongodb";var mt=class extends _{constructor(e){super();this.chatRepository=e}chatRepository;async execute(e){let{options:n,currentUser:s}=e,{page:i=1,limit:o=10}=n||{};return{data:await this.chatRepository._.findMany({where:{ownerId:new gn(s?.userId)},options:{page:i,limit:o,sortBy:{updatedAt:-1}}})}}};mt=A([fn()],mt);import{autoInjectable as pn}from"tsyringe";import{ObjectId as dn}from"mongodb";var yt=class extends _{constructor(e){super();this.mcpServerRepository=e}mcpServerRepository;async execute(e){let{options:n,currentUser:s}=e,{page:i=1,limit:o=10}=n||{};return{data:await this.mcpServerRepository._.findMany({where:{ownerId:new dn(s?.userId)},options:{page:i,limit:o,sortBy:{updatedAt:-1}}})}}};yt=A([pn()],yt);import{Client as mn}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var wt=class r extends R{constructor(e,n,s,i,o){super(e);this.props=e;this.name=n;this.url=s;this.type=i;this.headers=o}props;name;url;type;headers;mcpClient;static fromJSON(e){return new r(e,e.name||void 0,e.url||void 0,e.type||void 0,e.headers||void 0)}toJSON(){return{...super.toJSON(),name:this.name,url:this.url,type:this.type,headers:this.headers}}async connect(){if(!this.url)throw new Error(`[McpServer] "${this.name}" is missing a url`);if(this.type!=="http")throw new Error(`[McpServer] "${this.name}" has an unsupported type "${this.type}" \u2014 only "http" is allowed`);let e=new yn(new URL(this.url),{requestInit:{headers:this.headers??{}}}),n=new mn({name:`open-loops-${this.name??"mcp"}`,version:"1.0.0"});return await n.connect(e),this.mcpClient=n,n}async disconnect(){await this.mcpClient?.close(),this.mcpClient=void 0}};import{autoInjectable as wn}from"tsyringe";var bt=class extends _{constructor(e){super();this.mcpServerRepository=e}mcpServerRepository;async execute(e){let{payload:n,currentUser:s}=e,i=wt.fromJSON({...n});i.setCreatedBy(s),i.setOwner(s);let o=await this.mcpServerRepository.create(i);return{data:i.toJSON()}}};bt=A([wn()],bt);import{autoInjectable as On}from"tsyringe";import{ObjectId as Xe}from"mongodb";import{MongoClient as bn}from"mongodb";var me=class{client;logger=D;isConnected=!1;constructor(t,e){if(!t)throw new Error("[Mongo Client]: uri parameter is required");this.client=new bn(t,{...e,connectTimeoutMS:5e3,serverSelectionTimeoutMS:5e3}),this.logger.info("[Mongo Client] Client initialized")}async connect(){if(!this.client)throw new Error("[Mongo Client]: Client is not initialized");this.isConnected||(await this.client.connect(),this.isConnected=!0,this.logger.info("[Mongo Client]: Connected to MongoDB"))}async close(t){await this.client.close(t||!1),this.isConnected=!1}async db(t,e){try{await this.connect()}catch(n){throw this.logger.error("[Mongo Client]: Error connecting to MongoDB"),await rt(`Error connecting to MongoDB: ${n.message}`,{error:n}),n}return this.client.db(t,e)}},de=new Map;function Ze(r="OPENLOOPS_DB_URI"){if(!de.has(r)){let t=U.get(r);t&&de.set(r,new me(t,{}))}return de.get(r)}var Sn=10,qt=class{database;collection;dbClient;_where={deletedAt:null,archivedAt:null};report=rt;constructor(t){let{database:e,collection:n,envvar:s}=t||{};if(!e)throw new Error("[Mongo Repository] Database name is required");if(!n)throw new Error("[Mongo Repository] Collection name is required");if(this.dbClient=Ze(s),!this.dbClient)throw new Error("[Mongo Repository] Database client not found");this.database=e,this.collection=n}parseId(t){return typeof t=="string"&&Xe.isValid(t)?new Xe(t):void 0}cleanInput(t){return t?.replace(/[{}[\]()\/\\]/g,"")}clampLimit(t){let e=Number(t);return!Number.isFinite(e)||e<=0?Sn:e}async findOne({where:t,select:e,options:n}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).findOne({...t,...this._where},{...e?{projection:e}:{},...n})}catch(s){throw await this.report(s),s}}async findMany({where:t,select:e,options:n}){try{let i=(await this.dbClient.db(this.database)).collection(this.collection),{page:o=1,limit:a=10}=n||{},u=this.clampLimit(a),p=+o>0?(+o-1)*u:0;return await i.find({...t,...this._where},{projection:e}).sort(n?.sortBy||{_id:-1}).skip(p).limit(u).toArray()}catch(s){throw await this.report(s),s}}async findAll({where:t,select:e}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).find({...t,...this._where},{projection:e}).toArray()}catch(n){throw await this.report(n),n}}async createOne({payload:t}){if(!t||Object.keys(t).length===0)throw new Error("[Mongo Repository] Payload is required for createOne operation");try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{insertedId:s}=await n.insertOne({...t,__v:1});return s}catch(e){throw await this.report(e),e}}async createMany({payload:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{insertedIds:s}=await n.insertMany(t);return s}catch(e){throw await this.report(e),e}}async updateOne({where:t,payload:e,options:n}){if(!t||Object.keys(t).length===0)throw new Error("[Mongo Repository] Where is required for updateOne operation");if(!e||Object.keys(e).length===0)throw new Error("[Mongo Repository] Payload is required for updateOne operation");try{let i=(await this.dbClient.db(this.database)).collection(this.collection),{_id:o,__v:a,createdAt:u,createdBy:p,toUnset:f,...h}=e,m={...h?{$set:h}:{},...f?{$unset:f}:{}};return await i.findOneAndUpdate({...t,...this._where},{$inc:{__v:1},...m},{returnDocument:"after"})}catch(s){throw await this.report(s),s}}async updateMany({where:t,payload:e}){try{return(await(await this.dbClient.db(this.database)).collection(this.collection).updateMany({...t,...this._where},{$set:e})).modifiedCount}catch(n){throw await this.report(n),n}}async deleteOne({where:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{deletedCount:s}=await n.deleteOne({...t});return s}catch(e){throw await this.report(e),e}}async deleteMany({where:t}){try{let n=(await this.dbClient.db(this.database)).collection(this.collection),{deletedCount:s}=await n.deleteMany({...t});return s}catch(e){throw await this.report(e),e}}async count({where:t,options:e}){try{return await(await this.dbClient.db(this.database)).collection(this.collection).countDocuments({...t,...e?.includeDeleted?{}:this._where})}catch(n){throw await this.report(n),n}}async aggregate(t){try{return await(await this.dbClient.db(this.database)).collection(this.collection).aggregate(t).toArray()}catch(e){throw await this.report(e),e}}async distinct(t,e){try{return await(await this.dbClient.db(this.database)).collection(this.collection).distinct(t,{...e,...this._where})}catch(n){throw await this.report(n),n}}};var ot=class{_=new qt({database:U.get("OPENLOOPS_DB_NAME"),collection:"chats"});async create(t){let e=await this._.createOne({payload:t.toDocument()});return e&&t.setId(e),t}async update(t){return await this._.updateOne({where:{_id:t._id},payload:t.toFlatDocument()})}async findById(t,e){return await this._.findOne({where:{_id:this._.parseId(t)},select:e})}async deleteById(t){return await this._.deleteOne({where:{_id:this._.parseId(t)}})}async findByProps(t,e){return await this._.findMany({where:t,options:e})}};ot=A([On()],ot);import{autoInjectable as Nn}from"tsyringe";var St=class extends _{constructor(e){super();this.llmCallRepository=e}llmCallRepository;async execute(e){let{filters:n,currentUser:s}=e,{sessionId:i,messageId:o,fromDate:a,toDate:u}=n,p=s?.userId;if(!p)return{data:{}};let f=s?.timezoneOffset,h=new Date,m=new Date(h.getFullYear(),h.getMonth(),1),b=new Date(h.getFullYear(),h.getMonth()+1,0,23,59,59,999),x=a||m,y=u||b,w=[{$match:{ownerId:this.llmCallRepository._.parseId(p),...i?{sessionId:this.llmCallRepository._.parseId(i)}:{},...o?{answerId:this.llmCallRepository._.parseId(o)}:{}}},{$addFields:{fromDateUTC:{$cond:{if:{$and:[x,{$ne:[x,null]}]},then:{$dateSubtract:{startDate:new Date(x),unit:"minute",amount:f||0}},else:null}},toDateUTC:{$cond:{if:{$and:[y,{$ne:[y,null]}]},then:{$dateSubtract:{startDate:new Date(y),unit:"minute",amount:f||0}},else:null}}}},{$match:{$expr:{$and:[{$gte:["$createdAt","$fromDateUTC"]},{$lte:["$createdAt","$toDateUTC"]}]}}},{$group:{_id:"$ownerId",totalTokens:{$sum:"$response.usage.totalTokens"}}}];return{data:{...(await this.llmCallRepository._.aggregate(w))[0],tokensLimit:5e6}}}};St=A([Nn()],St);var et=class r{name;description;destructive;parameters;handler;constructor(t){this.name=t.name,this.description=t.description,this.destructive=t.destructive??!1,this.parameters=t.parameters,this.handler=t.handler}async run(...t){return this.handler(...t)}static fromMcp(t,e,n){return new r({name:`${n.namespace}__${t.name}`,description:t.description??"",destructive:t.annotations?.destructiveHint??!1,parameters:t.inputSchema,handler:async(s={})=>{let{currentUser:i,sessionId:o,answerId:a,...u}=s;return{data:await e.callTool({name:t.name,arguments:u})}}})}};import In from"axios";var Ht=class{logger=new v;async searchOnGoogle(t){let{query:e,type:n,page:s,num:i,countryCode:o,languageCode:a}=t,u=U.get("SERPER_API_KEY"),p={q:e,type:n,page:s,num:i,...o?{gl:o}:{},...a?{hl:a}:{},engine:"google"},f={method:"post",maxBodyLength:1/0,url:"https://google.serper.dev/search",headers:{"X-API-KEY":u,"Content-Type":"application/json"},data:p};try{this.logger.debug({...p},"[Serper Client] Searching on internet...");let{data:h}=await In.request(f);return this.logger.debug({...h},"[Serper Client] Search results"),h}catch(h){this.logger.error(h)}}};var Yt=new et({name:"web_search",description:"Search on web",destructive:!1,parameters:{type:"object",properties:{query:{type:"string",description:"search query"}},required:["query"]},handler:async r=>{if(!r)throw new Error("[web_search] params is required");let{currentUser:t,sessionId:e,answerId:n,...s}=r;return{data:await new Ht().searchOnGoogle(s)}}});import{container as Bn}from"tsyringe";import"reflect-metadata";import{container as Tn}from"tsyringe";import{Langfuse as An}from"langfuse";import{autoInjectable as En}from"tsyringe";var Gt=class r extends R{constructor(e,n,s,i,o,a){super(e);this.props=e;this.taskName=n;this.answerId=s;this.sessionId=i;this.costInUsd=o;this.response=a}props;taskName;answerId;sessionId;costInUsd;response;static fromJSON(e){return new r(e,e.taskName||void 0,R.toObjectId(e.answerId),R.toObjectId(e.sessionId),e.costInUsd?Number(e.costInUsd):void 0,e.response||void 0)}toJSON(){return{...super.toJSON(),taskName:this.taskName,answerId:this.answerId,sessionId:this.sessionId,costInUsd:this.costInUsd,response:this.response}}setResponse(e){this.response=e}setTaskName(e){this.taskName=e}};var Ot=class extends _{constructor(e){super();this.llmCallRepository=e}llmCallRepository;async execute(e){let{payload:n,currentUser:s}=e,i=Gt.fromJSON({...n});i.setCreatedBy(s),i.setOwner(s);let o=await this.llmCallRepository.create(i);return{data:i.toJSON()}}};Ot=A([En()],Ot);var Wt=class{logger=new v;langfuse;constructor(){process.env.OPENAI_API_KEY=U.get("OPENAI_API_KEY"),this.langfuse=new An({publicKey:U.get("LANGFUSE_PUBLIC_KEY"),secretKey:U.get("LANGFUSE_SECRET_KEY"),baseUrl:process.env.LANGFUSE_BASE_URL})}async complete(t){let{getModel:e,complete:n}=await import("@mariozechner/pi-ai"),{taskName:s,sessionId:i,answerId:o,currentUser:a,systemPrompt:u,messages:p,provider:f="openai",modelName:h="gpt-4o-mini",temperature:m=.7}=t??{},b=e(f,h),x={systemPrompt:u,messages:p};this.logger.debug({taskName:s,context:{...x,messages:this.formatMessagesForLog(p)}},"[LLM Service] context");let w=this.langfuse.trace({sessionId:i,name:s,userId:a?.userId,metadata:{taskName:s,email:a?.email,sessionId:i}}).generation({name:"llm-completion",model:h,modelParameters:{temperature:m,provider:f},input:x});try{let S=await n(b,x,{temperature:m});return w.end({output:S,usage:S.usage?{promptTokens:S.usage.input,completionTokens:S.usage.output,totalTokens:S.usage.totalTokens}:void 0}),await this.langfuse.flushAsync(),this.logger.debug({taskName:s,response:{...S,content:this.formatContentForLog(S?.content)}},"[LLM Service] Response"),await this.postResponse({taskName:s,sessionId:i,answerId:o,currentUser:a,response:S}),S}catch(S){throw w.end({level:"ERROR",statusMessage:S.message}),await this.langfuse.flushAsync(),S}}async postResponse(t){let{taskName:e,sessionId:n,answerId:s,currentUser:i,response:o}=t??{};await Tn.resolve(Ot).execute({payload:{taskName:e,sessionId:n,answerId:s,response:o,costInUsd:o?.usage?.cost?.total},currentUser:i})}formatContentForLog(t){return t?.map(e=>{let n=e?.text,s=Jt(n),i=Object.keys(s).length>0;return{...e,text:i?s:n}})}formatMessagesForLog(t){return t.map(e=>({...e,content:this.formatContentForLog(e?.content)??e?.content}))}};var Kt=class{name;version;description;temperature;systemInstructions;constructor(t){this.name=t.name,this.version=t.version,this.description=t.description,this.temperature=t.temperature,this.systemInstructions=t.systemInstructions}async run(t){let{sessionId:e,answerId:n,userMessage:s,currentUser:i,currentSession:o,contextInjection:a={},input:u={},chat:p}=t;try{let f=Bn.resolve(Wt),h=o?.location?.country,m=o?.currencyCode,b=new Date,x=o?.location?.timezone,y=x?b.toLocaleString("sv-SE",{timeZone:x}):void 0,w={SYSTEM_INSTRUCTIONS:{...this.systemInstructions},CONTEXT:{now_utc:new Date().toISOString(),now_local:y,timezone:o?.location?.timezone,day_of_week:new Date().toLocaleDateString("en-US",{weekday:"long"}),...p?.state?.language?{detected_language:p.state.language}:{},...i?{user_details:{first_name:i?.firstName,last_name:i?.lastName,preferred_language:i?.language,residence_country_code:i?.preferences?.country?.isoCode,preferred_currency_code:i?.preferences?.currency?.isoCode}}:{},...o?{session_details:{current_location:{country_code:h,currency_code:m,timezone_offset:o?.timezoneOffset},client_info:{platform:o?.device?.os,brand:o?.device?.brand,model:o?.device?.model}}}:{},...a},INPUT:{...s?{user_message:s}:{},...u}},S=await f.complete({sessionId:e,answerId:n,taskName:this.name,currentUser:i,messages:[{role:"user",timestamp:Date.now(),content:[{type:"text",text:JSON.stringify(w)}]}],temperature:this.temperature??.7}),E={...this.parseJsonResponse(S),responseId:S.responseId??"",costInUsd:S?.usage?.cost?.total};return p?.addTrace({node:this.name,reasoning:E?.reasoning}),E}catch(f){throw p?.addTrace({node:this.name,reasoning:`Failed: ${f?.message??f}`}),f}}parseJsonResponse(t){let e=t?.content??[],n=e[0]?.type==="text"?e[0].text:void 0;if(!n)throw new Error("LLM response text is empty or invalid");let s=Jt(n);if(!s)throw new Error("Failed to extract JSON from LLM response");return s}};var Qe="FORMATTING: Present information in a clear, professional, and friendly manner. Use Markdown formatting (lists, bold text, code blocks) when appropriate to improve readability.",tr="LATEX_FORMATTING: When outputting mathematical formulas or equations, use inline LaTeX with single dollar signs (e.g., $G_{\\mu\\nu}$) for inline expressions, and display block LaTeX (e.g., \\[ ... \\] or $$ ... $$) for standalone equations. Never wrap LaTeX inline symbols inside Markdown bold (**).",er="CITATION_FORMATTING: Always includes source links in Markdown format whenever available or relevant.";var ye=new Kt({name:"call-ai",version:"1.0.0",description:"Executes custom AI analysis, summarization, extraction, or transformation tasks using dynamic agent-provided instructions and input context.",temperature:.3,systemInstructions:{instruction_set:{goal:"Execute the given task according to the specified instruction prompt, analyzing or processing the provided input to produce a clear, high-quality result.",role:"Flexible AI reasoning, analysis, summarization, and task execution engine",logic_rules:["INSTRUCTION_EXECUTION: Strictly follow the custom guidelines, criteria, and role instructions defined in 'systemPrompt'.","TASK_PROCESSING: Process the provided 'input_data' or context thoroughly, applying reasoning, extraction, or summarization as requested.","REASONING_LOG: Provide a concise, step-by-step logical justification of the proposed strategy in 'reasoning' strictly in English.",Qe,tr,er,"STRICT_OUTPUT: Return ONLY the JSON object matching response_schema."],response_schema:{result:"string",reasoning:"string"}}}});var Zt=new et({name:"call_ai",description:ye.description??"",destructive:!1,parameters:{type:"object",properties:{instructions:{type:"string",description:"System instructions or guidelines to perform the analysis, extraction, or transformation task."},input_data:{type:"string",description:"The raw text, data, or context to be processed."},temperature:{type:"number",description:"Optional sampling temperature (0.0 to 1.0) to control creativity or precision."}},required:["instructions","input_data"]},handler:async r=>{let{payload:t,currentUser:e,sessionId:n,answerId:s}=r,{instructions:i,input_data:o}=t;if(!i)throw new Error("[call_ai_tool] Param instructions is required");if(!o)throw new Error("[call_ai_tool] Param input_data is required");return{data:await ye.run({sessionId:n,answerId:s,input:o,contextInjection:{systemPrompt:i},currentUser:e})}}});function Cn(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rr(r,t,e=.1){let i=[];for(let o of t){let a=0,u=new Set,p=o.name.replace(/_/g," "),f=o.description||"";for(let{keyword:h,weight:m}of r){if(!h||m<=0)continue;let b=h.trim(),x=Cn(b),y=new RegExp(`\\b${x}\\b`,"gi"),w=(p.match(y)||[]).length,S=(f.match(y)||[]).length;if(w>0||S>0){u.add(b);let E=Math.sqrt(w)*2.5,F=Math.sqrt(S)*1,g=(E+F)*m;a+=g}}a>=e&&i.push({toolName:o.name,score:Number(a.toFixed(4)),matchedKeywords:Array.from(u),tool:o})}return i.sort((o,a)=>a.score-o.score)}var xn={NODE_NOT_FOUND:"AGENT_NODE_NOT_FOUND"},Pn=50,nr=class r{updateChatUseCase=Z.resolve(it);chatRepository=Z.resolve(ot);logger=new v;_loop;_tools;_mcps=[];_preHooks=[];_postHooks=[];currentChat;currentUser;currentSession;currentMessage="";answerId="";stopLoop=!1;stopRequested=!1;pendingNextNode;static async getChat(t){return Z.resolve(ot).findById(t)}static async interruptExecution(t,e){let n=Z.resolve(it);new v().debug("[AGENT] Interrupt execution triggered"),await n.execute({id:t,payload:{state:{stopRequested:!0}},currentUser:e})}static async createChatSession(t,e){if(!t)throw new Error("[AGENT] CurrentUser is required to create a new chat");let n=Z.resolve(dt),s=V.withDefaults(e?.name),{data:i}=await n.execute({payload:s.toJSON(),currentUser:t});if(!i)throw new Error("[AGENT] There was an error creating the chat");return V.fromJSON(i)}static async listUserChats(t,e){let n=Z.resolve(mt),{page:s,limit:i}=t||{},{data:o}=await n.execute({options:{page:s,limit:i},currentUser:e});return o}static async getLLMUsage(t,e){let n=Z.resolve(St),{data:s}=await n.execute({filters:t,currentUser:e});return s}static async listUserMcpServers(t,e){let n=Z.resolve(yt),{page:s,limit:i}=t||{},{data:o}=await n.execute({options:{page:s,limit:i},currentUser:e});return o}static async createMcpServer(t,e){if(!e)throw new Error("[AGENT] CurrentUser is required to create a new mcp server");let n=Z.resolve(bt),{data:s}=await n.execute({payload:t,currentUser:e});if(!s)throw new Error("[AGENT] There was an error creating the mcp server");return s}constructor(t){if(!t?.loop)throw new Error("[AGENT] An AgentLoop instance is required");this._loop=t.loop,this._tools=t.tools??[],this.currentChat=V.withDefaults(this._loop.name)}get tools(){return this._tools}get mcps(){return this._mcps}get notifyOnCompletion(){return this.currentChat?.settings?.notifyOnCompletion}get lastAssistantAnswer(){return this.currentChat.lastAnswer}async run(t,e,n){try{let{chatId:s,message:i}=t||{};if(this.logger.debug(t,"[AGENT] Agent started"),!i)throw new Error("[AGENT] Message is required");if(!e)throw new Error("[AGENT] CurrentUser is required");return this.stopLoop=!1,this.stopRequested=!1,this.pendingNextNode=void 0,this.currentUser=e,this.currentSession=n,this.currentMessage=i,this.answerId=new(cr("mongodb")).ObjectId().toString(),await this.preRunner(s),await this.runLoop(),await this.postRunner(),{data:this.currentChat}}catch{this.currentChat.state?.setStatus("failed"),this.currentChat.state?.setCurrentActivity("stopped"),await this.saveChat(),await this.disconnectMcpServers()}}stopAgent(){this.stopLoop=!0}addTool(t){this._tools.push(t)}addHook(t,e){t==="pre_execution"&&this._preHooks.push(e),t==="post_execution"&&this._postHooks.push(e)}async preRunner(t){let e;if(t&&(e=await this.chatRepository?.findById(t)),e)this.logger.debug("[AGENT] Existing chat found"),this.currentChat=V.fromJSON(e),this.currentChat.state?.setStopRequested(!1),this.currentChat.switchLoop(this._loop.name);else{if(this.logger.debug("[AGENT] Not existing chat found"),!this.currentUser)throw new Error("[AGENT] CurrentUser params is required");this.currentChat=await r.createChatSession(this.currentUser,this._loop)}this.currentChat.pushMessage({role:"user",content:this.currentMessage}),this.currentChat.state?.setStatus("processing"),this.currentChat.state?.setCurrentActivity("Starting..."),await this.saveChat({resetStop:!0}),await this.loadMcpServers();for(let n of this._preHooks)await n()}async postRunner(){for(let t of this._postHooks)await t();this.currentChat.state?.setCurrentActivity("stopped"),await this.saveChat(),await this.disconnectMcpServers()}async loadMcpServers(){if(!this.currentUser)return;let t=await r.listUserMcpServers({},this.currentUser);for(let e of t??[]){let n=wt.fromJSON(e);try{let s=await n.connect(),{tools:i}=await s.listTools(),o=i.map(a=>et.fromMcp(a,s,{namespace:n.name??"mcp"}));this._tools.push(...o),this._mcps.push(n)}catch(s){this.logger.error({error:s,mcpServer:n.name},"[AGENT] Failed to connect MCP server")}}}async disconnectMcpServers(){for(let t of this._mcps)await t.disconnect().catch(e=>{this.logger.error({error:e,mcpServer:t.name},"[AGENT] Failed to disconnect MCP server")});this._mcps=[]}async saveChat(t){this.currentChat?._id&&(this.logger.debug("[AGENT] Updating chat..."),t?.resetStop||(this.logger.debug("[Agent] Removing stopRequested"),delete this.currentChat.state?.stopRequested),await this.updateChatUseCase?.execute({id:this.currentChat?._id.toString(),payload:this.currentChat.toJSON(),currentUser:this.currentUser}))}async checkInterruptionRequest(){let t=this.currentChat?._id?.toString(),e=t&&await this.chatRepository.findById(t,{state:1});e&&e.state?.stopRequested&&(this.stopRequested=!0)}async runLoop(){this.logger.info("[AGENT] Agent Loop started");let t=0;for(;!this.stopLoop&&t<Pn;){if(t++,await this.checkInterruptionRequest(),this.stopRequested){this.stopLoop=!0,this.currentChat.state?.setStatus("idle"),this.resetNextNode(),this.currentChat.state?.setStopRequested(!1);break}let n=this.currentChat.activeTask?.nextNode??this.pendingNextNode??this.resolveNodeName(this._loop.initialNode),s=n?this._loop.nodes[n]:void 0;if(!s){this.logger.error({nodeName:n,loop:this._loop.name},"[AGENT] Node not found in current loop"),this.currentChat.state?.setStatus("failed"),this.currentChat.state?.setLastError({code:xn.NODE_NOT_FOUND,message:`Node "${n}" is not implemented by loop "${this._loop.name}"`,isRetryable:!1,timestamp:new Date}),this.currentChat.addTrace({node:n??"",reasoning:"Node not found"}),this.stopLoop=!0;break}if(await s.call(this._loop,this.buildRunContext()),await this.saveChat(),!this.currentChat.state||this.currentChat.state?.status==="idle"||this.currentChat.state?.status==="failed"||this.currentChat.state?.status==="awaiting_user_input"||this.currentChat.state?.status==="awaiting_user_confirmation"){this.stopLoop=!0;break}}this.logger.info("[AGENT] Agent Loop stopped")}resetNextNode(){let t=this.resolveNodeName(this._loop.initialNode),e=this.currentChat.activeTask;e?e.setNextNode(t):this.pendingNextNode=t}resolveNodeName(t){return typeof t!="function"?t:Object.entries(this._loop.nodes).find(([,e])=>e===t)?.[0]}searchTools(t,e){this.logger.debug({opts:e},"[AGENT] Searching tools");let n=e?.page??1,s=e?.limit??5,i=rr(t,this._tools);i.length<=5&&!i.some(a=>a.toolName===Yt.name)&&i.push({toolName:Yt.name,score:.1,matchedKeywords:[],tool:Yt}),i.length<=5&&!i.some(a=>a.toolName===Zt.name)&&i.push({toolName:Zt.name,score:.1,matchedKeywords:[],tool:Zt});let o=(n-1)*s;return i.slice(o,o+s)}buildRunContext(){let t=this.currentChat._id?.toString()??"";return{task:this.currentChat.activeTask,chat:this.currentChat,currentUser:this.currentUser,currentSession:this.currentSession,currentMessage:this.currentMessage,answerId:this.answerId,tools:this._tools,searchTools:this.searchTools.bind(this),baseParams:{currentUser:this.currentUser,sessionId:t,answerId:this.answerId},skillParams:{sessionId:t,answerId:this.answerId,userMessage:this.currentMessage,currentUser:this.currentUser,currentSession:this.currentSession,chat:this.currentChat},reply:e=>this.currentChat.pushMessage({_id:this.answerId,role:"assistant",content:e}),setNextNode:e=>{let n=this.resolveNodeName(e),s=this.currentChat.activeTask;s?s.setNextNode(n):this.pendingNextNode=n},logger:this.logger}}};export{xn as AGENT_ERROR_CODES,nr as Agent,we as AgentLoop,lt as AgentState,be as AgentStatus};