@ductape/sdk 0.1.8 → 0.1.9

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 (1000) hide show
  1. package/dist/agents/agent-context.d.ts +100 -0
  2. package/dist/agents/agent-context.js +604 -0
  3. package/dist/agents/agent-context.js.map +1 -0
  4. package/dist/agents/agent-executor.d.ts +180 -0
  5. package/dist/agents/agent-executor.js +715 -0
  6. package/dist/agents/agent-executor.js.map +1 -0
  7. package/dist/agents/agents.service.d.ts +310 -0
  8. package/dist/agents/agents.service.js +1255 -0
  9. package/dist/agents/agents.service.js.map +1 -0
  10. package/dist/agents/index.d.ts +55 -0
  11. package/dist/agents/index.js +110 -0
  12. package/dist/agents/index.js.map +1 -0
  13. package/dist/agents/memory-manager.d.ts +182 -0
  14. package/dist/agents/memory-manager.js +383 -0
  15. package/dist/agents/memory-manager.js.map +1 -0
  16. package/dist/agents/tool-registry.d.ts +141 -0
  17. package/dist/agents/tool-registry.js +355 -0
  18. package/dist/agents/tool-registry.js.map +1 -0
  19. package/dist/agents/types/agents.types.d.ts +1240 -0
  20. package/dist/agents/types/agents.types.js +12 -0
  21. package/dist/agents/types/agents.types.js.map +1 -0
  22. package/dist/agents/types/index.d.ts +6 -0
  23. package/dist/agents/types/index.js +23 -0
  24. package/dist/agents/types/index.js.map +1 -0
  25. package/dist/agents/vector-store-adapter.d.ts +108 -0
  26. package/dist/agents/vector-store-adapter.js +213 -0
  27. package/dist/agents/vector-store-adapter.js.map +1 -0
  28. package/dist/api/services/appApi.service.d.ts +78 -0
  29. package/dist/api/services/appApi.service.js +303 -0
  30. package/dist/api/services/appApi.service.js.map +1 -0
  31. package/dist/api/services/cloudApi.service.d.ts +31 -0
  32. package/dist/api/services/cloudApi.service.js +103 -0
  33. package/dist/api/services/cloudApi.service.js.map +1 -0
  34. package/dist/api/services/logsApi.service.d.ts +62 -0
  35. package/dist/api/services/logsApi.service.js +67 -0
  36. package/dist/api/services/logsApi.service.js.map +1 -0
  37. package/dist/api/services/pricingApi.service.d.ts +10 -0
  38. package/dist/api/services/pricingApi.service.js +34 -0
  39. package/dist/api/services/pricingApi.service.js.map +1 -0
  40. package/dist/api/services/processorApi.service.d.ts +927 -0
  41. package/dist/api/services/processorApi.service.js +787 -0
  42. package/dist/api/services/processorApi.service.js.map +1 -0
  43. package/dist/api/services/productsApi.service.d.ts +167 -0
  44. package/dist/api/services/productsApi.service.js +293 -0
  45. package/dist/api/services/productsApi.service.js.map +1 -0
  46. package/dist/api/services/resilienceApi.service.d.ts +106 -0
  47. package/dist/api/services/resilienceApi.service.js +224 -0
  48. package/dist/api/services/resilienceApi.service.js.map +1 -0
  49. package/dist/api/services/secretsApi.service.d.ts +51 -0
  50. package/dist/api/services/secretsApi.service.js +126 -0
  51. package/dist/api/services/secretsApi.service.js.map +1 -0
  52. package/dist/api/services/userApi.service.d.ts +10 -0
  53. package/dist/api/services/userApi.service.js +20 -0
  54. package/dist/api/services/userApi.service.js.map +1 -0
  55. package/dist/api/services/webhooksApi.service.d.ts +14 -0
  56. package/dist/api/services/webhooksApi.service.js +65 -0
  57. package/dist/api/services/webhooksApi.service.js.map +1 -0
  58. package/dist/api/services/workflowApi.service.d.ts +199 -0
  59. package/dist/api/services/workflowApi.service.js +201 -0
  60. package/dist/api/services/workflowApi.service.js.map +1 -0
  61. package/dist/api/services/workspaceApi.service.d.ts +20 -0
  62. package/dist/api/services/workspaceApi.service.js +54 -0
  63. package/dist/api/services/workspaceApi.service.js.map +1 -0
  64. package/dist/api/urls.d.ts +145 -0
  65. package/dist/api/urls.js +195 -0
  66. package/dist/api/urls.js.map +1 -0
  67. package/dist/api/utils/auth.utils.d.ts +10 -0
  68. package/dist/api/utils/auth.utils.js +24 -0
  69. package/dist/api/utils/auth.utils.js.map +1 -0
  70. package/dist/api/utils/cache.utils.d.ts +3 -0
  71. package/dist/api/utils/cache.utils.js +18 -0
  72. package/dist/api/utils/cache.utils.js.map +1 -0
  73. package/dist/api/utils/integration-api-error.d.ts +6 -0
  74. package/dist/api/utils/integration-api-error.js +45 -0
  75. package/dist/api/utils/integration-api-error.js.map +1 -0
  76. package/dist/api/utils/strings.utils.d.ts +7 -0
  77. package/dist/api/utils/strings.utils.js +64 -0
  78. package/dist/api/utils/strings.utils.js.map +1 -0
  79. package/dist/apps/services/app.service.d.ts +126 -0
  80. package/dist/apps/services/app.service.js +1436 -0
  81. package/dist/apps/services/app.service.js.map +1 -0
  82. package/dist/apps/utils/auth-context-manager.d.ts +137 -0
  83. package/dist/apps/utils/auth-context-manager.js +248 -0
  84. package/dist/apps/utils/auth-context-manager.js.map +1 -0
  85. package/dist/apps/utils/credential-manager.d.ts +128 -0
  86. package/dist/apps/utils/credential-manager.js +199 -0
  87. package/dist/apps/utils/credential-manager.js.map +1 -0
  88. package/dist/apps/utils/index.d.ts +10 -0
  89. package/dist/apps/utils/index.js +54 -0
  90. package/dist/apps/utils/index.js.map +1 -0
  91. package/dist/apps/utils/input-helpers.d.ts +67 -0
  92. package/dist/apps/utils/input-helpers.js +185 -0
  93. package/dist/apps/utils/input-helpers.js.map +1 -0
  94. package/dist/apps/utils/input-resolver.d.ts +165 -0
  95. package/dist/apps/utils/input-resolver.js +477 -0
  96. package/dist/apps/utils/input-resolver.js.map +1 -0
  97. package/dist/apps/utils/oauth-manager.d.ts +196 -0
  98. package/dist/apps/utils/oauth-manager.js +429 -0
  99. package/dist/apps/utils/oauth-manager.js.map +1 -0
  100. package/dist/apps/utils/objects.utils.d.ts +4 -0
  101. package/dist/apps/utils/objects.utils.js +59 -0
  102. package/dist/apps/utils/objects.utils.js.map +1 -0
  103. package/dist/apps/utils/string.utils.d.ts +9 -0
  104. package/dist/apps/utils/string.utils.js +89 -0
  105. package/dist/apps/utils/string.utils.js.map +1 -0
  106. package/dist/apps/validators/index.d.ts +17 -0
  107. package/dist/apps/validators/index.js +39 -0
  108. package/dist/apps/validators/index.js.map +1 -0
  109. package/dist/apps/validators/joi-validators/create.app.validator.d.ts +3 -0
  110. package/dist/apps/validators/joi-validators/create.app.validator.js +43 -0
  111. package/dist/apps/validators/joi-validators/create.app.validator.js.map +1 -0
  112. package/dist/apps/validators/joi-validators/create.appAction.validator.d.ts +3 -0
  113. package/dist/apps/validators/joi-validators/create.appAction.validator.js +72 -0
  114. package/dist/apps/validators/joi-validators/create.appAction.validator.js.map +1 -0
  115. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.d.ts +7 -0
  116. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.js +81 -0
  117. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.js.map +1 -0
  118. package/dist/apps/validators/joi-validators/create.appAuth.validator.d.ts +3 -0
  119. package/dist/apps/validators/joi-validators/create.appAuth.validator.js +64 -0
  120. package/dist/apps/validators/joi-validators/create.appAuth.validator.js.map +1 -0
  121. package/dist/apps/validators/joi-validators/create.appBody.validators.d.ts +4 -0
  122. package/dist/apps/validators/joi-validators/create.appBody.validators.js +44 -0
  123. package/dist/apps/validators/joi-validators/create.appBody.validators.js.map +1 -0
  124. package/dist/apps/validators/joi-validators/create.appConstants.validator.d.ts +4 -0
  125. package/dist/apps/validators/joi-validators/create.appConstants.validator.js +45 -0
  126. package/dist/apps/validators/joi-validators/create.appConstants.validator.js.map +1 -0
  127. package/dist/apps/validators/joi-validators/create.appEnv.validator.d.ts +4 -0
  128. package/dist/apps/validators/joi-validators/create.appEnv.validator.js +50 -0
  129. package/dist/apps/validators/joi-validators/create.appEnv.validator.js.map +1 -0
  130. package/dist/apps/validators/joi-validators/create.appVariable.validator.d.ts +4 -0
  131. package/dist/apps/validators/joi-validators/create.appVariable.validator.js +47 -0
  132. package/dist/apps/validators/joi-validators/create.appVariable.validator.js.map +1 -0
  133. package/dist/apps/validators/joi-validators/create.appWebhook.validator.d.ts +4 -0
  134. package/dist/apps/validators/joi-validators/create.appWebhook.validator.js +60 -0
  135. package/dist/apps/validators/joi-validators/create.appWebhook.validator.js.map +1 -0
  136. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.d.ts +3 -0
  137. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.js +48 -0
  138. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.js.map +1 -0
  139. package/dist/apps/validators/joi-validators/sample.validator.d.ts +6 -0
  140. package/dist/apps/validators/joi-validators/sample.validator.js +65 -0
  141. package/dist/apps/validators/joi-validators/sample.validator.js.map +1 -0
  142. package/dist/apps/validators/joi-validators/update.app.validator.d.ts +4 -0
  143. package/dist/apps/validators/joi-validators/update.app.validator.js +66 -0
  144. package/dist/apps/validators/joi-validators/update.app.validator.js.map +1 -0
  145. package/dist/apps/validators/joi-validators/update.appAction.validator.d.ts +4 -0
  146. package/dist/apps/validators/joi-validators/update.appAction.validator.js +76 -0
  147. package/dist/apps/validators/joi-validators/update.appAction.validator.js.map +1 -0
  148. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.d.ts +3 -0
  149. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js +57 -0
  150. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js.map +1 -0
  151. package/dist/apps/validators/joi-validators/update.appAuth.validator.d.ts +4 -0
  152. package/dist/apps/validators/joi-validators/update.appAuth.validator.js +52 -0
  153. package/dist/apps/validators/joi-validators/update.appAuth.validator.js.map +1 -0
  154. package/dist/apps/validators/joi-validators/update.appConstants.validator.d.ts +4 -0
  155. package/dist/apps/validators/joi-validators/update.appConstants.validator.js +45 -0
  156. package/dist/apps/validators/joi-validators/update.appConstants.validator.js.map +1 -0
  157. package/dist/apps/validators/joi-validators/update.appEnv.validator.d.ts +4 -0
  158. package/dist/apps/validators/joi-validators/update.appEnv.validator.js +50 -0
  159. package/dist/apps/validators/joi-validators/update.appEnv.validator.js.map +1 -0
  160. package/dist/apps/validators/joi-validators/update.appVariables.validator.d.ts +4 -0
  161. package/dist/apps/validators/joi-validators/update.appVariables.validator.js +47 -0
  162. package/dist/apps/validators/joi-validators/update.appVariables.validator.js.map +1 -0
  163. package/dist/apps/validators/joi-validators/update.appWebhook.validator.d.ts +4 -0
  164. package/dist/apps/validators/joi-validators/update.appWebhook.validator.js +59 -0
  165. package/dist/apps/validators/joi-validators/update.appWebhook.validator.js.map +1 -0
  166. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.d.ts +3 -0
  167. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.js +48 -0
  168. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.js.map +1 -0
  169. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.d.ts +3 -0
  170. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.js +60 -0
  171. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.js.map +1 -0
  172. package/dist/bin.d.ts +26 -0
  173. package/dist/bin.js +28 -0
  174. package/dist/bin.js.map +1 -0
  175. package/dist/brokers/brokers.service.d.ts +438 -0
  176. package/dist/brokers/brokers.service.js +1315 -0
  177. package/dist/brokers/brokers.service.js.map +1 -0
  178. package/dist/brokers/index.d.ts +46 -0
  179. package/dist/brokers/index.js +83 -0
  180. package/dist/brokers/index.js.map +1 -0
  181. package/dist/brokers/types/index.d.ts +569 -0
  182. package/dist/brokers/types/index.js +8 -0
  183. package/dist/brokers/types/index.js.map +1 -0
  184. package/dist/brokers/utils/broker.util.d.ts +33 -0
  185. package/dist/brokers/utils/broker.util.js +125 -0
  186. package/dist/brokers/utils/broker.util.js.map +1 -0
  187. package/dist/brokers/utils/providers/aws-sqs.service.d.ts +16 -0
  188. package/dist/brokers/utils/providers/aws-sqs.service.js +71 -0
  189. package/dist/brokers/utils/providers/aws-sqs.service.js.map +1 -0
  190. package/dist/brokers/utils/providers/google-pubsub.service.d.ts +16 -0
  191. package/dist/brokers/utils/providers/google-pubsub.service.js +43 -0
  192. package/dist/brokers/utils/providers/google-pubsub.service.js.map +1 -0
  193. package/dist/brokers/utils/providers/index.d.ts +6 -0
  194. package/dist/brokers/utils/providers/index.js +16 -0
  195. package/dist/brokers/utils/providers/index.js.map +1 -0
  196. package/dist/brokers/utils/providers/kafka.service.d.ts +23 -0
  197. package/dist/brokers/utils/providers/kafka.service.js +131 -0
  198. package/dist/brokers/utils/providers/kafka.service.js.map +1 -0
  199. package/dist/brokers/utils/providers/nats.service.d.ts +18 -0
  200. package/dist/brokers/utils/providers/nats.service.js +63 -0
  201. package/dist/brokers/utils/providers/nats.service.js.map +1 -0
  202. package/dist/brokers/utils/providers/rabbitmq.service.d.ts +25 -0
  203. package/dist/brokers/utils/providers/rabbitmq.service.js +138 -0
  204. package/dist/brokers/utils/providers/rabbitmq.service.js.map +1 -0
  205. package/dist/brokers/utils/providers/redis.service.d.ts +18 -0
  206. package/dist/brokers/utils/providers/redis.service.js +93 -0
  207. package/dist/brokers/utils/providers/redis.service.js.map +1 -0
  208. package/dist/cache/cache.manager.d.ts +308 -0
  209. package/dist/cache/cache.manager.js +900 -0
  210. package/dist/cache/cache.manager.js.map +1 -0
  211. package/dist/cache/cache.service.d.ts +194 -0
  212. package/dist/cache/cache.service.js +601 -0
  213. package/dist/cache/cache.service.js.map +1 -0
  214. package/dist/cache/index.d.ts +52 -0
  215. package/dist/cache/index.js +81 -0
  216. package/dist/cache/index.js.map +1 -0
  217. package/dist/cache/types/index.d.ts +114 -0
  218. package/dist/cache/types/index.js +6 -0
  219. package/dist/cache/types/index.js.map +1 -0
  220. package/dist/clients/apps.client.d.ts +4 -0
  221. package/dist/clients/apps.client.js +31 -0
  222. package/dist/clients/apps.client.js.map +1 -0
  223. package/dist/clients/email.client.d.ts +4 -0
  224. package/dist/clients/email.client.js +29 -0
  225. package/dist/clients/email.client.js.map +1 -0
  226. package/dist/clients/expo.client.d.ts +3 -0
  227. package/dist/clients/expo.client.js +28 -0
  228. package/dist/clients/expo.client.js.map +1 -0
  229. package/dist/clients/function.client.d.ts +3 -0
  230. package/dist/clients/function.client.js +27 -0
  231. package/dist/clients/function.client.js.map +1 -0
  232. package/dist/clients/http.client.d.ts +3 -0
  233. package/dist/clients/http.client.js +27 -0
  234. package/dist/clients/http.client.js.map +1 -0
  235. package/dist/clients/logs.client.d.ts +4 -0
  236. package/dist/clients/logs.client.js +34 -0
  237. package/dist/clients/logs.client.js.map +1 -0
  238. package/dist/clients/pricing.client.d.ts +4 -0
  239. package/dist/clients/pricing.client.js +34 -0
  240. package/dist/clients/pricing.client.js.map +1 -0
  241. package/dist/clients/products.client.d.ts +3 -0
  242. package/dist/clients/products.client.js +32 -0
  243. package/dist/clients/products.client.js.map +1 -0
  244. package/dist/clients/users.client.d.ts +4 -0
  245. package/dist/clients/users.client.js +34 -0
  246. package/dist/clients/users.client.js.map +1 -0
  247. package/dist/clients/webhooks.client.d.ts +4 -0
  248. package/dist/clients/webhooks.client.js +34 -0
  249. package/dist/clients/webhooks.client.js.map +1 -0
  250. package/dist/clients/workspace.client.d.ts +7 -0
  251. package/dist/clients/workspace.client.js +39 -0
  252. package/dist/clients/workspace.client.js.map +1 -0
  253. package/dist/cloud/cloud-runtime.util.d.ts +22 -0
  254. package/dist/cloud/cloud-runtime.util.js +61 -0
  255. package/dist/cloud/cloud-runtime.util.js.map +1 -0
  256. package/dist/cloud/cloud.service.d.ts +43 -0
  257. package/dist/cloud/cloud.service.js +121 -0
  258. package/dist/cloud/cloud.service.js.map +1 -0
  259. package/dist/cloud/index.d.ts +5 -0
  260. package/dist/cloud/index.js +25 -0
  261. package/dist/cloud/index.js.map +1 -0
  262. package/dist/cloud/types/cloud.types.d.ts +140 -0
  263. package/dist/cloud/types/cloud.types.js +6 -0
  264. package/dist/cloud/types/cloud.types.js.map +1 -0
  265. package/dist/cloud/types/index.d.ts +1 -0
  266. package/dist/cloud/types/index.js +18 -0
  267. package/dist/cloud/types/index.js.map +1 -0
  268. package/dist/database/actions/action-manager.d.ts +170 -0
  269. package/dist/database/actions/action-manager.js +465 -0
  270. package/dist/database/actions/action-manager.js.map +1 -0
  271. package/dist/database/actions/index.d.ts +6 -0
  272. package/dist/database/actions/index.js +13 -0
  273. package/dist/database/actions/index.js.map +1 -0
  274. package/dist/database/adapters/adapter.factory.d.ts +62 -0
  275. package/dist/database/adapters/adapter.factory.js +97 -0
  276. package/dist/database/adapters/adapter.factory.js.map +1 -0
  277. package/dist/database/adapters/base.adapter.d.ts +423 -0
  278. package/dist/database/adapters/base.adapter.js +260 -0
  279. package/dist/database/adapters/base.adapter.js.map +1 -0
  280. package/dist/database/adapters/cassandra.adapter.d.ts +92 -0
  281. package/dist/database/adapters/cassandra.adapter.js +1091 -0
  282. package/dist/database/adapters/cassandra.adapter.js.map +1 -0
  283. package/dist/database/adapters/dynamodb.adapter.d.ts +110 -0
  284. package/dist/database/adapters/dynamodb.adapter.js +1564 -0
  285. package/dist/database/adapters/dynamodb.adapter.js.map +1 -0
  286. package/dist/database/adapters/index.d.ts +11 -0
  287. package/dist/database/adapters/index.js +27 -0
  288. package/dist/database/adapters/index.js.map +1 -0
  289. package/dist/database/adapters/mariadb.adapter.d.ts +100 -0
  290. package/dist/database/adapters/mariadb.adapter.js +247 -0
  291. package/dist/database/adapters/mariadb.adapter.js.map +1 -0
  292. package/dist/database/adapters/mongodb.adapter.d.ts +121 -0
  293. package/dist/database/adapters/mongodb.adapter.js +1284 -0
  294. package/dist/database/adapters/mongodb.adapter.js.map +1 -0
  295. package/dist/database/adapters/mysql.adapter.d.ts +86 -0
  296. package/dist/database/adapters/mysql.adapter.js +1371 -0
  297. package/dist/database/adapters/mysql.adapter.js.map +1 -0
  298. package/dist/database/adapters/postgresql.adapter.d.ts +90 -0
  299. package/dist/database/adapters/postgresql.adapter.js +1487 -0
  300. package/dist/database/adapters/postgresql.adapter.js.map +1 -0
  301. package/dist/database/databases.service.d.ts +1526 -0
  302. package/dist/database/databases.service.js +3370 -0
  303. package/dist/database/databases.service.js.map +1 -0
  304. package/dist/database/index.d.ts +46 -0
  305. package/dist/database/index.js +109 -0
  306. package/dist/database/index.js.map +1 -0
  307. package/dist/database/migrations/index.d.ts +6 -0
  308. package/dist/database/migrations/index.js +12 -0
  309. package/dist/database/migrations/index.js.map +1 -0
  310. package/dist/database/migrations/migration-engine.d.ts +136 -0
  311. package/dist/database/migrations/migration-engine.js +1421 -0
  312. package/dist/database/migrations/migration-engine.js.map +1 -0
  313. package/dist/database/operators/aggregation-builder.d.ts +67 -0
  314. package/dist/database/operators/aggregation-builder.js +841 -0
  315. package/dist/database/operators/aggregation-builder.js.map +1 -0
  316. package/dist/database/operators/index.d.ts +7 -0
  317. package/dist/database/operators/index.js +15 -0
  318. package/dist/database/operators/index.js.map +1 -0
  319. package/dist/database/operators/query-builder.d.ts +69 -0
  320. package/dist/database/operators/query-builder.js +447 -0
  321. package/dist/database/operators/query-builder.js.map +1 -0
  322. package/dist/database/presave/decrypt.d.ts +25 -0
  323. package/dist/database/presave/decrypt.js +146 -0
  324. package/dist/database/presave/decrypt.js.map +1 -0
  325. package/dist/database/presave/index.d.ts +9 -0
  326. package/dist/database/presave/index.js +18 -0
  327. package/dist/database/presave/index.js.map +1 -0
  328. package/dist/database/presave/presave-processor.d.ts +148 -0
  329. package/dist/database/presave/presave-processor.js +702 -0
  330. package/dist/database/presave/presave-processor.js.map +1 -0
  331. package/dist/database/schema/index.d.ts +7 -0
  332. package/dist/database/schema/index.js +13 -0
  333. package/dist/database/schema/index.js.map +1 -0
  334. package/dist/database/schema/schema-manager.d.ts +258 -0
  335. package/dist/database/schema/schema-manager.js +638 -0
  336. package/dist/database/schema/schema-manager.js.map +1 -0
  337. package/dist/database/transactions/index.d.ts +6 -0
  338. package/dist/database/transactions/index.js +13 -0
  339. package/dist/database/transactions/index.js.map +1 -0
  340. package/dist/database/transactions/transaction-manager.d.ts +113 -0
  341. package/dist/database/transactions/transaction-manager.js +344 -0
  342. package/dist/database/transactions/transaction-manager.js.map +1 -0
  343. package/dist/database/triggers/index.d.ts +7 -0
  344. package/dist/database/triggers/index.js +14 -0
  345. package/dist/database/triggers/index.js.map +1 -0
  346. package/dist/database/triggers/trigger-processor.d.ts +239 -0
  347. package/dist/database/triggers/trigger-processor.js +1034 -0
  348. package/dist/database/triggers/trigger-processor.js.map +1 -0
  349. package/dist/database/types/action.interface.d.ts +148 -0
  350. package/dist/database/types/action.interface.js +6 -0
  351. package/dist/database/types/action.interface.js.map +1 -0
  352. package/dist/database/types/aggregation.interface.d.ts +185 -0
  353. package/dist/database/types/aggregation.interface.js +6 -0
  354. package/dist/database/types/aggregation.interface.js.map +1 -0
  355. package/dist/database/types/connection.interface.d.ts +141 -0
  356. package/dist/database/types/connection.interface.js +6 -0
  357. package/dist/database/types/connection.interface.js.map +1 -0
  358. package/dist/database/types/dashboard.interface.d.ts +74 -0
  359. package/dist/database/types/dashboard.interface.js +7 -0
  360. package/dist/database/types/dashboard.interface.js.map +1 -0
  361. package/dist/database/types/enums.d.ts +195 -0
  362. package/dist/database/types/enums.js +244 -0
  363. package/dist/database/types/enums.js.map +1 -0
  364. package/dist/database/types/index.d.ts +15 -0
  365. package/dist/database/types/index.js +31 -0
  366. package/dist/database/types/index.js.map +1 -0
  367. package/dist/database/types/migration.interface.d.ts +686 -0
  368. package/dist/database/types/migration.interface.js +9 -0
  369. package/dist/database/types/migration.interface.js.map +1 -0
  370. package/dist/database/types/presave.interface.d.ts +292 -0
  371. package/dist/database/types/presave.interface.js +60 -0
  372. package/dist/database/types/presave.interface.js.map +1 -0
  373. package/dist/database/types/query.interface.d.ts +205 -0
  374. package/dist/database/types/query.interface.js +6 -0
  375. package/dist/database/types/query.interface.js.map +1 -0
  376. package/dist/database/types/schema.interface.d.ts +412 -0
  377. package/dist/database/types/schema.interface.js +6 -0
  378. package/dist/database/types/schema.interface.js.map +1 -0
  379. package/dist/database/types/transaction.interface.d.ts +84 -0
  380. package/dist/database/types/transaction.interface.js +6 -0
  381. package/dist/database/types/transaction.interface.js.map +1 -0
  382. package/dist/database/types/trigger.interface.d.ts +612 -0
  383. package/dist/database/types/trigger.interface.js +121 -0
  384. package/dist/database/types/trigger.interface.js.map +1 -0
  385. package/dist/database/types/write.interface.d.ts +216 -0
  386. package/dist/database/types/write.interface.js +6 -0
  387. package/dist/database/types/write.interface.js.map +1 -0
  388. package/dist/database/utils/database-error.d.ts +96 -0
  389. package/dist/database/utils/database-error.js +221 -0
  390. package/dist/database/utils/database-error.js.map +1 -0
  391. package/dist/database/utils/index.d.ts +6 -0
  392. package/dist/database/utils/index.js +11 -0
  393. package/dist/database/utils/index.js.map +1 -0
  394. package/dist/graph/adapters/adapter.factory.d.ts +47 -0
  395. package/dist/graph/adapters/adapter.factory.js +77 -0
  396. package/dist/graph/adapters/adapter.factory.js.map +1 -0
  397. package/dist/graph/adapters/arangodb.adapter.d.ts +86 -0
  398. package/dist/graph/adapters/arangodb.adapter.js +1588 -0
  399. package/dist/graph/adapters/arangodb.adapter.js.map +1 -0
  400. package/dist/graph/adapters/base.adapter.d.ts +264 -0
  401. package/dist/graph/adapters/base.adapter.js +156 -0
  402. package/dist/graph/adapters/base.adapter.js.map +1 -0
  403. package/dist/graph/adapters/index.d.ts +11 -0
  404. package/dist/graph/adapters/index.js +21 -0
  405. package/dist/graph/adapters/index.js.map +1 -0
  406. package/dist/graph/adapters/memgraph.adapter.d.ts +110 -0
  407. package/dist/graph/adapters/memgraph.adapter.js +1452 -0
  408. package/dist/graph/adapters/memgraph.adapter.js.map +1 -0
  409. package/dist/graph/adapters/neo4j.adapter.d.ts +81 -0
  410. package/dist/graph/adapters/neo4j.adapter.js +1317 -0
  411. package/dist/graph/adapters/neo4j.adapter.js.map +1 -0
  412. package/dist/graph/adapters/neptune.adapter.d.ts +82 -0
  413. package/dist/graph/adapters/neptune.adapter.js +1369 -0
  414. package/dist/graph/adapters/neptune.adapter.js.map +1 -0
  415. package/dist/graph/graphs.service.d.ts +633 -0
  416. package/dist/graph/graphs.service.js +2684 -0
  417. package/dist/graph/graphs.service.js.map +1 -0
  418. package/dist/graph/index.d.ts +58 -0
  419. package/dist/graph/index.js +77 -0
  420. package/dist/graph/index.js.map +1 -0
  421. package/dist/graph/transactions/index.d.ts +4 -0
  422. package/dist/graph/transactions/index.js +9 -0
  423. package/dist/graph/transactions/index.js.map +1 -0
  424. package/dist/graph/transactions/transaction-manager.d.ts +61 -0
  425. package/dist/graph/transactions/transaction-manager.js +126 -0
  426. package/dist/graph/transactions/transaction-manager.js.map +1 -0
  427. package/dist/graph/types/connection.interface.d.ts +161 -0
  428. package/dist/graph/types/connection.interface.js +9 -0
  429. package/dist/graph/types/connection.interface.js.map +1 -0
  430. package/dist/graph/types/enums.d.ts +101 -0
  431. package/dist/graph/types/enums.js +114 -0
  432. package/dist/graph/types/enums.js.map +1 -0
  433. package/dist/graph/types/index.d.ts +13 -0
  434. package/dist/graph/types/index.js +20 -0
  435. package/dist/graph/types/index.js.map +1 -0
  436. package/dist/graph/types/node.interface.d.ts +248 -0
  437. package/dist/graph/types/node.interface.js +9 -0
  438. package/dist/graph/types/node.interface.js.map +1 -0
  439. package/dist/graph/types/query.interface.d.ts +175 -0
  440. package/dist/graph/types/query.interface.js +9 -0
  441. package/dist/graph/types/query.interface.js.map +1 -0
  442. package/dist/graph/types/relationship.interface.d.ts +207 -0
  443. package/dist/graph/types/relationship.interface.js +9 -0
  444. package/dist/graph/types/relationship.interface.js.map +1 -0
  445. package/dist/graph/types/schema.interface.d.ts +295 -0
  446. package/dist/graph/types/schema.interface.js +9 -0
  447. package/dist/graph/types/schema.interface.js.map +1 -0
  448. package/dist/graph/types/transaction.interface.d.ts +55 -0
  449. package/dist/graph/types/transaction.interface.js +9 -0
  450. package/dist/graph/types/transaction.interface.js.map +1 -0
  451. package/dist/graph/types/traversal.interface.d.ts +181 -0
  452. package/dist/graph/types/traversal.interface.js +9 -0
  453. package/dist/graph/types/traversal.interface.js.map +1 -0
  454. package/dist/graph/utils/graph-error.d.ts +71 -0
  455. package/dist/graph/utils/graph-error.js +142 -0
  456. package/dist/graph/utils/graph-error.js.map +1 -0
  457. package/dist/graph/utils/index.d.ts +4 -0
  458. package/dist/graph/utils/index.js +9 -0
  459. package/dist/graph/utils/index.js.map +1 -0
  460. package/dist/imports/imports.repo.d.ts +0 -0
  461. package/dist/imports/imports.repo.js +1 -0
  462. package/dist/imports/imports.repo.js.map +1 -0
  463. package/dist/imports/imports.service.d.ts +23 -0
  464. package/dist/imports/imports.service.js +71 -0
  465. package/dist/imports/imports.service.js.map +1 -0
  466. package/dist/imports/imports.types.d.ts +350 -0
  467. package/dist/imports/imports.types.js +33 -0
  468. package/dist/imports/imports.types.js.map +1 -0
  469. package/dist/imports/openAPI3.0.types.d.ts +52 -0
  470. package/dist/imports/openAPI3.0.types.js +3 -0
  471. package/dist/imports/openAPI3.0.types.js.map +1 -0
  472. package/dist/imports/repos/openApi.repo.d.ts +6 -0
  473. package/dist/imports/repos/openApi.repo.js +422 -0
  474. package/dist/imports/repos/openApi.repo.js.map +1 -0
  475. package/dist/imports/repos/postmanV21.repo.d.ts +14 -0
  476. package/dist/imports/repos/postmanV21.repo.js +257 -0
  477. package/dist/imports/repos/postmanV21.repo.js.map +1 -0
  478. package/dist/imports/utils/imports.utils.d.ts +80 -0
  479. package/dist/imports/utils/imports.utils.js +114 -0
  480. package/dist/imports/utils/imports.utils.js.map +1 -0
  481. package/dist/imports/validators/index.d.ts +0 -0
  482. package/dist/imports/validators/index.js +1 -0
  483. package/dist/imports/validators/index.js.map +1 -0
  484. package/dist/imports/validators/joi-validators/postmanV21.validator.d.ts +5 -0
  485. package/dist/imports/validators/joi-validators/postmanV21.validator.js +96 -0
  486. package/dist/imports/validators/joi-validators/postmanV21.validator.js.map +1 -0
  487. package/dist/index.d.ts +4233 -0
  488. package/dist/index.js +5933 -0
  489. package/dist/index.js.map +1 -0
  490. package/dist/init.interface.d.ts +407 -0
  491. package/dist/init.interface.js +3 -0
  492. package/dist/init.interface.js.map +1 -0
  493. package/dist/inputs/inputs.repo.d.ts +7 -0
  494. package/dist/inputs/inputs.repo.js +16 -0
  495. package/dist/inputs/inputs.repo.js.map +1 -0
  496. package/dist/inputs/inputs.service.d.ts +61 -0
  497. package/dist/inputs/inputs.service.js +468 -0
  498. package/dist/inputs/inputs.service.js.map +1 -0
  499. package/dist/inputs/utils/inputs.utils.create.d.ts +11 -0
  500. package/dist/inputs/utils/inputs.utils.create.js +273 -0
  501. package/dist/inputs/utils/inputs.utils.create.js.map +1 -0
  502. package/dist/inputs/validators/inputs.validator.parse.d.ts +4 -0
  503. package/dist/inputs/validators/inputs.validator.parse.js +53 -0
  504. package/dist/inputs/validators/inputs.validator.parse.js.map +1 -0
  505. package/dist/jobs/index.d.ts +38 -0
  506. package/dist/jobs/index.js +50 -0
  507. package/dist/jobs/index.js.map +1 -0
  508. package/dist/jobs/jobs.service.d.ts +154 -0
  509. package/dist/jobs/jobs.service.js +491 -0
  510. package/dist/jobs/jobs.service.js.map +1 -0
  511. package/dist/jobs/jobs.state.d.ts +113 -0
  512. package/dist/jobs/jobs.state.js +447 -0
  513. package/dist/jobs/jobs.state.js.map +1 -0
  514. package/dist/jobs/types.d.ts +449 -0
  515. package/dist/jobs/types.js +74 -0
  516. package/dist/jobs/types.js.map +1 -0
  517. package/dist/logs/logs.repo.d.ts +6 -0
  518. package/dist/logs/logs.repo.js +12 -0
  519. package/dist/logs/logs.repo.js.map +1 -0
  520. package/dist/logs/logs.service.d.ts +30 -0
  521. package/dist/logs/logs.service.js +89 -0
  522. package/dist/logs/logs.service.js.map +1 -0
  523. package/dist/logs/logs.types.d.ts +85 -0
  524. package/dist/logs/logs.types.js +52 -0
  525. package/dist/logs/logs.types.js.map +1 -0
  526. package/dist/logs/utils/logs.utils.create.d.ts +0 -0
  527. package/dist/logs/utils/logs.utils.create.js +1 -0
  528. package/dist/logs/utils/logs.utils.create.js.map +1 -0
  529. package/dist/logs/utils/logs.utils.errors.d.ts +2 -0
  530. package/dist/logs/utils/logs.utils.errors.js +8 -0
  531. package/dist/logs/utils/logs.utils.errors.js.map +1 -0
  532. package/dist/models/index.d.ts +6 -0
  533. package/dist/models/index.js +11 -0
  534. package/dist/models/index.js.map +1 -0
  535. package/dist/models/models.service.d.ts +137 -0
  536. package/dist/models/models.service.js +195 -0
  537. package/dist/models/models.service.js.map +1 -0
  538. package/dist/notifications/index.d.ts +13 -0
  539. package/dist/notifications/index.js +26 -0
  540. package/dist/notifications/index.js.map +1 -0
  541. package/dist/notifications/notifications.service.d.ts +270 -0
  542. package/dist/notifications/notifications.service.js +912 -0
  543. package/dist/notifications/notifications.service.js.map +1 -0
  544. package/dist/notifications/types/index.d.ts +4 -0
  545. package/dist/notifications/types/index.js +21 -0
  546. package/dist/notifications/types/index.js.map +1 -0
  547. package/dist/notifications/types/notifications.types.d.ts +456 -0
  548. package/dist/notifications/types/notifications.types.js +51 -0
  549. package/dist/notifications/types/notifications.types.js.map +1 -0
  550. package/dist/parsers/index.d.ts +3 -0
  551. package/dist/parsers/index.js +27 -0
  552. package/dist/parsers/index.js.map +1 -0
  553. package/dist/parsers/pipelines/postman.pipelines.d.ts +15 -0
  554. package/dist/parsers/pipelines/postman.pipelines.js +103 -0
  555. package/dist/parsers/pipelines/postman.pipelines.js.map +1 -0
  556. package/dist/parsers/types/postman.types.d.ts +200 -0
  557. package/dist/parsers/types/postman.types.js +3 -0
  558. package/dist/parsers/types/postman.types.js.map +1 -0
  559. package/dist/parsers/utils/postman.utils.d.ts +12 -0
  560. package/dist/parsers/utils/postman.utils.js +116 -0
  561. package/dist/parsers/utils/postman.utils.js.map +1 -0
  562. package/dist/parsers/validators/postman-auth.validators.d.ts +10 -0
  563. package/dist/parsers/validators/postman-auth.validators.js +127 -0
  564. package/dist/parsers/validators/postman-auth.validators.js.map +1 -0
  565. package/dist/parsers/validators/postman-request.validators.d.ts +13 -0
  566. package/dist/parsers/validators/postman-request.validators.js +139 -0
  567. package/dist/parsers/validators/postman-request.validators.js.map +1 -0
  568. package/dist/parsers/validators/postman-response.validators.d.ts +13 -0
  569. package/dist/parsers/validators/postman-response.validators.js +150 -0
  570. package/dist/parsers/validators/postman-response.validators.js.map +1 -0
  571. package/dist/parsers/validators/postman-variable.validators.d.ts +14 -0
  572. package/dist/parsers/validators/postman-variable.validators.js +163 -0
  573. package/dist/parsers/validators/postman-variable.validators.js.map +1 -0
  574. package/dist/pricing/pricing.repo.d.ts +0 -0
  575. package/dist/pricing/pricing.repo.js +1 -0
  576. package/dist/pricing/pricing.repo.js.map +1 -0
  577. package/dist/pricing/pricing.service.d.ts +24 -0
  578. package/dist/pricing/pricing.service.js +51 -0
  579. package/dist/pricing/pricing.service.js.map +1 -0
  580. package/dist/pricing/pricing.types.d.ts +76 -0
  581. package/dist/pricing/pricing.types.js +21 -0
  582. package/dist/pricing/pricing.types.js.map +1 -0
  583. package/dist/pricing/utils/string.utils.d.ts +1 -0
  584. package/dist/pricing/utils/string.utils.js +9 -0
  585. package/dist/pricing/utils/string.utils.js.map +1 -0
  586. package/dist/processor/repos/mongo.repo.d.ts +39 -0
  587. package/dist/processor/repos/mongo.repo.js +260 -0
  588. package/dist/processor/repos/mongo.repo.js.map +1 -0
  589. package/dist/processor/repos/postgres.repo.d.ts +31 -0
  590. package/dist/processor/repos/postgres.repo.js +185 -0
  591. package/dist/processor/repos/postgres.repo.js.map +1 -0
  592. package/dist/processor/repos/sms.repo.d.ts +39 -0
  593. package/dist/processor/repos/sms.repo.js +124 -0
  594. package/dist/processor/repos/sms.repo.js.map +1 -0
  595. package/dist/processor/services/processor.service.d.ts +465 -0
  596. package/dist/processor/services/processor.service.js +5343 -0
  597. package/dist/processor/services/processor.service.js.map +1 -0
  598. package/dist/processor/services/request.service.d.ts +36 -0
  599. package/dist/processor/services/request.service.js +304 -0
  600. package/dist/processor/services/request.service.js.map +1 -0
  601. package/dist/processor/types/request.types.d.ts +14 -0
  602. package/dist/processor/types/request.types.js +3 -0
  603. package/dist/processor/types/request.types.js.map +1 -0
  604. package/dist/processor/utils/processor.utils.d.ts +104 -0
  605. package/dist/processor/utils/processor.utils.js +1066 -0
  606. package/dist/processor/utils/processor.utils.js.map +1 -0
  607. package/dist/processor/utils/request.utils.d.ts +20 -0
  608. package/dist/processor/utils/request.utils.js +113 -0
  609. package/dist/processor/utils/request.utils.js.map +1 -0
  610. package/dist/processor/utils/storage.util.d.ts +8 -0
  611. package/dist/processor/utils/storage.util.js +106 -0
  612. package/dist/processor/utils/storage.util.js.map +1 -0
  613. package/dist/products/services/products.service.d.ts +579 -0
  614. package/dist/products/services/products.service.js +5853 -0
  615. package/dist/products/services/products.service.js.map +1 -0
  616. package/dist/products/utils/crypt.utils.d.ts +1 -0
  617. package/dist/products/utils/crypt.utils.js +17 -0
  618. package/dist/products/utils/crypt.utils.js.map +1 -0
  619. package/dist/products/utils/functions.utils.d.ts +13 -0
  620. package/dist/products/utils/functions.utils.js +294 -0
  621. package/dist/products/utils/functions.utils.js.map +1 -0
  622. package/dist/products/utils/objects.utils.d.ts +13 -0
  623. package/dist/products/utils/objects.utils.js +89 -0
  624. package/dist/products/utils/objects.utils.js.map +1 -0
  625. package/dist/products/utils/string.utils.d.ts +12 -0
  626. package/dist/products/utils/string.utils.js +168 -0
  627. package/dist/products/utils/string.utils.js.map +1 -0
  628. package/dist/products/validators/index.d.ts +33 -0
  629. package/dist/products/validators/index.js +75 -0
  630. package/dist/products/validators/index.js.map +1 -0
  631. package/dist/products/validators/joi-validators/create.html.validator.d.ts +2 -0
  632. package/dist/products/validators/joi-validators/create.html.validator.js +55 -0
  633. package/dist/products/validators/joi-validators/create.html.validator.js.map +1 -0
  634. package/dist/products/validators/joi-validators/create.productAgent.validator.d.ts +3 -0
  635. package/dist/products/validators/joi-validators/create.productAgent.validator.js +266 -0
  636. package/dist/products/validators/joi-validators/create.productAgent.validator.js.map +1 -0
  637. package/dist/products/validators/joi-validators/create.productApp.validator.d.ts +4 -0
  638. package/dist/products/validators/joi-validators/create.productApp.validator.js +61 -0
  639. package/dist/products/validators/joi-validators/create.productApp.validator.js.map +1 -0
  640. package/dist/products/validators/joi-validators/create.productCache.validator.d.ts +3 -0
  641. package/dist/products/validators/joi-validators/create.productCache.validator.js +46 -0
  642. package/dist/products/validators/joi-validators/create.productCache.validator.js.map +1 -0
  643. package/dist/products/validators/joi-validators/create.productDatabase.validator.d.ts +3 -0
  644. package/dist/products/validators/joi-validators/create.productDatabase.validator.js +77 -0
  645. package/dist/products/validators/joi-validators/create.productDatabase.validator.js.map +1 -0
  646. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.d.ts +7 -0
  647. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.js +194 -0
  648. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.js.map +1 -0
  649. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.d.ts +4 -0
  650. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.js +63 -0
  651. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.js.map +1 -0
  652. package/dist/products/validators/joi-validators/create.productEnv.validator.d.ts +3 -0
  653. package/dist/products/validators/joi-validators/create.productEnv.validator.js +45 -0
  654. package/dist/products/validators/joi-validators/create.productEnv.validator.js.map +1 -0
  655. package/dist/products/validators/joi-validators/create.productFallback.validator.d.ts +3 -0
  656. package/dist/products/validators/joi-validators/create.productFallback.validator.js +64 -0
  657. package/dist/products/validators/joi-validators/create.productFallback.validator.js.map +1 -0
  658. package/dist/products/validators/joi-validators/create.productFeature.validator.d.ts +14 -0
  659. package/dist/products/validators/joi-validators/create.productFeature.validator.js +140 -0
  660. package/dist/products/validators/joi-validators/create.productFeature.validator.js.map +1 -0
  661. package/dist/products/validators/joi-validators/create.productFunction.validator.d.ts +3 -0
  662. package/dist/products/validators/joi-validators/create.productFunction.validator.js +57 -0
  663. package/dist/products/validators/joi-validators/create.productFunction.validator.js.map +1 -0
  664. package/dist/products/validators/joi-validators/create.productGraph.validator.d.ts +3 -0
  665. package/dist/products/validators/joi-validators/create.productGraph.validator.js +89 -0
  666. package/dist/products/validators/joi-validators/create.productGraph.validator.js.map +1 -0
  667. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.d.ts +4 -0
  668. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js +58 -0
  669. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js.map +1 -0
  670. package/dist/products/validators/joi-validators/create.productJob.validator.d.ts +12 -0
  671. package/dist/products/validators/joi-validators/create.productJob.validator.js +60 -0
  672. package/dist/products/validators/joi-validators/create.productJob.validator.js.map +1 -0
  673. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.d.ts +3 -0
  674. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.js +52 -0
  675. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.js.map +1 -0
  676. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.d.ts +3 -0
  677. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.js +193 -0
  678. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.js.map +1 -0
  679. package/dist/products/validators/joi-validators/create.productModel.validator.d.ts +3 -0
  680. package/dist/products/validators/joi-validators/create.productModel.validator.js +132 -0
  681. package/dist/products/validators/joi-validators/create.productModel.validator.js.map +1 -0
  682. package/dist/products/validators/joi-validators/create.productNotification.validator.d.ts +4 -0
  683. package/dist/products/validators/joi-validators/create.productNotification.validator.js +241 -0
  684. package/dist/products/validators/joi-validators/create.productNotification.validator.js.map +1 -0
  685. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.d.ts +3 -0
  686. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.js +57 -0
  687. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.js.map +1 -0
  688. package/dist/products/validators/joi-validators/create.productNotifications.validator.d.ts +0 -0
  689. package/dist/products/validators/joi-validators/create.productNotifications.validator.js +1 -0
  690. package/dist/products/validators/joi-validators/create.productNotifications.validator.js.map +1 -0
  691. package/dist/products/validators/joi-validators/create.productQuota.validator.d.ts +3 -0
  692. package/dist/products/validators/joi-validators/create.productQuota.validator.js +67 -0
  693. package/dist/products/validators/joi-validators/create.productQuota.validator.js.map +1 -0
  694. package/dist/products/validators/joi-validators/create.productStorage.validator.d.ts +3 -0
  695. package/dist/products/validators/joi-validators/create.productStorage.validator.js +158 -0
  696. package/dist/products/validators/joi-validators/create.productStorage.validator.js.map +1 -0
  697. package/dist/products/validators/joi-validators/create.productVector.validator.d.ts +3 -0
  698. package/dist/products/validators/joi-validators/create.productVector.validator.js +136 -0
  699. package/dist/products/validators/joi-validators/create.productVector.validator.js.map +1 -0
  700. package/dist/products/validators/joi-validators/create.products.validator.d.ts +3 -0
  701. package/dist/products/validators/joi-validators/create.products.validator.js +43 -0
  702. package/dist/products/validators/joi-validators/create.products.validator.js.map +1 -0
  703. package/dist/products/validators/joi-validators/create.requestAction.validator.d.ts +2 -0
  704. package/dist/products/validators/joi-validators/create.requestAction.validator.js +45 -0
  705. package/dist/products/validators/joi-validators/create.requestAction.validator.js.map +1 -0
  706. package/dist/products/validators/joi-validators/create.userAuth.validator.d.ts +3 -0
  707. package/dist/products/validators/joi-validators/create.userAuth.validator.js +48 -0
  708. package/dist/products/validators/joi-validators/create.userAuth.validator.js.map +1 -0
  709. package/dist/products/validators/joi-validators/register.productWebhooks.validator.d.ts +3 -0
  710. package/dist/products/validators/joi-validators/register.productWebhooks.validator.js +48 -0
  711. package/dist/products/validators/joi-validators/register.productWebhooks.validator.js.map +1 -0
  712. package/dist/products/validators/joi-validators/update.dataValue.validator.d.ts +3 -0
  713. package/dist/products/validators/joi-validators/update.dataValue.validator.js +104 -0
  714. package/dist/products/validators/joi-validators/update.dataValue.validator.js.map +1 -0
  715. package/dist/products/validators/joi-validators/update.productApp.validator.d.ts +3 -0
  716. package/dist/products/validators/joi-validators/update.productApp.validator.js +42 -0
  717. package/dist/products/validators/joi-validators/update.productApp.validator.js.map +1 -0
  718. package/dist/products/validators/joi-validators/update.productCache.validator.d.ts +3 -0
  719. package/dist/products/validators/joi-validators/update.productCache.validator.js +45 -0
  720. package/dist/products/validators/joi-validators/update.productCache.validator.js.map +1 -0
  721. package/dist/products/validators/joi-validators/update.productDatabase.validator.d.ts +3 -0
  722. package/dist/products/validators/joi-validators/update.productDatabase.validator.js +76 -0
  723. package/dist/products/validators/joi-validators/update.productDatabase.validator.js.map +1 -0
  724. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.d.ts +3 -0
  725. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.js +79 -0
  726. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.js.map +1 -0
  727. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.d.ts +4 -0
  728. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.js +64 -0
  729. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.js.map +1 -0
  730. package/dist/products/validators/joi-validators/update.productEnv.validator.d.ts +3 -0
  731. package/dist/products/validators/joi-validators/update.productEnv.validator.js +46 -0
  732. package/dist/products/validators/joi-validators/update.productEnv.validator.js.map +1 -0
  733. package/dist/products/validators/joi-validators/update.productFallback.validator.d.ts +3 -0
  734. package/dist/products/validators/joi-validators/update.productFallback.validator.js +60 -0
  735. package/dist/products/validators/joi-validators/update.productFallback.validator.js.map +1 -0
  736. package/dist/products/validators/joi-validators/update.productFeature.validator.d.ts +3 -0
  737. package/dist/products/validators/joi-validators/update.productFeature.validator.js +53 -0
  738. package/dist/products/validators/joi-validators/update.productFeature.validator.js.map +1 -0
  739. package/dist/products/validators/joi-validators/update.productFunction.validator.d.ts +3 -0
  740. package/dist/products/validators/joi-validators/update.productFunction.validator.js +41 -0
  741. package/dist/products/validators/joi-validators/update.productFunction.validator.js.map +1 -0
  742. package/dist/products/validators/joi-validators/update.productGraph.validator.d.ts +3 -0
  743. package/dist/products/validators/joi-validators/update.productGraph.validator.js +88 -0
  744. package/dist/products/validators/joi-validators/update.productGraph.validator.js.map +1 -0
  745. package/dist/products/validators/joi-validators/update.productJob.validator.d.ts +3 -0
  746. package/dist/products/validators/joi-validators/update.productJob.validator.js +50 -0
  747. package/dist/products/validators/joi-validators/update.productJob.validator.js.map +1 -0
  748. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.d.ts +3 -0
  749. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.js +52 -0
  750. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.js.map +1 -0
  751. package/dist/products/validators/joi-validators/update.productNotification.validator.d.ts +3 -0
  752. package/dist/products/validators/joi-validators/update.productNotification.validator.js +47 -0
  753. package/dist/products/validators/joi-validators/update.productNotification.validator.js.map +1 -0
  754. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.d.ts +3 -0
  755. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.js +58 -0
  756. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.js.map +1 -0
  757. package/dist/products/validators/joi-validators/update.productQuota.validator.d.ts +3 -0
  758. package/dist/products/validators/joi-validators/update.productQuota.validator.js +64 -0
  759. package/dist/products/validators/joi-validators/update.productQuota.validator.js.map +1 -0
  760. package/dist/products/validators/joi-validators/update.userAuth.validator.d.ts +3 -0
  761. package/dist/products/validators/joi-validators/update.userAuth.validator.js +48 -0
  762. package/dist/products/validators/joi-validators/update.userAuth.validator.js.map +1 -0
  763. package/dist/resilience/fallback.service.d.ts +143 -0
  764. package/dist/resilience/fallback.service.js +771 -0
  765. package/dist/resilience/fallback.service.js.map +1 -0
  766. package/dist/resilience/healthcheck.service.d.ts +165 -0
  767. package/dist/resilience/healthcheck.service.js +1019 -0
  768. package/dist/resilience/healthcheck.service.js.map +1 -0
  769. package/dist/resilience/index.d.ts +104 -0
  770. package/dist/resilience/index.js +140 -0
  771. package/dist/resilience/index.js.map +1 -0
  772. package/dist/resilience/quota.service.d.ts +85 -0
  773. package/dist/resilience/quota.service.js +523 -0
  774. package/dist/resilience/quota.service.js.map +1 -0
  775. package/dist/resilience/resilience.service.d.ts +98 -0
  776. package/dist/resilience/resilience.service.js +560 -0
  777. package/dist/resilience/resilience.service.js.map +1 -0
  778. package/dist/resilience/types/index.d.ts +515 -0
  779. package/dist/resilience/types/index.js +29 -0
  780. package/dist/resilience/types/index.js.map +1 -0
  781. package/dist/runtime/runtime-defaults.d.ts +28 -0
  782. package/dist/runtime/runtime-defaults.js +38 -0
  783. package/dist/runtime/runtime-defaults.js.map +1 -0
  784. package/dist/secrets/index.d.ts +10 -0
  785. package/dist/secrets/index.js +33 -0
  786. package/dist/secrets/index.js.map +1 -0
  787. package/dist/secrets/secrets.resolver.d.ts +52 -0
  788. package/dist/secrets/secrets.resolver.js +236 -0
  789. package/dist/secrets/secrets.resolver.js.map +1 -0
  790. package/dist/secrets/secrets.service.d.ts +93 -0
  791. package/dist/secrets/secrets.service.js +246 -0
  792. package/dist/secrets/secrets.service.js.map +1 -0
  793. package/dist/secrets/secrets.types.d.ts +188 -0
  794. package/dist/secrets/secrets.types.js +87 -0
  795. package/dist/secrets/secrets.types.js.map +1 -0
  796. package/dist/sessions/index.d.ts +50 -0
  797. package/dist/sessions/index.js +96 -0
  798. package/dist/sessions/index.js.map +1 -0
  799. package/dist/sessions/sessions.helper.d.ts +88 -0
  800. package/dist/sessions/sessions.helper.js +190 -0
  801. package/dist/sessions/sessions.helper.js.map +1 -0
  802. package/dist/sessions/sessions.resolver.d.ts +188 -0
  803. package/dist/sessions/sessions.resolver.js +603 -0
  804. package/dist/sessions/sessions.resolver.js.map +1 -0
  805. package/dist/sessions/sessions.service.d.ts +196 -0
  806. package/dist/sessions/sessions.service.js +993 -0
  807. package/dist/sessions/sessions.service.js.map +1 -0
  808. package/dist/sessions/types/index.d.ts +347 -0
  809. package/dist/sessions/types/index.js +6 -0
  810. package/dist/sessions/types/index.js.map +1 -0
  811. package/dist/storage/index.d.ts +66 -0
  812. package/dist/storage/index.js +99 -0
  813. package/dist/storage/index.js.map +1 -0
  814. package/dist/storage/storage.service.d.ts +179 -0
  815. package/dist/storage/storage.service.js +938 -0
  816. package/dist/storage/storage.service.js.map +1 -0
  817. package/dist/storage/types/index.d.ts +273 -0
  818. package/dist/storage/types/index.js +6 -0
  819. package/dist/storage/types/index.js.map +1 -0
  820. package/dist/storage/utils/storage.util.d.ts +62 -0
  821. package/dist/storage/utils/storage.util.js +623 -0
  822. package/dist/storage/utils/storage.util.js.map +1 -0
  823. package/dist/types/actions.types.d.ts +0 -0
  824. package/dist/types/actions.types.js +1 -0
  825. package/dist/types/actions.types.js.map +1 -0
  826. package/dist/types/appBuilder.types.d.ts +316 -0
  827. package/dist/types/appBuilder.types.js +3 -0
  828. package/dist/types/appBuilder.types.js.map +1 -0
  829. package/dist/types/database.types.d.ts +9 -0
  830. package/dist/types/database.types.js +3 -0
  831. package/dist/types/database.types.js.map +1 -0
  832. package/dist/types/enums.d.ts +232 -0
  833. package/dist/types/enums.js +262 -0
  834. package/dist/types/enums.js.map +1 -0
  835. package/dist/types/index.d.ts +12 -0
  836. package/dist/types/index.js +29 -0
  837. package/dist/types/index.js.map +1 -0
  838. package/dist/types/index.types.d.ts +37 -0
  839. package/dist/types/index.types.js +18 -0
  840. package/dist/types/index.types.js.map +1 -0
  841. package/dist/types/inputs.types.d.ts +114 -0
  842. package/dist/types/inputs.types.js +44 -0
  843. package/dist/types/inputs.types.js.map +1 -0
  844. package/dist/types/logs.types.d.ts +19 -0
  845. package/dist/types/logs.types.js +8 -0
  846. package/dist/types/logs.types.js.map +1 -0
  847. package/dist/types/pricing.types.d.ts +4 -0
  848. package/dist/types/pricing.types.js +3 -0
  849. package/dist/types/pricing.types.js.map +1 -0
  850. package/dist/types/processor.types.d.ts +602 -0
  851. package/dist/types/processor.types.js +19 -0
  852. package/dist/types/processor.types.js.map +1 -0
  853. package/dist/types/productsBuilder.types.d.ts +1583 -0
  854. package/dist/types/productsBuilder.types.js +303 -0
  855. package/dist/types/productsBuilder.types.js.map +1 -0
  856. package/dist/types/request-tracker.interface.d.ts +0 -0
  857. package/dist/types/request-tracker.interface.js +1 -0
  858. package/dist/types/request-tracker.interface.js.map +1 -0
  859. package/dist/types/requests.types.d.ts +8 -0
  860. package/dist/types/requests.types.js +3 -0
  861. package/dist/types/requests.types.js.map +1 -0
  862. package/dist/types/workspaces.types.d.ts +28 -0
  863. package/dist/types/workspaces.types.js +4 -0
  864. package/dist/types/workspaces.types.js.map +1 -0
  865. package/dist/utils/constants.d.ts +1 -0
  866. package/dist/utils/constants.js +5 -0
  867. package/dist/utils/constants.js.map +1 -0
  868. package/dist/utils/index.d.ts +2 -0
  869. package/dist/utils/index.js +109 -0
  870. package/dist/utils/index.js.map +1 -0
  871. package/dist/vector/actions/action-manager.d.ts +140 -0
  872. package/dist/vector/actions/action-manager.js +356 -0
  873. package/dist/vector/actions/action-manager.js.map +1 -0
  874. package/dist/vector/adapters/base.adapter.d.ts +169 -0
  875. package/dist/vector/adapters/base.adapter.js +218 -0
  876. package/dist/vector/adapters/base.adapter.js.map +1 -0
  877. package/dist/vector/adapters/index.d.ts +10 -0
  878. package/dist/vector/adapters/index.js +19 -0
  879. package/dist/vector/adapters/index.js.map +1 -0
  880. package/dist/vector/adapters/memory.adapter.d.ts +85 -0
  881. package/dist/vector/adapters/memory.adapter.js +505 -0
  882. package/dist/vector/adapters/memory.adapter.js.map +1 -0
  883. package/dist/vector/adapters/pinecone.adapter.d.ts +52 -0
  884. package/dist/vector/adapters/pinecone.adapter.js +433 -0
  885. package/dist/vector/adapters/pinecone.adapter.js.map +1 -0
  886. package/dist/vector/adapters/qdrant.adapter.d.ts +56 -0
  887. package/dist/vector/adapters/qdrant.adapter.js +442 -0
  888. package/dist/vector/adapters/qdrant.adapter.js.map +1 -0
  889. package/dist/vector/adapters/weaviate.adapter.d.ts +68 -0
  890. package/dist/vector/adapters/weaviate.adapter.js +661 -0
  891. package/dist/vector/adapters/weaviate.adapter.js.map +1 -0
  892. package/dist/vector/index.d.ts +37 -0
  893. package/dist/vector/index.js +72 -0
  894. package/dist/vector/index.js.map +1 -0
  895. package/dist/vector/types/action.interface.d.ts +195 -0
  896. package/dist/vector/types/action.interface.js +100 -0
  897. package/dist/vector/types/action.interface.js.map +1 -0
  898. package/dist/vector/types/connection.interface.d.ts +151 -0
  899. package/dist/vector/types/connection.interface.js +8 -0
  900. package/dist/vector/types/connection.interface.js.map +1 -0
  901. package/dist/vector/types/embedding.interface.d.ts +144 -0
  902. package/dist/vector/types/embedding.interface.js +8 -0
  903. package/dist/vector/types/embedding.interface.js.map +1 -0
  904. package/dist/vector/types/enums.d.ts +104 -0
  905. package/dist/vector/types/enums.js +113 -0
  906. package/dist/vector/types/enums.js.map +1 -0
  907. package/dist/vector/types/index.d.ts +11 -0
  908. package/dist/vector/types/index.js +23 -0
  909. package/dist/vector/types/index.js.map +1 -0
  910. package/dist/vector/types/vector.interface.d.ts +315 -0
  911. package/dist/vector/types/vector.interface.js +8 -0
  912. package/dist/vector/types/vector.interface.js.map +1 -0
  913. package/dist/vector/utils/index.d.ts +7 -0
  914. package/dist/vector/utils/index.js +13 -0
  915. package/dist/vector/utils/index.js.map +1 -0
  916. package/dist/vector/utils/metadata-schema.d.ts +14 -0
  917. package/dist/vector/utils/metadata-schema.js +79 -0
  918. package/dist/vector/utils/metadata-schema.js.map +1 -0
  919. package/dist/vector/utils/vector-error.d.ts +69 -0
  920. package/dist/vector/utils/vector-error.js +116 -0
  921. package/dist/vector/utils/vector-error.js.map +1 -0
  922. package/dist/vector/vector-database.service.d.ts +511 -0
  923. package/dist/vector/vector-database.service.js +1073 -0
  924. package/dist/vector/vector-database.service.js.map +1 -0
  925. package/dist/vector/vector.service.d.ts +283 -0
  926. package/dist/vector/vector.service.js +544 -0
  927. package/dist/vector/vector.service.js.map +1 -0
  928. package/dist/warehouse/executor/index.d.ts +5 -0
  929. package/dist/warehouse/executor/index.js +12 -0
  930. package/dist/warehouse/executor/index.js.map +1 -0
  931. package/dist/warehouse/executor/joins/index.d.ts +5 -0
  932. package/dist/warehouse/executor/joins/index.js +11 -0
  933. package/dist/warehouse/executor/joins/index.js.map +1 -0
  934. package/dist/warehouse/executor/joins/join-executor.d.ts +101 -0
  935. package/dist/warehouse/executor/joins/join-executor.js +493 -0
  936. package/dist/warehouse/executor/joins/join-executor.js.map +1 -0
  937. package/dist/warehouse/executor/joins/semantic-join.d.ts +64 -0
  938. package/dist/warehouse/executor/joins/semantic-join.js +241 -0
  939. package/dist/warehouse/executor/joins/semantic-join.js.map +1 -0
  940. package/dist/warehouse/executor/single-source-executor.d.ts +155 -0
  941. package/dist/warehouse/executor/single-source-executor.js +573 -0
  942. package/dist/warehouse/executor/single-source-executor.js.map +1 -0
  943. package/dist/warehouse/index.d.ts +79 -0
  944. package/dist/warehouse/index.js +111 -0
  945. package/dist/warehouse/index.js.map +1 -0
  946. package/dist/warehouse/parser/index.d.ts +4 -0
  947. package/dist/warehouse/parser/index.js +10 -0
  948. package/dist/warehouse/parser/index.js.map +1 -0
  949. package/dist/warehouse/parser/query-parser.d.ts +181 -0
  950. package/dist/warehouse/parser/query-parser.js +415 -0
  951. package/dist/warehouse/parser/query-parser.js.map +1 -0
  952. package/dist/warehouse/registry/data-source-registry.d.ts +207 -0
  953. package/dist/warehouse/registry/data-source-registry.js +396 -0
  954. package/dist/warehouse/registry/data-source-registry.js.map +1 -0
  955. package/dist/warehouse/registry/index.d.ts +4 -0
  956. package/dist/warehouse/registry/index.js +9 -0
  957. package/dist/warehouse/registry/index.js.map +1 -0
  958. package/dist/warehouse/transactions/index.d.ts +4 -0
  959. package/dist/warehouse/transactions/index.js +9 -0
  960. package/dist/warehouse/transactions/index.js.map +1 -0
  961. package/dist/warehouse/transactions/saga-orchestrator.d.ts +92 -0
  962. package/dist/warehouse/transactions/saga-orchestrator.js +383 -0
  963. package/dist/warehouse/transactions/saga-orchestrator.js.map +1 -0
  964. package/dist/warehouse/types/index.d.ts +9 -0
  965. package/dist/warehouse/types/index.js +33 -0
  966. package/dist/warehouse/types/index.js.map +1 -0
  967. package/dist/warehouse/types/join.interface.d.ts +225 -0
  968. package/dist/warehouse/types/join.interface.js +87 -0
  969. package/dist/warehouse/types/join.interface.js.map +1 -0
  970. package/dist/warehouse/types/query.interface.d.ts +232 -0
  971. package/dist/warehouse/types/query.interface.js +9 -0
  972. package/dist/warehouse/types/query.interface.js.map +1 -0
  973. package/dist/warehouse/types/transaction.interface.d.ts +236 -0
  974. package/dist/warehouse/types/transaction.interface.js +74 -0
  975. package/dist/warehouse/types/transaction.interface.js.map +1 -0
  976. package/dist/warehouse/types/where.interface.d.ts +208 -0
  977. package/dist/warehouse/types/where.interface.js +89 -0
  978. package/dist/warehouse/types/where.interface.js.map +1 -0
  979. package/dist/warehouse/warehouse.service.d.ts +200 -0
  980. package/dist/warehouse/warehouse.service.js +470 -0
  981. package/dist/warehouse/warehouse.service.js.map +1 -0
  982. package/dist/workflows/index.d.ts +30 -0
  983. package/dist/workflows/index.js +64 -0
  984. package/dist/workflows/index.js.map +1 -0
  985. package/dist/workflows/types/index.d.ts +6 -0
  986. package/dist/workflows/types/index.js +23 -0
  987. package/dist/workflows/types/index.js.map +1 -0
  988. package/dist/workflows/types/workflows.types.d.ts +1095 -0
  989. package/dist/workflows/types/workflows.types.js +13 -0
  990. package/dist/workflows/types/workflows.types.js.map +1 -0
  991. package/dist/workflows/workflow-builder.d.ts +70 -0
  992. package/dist/workflows/workflow-builder.js +353 -0
  993. package/dist/workflows/workflow-builder.js.map +1 -0
  994. package/dist/workflows/workflow-executor.d.ts +289 -0
  995. package/dist/workflows/workflow-executor.js +2467 -0
  996. package/dist/workflows/workflow-executor.js.map +1 -0
  997. package/dist/workflows/workflows.service.d.ts +412 -0
  998. package/dist/workflows/workflows.service.js +2233 -0
  999. package/dist/workflows/workflows.service.js.map +1 -0
  1000. package/package.json +3 -2
@@ -0,0 +1,3370 @@
1
+ "use strict";
2
+ /**
3
+ * DatabaseService - Main ORM Service Class
4
+ *
5
+ * This is the primary entry point for all database operations in the Ductape SDK.
6
+ * It provides a unified interface for querying, writing, transactions, schema management,
7
+ * migrations, and database actions across multiple database types.
8
+ *
9
+ * Supported databases: PostgreSQL, MySQL, MongoDB, DynamoDB, MariaDB, Cassandra
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.databaseService = exports.DatabaseConnection = exports.DatabaseService = void 0;
49
+ const enums_1 = require("./types/enums");
50
+ const presave_processor_1 = require("./presave/presave-processor");
51
+ const adapter_factory_1 = require("./adapters/adapter.factory");
52
+ const query_builder_1 = require("./operators/query-builder");
53
+ const aggregation_builder_1 = require("./operators/aggregation-builder");
54
+ const transaction_manager_1 = require("./transactions/transaction-manager");
55
+ const schema_manager_1 = require("./schema/schema-manager");
56
+ const migration_engine_1 = require("./migrations/migration-engine");
57
+ const action_manager_1 = require("./actions/action-manager");
58
+ const trigger_processor_1 = require("./triggers/trigger-processor");
59
+ const trigger_interface_1 = require("./types/trigger.interface");
60
+ const database_error_1 = require("./utils/database-error");
61
+ const products_service_1 = __importDefault(require("../products/services/products.service"));
62
+ const types_1 = require("../types");
63
+ const cache_manager_1 = require("../cache/cache.manager");
64
+ const processor_service_1 = __importDefault(require("../processor/services/processor.service"));
65
+ const crypto_1 = require("crypto");
66
+ const logs_service_1 = __importDefault(require("../logs/logs.service"));
67
+ const logs_types_1 = require("../logs/logs.types");
68
+ const processor_utils_1 = require("../processor/utils/processor.utils");
69
+ const secrets_1 = require("../secrets");
70
+ const cloud_runtime_util_1 = require("../cloud/cloud-runtime.util");
71
+ /** Module-level: last time we logged connect initiated/success/failed per key, to avoid duplicate logs across multiple DatabaseService instances */
72
+ const lastConnectLogAt = new Map();
73
+ const CONNECT_LOG_DEBOUNCE_MS = 15000;
74
+ function getConnectLogKey(product, database, env) {
75
+ return `${product !== null && product !== void 0 ? product : ''}:${database}:${env}`;
76
+ }
77
+ const sharedConnectionRegistry = new Map();
78
+ const sharedConnectInFlight = new Map();
79
+ function getSharedConnectionKey(workspaceId, product, database, env) {
80
+ return `${workspaceId}:${product}:${database}:${env}`;
81
+ }
82
+ /**
83
+ * Main Database Service class
84
+ * Provides unified ORM interface for all supported databases
85
+ */
86
+ class DatabaseService {
87
+ /**
88
+ * Create a new DatabaseService instance
89
+ * @param config - Optional configuration for authentication and workspace context
90
+ */
91
+ constructor(config) {
92
+ this.adapters = new Map();
93
+ this.connectionContexts = new Map();
94
+ this.currentContext = null;
95
+ this.schemaManagers = new Map();
96
+ this.migrationEngines = new Map();
97
+ /** Service configuration */
98
+ this.config = null;
99
+ /** ProductBuilder instances cache (keyed by product tag) */
100
+ this.productBuilders = new Map();
101
+ /** LogService instance for logging operations */
102
+ this.logService = null;
103
+ /** Current product ID for logging */
104
+ this.productId = '';
105
+ /** CacheManager for two-tier caching (Redis + remote) */
106
+ this.cacheManager = null;
107
+ /** Private keys cache for products (keyed by product tag) */
108
+ this.privateKeys = new Map();
109
+ /** Local cache for cache configurations to avoid repeated API calls (5 minute TTL) */
110
+ this.cacheConfigCache = new Map();
111
+ /** In-flight connect() promises per contextKey to deduplicate concurrent connects and avoid duplicate logs */
112
+ this.connectPromises = new Map();
113
+ this.runtimeDefaults = {};
114
+ this.config = config || null;
115
+ this.adapterFactory = new adapter_factory_1.AdapterFactory();
116
+ this.transactionManager = new transaction_manager_1.TransactionManager();
117
+ this.actionManager = new action_manager_1.ActionManager(this);
118
+ this._privateKey = (config === null || config === void 0 ? void 0 : config.private_key) || '';
119
+ if ((config === null || config === void 0 ? void 0 : config.default_product) || (config === null || config === void 0 ? void 0 : config.default_env)) {
120
+ this.runtimeDefaults = {
121
+ default_product: config.default_product,
122
+ default_env: config.default_env,
123
+ };
124
+ }
125
+ // Initialize CacheManager (Redis is optional - Tier 1 internal cache and Tier 3 remote cache always work)
126
+ if ((config === null || config === void 0 ? void 0 : config.workspace_id) && (config === null || config === void 0 ? void 0 : config.public_key) && (config === null || config === void 0 ? void 0 : config.user_id) && (config === null || config === void 0 ? void 0 : config.token)) {
127
+ this.cacheManager = new cache_manager_1.CacheManager({
128
+ workspace_id: config.workspace_id,
129
+ public_key: config.public_key,
130
+ user_id: config.user_id,
131
+ token: config.token,
132
+ env_type: config.env_type,
133
+ redis_client: config.redis_client, // Optional - Tier 2 cache
134
+ });
135
+ }
136
+ }
137
+ /**
138
+ * Get or create a SchemaManager for the given adapter key or current context
139
+ */
140
+ getSchemaManager(adapterKey) {
141
+ // If no key provided, use current context
142
+ if (!adapterKey) {
143
+ if (!this.currentContext) {
144
+ throw new database_error_1.DatabaseError('No active database connection. Please connect first.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
145
+ }
146
+ adapterKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
147
+ }
148
+ let manager = this.schemaManagers.get(adapterKey);
149
+ if (!manager) {
150
+ const adapter = this.adapters.get(adapterKey);
151
+ if (!adapter) {
152
+ throw new database_error_1.DatabaseError(`No adapter found for key: ${adapterKey}`, enums_1.DatabaseErrorType.NOT_FOUND);
153
+ }
154
+ manager = new schema_manager_1.SchemaManager(adapter);
155
+ this.schemaManagers.set(adapterKey, manager);
156
+ }
157
+ return manager;
158
+ }
159
+ /**
160
+ * Get or create a MigrationEngine for the given adapter key or current context
161
+ */
162
+ getMigrationEngine(adapterKey) {
163
+ // If no key provided, use current context
164
+ if (!adapterKey) {
165
+ if (!this.currentContext) {
166
+ throw new database_error_1.DatabaseError('No active database connection. Please connect first.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
167
+ }
168
+ adapterKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
169
+ }
170
+ let engine = this.migrationEngines.get(adapterKey);
171
+ if (!engine) {
172
+ const adapter = this.adapters.get(adapterKey);
173
+ if (!adapter) {
174
+ throw new database_error_1.DatabaseError(`No adapter found for key: ${adapterKey}`, enums_1.DatabaseErrorType.NOT_FOUND);
175
+ }
176
+ engine = new migration_engine_1.MigrationEngine(adapter);
177
+ this.migrationEngines.set(adapterKey, engine);
178
+ }
179
+ return engine;
180
+ }
181
+ // ==================== PRODUCT BUILDER MANAGEMENT ====================
182
+ /**
183
+ * Create a new ProductBuilder instance
184
+ */
185
+ createNewProductBuilder() {
186
+ if (!this.config) {
187
+ throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
188
+ }
189
+ return new products_service_1.default({
190
+ workspace_id: this.config.workspace_id,
191
+ public_key: this.config.public_key,
192
+ user_id: this.config.user_id,
193
+ token: this.config.token,
194
+ env_type: this.config.env_type,
195
+ access_key: this.config.access_key,
196
+ });
197
+ }
198
+ /**
199
+ * Get or create a ProductBuilder instance for the given product tag
200
+ */
201
+ async getProductBuilder(productTag) {
202
+ let builder = this.productBuilders.get(productTag);
203
+ if (!builder) {
204
+ builder = this.createNewProductBuilder();
205
+ await builder.initializeProductByTag(productTag);
206
+ this.productBuilders.set(productTag, builder);
207
+ // Update productId for logging
208
+ this.productId = builder.fetchProductId() || '';
209
+ // Cache private key for caching operations
210
+ const privateKey = builder.fetchPrivateKey();
211
+ if (privateKey) {
212
+ this.privateKeys.set(productTag, privateKey);
213
+ }
214
+ }
215
+ return builder;
216
+ }
217
+ /**
218
+ * Initialize logging service
219
+ */
220
+ initializeLogService() {
221
+ var _a;
222
+ if (!this.logService && this.config) {
223
+ this.logService = new logs_service_1.default({
224
+ product_id: this.productId,
225
+ workspace_id: this.config.workspace_id,
226
+ public_key: this.config.public_key,
227
+ user_id: this.config.user_id,
228
+ token: this.config.token,
229
+ env_type: this.config.env_type,
230
+ workspace_private_key: (_a = this._privateKey) !== null && _a !== void 0 ? _a : undefined,
231
+ });
232
+ }
233
+ }
234
+ /**
235
+ * Create a new ProcessorService instance for job scheduling
236
+ */
237
+ createNewProcessor() {
238
+ if (!this.config) {
239
+ throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
240
+ }
241
+ return new processor_service_1.default({
242
+ workspace_id: this.config.workspace_id,
243
+ public_key: this.config.public_key,
244
+ user_id: this.config.user_id,
245
+ token: this.config.token,
246
+ env_type: this.config.env_type,
247
+ private_key: this._privateKey,
248
+ });
249
+ }
250
+ // ==================== DATABASE CRUD OPERATIONS ====================
251
+ /**
252
+ * Register a new database configuration for a product
253
+ * @param productTag - The product tag
254
+ * @param data - The database configuration data
255
+ */
256
+ async registerDatabase(productTag, data) {
257
+ const builder = await this.getProductBuilder(productTag);
258
+ return builder.createDatabase(data);
259
+ }
260
+ /**
261
+ * Fetch all databases for a product
262
+ * @param productTag - The product tag
263
+ * @returns Array of database configurations
264
+ */
265
+ async fetchAllDatabases(productTag) {
266
+ const builder = await this.getProductBuilder(productTag);
267
+ return builder.fetchDatabases();
268
+ }
269
+ /**
270
+ * Fetch a specific database by tag
271
+ * @param productTag - The product tag
272
+ * @param databaseTag - The database tag
273
+ * @returns The database configuration or null if not found
274
+ */
275
+ async fetchDatabase(productTag, databaseTag) {
276
+ const builder = await this.getProductBuilder(productTag);
277
+ return builder.fetchDatabase(databaseTag);
278
+ }
279
+ /**
280
+ * Update a database configuration
281
+ * @param productTag - The product tag
282
+ * @param databaseTag - The database tag
283
+ * @param data - The data to update
284
+ */
285
+ async updateDatabase(productTag, databaseTag, data) {
286
+ const builder = await this.getProductBuilder(productTag);
287
+ // Process connection URLs in envs if provided
288
+ if (data.envs && data.envs.length > 0) {
289
+ const secretsService = (0, secrets_1.getSecretsService)();
290
+ const processedEnvs = [];
291
+ for (const env of data.envs) {
292
+ let connectionUrl = env.connection_url;
293
+ const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
294
+ // If not already a secret reference and we have a secrets service, store it as a secret
295
+ if (!secretCheck.isSecret && secretsService) {
296
+ const secretKey = this.generateDbSecretKey(productTag, databaseTag, env.slug);
297
+ try {
298
+ const exists = await secretsService.exists(secretKey);
299
+ if (exists) {
300
+ await secretsService.update(secretKey, { value: connectionUrl });
301
+ console.log(`[Secrets] Updated existing secret '${secretKey}' for database '${databaseTag}' in environment '${env.slug}'`);
302
+ }
303
+ else {
304
+ await secretsService.create({
305
+ key: secretKey,
306
+ value: connectionUrl,
307
+ description: `Database connection URL for ${databaseTag} in ${env.slug}`,
308
+ scope: [productTag, databaseTag],
309
+ envs: [env.slug],
310
+ });
311
+ console.log(`[Secrets] Created new secret '${secretKey}' for database '${databaseTag}' in environment '${env.slug}'`);
312
+ }
313
+ // Update the connection URL to use the secret reference
314
+ connectionUrl = `$Secret{${secretKey}}`;
315
+ console.log(`[Secrets] Connection URL converted to secret reference: $Secret{${secretKey}}`);
316
+ }
317
+ catch (error) {
318
+ console.warn(`[Secrets] Failed to store database connection URL as secret: ${error}`);
319
+ // Continue with the original connection URL
320
+ }
321
+ }
322
+ processedEnvs.push(Object.assign(Object.assign({}, env), { connection_url: connectionUrl }));
323
+ }
324
+ data = Object.assign(Object.assign({}, data), { envs: processedEnvs });
325
+ }
326
+ return builder.updateDatabase(databaseTag, data);
327
+ }
328
+ // ==================== DATABASE TRIGGER OPERATIONS ====================
329
+ /**
330
+ * Create a database trigger
331
+ * @param productTag - The product tag
332
+ * @param data - The trigger configuration
333
+ */
334
+ async createTrigger(productTag, data) {
335
+ const builder = await this.getProductBuilder(productTag);
336
+ return builder.createDatabaseTrigger(data);
337
+ }
338
+ /**
339
+ * Update a database trigger
340
+ * @param productTag - The product tag
341
+ * @param data - The trigger configuration
342
+ */
343
+ async updateTrigger(productTag, data) {
344
+ const builder = await this.getProductBuilder(productTag);
345
+ return builder.updateDatabaseTrigger(data);
346
+ }
347
+ /**
348
+ * Fetch a database trigger
349
+ * @param productTag - The product tag
350
+ * @param tag - The trigger tag (format: database_tag:trigger_tag)
351
+ */
352
+ async fetchTrigger(productTag, tag) {
353
+ const builder = await this.getProductBuilder(productTag);
354
+ return builder.fetchDatabaseTrigger(tag);
355
+ }
356
+ /**
357
+ * Fetch all triggers for a database
358
+ * @param productTag - The product tag
359
+ * @param databaseTag - The database tag
360
+ */
361
+ async fetchTriggers(productTag, databaseTag) {
362
+ const builder = await this.getProductBuilder(productTag);
363
+ return builder.fetchDatabaseTriggers(databaseTag);
364
+ }
365
+ /**
366
+ * Delete a database trigger
367
+ * @param productTag - The product tag
368
+ * @param tag - The trigger tag (format: database_tag:trigger_tag)
369
+ */
370
+ async deleteTrigger(productTag, tag) {
371
+ const builder = await this.getProductBuilder(productTag);
372
+ return builder.deleteDatabaseTrigger(tag);
373
+ }
374
+ /**
375
+ * Get the current service configuration
376
+ */
377
+ getConfig() {
378
+ return this.config;
379
+ }
380
+ /**
381
+ * Validate cache tag exists in product and return cache configuration
382
+ * Uses local in-memory cache to avoid repeated API calls (5 minute TTL)
383
+ */
384
+ async validateCache(productTag, cacheTag) {
385
+ const cacheKey = `${productTag}:${cacheTag}`;
386
+ const cached = this.cacheConfigCache.get(cacheKey);
387
+ const now = Date.now();
388
+ const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
389
+ // Return cached config if still valid
390
+ if (cached && (now - cached.fetchedAt) < CACHE_TTL) {
391
+ return { expiry: cached.expiry };
392
+ }
393
+ // Fetch from API and cache the result
394
+ const builder = await this.getProductBuilder(productTag);
395
+ const cache = await builder.fetchCache(cacheTag);
396
+ if (!cache) {
397
+ throw new database_error_1.DatabaseError(`Cache configuration '${cacheTag}' does not exist`, enums_1.DatabaseErrorType.NOT_FOUND);
398
+ }
399
+ this.cacheConfigCache.set(cacheKey, { expiry: cache.expiry, fetchedAt: now });
400
+ return { expiry: cache.expiry };
401
+ }
402
+ /**
403
+ * Update the service configuration (used after auth is complete)
404
+ */
405
+ updateConfig(config) {
406
+ if (this.config) {
407
+ this.config = Object.assign(Object.assign({}, this.config), config);
408
+ }
409
+ else {
410
+ this.config = config;
411
+ }
412
+ }
413
+ /**
414
+ * Get workspace ID from config
415
+ */
416
+ getWorkspaceId() {
417
+ var _a;
418
+ return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || null;
419
+ }
420
+ /**
421
+ * Get user ID from config
422
+ */
423
+ getUserId() {
424
+ var _a;
425
+ return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.user_id) || null;
426
+ }
427
+ /**
428
+ * Get authentication token from config
429
+ */
430
+ getToken() {
431
+ var _a;
432
+ return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.token) || null;
433
+ }
434
+ /**
435
+ * Get environment type from config
436
+ */
437
+ getEnvType() {
438
+ var _a;
439
+ return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.env_type) || null;
440
+ }
441
+ // ==================== CONNECTION MANAGEMENT ====================
442
+ /**
443
+ * Create/register a new database configuration
444
+ *
445
+ * @example
446
+ * // Persist to product
447
+ * await ductape.database.create({
448
+ * product: 'my-product',
449
+ * name: 'User Database',
450
+ * tag: 'users-db',
451
+ * type: 'postgresql',
452
+ * description: 'Stores user accounts and profiles',
453
+ * envs: [
454
+ * { slug: 'dev', connection_url: 'postgresql://localhost:5432/myapp_dev' },
455
+ * { slug: 'prd', connection_url: 'postgresql://prod-host:5432/myapp_prod' },
456
+ * ],
457
+ * });
458
+ *
459
+ * // Local only (not persisted)
460
+ * await ductape.database.create({
461
+ * name: 'Temp Database',
462
+ * tag: 'temp-db',
463
+ * type: 'postgresql',
464
+ * envs: [{ slug: 'dev', connection_url: 'postgresql://localhost:5432/temp' }],
465
+ * });
466
+ */
467
+ async create(config) {
468
+ var _a;
469
+ // Validate required fields
470
+ if (!config.name || !config.tag || !config.type || !((_a = config.envs) === null || _a === void 0 ? void 0 : _a.length)) {
471
+ throw new database_error_1.DatabaseError('Missing required fields: name, tag, type, and envs are required', enums_1.DatabaseErrorType.VALIDATION_ERROR);
472
+ }
473
+ const exists = await this.fetchDatabase(config.product, config.tag);
474
+ if (exists) {
475
+ return;
476
+ }
477
+ // Validate database type
478
+ if (!Object.values(enums_1.DatabaseType).includes(config.type)) {
479
+ throw new database_error_1.DatabaseError(`Unsupported database type: ${config.type}. Supported types: ${Object.values(enums_1.DatabaseType).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
480
+ }
481
+ // Process connection URLs - store as secrets if not already secret references
482
+ const secretsService = (0, secrets_1.getSecretsService)();
483
+ const processedEnvs = [];
484
+ for (const env of config.envs) {
485
+ let connectionUrl = env.connection_url;
486
+ const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
487
+ // If not already a secret reference and we have a secrets service, store it as a secret
488
+ if (!secretCheck.isSecret && secretsService && config.product) {
489
+ const secretKey = this.generateDbSecretKey(config.product, config.tag, env.slug);
490
+ try {
491
+ const exists = await secretsService.exists(secretKey);
492
+ if (exists) {
493
+ await secretsService.update(secretKey, { value: connectionUrl });
494
+ }
495
+ else {
496
+ await secretsService.create({
497
+ key: secretKey,
498
+ value: connectionUrl,
499
+ description: `Database connection URL for ${config.tag} in ${env.slug}`,
500
+ scope: [config.product, config.tag],
501
+ envs: [env.slug],
502
+ });
503
+ }
504
+ // Update the connection URL to use the secret reference
505
+ connectionUrl = `$Secret{${secretKey}}`;
506
+ }
507
+ catch (error) {
508
+ // Continue with the original connection URL on failure
509
+ }
510
+ }
511
+ processedEnvs.push(Object.assign(Object.assign({}, env), { connection_url: connectionUrl }));
512
+ }
513
+ // Persist to ProductBuilder if product is specified
514
+ if (config.product) {
515
+ const productBuilder = await this.getProductBuilder(config.product);
516
+ await productBuilder.createDatabase({
517
+ name: config.name,
518
+ tag: config.tag,
519
+ type: config.type, // DatabaseType maps to DatabaseTypes enum
520
+ description: config.description,
521
+ envs: processedEnvs.map(env => ({
522
+ slug: env.slug,
523
+ connection_url: env.connection_url,
524
+ description: env.description,
525
+ })),
526
+ });
527
+ }
528
+ // Create local adapters and connection contexts
529
+ this.createAdapter({
530
+ tag: config.tag,
531
+ name: config.name,
532
+ type: config.type,
533
+ description: config.description,
534
+ envs: processedEnvs,
535
+ });
536
+ }
537
+ /**
538
+ * Create local adapter and connection context for a database configuration.
539
+ * This is a lightweight operation that only sets up local state without API calls.
540
+ * Use this when the database config is already fetched/decrypted from the API.
541
+ *
542
+ * @param config - The database configuration (already decrypted if from API)
543
+ */
544
+ createAdapter(config) {
545
+ var _a;
546
+ // Validate required fields
547
+ if (!config.tag || !config.type || !((_a = config.envs) === null || _a === void 0 ? void 0 : _a.length)) {
548
+ throw new database_error_1.DatabaseError('Database configuration requires tag, type, and at least one environment', enums_1.DatabaseErrorType.VALIDATION_ERROR);
549
+ }
550
+ const databaseType = typeof config.type === 'string'
551
+ ? this.convertDatabaseType(config.type)
552
+ : config.type;
553
+ // Validate database type
554
+ if (!Object.values(enums_1.DatabaseType).includes(databaseType)) {
555
+ throw new database_error_1.DatabaseError(`Unsupported database type: ${config.type}. Supported types: ${Object.values(enums_1.DatabaseType).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
556
+ }
557
+ // Create adapters and contexts for each environment
558
+ for (const envConfig of config.envs) {
559
+ const contextKey = this.buildContextKey(config.tag, envConfig.slug);
560
+ // Skip if already exists
561
+ if (this.adapters.has(contextKey) && this.connectionContexts.has(contextKey)) {
562
+ continue;
563
+ }
564
+ const adapter = this.adapterFactory.create(databaseType);
565
+ this.adapters.set(contextKey, adapter);
566
+ this.connectionContexts.set(contextKey, {
567
+ database: config.tag,
568
+ env: envConfig.slug,
569
+ type: databaseType,
570
+ connectionUrl: envConfig.connection_url,
571
+ connected: false,
572
+ name: config.name,
573
+ description: config.description,
574
+ authMode: envConfig.authMode,
575
+ cloudConnectionId: envConfig.cloudConnectionId,
576
+ });
577
+ }
578
+ }
579
+ /**
580
+ * Generate a secret key for database connection URLs
581
+ * Format: DB_{PRODUCT}_{ASSET_TAG}_{ENV}_{KEY}
582
+ *
583
+ * Where:
584
+ * - PRODUCT = productTag.split('.')[1] (second part after workspace)
585
+ * - ASSET_TAG = if dbTag starts with same workspace prefix, use second part; otherwise sanitize full tag
586
+ * - All parts are automatically capitalized
587
+ */
588
+ generateDbSecretKey(product, dbTag, env) {
589
+ const sanitize = (str) => str.toUpperCase().replace(/[^A-Z0-9]/g, '_');
590
+ // Support both ':' and '.' delimiters for product tags (e.g., 'ductape:rematch' or 'ductape.rematch')
591
+ const productParts = product.includes(':') ? product.split(':') : product.split('.');
592
+ const productKey = productParts[1] || productParts[0]; // Use product name (index 1), fallback to index 0
593
+ const workspace = productParts[0];
594
+ // Support both ':' and '.' delimiters for database tags
595
+ const dbParts = dbTag.includes(':') ? dbTag.split(':') : dbTag.split('.');
596
+ let assetTag;
597
+ if (dbParts.length > 1 && dbParts[0] === workspace) {
598
+ // Same workspace prefix, use second part
599
+ assetTag = dbParts[1];
600
+ }
601
+ else {
602
+ // Different or no prefix, use full tag
603
+ assetTag = dbTag;
604
+ }
605
+ return `DB_${sanitize(productKey)}_${sanitize(assetTag)}_${sanitize(env)}_URL`;
606
+ }
607
+ resolveRuntimeProductEnv(fields) {
608
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
609
+ return {
610
+ product: (_d = (_c = (_a = fields.product) !== null && _a !== void 0 ? _a : (_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.product) !== null && _c !== void 0 ? _c : this.runtimeDefaults.default_product) !== null && _d !== void 0 ? _d : (_e = this.config) === null || _e === void 0 ? void 0 : _e.default_product,
611
+ env: (_j = (_h = (_f = fields.env) !== null && _f !== void 0 ? _f : (_g = this.currentContext) === null || _g === void 0 ? void 0 : _g.env) !== null && _h !== void 0 ? _h : this.runtimeDefaults.default_env) !== null && _j !== void 0 ? _j : (_k = this.config) === null || _k === void 0 ? void 0 : _k.default_env,
612
+ };
613
+ }
614
+ mergeConnectionConfig(config) {
615
+ const { product, env } = this.resolveRuntimeProductEnv(config);
616
+ if (!(product === null || product === void 0 ? void 0 : product.trim()) || !(env === null || env === void 0 ? void 0 : env.trim())) {
617
+ throw new database_error_1.DatabaseError('product and env are required. Pass them in connect() or set both on the Ductape constructor.', enums_1.DatabaseErrorType.VALIDATION_ERROR);
618
+ }
619
+ return Object.assign(Object.assign({}, config), { product: product.trim(), env: env.trim() });
620
+ }
621
+ /**
622
+ * Connect to a database
623
+ *
624
+ * @example
625
+ * const result = await ductape.database.connect({
626
+ * env: 'dev',
627
+ * product: 'my-app',
628
+ * database: 'users-db',
629
+ * });
630
+ * console.log('Connected:', result.connected);
631
+ * console.log('Database Version:', result.version);
632
+ * console.log('Latency:', result.latency, 'ms');
633
+ *
634
+ * // With the returned connection object, you can use scoped operations:
635
+ * const db = await ductape.databases.connect({ env: 'dev', product: 'my-app', database: 'users-db' });
636
+ * await db.triggers.create({ tag: 'my-trigger', ... });
637
+ */
638
+ async connect(config) {
639
+ var _a, _b, _c;
640
+ config = this.mergeConnectionConfig(config);
641
+ const process_id = (0, processor_utils_1.generateObjectId)();
642
+ const start = Date.now();
643
+ const contextKey = this.buildContextKey(config.database, config.env);
644
+ const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
645
+ const product = (_c = config.product) !== null && _c !== void 0 ? _c : '';
646
+ // Use shared registry only when we have an authenticated scope (workspace + product).
647
+ // Connections are never shared across workspaces or products.
648
+ const useShared = workspaceId !== '' && product !== '';
649
+ if (useShared) {
650
+ const sharedKey = getSharedConnectionKey(workspaceId, product, config.database, config.env);
651
+ const existing = sharedConnectionRegistry.get(sharedKey);
652
+ if (existing === null || existing === void 0 ? void 0 : existing.context.connected) {
653
+ this.adapters.set(contextKey, existing.adapter);
654
+ this.connectionContexts.set(contextKey, existing.context);
655
+ return new DatabaseConnection(this, config.database, config.env, config.product || '');
656
+ }
657
+ const inFlight = sharedConnectInFlight.get(sharedKey);
658
+ if (inFlight) {
659
+ const entry = await inFlight;
660
+ this.adapters.set(contextKey, entry.adapter);
661
+ this.connectionContexts.set(contextKey, entry.context);
662
+ return new DatabaseConnection(this, config.database, config.env, config.product || '');
663
+ }
664
+ const createPromise = this.connectAndRegisterShared(sharedKey, config, contextKey, process_id, start);
665
+ sharedConnectInFlight.set(sharedKey, createPromise);
666
+ try {
667
+ const entry = await createPromise;
668
+ this.adapters.set(contextKey, entry.adapter);
669
+ this.connectionContexts.set(contextKey, entry.context);
670
+ return new DatabaseConnection(this, config.database, config.env, config.product || '');
671
+ }
672
+ finally {
673
+ sharedConnectInFlight.delete(sharedKey);
674
+ }
675
+ }
676
+ // Per-instance path when shared registry is not used (no workspace/product scope)
677
+ let adapter = this.adapters.get(contextKey);
678
+ let context = this.connectionContexts.get(contextKey);
679
+ if (!adapter || !context) {
680
+ if (!config.product) {
681
+ throw new database_error_1.DatabaseError(`Database '${config.database}' not found locally. Please provide 'product' to fetch from remote.`, enums_1.DatabaseErrorType.NOT_FOUND);
682
+ }
683
+ await this.getProductBuilder(config.product);
684
+ const dbConfig = await this.fetchDatabase(config.product, config.database);
685
+ if (!dbConfig) {
686
+ throw new database_error_1.DatabaseError(`Database '${config.database}' not found for product '${config.product}'.`, enums_1.DatabaseErrorType.NOT_FOUND);
687
+ }
688
+ this.createAdapter({
689
+ tag: config.database,
690
+ name: dbConfig.name,
691
+ type: dbConfig.type,
692
+ description: dbConfig.description,
693
+ envs: dbConfig.envs.map(e => ({
694
+ slug: e.slug,
695
+ connection_url: e.connection_url,
696
+ description: e.description,
697
+ authMode: e.authMode,
698
+ cloudConnectionId: e.cloudConnectionId,
699
+ })),
700
+ });
701
+ adapter = this.adapters.get(contextKey);
702
+ context = this.connectionContexts.get(contextKey);
703
+ }
704
+ if (!adapter || !context) {
705
+ throw new database_error_1.DatabaseError(`Failed to initialize adapter for ${contextKey}`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
706
+ }
707
+ if (context.connected) {
708
+ return new DatabaseConnection(this, config.database, config.env, config.product || '');
709
+ }
710
+ const inFlight = this.connectPromises.get(contextKey);
711
+ if (inFlight) {
712
+ return inFlight;
713
+ }
714
+ const connectPromise = this.runConnect(config, contextKey, adapter, context, process_id, start);
715
+ this.connectPromises.set(contextKey, connectPromise);
716
+ try {
717
+ return await connectPromise;
718
+ }
719
+ finally {
720
+ this.connectPromises.delete(contextKey);
721
+ }
722
+ }
723
+ /**
724
+ * Disconnect any existing connection to this resource from the SDK (shared registry and this instance) before creating a fresh one.
725
+ */
726
+ async disconnectExistingForResource(sharedKey, contextKey, workspaceId, product, database, env) {
727
+ const existingInRegistry = sharedConnectionRegistry.get(sharedKey);
728
+ if (existingInRegistry) {
729
+ try {
730
+ await existingInRegistry.adapter.disconnect();
731
+ existingInRegistry.context.connected = false;
732
+ }
733
+ catch (_a) {
734
+ // Non-fatal
735
+ }
736
+ sharedConnectionRegistry.delete(sharedKey);
737
+ }
738
+ const context = this.connectionContexts.get(contextKey);
739
+ if (context === null || context === void 0 ? void 0 : context.connected) {
740
+ const adapter = this.adapters.get(contextKey);
741
+ if (adapter) {
742
+ try {
743
+ await adapter.disconnect();
744
+ }
745
+ catch (_b) {
746
+ // Non-fatal
747
+ }
748
+ context.connected = false;
749
+ if (workspaceId && product) {
750
+ sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, database, env));
751
+ }
752
+ }
753
+ }
754
+ }
755
+ /**
756
+ * Get or create adapter/context, connect, and register in shared registry.
757
+ * Only used when connect() is scoped with workspace_id and product (no cross-tenant sharing).
758
+ */
759
+ async connectAndRegisterShared(sharedKey, config, contextKey, process_id, start) {
760
+ var _a, _b, _c;
761
+ const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
762
+ const product = (_c = config.product) !== null && _c !== void 0 ? _c : '';
763
+ await this.disconnectExistingForResource(sharedKey, contextKey, workspaceId, product, config.database, config.env);
764
+ let adapter = this.adapters.get(contextKey);
765
+ let context = this.connectionContexts.get(contextKey);
766
+ if (!adapter || !context) {
767
+ if (!config.product) {
768
+ throw new database_error_1.DatabaseError(`Database '${config.database}' not found locally. Please provide 'product' to fetch from remote.`, enums_1.DatabaseErrorType.NOT_FOUND);
769
+ }
770
+ await this.getProductBuilder(config.product);
771
+ const dbConfig = await this.fetchDatabase(config.product, config.database);
772
+ if (!dbConfig) {
773
+ throw new database_error_1.DatabaseError(`Database '${config.database}' not found for product '${config.product}'.`, enums_1.DatabaseErrorType.NOT_FOUND);
774
+ }
775
+ this.createAdapter({
776
+ tag: config.database,
777
+ name: dbConfig.name,
778
+ type: dbConfig.type,
779
+ description: dbConfig.description,
780
+ envs: dbConfig.envs.map(e => ({
781
+ slug: e.slug,
782
+ connection_url: e.connection_url,
783
+ description: e.description,
784
+ authMode: e.authMode,
785
+ cloudConnectionId: e.cloudConnectionId,
786
+ })),
787
+ });
788
+ adapter = this.adapters.get(contextKey);
789
+ context = this.connectionContexts.get(contextKey);
790
+ }
791
+ await this.runConnect(config, contextKey, adapter, context, process_id, start);
792
+ const entry = { adapter, context };
793
+ const raceExisting = sharedConnectionRegistry.get(sharedKey);
794
+ if (raceExisting) {
795
+ try {
796
+ await raceExisting.adapter.disconnect();
797
+ raceExisting.context.connected = false;
798
+ }
799
+ catch (_d) {
800
+ // Non-fatal
801
+ }
802
+ sharedConnectionRegistry.delete(sharedKey);
803
+ }
804
+ sharedConnectionRegistry.set(sharedKey, entry);
805
+ return entry;
806
+ }
807
+ /**
808
+ * Performs the actual connect (resolve URL, adapter.connect(), log). Called once per contextKey when not already connected.
809
+ */
810
+ async runConnect(config, contextKey, adapter, context, process_id, start) {
811
+ var _a, _b, _c, _d, _e, _f, _g;
812
+ this.initializeLogService();
813
+ const envValue = config.env || '';
814
+ const baseLogs = {
815
+ product_tag: config.product || '',
816
+ workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '',
817
+ env: envValue,
818
+ app_env: envValue,
819
+ process_id,
820
+ type: logs_types_1.LogEventTypes.DATABASE,
821
+ parent_tag: config.database,
822
+ child_tag: 'connect',
823
+ data: { database: config.database, env: envValue, operation: 'connect' },
824
+ };
825
+ const logKey = getConnectLogKey(config.product, config.database, config.env);
826
+ const now = Date.now();
827
+ const last = (_b = lastConnectLogAt.get(logKey)) !== null && _b !== void 0 ? _b : {};
828
+ if (this.logService && (!last.initiated || now - last.initiated >= CONNECT_LOG_DEBOUNCE_MS)) {
829
+ lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, last), { initiated: now }));
830
+ this.logService.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database connect - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
831
+ }
832
+ try {
833
+ let connectionUrl = context.connectionUrl;
834
+ if (this.config && (context.authMode === 'cloud_connection' || (0, secrets_1.isSecretReference)(connectionUrl).isSecret)) {
835
+ const resolvedEnv = await (0, cloud_runtime_util_1.resolveCloudLinkedEnvConfig)({
836
+ connection_url: context.connectionUrl,
837
+ authMode: context.authMode,
838
+ cloudConnectionId: context.cloudConnectionId,
839
+ }, {
840
+ environment: this.config.env_type,
841
+ auth: {
842
+ token: this.config.token,
843
+ public_key: this.config.public_key,
844
+ user_id: this.config.user_id,
845
+ workspace_id: this.config.workspace_id,
846
+ access_key: this.config.access_key,
847
+ },
848
+ productTag: config.product || '',
849
+ componentTag: config.database,
850
+ envSlug: config.env,
851
+ });
852
+ connectionUrl = String(resolvedEnv.connection_url || connectionUrl);
853
+ }
854
+ else {
855
+ const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
856
+ if (secretCheck.isSecret) {
857
+ const secretsService = (0, secrets_1.getSecretsService)();
858
+ if (secretsService) {
859
+ const resolved = await secretsService.resolve(connectionUrl, { env: config.env });
860
+ connectionUrl = resolved.value;
861
+ }
862
+ else {
863
+ throw new database_error_1.DatabaseError(`Connection URL contains secret reference but secrets service is not initialized.`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
864
+ }
865
+ }
866
+ }
867
+ await adapter.connect({
868
+ connectionUrl,
869
+ });
870
+ context.connected = true;
871
+ context.product = config.product;
872
+ this.currentContext = context;
873
+ const end = Date.now();
874
+ const lastSuccess = (_c = lastConnectLogAt.get(logKey)) !== null && _c !== void 0 ? _c : {};
875
+ if (this.logService && (!lastSuccess.success || end - lastSuccess.success >= CONNECT_LOG_DEBOUNCE_MS)) {
876
+ lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, lastSuccess), { success: end }));
877
+ this.logService.add(Object.assign(Object.assign({}, baseLogs), { start,
878
+ end, message: 'Database connect - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
879
+ this.logService.publish();
880
+ }
881
+ return new DatabaseConnection(this, config.database, config.env, config.product || '');
882
+ }
883
+ catch (error) {
884
+ const end = Date.now();
885
+ const lastFail = (_d = lastConnectLogAt.get(logKey)) !== null && _d !== void 0 ? _d : {};
886
+ if (this.logService && (!lastFail.failed || end - lastFail.failed >= CONNECT_LOG_DEBOUNCE_MS)) {
887
+ lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, lastFail), { failed: end }));
888
+ this.logService.add(Object.assign(Object.assign({}, baseLogs), { start,
889
+ end, message: 'Database connect - failed', failed_execution: true, data: { database: config.database, env: config.env, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
890
+ await this.logService.publish();
891
+ }
892
+ const err = error;
893
+ const baseMsg = (_e = err === null || err === void 0 ? void 0 : err.message) !== null && _e !== void 0 ? _e : String(error);
894
+ let detail = baseMsg;
895
+ if (err === null || err === void 0 ? void 0 : err.response) {
896
+ const status = (_f = err.response) === null || _f === void 0 ? void 0 : _f.status;
897
+ const body = (_g = err.response) === null || _g === void 0 ? void 0 : _g.data;
898
+ const bodyStr = typeof body === 'object' ? JSON.stringify(body) : body;
899
+ detail = bodyStr ? `${baseMsg} (HTTP ${status}): ${bodyStr}` : `${baseMsg} (HTTP ${status})`;
900
+ }
901
+ throw new database_error_1.DatabaseError(`Failed to connect to database: ${detail}`, enums_1.DatabaseErrorType.CONNECTION_ERROR, error);
902
+ }
903
+ }
904
+ /**
905
+ * Test database connection without establishing persistent connection
906
+ *
907
+ * @example
908
+ * const result = await ductape.database.testConnection({
909
+ * env: 'dev',
910
+ * product: 'my-app',
911
+ * database: 'users-db',
912
+ * });
913
+ * if (result.connected) {
914
+ * console.log('Connection successful!');
915
+ * } else {
916
+ * console.error('Connection failed:', result.error);
917
+ * }
918
+ */
919
+ async testConnection(config) {
920
+ const contextKey = this.buildContextKey(config.database, config.env);
921
+ let adapter = this.adapters.get(contextKey);
922
+ let context = this.connectionContexts.get(contextKey);
923
+ if (!adapter || !context) {
924
+ return {
925
+ connected: false,
926
+ error: `Database '${config.database}' not found for environment '${config.env}'`,
927
+ };
928
+ }
929
+ const startTime = Date.now();
930
+ try {
931
+ const result = await adapter.testConnection({
932
+ connectionUrl: context.connectionUrl,
933
+ });
934
+ return {
935
+ connected: result.connected,
936
+ version: result.version,
937
+ latency: Date.now() - startTime,
938
+ };
939
+ }
940
+ catch (error) {
941
+ return {
942
+ connected: false,
943
+ error: error.message,
944
+ latency: Date.now() - startTime,
945
+ };
946
+ }
947
+ }
948
+ /**
949
+ * Disconnect from the current database
950
+ */
951
+ async disconnect() {
952
+ var _a, _b, _c;
953
+ if (this.currentContext) {
954
+ const contextKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
955
+ const adapter = this.adapters.get(contextKey);
956
+ if (adapter) {
957
+ await adapter.disconnect();
958
+ this.currentContext.connected = false;
959
+ const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
960
+ const product = (_c = this.currentContext.product) !== null && _c !== void 0 ? _c : '';
961
+ if (workspaceId && product) {
962
+ sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, this.currentContext.database, this.currentContext.env));
963
+ }
964
+ }
965
+ this.currentContext = null;
966
+ }
967
+ }
968
+ /**
969
+ * Close all database connections
970
+ *
971
+ * @example
972
+ * await ductape.database.closeAll();
973
+ */
974
+ async closeAll() {
975
+ var _a, _b, _c;
976
+ const disconnectPromises = [];
977
+ const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
978
+ for (const [key, adapter] of this.adapters) {
979
+ disconnectPromises.push(adapter.disconnect());
980
+ const context = this.connectionContexts.get(key);
981
+ if (context) {
982
+ context.connected = false;
983
+ const product = (_c = context.product) !== null && _c !== void 0 ? _c : '';
984
+ if (workspaceId && product) {
985
+ sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, context.database, context.env));
986
+ }
987
+ }
988
+ }
989
+ await Promise.all(disconnectPromises);
990
+ this.currentContext = null;
991
+ }
992
+ /**
993
+ * Fetch all registered databases
994
+ *
995
+ * @example
996
+ * const databases = await ductape.database.fetchAll();
997
+ * databases.forEach((db) => {
998
+ * console.log(`${db.name} (${db.tag}): ${db.type}`);
999
+ * });
1000
+ */
1001
+ async fetchAll(product) {
1002
+ const databases = new Map();
1003
+ for (const [key, context] of this.connectionContexts) {
1004
+ if (!databases.has(context.database)) {
1005
+ databases.set(context.database, {
1006
+ product,
1007
+ name: context.name || context.database,
1008
+ tag: context.database,
1009
+ type: context.type,
1010
+ description: context.description,
1011
+ envs: [],
1012
+ });
1013
+ }
1014
+ databases.get(context.database).envs.push({
1015
+ slug: context.env,
1016
+ connection_url: context.connectionUrl,
1017
+ });
1018
+ }
1019
+ return Array.from(databases.values());
1020
+ }
1021
+ /**
1022
+ * Fetch a specific database configuration
1023
+ *
1024
+ * @example
1025
+ * const usersDb = await ductape.database.fetch('users-db');
1026
+ * console.log('Database:', usersDb.name);
1027
+ * console.log('Type:', usersDb.type);
1028
+ * console.log('Environments:', usersDb.envs);
1029
+ */
1030
+ async fetch(product, database) {
1031
+ const databases = await this.fetchAll(product);
1032
+ return databases.find((db) => db.tag === database) || null;
1033
+ }
1034
+ /**
1035
+ * Update a local database configuration
1036
+ *
1037
+ * @example
1038
+ * await ductape.database.updateLocalConfig('users-db', {
1039
+ * name: 'User Database v2',
1040
+ * description: 'Updated user storage',
1041
+ * envs: [
1042
+ * { slug: 'dev', connection_url: 'postgresql://new-dev-host:5432/myapp' },
1043
+ * ],
1044
+ * });
1045
+ */
1046
+ async updateLocalConfig(tag, updates) {
1047
+ for (const [key, context] of this.connectionContexts) {
1048
+ if (context.database === tag) {
1049
+ if (updates.name) {
1050
+ context.name = updates.name;
1051
+ }
1052
+ if (updates.description) {
1053
+ context.description = updates.description;
1054
+ }
1055
+ if (updates.envs) {
1056
+ const envUpdate = updates.envs.find((e) => e.slug === context.env);
1057
+ if (envUpdate) {
1058
+ context.connectionUrl = envUpdate.connection_url;
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+ // ==================== QUERY OPERATIONS ====================
1065
+ /**
1066
+ * Query records from a table
1067
+ *
1068
+ * @example
1069
+ * // With established connection
1070
+ * const result = await ductape.database.query({
1071
+ * table: 'users',
1072
+ * where: { status: 'active' },
1073
+ * orderBy: { column: 'created_at', order: 'DESC' },
1074
+ * limit: 10,
1075
+ * });
1076
+ *
1077
+ * // With explicit connection params
1078
+ * const result = await ductape.database.query({
1079
+ * env: 'prd',
1080
+ * product: 'my-app',
1081
+ * database: 'main-db',
1082
+ * table: 'users',
1083
+ * });
1084
+ */
1085
+ async query(options) {
1086
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
1087
+ const process_id = (0, processor_utils_1.generateObjectId)();
1088
+ const start = Date.now();
1089
+ this.initializeLogService();
1090
+ // Session log fields (will be populated if session is provided)
1091
+ let sessionLogFields = {};
1092
+ let resolvedOptions = options;
1093
+ // Process session if provided
1094
+ if (options.session && options.product) {
1095
+ const builder = await this.getProductBuilder(options.product);
1096
+ const privateKey = builder.fetchPrivateKey();
1097
+ if (privateKey) {
1098
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1099
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1100
+ fetchSessionSelector: async (sessionTag) => {
1101
+ const sessionConfig = await builder.fetchSession(sessionTag);
1102
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1103
+ },
1104
+ });
1105
+ if (sessionResult.error) {
1106
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
1107
+ }
1108
+ resolvedOptions = sessionResult.input;
1109
+ sessionLogFields = sessionResult.logFields;
1110
+ }
1111
+ }
1112
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1113
+ const baseLogs = Object.assign({ product_tag: options.product || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.product) || '', workspace_id: ((_c = this.config) === null || _c === void 0 ? void 0 : _c.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: options.database || ((_d = this.currentContext) === null || _d === void 0 ? void 0 : _d.database) || '', child_tag: 'query', data: {
1114
+ table: options.table,
1115
+ operation: 'query',
1116
+ database: options.database || ((_e = this.currentContext) === null || _e === void 0 ? void 0 : _e.database) || '',
1117
+ env: envValue,
1118
+ where: options.where,
1119
+ select: options.select,
1120
+ orderBy: options.orderBy,
1121
+ limit: options.limit,
1122
+ offset: options.offset,
1123
+ include: options.include,
1124
+ } }, sessionLogFields);
1125
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database query - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1126
+ // Check cache if cache tag is provided
1127
+ // Use product from options or from current context (set during connect)
1128
+ const productTag = options.product || ((_g = this.currentContext) === null || _g === void 0 ? void 0 : _g.product);
1129
+ const privateKey = productTag ? this.privateKeys.get(productTag) : undefined;
1130
+ let queryCacheKey;
1131
+ try {
1132
+ if (options.cache && this.cacheManager && privateKey) {
1133
+ const cacheOptions = {
1134
+ cache_tag: options.cache,
1135
+ product_tag: productTag || '',
1136
+ component_tag: options.database || ((_h = this.currentContext) === null || _h === void 0 ? void 0 : _h.database) || '',
1137
+ component_type: 'database',
1138
+ input: { table: options.table, where: options.where, select: options.select, orderBy: options.orderBy, limit: options.limit, offset: options.offset },
1139
+ privateKey,
1140
+ };
1141
+ const cached = await this.cacheManager.fetch(cacheOptions);
1142
+ queryCacheKey = cached.key;
1143
+ if (cached.hit && cached.data) {
1144
+ const end = Date.now();
1145
+ (_j = this.logService) === null || _j === void 0 ? void 0 : _j.add(Object.assign(Object.assign({}, baseLogs), { start,
1146
+ end, message: `Database query - cache hit (${cached.source})`, successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: cached.key, cache_status: true }));
1147
+ (_k = this.logService) === null || _k === void 0 ? void 0 : _k.publish();
1148
+ return cached.data;
1149
+ }
1150
+ }
1151
+ await this.ensureAdapterFor(resolvedOptions);
1152
+ const adapter = this.getAdapter(resolvedOptions);
1153
+ const queryBuilder = new query_builder_1.QueryBuilder(adapter.getDatabaseType());
1154
+ const builtQuery = queryBuilder.buildQuery(resolvedOptions);
1155
+ const result = await adapter.query(builtQuery);
1156
+ // Store in cache if cache tag is provided
1157
+ if (options.cache && this.cacheManager && privateKey && productTag) {
1158
+ const cacheConfig = await this.validateCache(productTag, options.cache);
1159
+ const cacheOptions = {
1160
+ cache_tag: options.cache,
1161
+ product_tag: productTag,
1162
+ component_tag: options.database || ((_l = this.currentContext) === null || _l === void 0 ? void 0 : _l.database) || '',
1163
+ component_type: 'database',
1164
+ input: { table: options.table, where: options.where, select: options.select, orderBy: options.orderBy, limit: options.limit, offset: options.offset },
1165
+ privateKey,
1166
+ expiry: cacheConfig.expiry,
1167
+ };
1168
+ this.cacheManager.store(cacheOptions, result); // Fire-and-forget
1169
+ }
1170
+ const end = Date.now();
1171
+ (_m = this.logService) === null || _m === void 0 ? void 0 : _m.add(Object.assign(Object.assign({}, baseLogs), { start,
1172
+ end, message: options.cache ? 'Database query - cache miss' : 'Database query - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: queryCacheKey }));
1173
+ (_o = this.logService) === null || _o === void 0 ? void 0 : _o.publish();
1174
+ return result;
1175
+ }
1176
+ catch (error) {
1177
+ const end = Date.now();
1178
+ (_p = this.logService) === null || _p === void 0 ? void 0 : _p.add(Object.assign(Object.assign({}, baseLogs), { start,
1179
+ end, message: 'Database query - failed', failed_execution: true, data: { table: options.table, operation: 'query', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL, cache_tag: options.cache, cache_key: queryCacheKey }));
1180
+ await ((_q = this.logService) === null || _q === void 0 ? void 0 : _q.publish());
1181
+ throw error;
1182
+ }
1183
+ }
1184
+ /**
1185
+ * Execute a raw query
1186
+ *
1187
+ * @example
1188
+ * // PostgreSQL
1189
+ * const result = await ductape.database.raw({
1190
+ * query: 'SELECT * FROM users WHERE created_at > $1 AND status = $2',
1191
+ * params: [new Date('2024-01-01'), 'active'],
1192
+ * });
1193
+ *
1194
+ * // MySQL
1195
+ * const result = await ductape.database.raw({
1196
+ * query: 'SELECT * FROM users WHERE created_at > ? AND status = ?',
1197
+ * params: [new Date('2024-01-01'), 'active'],
1198
+ * });
1199
+ *
1200
+ * // MongoDB
1201
+ * const result = await ductape.database.raw({
1202
+ * query: { status: 'active', created_at: { $gte: new Date('2024-01-01') } },
1203
+ * collection: 'users',
1204
+ * });
1205
+ */
1206
+ async raw(options) {
1207
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
1208
+ const process_id = (0, processor_utils_1.generateObjectId)();
1209
+ const start = Date.now();
1210
+ this.initializeLogService();
1211
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1212
+ const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1213
+ const baseLogs = {
1214
+ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '',
1215
+ workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '',
1216
+ env: envValue,
1217
+ app_env: envValue,
1218
+ process_id,
1219
+ type: logs_types_1.LogEventTypes.DATABASE,
1220
+ parent_tag: databaseValue,
1221
+ child_tag: 'raw',
1222
+ data: {
1223
+ operation: 'raw',
1224
+ database: databaseValue,
1225
+ env: envValue,
1226
+ collection: options.collection,
1227
+ query: options.query,
1228
+ params: options.params,
1229
+ },
1230
+ };
1231
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database raw query - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1232
+ // Check cache if cache tag is provided
1233
+ const privateKey = options.product ? this.privateKeys.get(options.product) : undefined;
1234
+ let rawQueryCacheKey;
1235
+ try {
1236
+ if (options.cache && this.cacheManager && privateKey) {
1237
+ const cacheOptions = {
1238
+ cache_tag: options.cache,
1239
+ product_tag: options.product || '',
1240
+ component_tag: options.database || '',
1241
+ component_type: 'database',
1242
+ input: { query: options.query, params: options.params, collection: options.collection },
1243
+ privateKey,
1244
+ };
1245
+ const cached = await this.cacheManager.fetch(cacheOptions);
1246
+ rawQueryCacheKey = cached.key;
1247
+ if (cached.hit && cached.data) {
1248
+ const end = Date.now();
1249
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1250
+ end, message: `Database raw query - cache hit (${cached.source})`, successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: cached.key, cache_status: true }));
1251
+ (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1252
+ return cached.data;
1253
+ }
1254
+ }
1255
+ await this.ensureAdapterFor(options);
1256
+ const adapter = this.getAdapter(options);
1257
+ const result = await adapter.raw(options);
1258
+ // Store in cache if cache tag is provided
1259
+ if (options.cache && this.cacheManager && privateKey && options.product) {
1260
+ const cacheConfig = await this.validateCache(options.product, options.cache);
1261
+ const cacheOptions = {
1262
+ cache_tag: options.cache,
1263
+ product_tag: options.product,
1264
+ component_tag: options.database || '',
1265
+ component_type: 'database',
1266
+ input: { query: options.query, params: options.params, collection: options.collection },
1267
+ privateKey,
1268
+ expiry: cacheConfig.expiry,
1269
+ };
1270
+ this.cacheManager.store(cacheOptions, result); // Fire-and-forget
1271
+ }
1272
+ const end = Date.now();
1273
+ (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1274
+ end, message: options.cache ? 'Database raw query - cache miss' : 'Database raw query - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: rawQueryCacheKey }));
1275
+ (_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish();
1276
+ return result;
1277
+ }
1278
+ catch (error) {
1279
+ const end = Date.now();
1280
+ (_k = this.logService) === null || _k === void 0 ? void 0 : _k.add(Object.assign(Object.assign({}, baseLogs), { start,
1281
+ end, message: 'Database raw query - failed', failed_execution: true, data: { operation: 'raw', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL, cache_tag: options.cache, cache_key: rawQueryCacheKey }));
1282
+ await ((_l = this.logService) === null || _l === void 0 ? void 0 : _l.publish());
1283
+ throw error;
1284
+ }
1285
+ }
1286
+ // ==================== WRITE OPERATIONS ====================
1287
+ /**
1288
+ * Insert one or more records
1289
+ *
1290
+ * @example
1291
+ * // Single record
1292
+ * const result = await ductape.database.insert({
1293
+ * table: 'users',
1294
+ * data: {
1295
+ * name: 'Jane Doe',
1296
+ * email: 'jane@example.com',
1297
+ * status: 'active',
1298
+ * },
1299
+ * returning: true,
1300
+ * });
1301
+ *
1302
+ * // Multiple records
1303
+ * const result = await ductape.database.insert({
1304
+ * table: 'users',
1305
+ * data: [
1306
+ * { name: 'User 1', email: 'user1@example.com' },
1307
+ * { name: 'User 2', email: 'user2@example.com' },
1308
+ * ],
1309
+ * });
1310
+ *
1311
+ * // With conflict handling (upsert)
1312
+ * const result = await ductape.database.insert({
1313
+ * table: 'users',
1314
+ * data: { email: 'john@example.com', name: 'John' },
1315
+ * onConflict: {
1316
+ * columns: ['email'],
1317
+ * action: 'update',
1318
+ * update: ['name'],
1319
+ * },
1320
+ * });
1321
+ */
1322
+ async insert(options) {
1323
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1324
+ const process_id = (0, processor_utils_1.generateObjectId)();
1325
+ const start = Date.now();
1326
+ this.initializeLogService();
1327
+ // Session log fields (will be populated if session is provided)
1328
+ let sessionLogFields = {};
1329
+ let resolvedOptions = options;
1330
+ // Process session if provided
1331
+ if (options.session && options.product) {
1332
+ const builder = await this.getProductBuilder(options.product);
1333
+ const privateKey = builder.fetchPrivateKey();
1334
+ if (privateKey) {
1335
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1336
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1337
+ fetchSessionSelector: async (sessionTag) => {
1338
+ const sessionConfig = await builder.fetchSession(sessionTag);
1339
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1340
+ },
1341
+ });
1342
+ if (sessionResult.error) {
1343
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
1344
+ }
1345
+ resolvedOptions = sessionResult.input;
1346
+ sessionLogFields = sessionResult.logFields;
1347
+ }
1348
+ }
1349
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1350
+ const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1351
+ const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'insert', data: {
1352
+ table: options.table,
1353
+ operation: 'insert',
1354
+ database: databaseValue,
1355
+ env: envValue,
1356
+ data: options.data,
1357
+ returning: options.returning,
1358
+ onConflict: options.onConflict,
1359
+ } }, sessionLogFields);
1360
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database insert - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1361
+ try {
1362
+ // Apply pre-save operations if specified
1363
+ let processedData = resolvedOptions.data;
1364
+ if (resolvedOptions.preSave && resolvedOptions.preSave.length > 0) {
1365
+ const processor = new presave_processor_1.PreSaveProcessor(resolvedOptions.preSaveConfig);
1366
+ const preSaveResult = await processor.process(resolvedOptions.data, resolvedOptions.preSave);
1367
+ processedData = preSaveResult.data;
1368
+ }
1369
+ await this.ensureAdapterFor(resolvedOptions);
1370
+ const adapter = this.getAdapter(resolvedOptions);
1371
+ const result = await adapter.insert(Object.assign(Object.assign({}, resolvedOptions), { data: processedData }));
1372
+ const end = Date.now();
1373
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1374
+ end, message: 'Database insert - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1375
+ (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1376
+ return result;
1377
+ }
1378
+ catch (error) {
1379
+ const end = Date.now();
1380
+ (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1381
+ end, message: 'Database insert - failed', failed_execution: true, data: { table: options.table, operation: 'insert', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1382
+ await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1383
+ throw error;
1384
+ }
1385
+ }
1386
+ /**
1387
+ * Update records matching conditions
1388
+ *
1389
+ * @example
1390
+ * // Simple update
1391
+ * const result = await ductape.database.update({
1392
+ * table: 'users',
1393
+ * data: { status: 'inactive' },
1394
+ * where: { last_login: { $LT: new Date('2023-01-01') } },
1395
+ * });
1396
+ *
1397
+ * // With increment/decrement
1398
+ * await ductape.database.update({
1399
+ * table: 'products',
1400
+ * data: { stock: { $inc: 10 } },
1401
+ * where: { id: productId },
1402
+ * });
1403
+ */
1404
+ async update(options) {
1405
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1406
+ const process_id = (0, processor_utils_1.generateObjectId)();
1407
+ const start = Date.now();
1408
+ this.initializeLogService();
1409
+ // Session log fields (will be populated if session is provided)
1410
+ let sessionLogFields = {};
1411
+ let resolvedOptions = options;
1412
+ // Process session if provided
1413
+ if (options.session && options.product) {
1414
+ const builder = await this.getProductBuilder(options.product);
1415
+ const privateKey = builder.fetchPrivateKey();
1416
+ if (privateKey) {
1417
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1418
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1419
+ fetchSessionSelector: async (sessionTag) => {
1420
+ const sessionConfig = await builder.fetchSession(sessionTag);
1421
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1422
+ },
1423
+ });
1424
+ if (sessionResult.error) {
1425
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
1426
+ }
1427
+ resolvedOptions = sessionResult.input;
1428
+ sessionLogFields = sessionResult.logFields;
1429
+ }
1430
+ }
1431
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1432
+ const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1433
+ const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'update', data: {
1434
+ table: options.table,
1435
+ operation: 'update',
1436
+ database: databaseValue,
1437
+ env: envValue,
1438
+ where: options.where,
1439
+ data: options.data,
1440
+ returning: options.returning,
1441
+ } }, sessionLogFields);
1442
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database update - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1443
+ try {
1444
+ // Apply pre-save operations if specified
1445
+ let processedData = resolvedOptions.data;
1446
+ if (resolvedOptions.preSave && resolvedOptions.preSave.length > 0) {
1447
+ const processor = new presave_processor_1.PreSaveProcessor(resolvedOptions.preSaveConfig);
1448
+ const preSaveResult = await processor.process(resolvedOptions.data, resolvedOptions.preSave);
1449
+ processedData = preSaveResult.data;
1450
+ }
1451
+ await this.ensureAdapterFor(resolvedOptions);
1452
+ const adapter = this.getAdapter(resolvedOptions);
1453
+ const result = await adapter.update(Object.assign(Object.assign({}, resolvedOptions), { data: processedData }));
1454
+ const end = Date.now();
1455
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1456
+ end, message: 'Database update - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1457
+ (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1458
+ return result;
1459
+ }
1460
+ catch (error) {
1461
+ const end = Date.now();
1462
+ (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1463
+ end, message: 'Database update - failed', failed_execution: true, data: { table: options.table, operation: 'update', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1464
+ await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1465
+ throw error;
1466
+ }
1467
+ }
1468
+ /**
1469
+ * Delete records matching conditions
1470
+ *
1471
+ * @example
1472
+ * const result = await ductape.database.delete({
1473
+ * table: 'users',
1474
+ * where: { status: 'deleted' },
1475
+ * });
1476
+ * console.log('Deleted count:', result.count);
1477
+ */
1478
+ async delete(options) {
1479
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1480
+ const process_id = (0, processor_utils_1.generateObjectId)();
1481
+ const start = Date.now();
1482
+ this.initializeLogService();
1483
+ // Session log fields (will be populated if session is provided)
1484
+ let sessionLogFields = {};
1485
+ let resolvedOptions = options;
1486
+ // Process session if provided
1487
+ if (options.session && options.product) {
1488
+ const builder = await this.getProductBuilder(options.product);
1489
+ const privateKey = builder.fetchPrivateKey();
1490
+ if (privateKey) {
1491
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1492
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1493
+ fetchSessionSelector: async (sessionTag) => {
1494
+ const sessionConfig = await builder.fetchSession(sessionTag);
1495
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1496
+ },
1497
+ });
1498
+ if (sessionResult.error) {
1499
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
1500
+ }
1501
+ resolvedOptions = sessionResult.input;
1502
+ sessionLogFields = sessionResult.logFields;
1503
+ }
1504
+ }
1505
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1506
+ const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1507
+ const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'delete', data: {
1508
+ table: options.table,
1509
+ operation: 'delete',
1510
+ database: databaseValue,
1511
+ env: envValue,
1512
+ where: options.where,
1513
+ } }, sessionLogFields);
1514
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database delete - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1515
+ try {
1516
+ await this.ensureAdapterFor(resolvedOptions);
1517
+ const adapter = this.getAdapter(resolvedOptions);
1518
+ const result = await adapter.delete(resolvedOptions);
1519
+ const end = Date.now();
1520
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1521
+ end, message: 'Database delete - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1522
+ (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1523
+ return result;
1524
+ }
1525
+ catch (error) {
1526
+ const end = Date.now();
1527
+ (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1528
+ end, message: 'Database delete - failed', failed_execution: true, data: { table: options.table, operation: 'delete', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1529
+ await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1530
+ throw error;
1531
+ }
1532
+ }
1533
+ /**
1534
+ * Insert or update a record based on conflict keys
1535
+ *
1536
+ * @example
1537
+ * const result = await ductape.database.upsert({
1538
+ * table: 'user_preferences',
1539
+ * data: {
1540
+ * user_id: 123,
1541
+ * theme: 'dark',
1542
+ * language: 'en',
1543
+ * },
1544
+ * conflictKeys: ['user_id'],
1545
+ * });
1546
+ * console.log('Operation:', result.operation); // 'inserted' or 'updated'
1547
+ */
1548
+ async upsert(options) {
1549
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1550
+ const process_id = (0, processor_utils_1.generateObjectId)();
1551
+ const start = Date.now();
1552
+ this.initializeLogService();
1553
+ // Session log fields (will be populated if session is provided)
1554
+ let sessionLogFields = {};
1555
+ let resolvedOptions = options;
1556
+ // Process session if provided
1557
+ if (options.session && options.product) {
1558
+ const builder = await this.getProductBuilder(options.product);
1559
+ const privateKey = builder.fetchPrivateKey();
1560
+ if (privateKey) {
1561
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1562
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1563
+ fetchSessionSelector: async (sessionTag) => {
1564
+ const sessionConfig = await builder.fetchSession(sessionTag);
1565
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1566
+ },
1567
+ });
1568
+ if (sessionResult.error) {
1569
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
1570
+ }
1571
+ resolvedOptions = sessionResult.input;
1572
+ sessionLogFields = sessionResult.logFields;
1573
+ }
1574
+ }
1575
+ const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1576
+ const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1577
+ const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'upsert', data: {
1578
+ table: options.table,
1579
+ operation: 'upsert',
1580
+ database: databaseValue,
1581
+ env: envValue,
1582
+ data: options.data,
1583
+ conflictKeys: options.conflictKeys,
1584
+ updateColumns: options.updateColumns,
1585
+ returning: options.returning,
1586
+ } }, sessionLogFields);
1587
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database upsert - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1588
+ try {
1589
+ await this.ensureAdapterFor(resolvedOptions);
1590
+ const adapter = this.getAdapter(resolvedOptions);
1591
+ const result = await adapter.upsert(resolvedOptions);
1592
+ const end = Date.now();
1593
+ (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1594
+ end, message: 'Database upsert - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1595
+ (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1596
+ return result;
1597
+ }
1598
+ catch (error) {
1599
+ const end = Date.now();
1600
+ (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1601
+ end, message: 'Database upsert - failed', failed_execution: true, data: { table: options.table, operation: 'upsert', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1602
+ await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1603
+ throw error;
1604
+ }
1605
+ }
1606
+ // ==================== AGGREGATION OPERATIONS ====================
1607
+ /**
1608
+ * Count records
1609
+ *
1610
+ * @example
1611
+ * const count = await ductape.database.count({
1612
+ * table: 'users',
1613
+ * where: { status: 'active' },
1614
+ * });
1615
+ */
1616
+ async count(options) {
1617
+ await this.ensureAdapterFor(options);
1618
+ const adapter = this.getAdapter(options);
1619
+ return adapter.count(options);
1620
+ }
1621
+ /**
1622
+ * Sum values of a column
1623
+ *
1624
+ * @example
1625
+ * const totalRevenue = await ductape.database.sum({
1626
+ * table: 'orders',
1627
+ * column: 'total',
1628
+ * where: { status: 'completed' },
1629
+ * });
1630
+ */
1631
+ async sum(options) {
1632
+ await this.ensureAdapterFor(options);
1633
+ const adapter = this.getAdapter(options);
1634
+ return adapter.sum(options);
1635
+ }
1636
+ /**
1637
+ * Calculate average of a column
1638
+ *
1639
+ * @example
1640
+ * const avgOrderValue = await ductape.database.avg({
1641
+ * table: 'orders',
1642
+ * column: 'total',
1643
+ * });
1644
+ */
1645
+ async avg(options) {
1646
+ await this.ensureAdapterFor(options);
1647
+ const adapter = this.getAdapter(options);
1648
+ return adapter.avg(options);
1649
+ }
1650
+ /**
1651
+ * Get minimum value of a column
1652
+ *
1653
+ * @example
1654
+ * const minPrice = await ductape.database.min({
1655
+ * table: 'products',
1656
+ * column: 'price',
1657
+ * });
1658
+ */
1659
+ async min(options) {
1660
+ await this.ensureAdapterFor(options);
1661
+ const adapter = this.getAdapter(options);
1662
+ return adapter.min(options);
1663
+ }
1664
+ /**
1665
+ * Get maximum value of a column
1666
+ *
1667
+ * @example
1668
+ * const maxPrice = await ductape.database.max({
1669
+ * table: 'products',
1670
+ * column: 'price',
1671
+ * });
1672
+ */
1673
+ async max(options) {
1674
+ await this.ensureAdapterFor(options);
1675
+ const adapter = this.getAdapter(options);
1676
+ return adapter.max(options);
1677
+ }
1678
+ /**
1679
+ * Perform multiple aggregations in one query
1680
+ *
1681
+ * @example
1682
+ * const stats = await ductape.database.aggregate({
1683
+ * table: 'orders',
1684
+ * operations: {
1685
+ * total_revenue: { $SUM: 'total' },
1686
+ * order_count: { $COUNT: '*' },
1687
+ * avg_order_value: { $AVG: 'total' },
1688
+ * },
1689
+ * where: { status: 'completed' },
1690
+ * });
1691
+ */
1692
+ async aggregate(options) {
1693
+ await this.ensureAdapterFor(options);
1694
+ const adapter = this.getAdapter(options);
1695
+ const aggregationBuilder = new aggregation_builder_1.AggregationBuilder(adapter.getDatabaseType());
1696
+ const builtAggregation = aggregationBuilder.buildAggregation(options);
1697
+ return adapter.aggregate(builtAggregation);
1698
+ }
1699
+ /**
1700
+ * Group records and perform aggregations
1701
+ *
1702
+ * @example
1703
+ * const salesByCategory = await ductape.database.groupBy({
1704
+ * table: 'products',
1705
+ * groupBy: ['category'],
1706
+ * operations: {
1707
+ * total_sales: { $SUM: 'sales_count' },
1708
+ * avg_price: { $AVG: 'price' },
1709
+ * },
1710
+ * having: {
1711
+ * total_sales: { $GT: 100 },
1712
+ * },
1713
+ * });
1714
+ */
1715
+ async groupBy(options) {
1716
+ await this.ensureAdapterFor(options);
1717
+ const adapter = this.getAdapter(options);
1718
+ const aggregationBuilder = new aggregation_builder_1.AggregationBuilder(adapter.getDatabaseType());
1719
+ const builtGroupBy = aggregationBuilder.buildGroupBy(options);
1720
+ return adapter.groupBy(builtGroupBy);
1721
+ }
1722
+ // ==================== TRANSACTION OPERATIONS ====================
1723
+ /**
1724
+ * Execute operations within a transaction (callback API - recommended)
1725
+ *
1726
+ * @example
1727
+ * const order = await ductape.database.transaction({
1728
+ * env: 'prd',
1729
+ * product: 'my-app',
1730
+ * database: 'main-db',
1731
+ * }, async (transaction) => {
1732
+ * const order = await ductape.database.insert({
1733
+ * table: 'orders',
1734
+ * data: { customer_id: 123, total: 99.99 },
1735
+ * transaction,
1736
+ * });
1737
+ *
1738
+ * await ductape.database.insert({
1739
+ * table: 'order_items',
1740
+ * data: items.map(item => ({ order_id: order.insertedIds[0], ...item })),
1741
+ * transaction,
1742
+ * });
1743
+ *
1744
+ * return order;
1745
+ * });
1746
+ */
1747
+ async transaction(options, callback) {
1748
+ await this.ensureAdapterFor(options);
1749
+ const adapter = this.getAdapter(options);
1750
+ return this.transactionManager.executeTransaction(adapter, options, callback);
1751
+ }
1752
+ /**
1753
+ * Begin a transaction manually
1754
+ *
1755
+ * @example
1756
+ * const transaction = await ductape.database.beginTransaction({
1757
+ * env: 'prd',
1758
+ * product: 'my-app',
1759
+ * database: 'main-db',
1760
+ * isolationLevel: 'REPEATABLE_READ',
1761
+ * });
1762
+ *
1763
+ * try {
1764
+ * await ductape.database.insert({ table: 'accounts', data: {...}, transaction });
1765
+ * await transaction.commit();
1766
+ * } catch (error) {
1767
+ * await transaction.rollback();
1768
+ * throw error;
1769
+ * }
1770
+ */
1771
+ async beginTransaction(options) {
1772
+ await this.ensureAdapterFor(options);
1773
+ const adapter = this.getAdapter(options);
1774
+ return this.transactionManager.beginTransaction(adapter, options);
1775
+ }
1776
+ // ==================== SCHEMA OPERATIONS ====================
1777
+ /**
1778
+ * Create a new table
1779
+ *
1780
+ * @example
1781
+ * import { SchemaHelpers } from '@ductape/sdk';
1782
+ *
1783
+ * await ductape.database.createTable(
1784
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1785
+ * {
1786
+ * name: 'products',
1787
+ * columns: [
1788
+ * SchemaHelpers.id(),
1789
+ * SchemaHelpers.string('name', 255, false),
1790
+ * SchemaHelpers.decimal('price', 10, 2),
1791
+ * ...SchemaHelpers.timestamps(),
1792
+ * ],
1793
+ * },
1794
+ * { ifNotExists: true }
1795
+ * );
1796
+ */
1797
+ async createTable(connectionConfigOrDefinition, tableDefinitionOrOptions, options) {
1798
+ // Check if first arg is a table definition (no connectionConfig provided)
1799
+ if ('columns' in connectionConfigOrDefinition || 'name' in connectionConfigOrDefinition && !('env' in connectionConfigOrDefinition)) {
1800
+ // Using current context - connectionConfigOrDefinition is actually tableDefinition
1801
+ const adapter = this.getAdapter();
1802
+ return adapter.createTable(connectionConfigOrDefinition, tableDefinitionOrOptions);
1803
+ }
1804
+ // Using explicit connection config
1805
+ const connConfig = connectionConfigOrDefinition;
1806
+ await this.ensureAdapterFor(connConfig);
1807
+ const adapter = this.getAdapter(connConfig);
1808
+ return adapter.createTable(tableDefinitionOrOptions, options);
1809
+ }
1810
+ /**
1811
+ * Alter an existing table
1812
+ *
1813
+ * @example
1814
+ * import { ColumnAlterationType, ColumnType } from '@ductape/sdk';
1815
+ *
1816
+ * // Add column
1817
+ * await ductape.database.alterTable(
1818
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1819
+ * 'products',
1820
+ * [{ type: ColumnAlterationType.ADD, column: { name: 'sku', type: ColumnType.STRING, length: 50 } }]
1821
+ * );
1822
+ *
1823
+ * // Drop column
1824
+ * await ductape.database.alterTable(
1825
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1826
+ * 'products',
1827
+ * [{ type: ColumnAlterationType.DROP, columnName: 'old_field' }]
1828
+ * );
1829
+ *
1830
+ * // Rename column
1831
+ * await ductape.database.alterTable(
1832
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1833
+ * 'products',
1834
+ * [{ type: ColumnAlterationType.RENAME, oldName: 'old_name', newName: 'new_name' }]
1835
+ * );
1836
+ */
1837
+ async alterTable(connectionConfigOrTableName, tableNameOrAlterations, alterations) {
1838
+ // Check if first arg is a string (tableName - no connectionConfig provided)
1839
+ if (typeof connectionConfigOrTableName === 'string') {
1840
+ const adapter = this.getAdapter();
1841
+ return adapter.alterTable(connectionConfigOrTableName, tableNameOrAlterations);
1842
+ }
1843
+ // Using explicit connection config
1844
+ const connConfig = connectionConfigOrTableName;
1845
+ await this.ensureAdapterFor(connConfig);
1846
+ const adapter = this.getAdapter(connConfig);
1847
+ return adapter.alterTable(tableNameOrAlterations, alterations);
1848
+ }
1849
+ /**
1850
+ * Drop a table
1851
+ *
1852
+ * @example
1853
+ * await ductape.database.dropTable(
1854
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1855
+ * 'old_table'
1856
+ * );
1857
+ */
1858
+ async dropTable(connectionConfigOrTableName, tableName) {
1859
+ // Check if first arg is a string (tableName - no connectionConfig provided)
1860
+ if (typeof connectionConfigOrTableName === 'string') {
1861
+ const adapter = this.getAdapter();
1862
+ return adapter.dropTable(connectionConfigOrTableName, true);
1863
+ }
1864
+ // Using explicit connection config
1865
+ const connConfig = connectionConfigOrTableName;
1866
+ await this.ensureAdapterFor(connConfig);
1867
+ const adapter = this.getAdapter(connConfig);
1868
+ return adapter.dropTable(tableName, true);
1869
+ }
1870
+ /**
1871
+ * List all tables in the database
1872
+ *
1873
+ * @example
1874
+ * const tables = await ductape.database.listTables({
1875
+ * env: 'dev',
1876
+ * product: 'my-app',
1877
+ * database: 'main-db',
1878
+ * });
1879
+ */
1880
+ async listTables(connectionConfig) {
1881
+ if (connectionConfig)
1882
+ await this.ensureAdapterFor(connectionConfig);
1883
+ const adapter = this.getAdapter(connectionConfig);
1884
+ return adapter.listTables();
1885
+ }
1886
+ /**
1887
+ * List all tables with basic information including estimated row counts
1888
+ *
1889
+ * @example
1890
+ * const tables = await ductape.database.listTablesWithInfo({
1891
+ * env: 'dev',
1892
+ * product: 'my-app',
1893
+ * database: 'main-db',
1894
+ * });
1895
+ * // Returns: [{ name: 'users', estimatedRowCount: 1247, schema: 'public' }, ...]
1896
+ */
1897
+ async listTablesWithInfo(connectionConfig) {
1898
+ if (connectionConfig)
1899
+ await this.ensureAdapterFor(connectionConfig);
1900
+ const adapter = this.getAdapter(connectionConfig);
1901
+ return adapter.listTablesWithInfo();
1902
+ }
1903
+ /**
1904
+ * Check if a table exists
1905
+ *
1906
+ * @example
1907
+ * const exists = await ductape.database.tableExists(
1908
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1909
+ * 'users'
1910
+ * );
1911
+ */
1912
+ async tableExists(connectionConfigOrTableName, tableName) {
1913
+ // Check if first arg is a string (tableName - no connectionConfig provided)
1914
+ if (typeof connectionConfigOrTableName === 'string') {
1915
+ const adapter = this.getAdapter();
1916
+ return adapter.tableExists(connectionConfigOrTableName);
1917
+ }
1918
+ // Using explicit connection config
1919
+ const connConfig = connectionConfigOrTableName;
1920
+ await this.ensureAdapterFor(connConfig);
1921
+ const adapter = this.getAdapter(connConfig);
1922
+ return adapter.tableExists(tableName);
1923
+ }
1924
+ /**
1925
+ * Get the schema of a table
1926
+ *
1927
+ * @example
1928
+ * const schema = await ductape.database.getTableSchema(
1929
+ * { env: 'dev', product: 'my-app', database: 'main-db' },
1930
+ * 'users'
1931
+ * );
1932
+ * console.log('Table:', schema.name);
1933
+ * console.log('Columns:', schema.columns);
1934
+ * console.log('Indexes:', schema.indexes);
1935
+ */
1936
+ async getTableSchema(connectionConfigOrTableName, tableName) {
1937
+ // Check if first arg is a string (tableName - no connectionConfig provided)
1938
+ if (typeof connectionConfigOrTableName === 'string') {
1939
+ const adapter = this.getAdapter();
1940
+ return adapter.getTableSchema(connectionConfigOrTableName);
1941
+ }
1942
+ // Using explicit connection config
1943
+ const connConfig = connectionConfigOrTableName;
1944
+ await this.ensureAdapterFor(connConfig);
1945
+ const adapter = this.getAdapter(connConfig);
1946
+ return adapter.getTableSchema(tableName);
1947
+ }
1948
+ /**
1949
+ * Create an index
1950
+ *
1951
+ * @example
1952
+ * await ductape.database.createIndex({
1953
+ * env: 'dev',
1954
+ * product: 'my-app',
1955
+ * database: 'main-db',
1956
+ * table: 'users',
1957
+ * index: {
1958
+ * name: 'idx_users_email',
1959
+ * table: 'users',
1960
+ * columns: [{ name: 'email' }],
1961
+ * unique: true,
1962
+ * },
1963
+ * ifNotExists: true,
1964
+ * concurrent: true, // PostgreSQL: create without locking
1965
+ * });
1966
+ */
1967
+ async createIndex(options) {
1968
+ await this.ensureAdapterFor(options);
1969
+ const adapter = this.getAdapter(options);
1970
+ return adapter.createIndex(options.index, options.ifNotExists, options.concurrent);
1971
+ }
1972
+ /**
1973
+ * Drop an index
1974
+ *
1975
+ * @example
1976
+ * await ductape.database.dropIndex({
1977
+ * env: 'dev',
1978
+ * product: 'my-app',
1979
+ * database: 'main-db',
1980
+ * table: 'users',
1981
+ * indexName: 'idx_users_old',
1982
+ * ifExists: true,
1983
+ * concurrent: true,
1984
+ * });
1985
+ */
1986
+ async dropIndex(options) {
1987
+ await this.ensureAdapterFor(options);
1988
+ const adapter = this.getAdapter(options);
1989
+ return adapter.dropIndex(options.table, options.indexName, options.ifExists, options.concurrent, options.cascade);
1990
+ }
1991
+ /**
1992
+ * List all indexes on a table
1993
+ *
1994
+ * @example
1995
+ * const indexes = await ductape.database.listIndexes({
1996
+ * env: 'dev',
1997
+ * product: 'my-app',
1998
+ * database: 'main-db',
1999
+ * table: 'users',
2000
+ * includeSystem: false,
2001
+ * });
2002
+ */
2003
+ async listIndexes(options) {
2004
+ await this.ensureAdapterFor(options);
2005
+ const adapter = this.getAdapter(options);
2006
+ return adapter.listIndexes(options.table, options.includeSystem);
2007
+ }
2008
+ /**
2009
+ * Get index statistics
2010
+ *
2011
+ * @example
2012
+ * // All indexes on a table
2013
+ * const stats = await ductape.database.getIndexStatistics(
2014
+ * { env: 'prd', product: 'my-app', database: 'main-db' },
2015
+ * 'users'
2016
+ * );
2017
+ *
2018
+ * // Specific index
2019
+ * const emailStats = await ductape.database.getIndexStatistics(
2020
+ * { env: 'prd', product: 'my-app', database: 'main-db' },
2021
+ * 'users',
2022
+ * 'idx_users_email'
2023
+ * );
2024
+ */
2025
+ async getIndexStatistics(connectionConfig, tableName, indexName) {
2026
+ await this.ensureAdapterFor(connectionConfig);
2027
+ const adapter = this.getAdapter(connectionConfig);
2028
+ return adapter.getIndexStatistics(tableName, indexName);
2029
+ }
2030
+ /**
2031
+ * Get a normalized schema snapshot for the given database/env context.
2032
+ *
2033
+ * @example
2034
+ * const snapshot = await ductape.database.getSchemaSnapshot({
2035
+ * env: 'prd',
2036
+ * product: 'my-product',
2037
+ * database: 'main-db',
2038
+ * });
2039
+ */
2040
+ async getSchemaSnapshot(connectionConfig, options) {
2041
+ var _a;
2042
+ await this.ensureAdapterFor(connectionConfig);
2043
+ const adapter = this.getAdapter(connectionConfig);
2044
+ const tableNames = ((_a = options === null || options === void 0 ? void 0 : options.includeTables) === null || _a === void 0 ? void 0 : _a.length) ? options.includeTables : await adapter.listTables();
2045
+ const tables = [];
2046
+ for (const tableName of tableNames) {
2047
+ tables.push(await adapter.getTableSchema(tableName));
2048
+ }
2049
+ return {
2050
+ database: connectionConfig.database,
2051
+ env: connectionConfig.env,
2052
+ tables,
2053
+ generatedAt: new Date().toISOString(),
2054
+ };
2055
+ }
2056
+ // ==================== MIGRATION OPERATIONS ====================
2057
+ /**
2058
+ * Run a migration
2059
+ *
2060
+ * @example
2061
+ * const result = await ductape.database.runMigration([migration]);
2062
+ * console.log('Migrated:', result.size);
2063
+ */
2064
+ async runMigration(migrations, options) {
2065
+ const engine = this.getMigrationEngine();
2066
+ return engine.migrate(migrations, options);
2067
+ }
2068
+ /**
2069
+ * Rollback migrations
2070
+ *
2071
+ * @example
2072
+ * const result = await ductape.database.rollbackMigration([migration], 1);
2073
+ * console.log('Rolled back:', result.size);
2074
+ */
2075
+ async rollbackMigration(migrations, count = 1) {
2076
+ const engine = this.getMigrationEngine();
2077
+ return engine.rollback(migrations, count);
2078
+ }
2079
+ /**
2080
+ * Get migration history (applied migrations)
2081
+ *
2082
+ * @example
2083
+ * const history = await ductape.database.getMigrationHistory();
2084
+ * history.forEach((entry) => {
2085
+ * console.log('Tag:', entry.tag);
2086
+ * console.log('Applied at:', entry.appliedAt);
2087
+ * });
2088
+ */
2089
+ async getMigrationHistory() {
2090
+ const engine = this.getMigrationEngine();
2091
+ return engine.getAppliedMigrations();
2092
+ }
2093
+ /**
2094
+ * Get status of all migrations
2095
+ *
2096
+ * @example
2097
+ * const status = await ductape.database.getMigrationStatus(allMigrations);
2098
+ * console.log('Pending:', status.pending);
2099
+ */
2100
+ async getMigrationStatus(migrations) {
2101
+ const engine = this.getMigrationEngine();
2102
+ return engine.getStatus(migrations);
2103
+ }
2104
+ // ==================== MIGRATION CRUD OPERATIONS ====================
2105
+ /**
2106
+ * Migration management sub-object
2107
+ * Provides CRUD operations for database migrations via ProductBuilder
2108
+ */
2109
+ get migration() {
2110
+ return {
2111
+ /**
2112
+ * Create a new database migration
2113
+ *
2114
+ * @example
2115
+ * await ductape.database.migration.create({
2116
+ * product: 'my-product',
2117
+ * database: 'main-db',
2118
+ * data: {
2119
+ * name: 'Add users table',
2120
+ * tag: 'main-db:add-users-table',
2121
+ * value: {
2122
+ * up: ['CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255))'],
2123
+ * down: ['DROP TABLE users'],
2124
+ * },
2125
+ * },
2126
+ * });
2127
+ */
2128
+ create: async (options) => {
2129
+ const builder = await this.getProductBuilder(options.product);
2130
+ // Format tag as database:migration if not already formatted
2131
+ const tag = options.data.tag.includes(':')
2132
+ ? options.data.tag
2133
+ : `${options.database}:${options.data.tag}`;
2134
+ await builder.createDatabaseMigration({
2135
+ name: options.data.name,
2136
+ tag,
2137
+ description: options.data.description,
2138
+ value: options.data.value,
2139
+ });
2140
+ },
2141
+ /**
2142
+ * Update an existing database migration
2143
+ *
2144
+ * @example
2145
+ * await ductape.database.migration.update({
2146
+ * product: 'my-product',
2147
+ * tag: 'main-db:add-users-table',
2148
+ * data: {
2149
+ * description: 'Updated description',
2150
+ * },
2151
+ * });
2152
+ */
2153
+ update: async (options) => {
2154
+ const builder = await this.getProductBuilder(options.product);
2155
+ await builder.updateDatabaseMigration(Object.assign({ tag: options.tag }, options.data));
2156
+ },
2157
+ /**
2158
+ * Fetch a specific database migration
2159
+ *
2160
+ * @example
2161
+ * const migration = await ductape.database.migration.fetch({
2162
+ * product: 'my-product',
2163
+ * tag: 'main-db:add-users-table',
2164
+ * });
2165
+ */
2166
+ fetch: async (options) => {
2167
+ const builder = await this.getProductBuilder(options.product);
2168
+ return builder.fetchDatabaseMigration(options.tag);
2169
+ },
2170
+ /**
2171
+ * Fetch all database migrations for a database
2172
+ *
2173
+ * @example
2174
+ * const migrations = await ductape.database.migration.fetchAll({
2175
+ * product: 'my-product',
2176
+ * database: 'main-db',
2177
+ * });
2178
+ */
2179
+ fetchAll: async (options) => {
2180
+ const builder = await this.getProductBuilder(options.product);
2181
+ return builder.fetchDatabaseMigrations(options.database);
2182
+ },
2183
+ /**
2184
+ * Delete a database migration
2185
+ *
2186
+ * @example
2187
+ * await ductape.database.migration.delete({
2188
+ * product: 'my-product',
2189
+ * tag: 'main-db:add-users-table',
2190
+ * });
2191
+ */
2192
+ delete: async (options) => {
2193
+ const builder = await this.getProductBuilder(options.product);
2194
+ return builder.deleteDatabaseMigration(options.tag);
2195
+ },
2196
+ /**
2197
+ * Run a database migration (up)
2198
+ * @deprecated Migration execution has been deprecated
2199
+ */
2200
+ run: async (_options) => {
2201
+ throw new Error('Migration execution has been deprecated');
2202
+ },
2203
+ /**
2204
+ * Rollback a database migration (down)
2205
+ * @deprecated Migration execution has been deprecated
2206
+ */
2207
+ rollback: async (_options) => {
2208
+ throw new Error('Migration execution has been deprecated');
2209
+ },
2210
+ };
2211
+ }
2212
+ // ==================== ACTION OPERATIONS ====================
2213
+ /**
2214
+ * Action management sub-object
2215
+ */
2216
+ get action() {
2217
+ return {
2218
+ /**
2219
+ * Create a new database action
2220
+ *
2221
+ * @example
2222
+ * await ductape.database.action.create({
2223
+ * name: 'Get Users Paginated',
2224
+ * tag: 'postgresdb:get-users-paginated',
2225
+ * tableName: 'users',
2226
+ * operation: DatabaseActionTypes.QUERY,
2227
+ * template: {
2228
+ * where: { is_active: true },
2229
+ * limit: '{{limit}}',
2230
+ * offset: '{{offset}}',
2231
+ * },
2232
+ * });
2233
+ */
2234
+ create: async (options) => {
2235
+ return this.actionManager.create(options);
2236
+ },
2237
+ /**
2238
+ * Update an existing action
2239
+ *
2240
+ * @example
2241
+ * await ductape.database.action.update({
2242
+ * tag: 'postgresdb:get-users',
2243
+ * template: { where: { status: '{{status}}' } },
2244
+ * });
2245
+ */
2246
+ update: async (options) => {
2247
+ return this.actionManager.update(options);
2248
+ },
2249
+ /**
2250
+ * Fetch a specific action
2251
+ *
2252
+ * @example
2253
+ * const action = await ductape.database.action.fetch('postgresdb:get-users');
2254
+ */
2255
+ fetch: async (tag) => {
2256
+ return this.actionManager.fetch(tag);
2257
+ },
2258
+ /**
2259
+ * Fetch all actions for a database
2260
+ *
2261
+ * @example
2262
+ * const actions = await ductape.database.action.fetchAll('postgresdb');
2263
+ */
2264
+ fetchAll: async (databaseTag) => {
2265
+ return this.actionManager.fetchAll(databaseTag);
2266
+ },
2267
+ /**
2268
+ * Delete a database action
2269
+ *
2270
+ * @example
2271
+ * await ductape.database.action.delete('postgresdb:get-users');
2272
+ */
2273
+ delete: async (tag) => {
2274
+ return this.actionManager.delete(tag);
2275
+ },
2276
+ /**
2277
+ * Dispatches a database action to run as a scheduled job.
2278
+ * @param {IDBActionDispatchInput} data - The database action dispatch input.
2279
+ * @returns {Promise<IDispatchResult>} The dispatch result with job ID and status.
2280
+ * @example
2281
+ * // Schedule a database action to run in 1 hour
2282
+ * await ductape.databases.action.dispatch({
2283
+ * product: 'my-product',
2284
+ * env: 'production',
2285
+ * database: 'users-db',
2286
+ * event: 'cleanup-inactive',
2287
+ * input: { query: { inactive: true } },
2288
+ * schedule: { start_at: Date.now() + 3600000 }
2289
+ * });
2290
+ *
2291
+ * // Run on a cron schedule
2292
+ * await ductape.databases.action.dispatch({
2293
+ * product: 'my-product',
2294
+ * env: 'production',
2295
+ * database: 'analytics-db',
2296
+ * event: 'aggregate-daily',
2297
+ * input: { query: {} },
2298
+ * schedule: { cron: '0 0 * * *' } // Daily at midnight
2299
+ * });
2300
+ */
2301
+ dispatch: async (data) => {
2302
+ const processorService = this.createNewProcessor();
2303
+ const productBuilder = await this.getProductBuilder(data.product);
2304
+ const schedule = data.schedule || {};
2305
+ const startAt = typeof schedule.start_at === 'string'
2306
+ ? new Date(schedule.start_at).getTime()
2307
+ : schedule.start_at || Date.now();
2308
+ // Generate job tag based on type, database, and event
2309
+ const jobTag = `database:${data.database}:${data.event}`;
2310
+ // Check if job exists, if not create it
2311
+ const existingJob = await productBuilder.fetchJob(jobTag);
2312
+ if (!existingJob) {
2313
+ await productBuilder.createJob({
2314
+ tag: jobTag,
2315
+ name: `Database: ${data.database}/${data.event}`,
2316
+ description: `Auto-created job for database action ${data.event} on database ${data.database}`,
2317
+ type: types_1.JobEventTypes.DATABASE_ACTION,
2318
+ app: data.database,
2319
+ event: data.event,
2320
+ executions: 0,
2321
+ intervals: schedule.every || 0,
2322
+ start_at: startAt,
2323
+ });
2324
+ }
2325
+ const jobInput = {
2326
+ product: data.product,
2327
+ env: data.env,
2328
+ event: jobTag,
2329
+ input: data.input,
2330
+ retries: data.retries || 0,
2331
+ start_at: startAt,
2332
+ session: data.session,
2333
+ cache: data.cache,
2334
+ repeat: schedule.cron || schedule.every ? {
2335
+ cron: schedule.cron,
2336
+ every: schedule.every,
2337
+ limit: schedule.limit,
2338
+ endDate: schedule.endDate,
2339
+ tz: schedule.tz,
2340
+ } : undefined,
2341
+ };
2342
+ await processorService.processJob(jobInput);
2343
+ const isRecurring = !!(schedule.cron || schedule.every);
2344
+ let nextRunAt;
2345
+ if (isRecurring && schedule.every) {
2346
+ nextRunAt = startAt + schedule.every;
2347
+ }
2348
+ return {
2349
+ job_id: (0, crypto_1.randomUUID)(),
2350
+ status: startAt > Date.now() ? 'scheduled' : 'queued',
2351
+ scheduled_at: startAt,
2352
+ recurring: isRecurring,
2353
+ next_run_at: nextRunAt,
2354
+ };
2355
+ },
2356
+ };
2357
+ }
2358
+ /**
2359
+ * Execute a database action
2360
+ *
2361
+ * @example
2362
+ * const users = await ductape.database.execute({
2363
+ * product: 'my-product',
2364
+ * env: 'prd',
2365
+ * database: 'postgresdb',
2366
+ * action: 'get-users-paginated',
2367
+ * input: {
2368
+ * limit: 25,
2369
+ * offset: 0,
2370
+ * },
2371
+ * });
2372
+ */
2373
+ async execute(options) {
2374
+ var _a, _b, _c, _d, _e, _f;
2375
+ const process_id = (0, processor_utils_1.generateObjectId)();
2376
+ const start = Date.now();
2377
+ // Session log fields (will be populated if session is provided)
2378
+ let sessionLogFields = {};
2379
+ let resolvedOptions = options;
2380
+ // Initialize product builder and logging
2381
+ if (options.product) {
2382
+ const builder = await this.getProductBuilder(options.product);
2383
+ // Process session if provided
2384
+ if (options.session) {
2385
+ const privateKey = builder.fetchPrivateKey();
2386
+ if (privateKey) {
2387
+ const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
2388
+ const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
2389
+ fetchSessionSelector: async (sessionTag) => {
2390
+ const sessionConfig = await builder.fetchSession(sessionTag);
2391
+ return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
2392
+ },
2393
+ });
2394
+ if (sessionResult.error) {
2395
+ throw new Error(`Session validation failed: ${sessionResult.error}`);
2396
+ }
2397
+ resolvedOptions = sessionResult.input;
2398
+ sessionLogFields = sessionResult.logFields;
2399
+ }
2400
+ }
2401
+ }
2402
+ this.initializeLogService();
2403
+ const baseLogs = Object.assign({ product_tag: options.product || '', workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '', env: options.env, process_id, type: logs_types_1.LogEventTypes.DB_ACTION, parent_tag: options.database, child_tag: options.action, data: { database: options.database, action: options.action } }, sessionLogFields);
2404
+ (_b = this.logService) === null || _b === void 0 ? void 0 : _b.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database action execute - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
2405
+ try {
2406
+ const result = await this.actionManager.execute(resolvedOptions);
2407
+ const end = Date.now();
2408
+ (_c = this.logService) === null || _c === void 0 ? void 0 : _c.add(Object.assign(Object.assign({}, baseLogs), { start,
2409
+ end, message: 'Database action execute - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
2410
+ (_d = this.logService) === null || _d === void 0 ? void 0 : _d.publish();
2411
+ return result;
2412
+ }
2413
+ catch (error) {
2414
+ const end = Date.now();
2415
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start,
2416
+ end, message: 'Database action execute - failed', failed_execution: true, data: { database: options.database, action: options.action, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
2417
+ await ((_f = this.logService) === null || _f === void 0 ? void 0 : _f.publish());
2418
+ throw error;
2419
+ }
2420
+ }
2421
+ /**
2422
+ * Dispatches a database operation to run as a scheduled job.
2423
+ * Use this for direct database operations (query, insert, update, delete, etc.).
2424
+ * @param {IDBOperationDispatchInput} data - The database operation dispatch input.
2425
+ * @returns {Promise<IDispatchResult>} The dispatch result with job ID and status.
2426
+ * @example
2427
+ * // Schedule a database operation to run in 1 hour
2428
+ * await ductape.databases.dispatch({
2429
+ * product: 'my-product',
2430
+ * env: 'production',
2431
+ * database: 'users-db',
2432
+ * operation: 'deleteMany',
2433
+ * input: { filter: { inactive: true, lastLogin: { $lt: '2024-01-01' } } },
2434
+ * schedule: { start_at: Date.now() + 3600000 }
2435
+ * });
2436
+ *
2437
+ * // Run daily database cleanup
2438
+ * await ductape.databases.dispatch({
2439
+ * product: 'my-product',
2440
+ * env: 'production',
2441
+ * database: 'logs-db',
2442
+ * operation: 'deleteMany',
2443
+ * input: { filter: { createdAt: { $lt: '$DateAdd($Now(), -30, "days")' } } },
2444
+ * schedule: { cron: '0 3 * * *' } // Daily at 3 AM
2445
+ * });
2446
+ */
2447
+ async dispatch(data) {
2448
+ var _a, _b, _c, _d, _e, _f;
2449
+ const process_id = (0, processor_utils_1.generateObjectId)();
2450
+ const start = Date.now();
2451
+ const processorService = this.createNewProcessor();
2452
+ const productBuilder = await this.getProductBuilder(data.product);
2453
+ const schedule = data.schedule || {};
2454
+ const startAt = typeof schedule.start_at === 'string'
2455
+ ? new Date(schedule.start_at).getTime()
2456
+ : schedule.start_at || Date.now();
2457
+ // Generate job tag based on type, database, and operation
2458
+ const jobTag = `database-operation:${data.database}:${data.operation}`;
2459
+ // Initialize logging
2460
+ this.initializeLogService();
2461
+ const baseLogs = {
2462
+ product_tag: data.product,
2463
+ workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '',
2464
+ env: data.env,
2465
+ process_id,
2466
+ type: logs_types_1.LogEventTypes.DATABASE,
2467
+ parent_tag: data.database,
2468
+ child_tag: data.operation,
2469
+ data: { database: data.database, operation: data.operation },
2470
+ };
2471
+ (_b = this.logService) === null || _b === void 0 ? void 0 : _b.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database dispatch - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
2472
+ try {
2473
+ // Check if job exists, if not create it
2474
+ const existingJob = await productBuilder.fetchJob(jobTag);
2475
+ if (!existingJob) {
2476
+ await productBuilder.createJob({
2477
+ tag: jobTag,
2478
+ name: `Database Operation: ${data.database}/${data.operation}`,
2479
+ description: `Auto-created job for database operation ${data.operation} on database ${data.database}`,
2480
+ type: types_1.JobEventTypes.DATABASE_OPERATION,
2481
+ app: data.database,
2482
+ event: data.operation,
2483
+ executions: 0,
2484
+ intervals: schedule.every || 0,
2485
+ start_at: startAt,
2486
+ });
2487
+ }
2488
+ const jobInput = {
2489
+ product: data.product,
2490
+ env: data.env,
2491
+ event: jobTag,
2492
+ input: data.input,
2493
+ retries: data.retries || 0,
2494
+ start_at: startAt,
2495
+ session: data.session,
2496
+ cache: data.cache,
2497
+ repeat: schedule.cron || schedule.every ? {
2498
+ cron: schedule.cron,
2499
+ every: schedule.every,
2500
+ limit: schedule.limit,
2501
+ endDate: schedule.endDate,
2502
+ tz: schedule.tz,
2503
+ } : undefined,
2504
+ };
2505
+ await processorService.processJob(jobInput);
2506
+ const isRecurring = !!(schedule.cron || schedule.every);
2507
+ let nextRunAt;
2508
+ if (isRecurring && schedule.every) {
2509
+ nextRunAt = startAt + schedule.every;
2510
+ }
2511
+ const job_id = (0, crypto_1.randomUUID)();
2512
+ const end = Date.now();
2513
+ (_c = this.logService) === null || _c === void 0 ? void 0 : _c.add(Object.assign(Object.assign({}, baseLogs), { start,
2514
+ end, message: 'Database dispatch - success', successful_execution: true, data: { database: data.database, operation: data.operation, job_id }, status: logs_types_1.LogEventStatus.SUCCESS }));
2515
+ (_d = this.logService) === null || _d === void 0 ? void 0 : _d.publish();
2516
+ return {
2517
+ job_id,
2518
+ status: startAt > Date.now() ? 'scheduled' : 'queued',
2519
+ scheduled_at: startAt,
2520
+ recurring: isRecurring,
2521
+ next_run_at: nextRunAt,
2522
+ };
2523
+ }
2524
+ catch (error) {
2525
+ const end = Date.now();
2526
+ (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start,
2527
+ end, message: 'Database dispatch - failed', failed_execution: true, data: { database: data.database, operation: data.operation, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
2528
+ await ((_f = this.logService) === null || _f === void 0 ? void 0 : _f.publish());
2529
+ throw error;
2530
+ }
2531
+ }
2532
+ // ==================== HELPER METHODS ====================
2533
+ /**
2534
+ * Get the appropriate adapter for the operation
2535
+ */
2536
+ getAdapter(options) {
2537
+ // If options specify env and database, use those
2538
+ if ((options === null || options === void 0 ? void 0 : options.env) && (options === null || options === void 0 ? void 0 : options.database)) {
2539
+ const contextKey = this.buildContextKey(options.database, options.env);
2540
+ const adapter = this.adapters.get(contextKey);
2541
+ if (!adapter) {
2542
+ throw new database_error_1.DatabaseError(`No adapter found for database '${options.database}' in environment '${options.env}'`, enums_1.DatabaseErrorType.NOT_FOUND);
2543
+ }
2544
+ return adapter;
2545
+ }
2546
+ // Otherwise use current context
2547
+ if (!this.currentContext) {
2548
+ throw new database_error_1.DatabaseError('No database connection established. Call connect() first or provide env and database options.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
2549
+ }
2550
+ const contextKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
2551
+ const adapter = this.adapters.get(contextKey);
2552
+ if (!adapter) {
2553
+ throw new database_error_1.DatabaseError('No adapter found for current connection context', enums_1.DatabaseErrorType.CONNECTION_ERROR);
2554
+ }
2555
+ return adapter;
2556
+ }
2557
+ /**
2558
+ * Ensure an adapter exists for the given database/env/product (connect on demand).
2559
+ * Use before getAdapter() when options include database+env+product (e.g. from proxy).
2560
+ */
2561
+ async ensureAdapterFor(options) {
2562
+ if (!(options === null || options === void 0 ? void 0 : options.database) || !(options === null || options === void 0 ? void 0 : options.env) || !(options === null || options === void 0 ? void 0 : options.product))
2563
+ return;
2564
+ const contextKey = this.buildContextKey(options.database, options.env);
2565
+ const existing = this.adapters.get(contextKey);
2566
+ if (existing && typeof existing.isConnected === 'function' && existing.isConnected())
2567
+ return;
2568
+ await this.connect({ database: options.database, env: options.env, product: options.product });
2569
+ }
2570
+ /**
2571
+ * Get the current connection context
2572
+ */
2573
+ getCurrentContext() {
2574
+ return this.currentContext;
2575
+ }
2576
+ /**
2577
+ * Get a connection-scoped interface for a specific database/environment.
2578
+ * This ensures schema operations are isolated to a specific connection.
2579
+ *
2580
+ * @example
2581
+ * const usersDb = db.connection('users-db', 'dev');
2582
+ * await usersDb.schema.create('users', { ... });
2583
+ *
2584
+ * const ordersDb = db.connection('orders-db', 'dev');
2585
+ * await ordersDb.schema.create('orders', { ... }); // Different connection
2586
+ */
2587
+ connection(database, env, product = '') {
2588
+ return new DatabaseConnection(this, database, env, product);
2589
+ }
2590
+ /**
2591
+ * Build a context key from database and environment
2592
+ */
2593
+ buildContextKey(database, env) {
2594
+ return `${database}:${env}`;
2595
+ }
2596
+ /**
2597
+ * Convert DatabaseTypes (from product API) to DatabaseType (ORM internal)
2598
+ */
2599
+ convertDatabaseType(type) {
2600
+ // Map from DatabaseTypes enum values to DatabaseType enum
2601
+ const typeMap = {
2602
+ 'postgresql': enums_1.DatabaseType.POSTGRESQL,
2603
+ 'mongodb': enums_1.DatabaseType.MONGODB,
2604
+ 'mysql': enums_1.DatabaseType.MYSQL,
2605
+ 'dynamodb': enums_1.DatabaseType.DYNAMODB,
2606
+ 'mariadb': enums_1.DatabaseType.MARIADB,
2607
+ 'cassandra': enums_1.DatabaseType.CASSANDRA,
2608
+ };
2609
+ const normalizedType = String(type).toLowerCase();
2610
+ const mappedType = typeMap[normalizedType];
2611
+ if (!mappedType) {
2612
+ throw new database_error_1.DatabaseError(`Unsupported database type: ${type}. Supported types: ${Object.keys(typeMap).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
2613
+ }
2614
+ return mappedType;
2615
+ }
2616
+ // ==================== SIMPLIFIED SCHEMA API ====================
2617
+ /**
2618
+ * Simplified schema operations API (Mongoose-style)
2619
+ *
2620
+ * @example
2621
+ * await db.connect({ env: 'dev', product: 'my-app', database: 'users-db' });
2622
+ *
2623
+ * // Create a table with Mongoose-style schema
2624
+ * await db.schema.create('users', {
2625
+ * id: { type: 'uuid', primaryKey: true },
2626
+ * email: { type: 'string', length: 255, required: true, unique: true },
2627
+ * name: { type: 'string', length: 100 },
2628
+ * age: 'integer', // Shorthand
2629
+ * status: { type: 'enum', enum: ['active', 'inactive'], default: 'active' },
2630
+ * }, { timestamps: true });
2631
+ */
2632
+ get schema() {
2633
+ return {
2634
+ /**
2635
+ * Create a collection/table with Mongoose-style schema definition
2636
+ */
2637
+ create: (name, definition, options) => this.schemaCreate(name, definition, options),
2638
+ /**
2639
+ * Drop a collection/table
2640
+ */
2641
+ drop: (name, options) => this.schemaDrop(name, options),
2642
+ /**
2643
+ * Add a field to a collection
2644
+ */
2645
+ addField: (collection, fieldName, definition) => this.schemaAddField(collection, fieldName, definition),
2646
+ /**
2647
+ * Drop a field from a collection
2648
+ */
2649
+ dropField: (collection, fieldName) => this.schemaDropField(collection, fieldName),
2650
+ /**
2651
+ * Rename a field in a collection
2652
+ */
2653
+ renameField: (collection, oldName, newName) => this.schemaRenameField(collection, oldName, newName),
2654
+ /**
2655
+ * Modify a field's definition
2656
+ */
2657
+ modifyField: (collection, fieldName, changes) => this.schemaModifyField(collection, fieldName, changes),
2658
+ /**
2659
+ * Create an index on a collection
2660
+ */
2661
+ createIndex: (collection, fields, options) => this.schemaCreateIndex(collection, fields, options),
2662
+ /**
2663
+ * Drop an index from a collection
2664
+ */
2665
+ dropIndex: (collection, indexName) => this.schemaDropIndex(collection, indexName),
2666
+ /**
2667
+ * Add a constraint (SQL databases only)
2668
+ */
2669
+ addConstraint: (collection, constraint) => this.schemaAddConstraint(collection, constraint),
2670
+ /**
2671
+ * Drop a constraint (SQL databases only)
2672
+ */
2673
+ dropConstraint: (collection, constraintName) => this.schemaDropConstraint(collection, constraintName),
2674
+ /**
2675
+ * Rename a collection/table
2676
+ */
2677
+ rename: (oldName, newName) => this.schemaRename(oldName, newName),
2678
+ /**
2679
+ * Check if a collection/table exists
2680
+ */
2681
+ exists: (name) => this.schemaExists(name),
2682
+ /**
2683
+ * List all collections/tables
2684
+ */
2685
+ list: (schemaName) => this.schemaList(schemaName),
2686
+ /**
2687
+ * Get detailed schema information for a collection
2688
+ */
2689
+ describe: (name) => this.schemaDescribe(name),
2690
+ /**
2691
+ * List indexes on a collection
2692
+ */
2693
+ indexes: (collection) => this.schemaListIndexes(collection),
2694
+ };
2695
+ }
2696
+ // ==================== PRIVATE SCHEMA IMPLEMENTATION ====================
2697
+ /**
2698
+ * Create a collection with Mongoose-style definition
2699
+ */
2700
+ async schemaCreate(name, definition, options) {
2701
+ var _a;
2702
+ const schemaManager = this.getSchemaManager();
2703
+ const fields = this.convertToFieldDefinitions(definition, options === null || options === void 0 ? void 0 : options.timestamps);
2704
+ // Convert simple index definitions to the expected format
2705
+ const indexes = (_a = options === null || options === void 0 ? void 0 : options.indexes) === null || _a === void 0 ? void 0 : _a.map(idx => ({
2706
+ name: idx.name || `idx_${name}_${Array.isArray(idx.fields) ? (typeof idx.fields[0] === 'string' ? idx.fields.join('_') : idx.fields.map((f) => f.name).join('_')) : idx.fields}`,
2707
+ fields: this.normalizeIndexFields(idx.fields),
2708
+ unique: idx.unique,
2709
+ }));
2710
+ return schemaManager.createCollection(name, fields, {
2711
+ autoApply: true,
2712
+ indexes,
2713
+ sqlOptions: options === null || options === void 0 ? void 0 : options.sqlOptions,
2714
+ mongoOptions: options === null || options === void 0 ? void 0 : options.mongoOptions,
2715
+ dynamoOptions: options === null || options === void 0 ? void 0 : options.dynamoOptions,
2716
+ cassandraOptions: options === null || options === void 0 ? void 0 : options.cassandraOptions,
2717
+ });
2718
+ }
2719
+ /**
2720
+ * Drop a collection
2721
+ */
2722
+ async schemaDrop(name, options) {
2723
+ const schemaManager = this.getSchemaManager();
2724
+ return schemaManager.dropCollection(name, {
2725
+ autoApply: true,
2726
+ ifExists: options === null || options === void 0 ? void 0 : options.ifExists,
2727
+ cascade: options === null || options === void 0 ? void 0 : options.cascade,
2728
+ });
2729
+ }
2730
+ /**
2731
+ * Add a field to a collection
2732
+ */
2733
+ async schemaAddField(collection, fieldName, definition) {
2734
+ const schemaManager = this.getSchemaManager();
2735
+ const field = this.convertFieldDefinition(fieldName, definition);
2736
+ return schemaManager.addField(collection, field, { autoApply: true });
2737
+ }
2738
+ /**
2739
+ * Drop a field from a collection
2740
+ */
2741
+ async schemaDropField(collection, fieldName) {
2742
+ const schemaManager = this.getSchemaManager();
2743
+ return schemaManager.dropField(collection, fieldName, { autoApply: true });
2744
+ }
2745
+ /**
2746
+ * Rename a field
2747
+ */
2748
+ async schemaRenameField(collection, oldName, newName) {
2749
+ const schemaManager = this.getSchemaManager();
2750
+ return schemaManager.renameField(collection, oldName, newName, { autoApply: true });
2751
+ }
2752
+ /**
2753
+ * Modify a field's definition
2754
+ */
2755
+ async schemaModifyField(collection, fieldName, changes) {
2756
+ const schemaManager = this.getSchemaManager();
2757
+ const fieldChanges = {};
2758
+ if (changes.type) {
2759
+ fieldChanges.type = this.normalizeFieldType(changes.type);
2760
+ }
2761
+ if (changes.minLength !== undefined) {
2762
+ fieldChanges.minLength = changes.minLength;
2763
+ }
2764
+ if (changes.maxLength !== undefined) {
2765
+ fieldChanges.maxLength = changes.maxLength;
2766
+ }
2767
+ if (changes.precision !== undefined) {
2768
+ fieldChanges.precision = changes.precision;
2769
+ }
2770
+ if (changes.scale !== undefined) {
2771
+ fieldChanges.scale = changes.scale;
2772
+ }
2773
+ if (changes.required !== undefined) {
2774
+ fieldChanges.nullable = !changes.required;
2775
+ }
2776
+ if (changes.unique !== undefined) {
2777
+ fieldChanges.unique = changes.unique;
2778
+ }
2779
+ if (changes.default !== undefined) {
2780
+ fieldChanges.defaultValue = changes.default;
2781
+ }
2782
+ if (changes.enum !== undefined) {
2783
+ fieldChanges.enumValues = changes.enum;
2784
+ }
2785
+ return schemaManager.modifyField(collection, fieldName, fieldChanges, { autoApply: true });
2786
+ }
2787
+ /**
2788
+ * Create an index
2789
+ */
2790
+ async schemaCreateIndex(collection, fields, options) {
2791
+ const schemaManager = this.getSchemaManager();
2792
+ const normalizedFields = this.normalizeIndexFields(fields);
2793
+ const indexName = (options === null || options === void 0 ? void 0 : options.name) || `idx_${collection}_${normalizedFields.map(f => f.name).join('_')}`;
2794
+ return schemaManager.createIndex(collection, indexName, normalizedFields, {
2795
+ autoApply: true,
2796
+ unique: options === null || options === void 0 ? void 0 : options.unique,
2797
+ sparse: options === null || options === void 0 ? void 0 : options.sparse,
2798
+ sqlOptions: (options === null || options === void 0 ? void 0 : options.where) ? { where: options.where } : undefined,
2799
+ mongoOptions: (options === null || options === void 0 ? void 0 : options.expireAfterSeconds) ? { expireAfterSeconds: options.expireAfterSeconds } : undefined,
2800
+ });
2801
+ }
2802
+ /**
2803
+ * Drop an index
2804
+ */
2805
+ async schemaDropIndex(collection, indexName) {
2806
+ const schemaManager = this.getSchemaManager();
2807
+ return schemaManager.dropIndex(collection, indexName, { autoApply: true, ifExists: true });
2808
+ }
2809
+ /**
2810
+ * Add a constraint (SQL only)
2811
+ */
2812
+ async schemaAddConstraint(collection, constraint) {
2813
+ const schemaManager = this.getSchemaManager();
2814
+ return schemaManager.addConstraint(collection, constraint, { autoApply: true });
2815
+ }
2816
+ /**
2817
+ * Drop a constraint (SQL only)
2818
+ */
2819
+ async schemaDropConstraint(collection, constraintName) {
2820
+ const schemaManager = this.getSchemaManager();
2821
+ return schemaManager.dropConstraint(collection, constraintName, { autoApply: true });
2822
+ }
2823
+ /**
2824
+ * Rename a collection
2825
+ */
2826
+ async schemaRename(oldName, newName) {
2827
+ const schemaManager = this.getSchemaManager();
2828
+ return schemaManager.renameCollection(oldName, newName, { autoApply: true });
2829
+ }
2830
+ /**
2831
+ * Check if collection exists
2832
+ */
2833
+ async schemaExists(name) {
2834
+ const schemaManager = this.getSchemaManager();
2835
+ return schemaManager.collectionExists(name);
2836
+ }
2837
+ /**
2838
+ * List all collections
2839
+ */
2840
+ async schemaList(schemaName) {
2841
+ const schemaManager = this.getSchemaManager();
2842
+ return schemaManager.listCollections(schemaName);
2843
+ }
2844
+ /**
2845
+ * Describe a collection's schema
2846
+ */
2847
+ async schemaDescribe(name) {
2848
+ const schemaManager = this.getSchemaManager();
2849
+ return schemaManager.getCollectionSchema(name);
2850
+ }
2851
+ /**
2852
+ * List indexes on a collection
2853
+ */
2854
+ async schemaListIndexes(collection) {
2855
+ const schemaManager = this.getSchemaManager();
2856
+ return schemaManager.listIndexes(collection);
2857
+ }
2858
+ // ==================== SCHEMA CONVERSION HELPERS ====================
2859
+ /**
2860
+ * Convert Mongoose-style schema definition to IFieldDefinition array
2861
+ */
2862
+ convertToFieldDefinitions(definition, timestamps) {
2863
+ const fields = [];
2864
+ for (const [name, config] of Object.entries(definition)) {
2865
+ fields.push(this.convertFieldDefinition(name, config));
2866
+ }
2867
+ if (timestamps) {
2868
+ fields.push({ name: 'created_at', type: 'timestamp', defaultValue: 'NOW()', nullable: false }, { name: 'updated_at', type: 'timestamp', defaultValue: 'NOW()', nullable: false });
2869
+ }
2870
+ return fields;
2871
+ }
2872
+ /**
2873
+ * Convert a single field definition
2874
+ */
2875
+ convertFieldDefinition(name, config) {
2876
+ // Handle shorthand: { name: 'string' }
2877
+ if (typeof config === 'string') {
2878
+ return { name, type: this.normalizeFieldType(config) };
2879
+ }
2880
+ // Validate autoIncrement only works with numeric types
2881
+ if (config.autoIncrement) {
2882
+ const normalizedType = this.normalizeFieldType(config.type);
2883
+ const numericTypes = ['integer', 'int', 'bigint', 'smallint', 'number', 'float', 'double', 'decimal'];
2884
+ if (!numericTypes.includes(normalizedType.toLowerCase())) {
2885
+ throw new database_error_1.DatabaseError(`autoIncrement can only be used with numeric types (integer, bigint, number, etc.), but field '${name}' has type '${config.type}'`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
2886
+ }
2887
+ }
2888
+ // Handle full definition
2889
+ return {
2890
+ name,
2891
+ type: this.normalizeFieldType(config.type),
2892
+ nullable: config.required === undefined ? true : !config.required,
2893
+ unique: config.unique,
2894
+ primaryKey: config.primaryKey,
2895
+ autoGenerate: config.autoIncrement,
2896
+ defaultValue: config.default,
2897
+ minLength: config.minLength,
2898
+ maxLength: config.maxLength,
2899
+ precision: config.precision,
2900
+ scale: config.scale,
2901
+ enumValues: config.enum,
2902
+ comment: config.comment,
2903
+ };
2904
+ }
2905
+ /**
2906
+ * Normalize Mongoose-style type names to FieldType
2907
+ */
2908
+ normalizeFieldType(type) {
2909
+ const typeMap = {
2910
+ // String types
2911
+ 'String': 'string',
2912
+ // Numeric types
2913
+ 'Number': 'double', // JS number is 64-bit float
2914
+ 'Integer': 'integer', // 32-bit signed integer
2915
+ 'BigInt': 'bigint', // 64-bit signed integer
2916
+ 'Float': 'float', // 32-bit floating point
2917
+ 'Double': 'double', // 64-bit floating point
2918
+ 'Decimal': 'decimal', // Exact precision (for money)
2919
+ // Other types
2920
+ 'Boolean': 'boolean',
2921
+ 'Date': 'datetime',
2922
+ 'ObjectId': 'uuid',
2923
+ 'Array': 'array',
2924
+ 'Object': 'json',
2925
+ 'Mixed': 'json',
2926
+ };
2927
+ return typeMap[type] || type;
2928
+ }
2929
+ /**
2930
+ * Normalize index fields to IIndexFieldDefinition array
2931
+ */
2932
+ normalizeIndexFields(fields) {
2933
+ if (fields.length === 0) {
2934
+ return [];
2935
+ }
2936
+ // Check if first element is a string
2937
+ if (typeof fields[0] === 'string') {
2938
+ return fields.map(name => ({ name }));
2939
+ }
2940
+ return fields;
2941
+ }
2942
+ /**
2943
+ * Get adapter by context key (used by DatabaseConnection)
2944
+ * @internal
2945
+ */
2946
+ getAdapterByContextKey(contextKey) {
2947
+ const adapter = this.adapters.get(contextKey);
2948
+ if (!adapter) {
2949
+ throw new database_error_1.DatabaseError(`No adapter found for context '${contextKey}'. Call connect() first.`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
2950
+ }
2951
+ return adapter;
2952
+ }
2953
+ // ==================== DASHBOARD ====================
2954
+ /**
2955
+ * Fetch database dashboard metrics from logs
2956
+ *
2957
+ * @example
2958
+ * ```ts
2959
+ * const dashboard = await databases.fetchDashboard({
2960
+ * product: 'my-product',
2961
+ * database: 'my-database',
2962
+ * env: 'production',
2963
+ * });
2964
+ * console.log(dashboard.dau, dashboard.activityTimeline);
2965
+ * ```
2966
+ */
2967
+ async fetchDashboard(options) {
2968
+ if (!this.config) {
2969
+ throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
2970
+ }
2971
+ const { product, database, env } = options;
2972
+ const { LogApiService } = await Promise.resolve().then(() => __importStar(require('../api/services/logsApi.service')));
2973
+ const logsApi = new LogApiService(this.config.env_type);
2974
+ try {
2975
+ const dashboard = await logsApi.fetchDatabaseDashboard({
2976
+ product_tag: product,
2977
+ database_tag: database,
2978
+ env,
2979
+ }, {
2980
+ workspace_id: this.config.workspace_id,
2981
+ user_id: this.config.user_id,
2982
+ public_key: this.config.public_key,
2983
+ token: this.config.token,
2984
+ });
2985
+ return {
2986
+ dau: dashboard.dau || { current: 0, previous: 0, change: 0 },
2987
+ wau: dashboard.wau || { current: 0, previous: 0, change: 0 },
2988
+ mau: dashboard.mau || { current: 0, previous: 0, change: 0 },
2989
+ totalOperations: dashboard.totalOperations || 0,
2990
+ successfulOperations: dashboard.successfulOperations || 0,
2991
+ failedOperations: dashboard.failedOperations || 0,
2992
+ newOperationsThisWeek: dashboard.newOperationsThisWeek || 0,
2993
+ avgExecutionTime: dashboard.avgExecutionTime || { current: '0ms', previous: '0ms', change: 0 },
2994
+ activityTimeline: dashboard.activityTimeline || [],
2995
+ peakHours: dashboard.peakHours || [],
2996
+ environmentBreakdown: dashboard.environmentBreakdown || [],
2997
+ methodBreakdown: dashboard.methodBreakdown || [],
2998
+ };
2999
+ }
3000
+ catch (error) {
3001
+ throw new database_error_1.DatabaseError(`Failed to fetch database dashboard: ${error}`, enums_1.DatabaseErrorType.QUERY_ERROR);
3002
+ }
3003
+ }
3004
+ }
3005
+ exports.DatabaseService = DatabaseService;
3006
+ /**
3007
+ * Connection-scoped database interface.
3008
+ * Provides isolated schema, query, and aggregation operations for a specific database/environment.
3009
+ */
3010
+ class DatabaseConnection {
3011
+ constructor(service, database, env, product) {
3012
+ this.service = service;
3013
+ this._database = database;
3014
+ this._env = env;
3015
+ this._product = product;
3016
+ this.contextKey = `${database}:${env}`;
3017
+ this.triggerProcessor = new trigger_processor_1.TriggerProcessor({}, null);
3018
+ }
3019
+ /** Database tag */
3020
+ get database() {
3021
+ return this._database;
3022
+ }
3023
+ /** Environment slug */
3024
+ get env() {
3025
+ return this._env;
3026
+ }
3027
+ /** Product tag */
3028
+ get product() {
3029
+ return this._product;
3030
+ }
3031
+ /** Get the adapter for this connection */
3032
+ getAdapter() {
3033
+ return this.service.getAdapterByContextKey(this.contextKey);
3034
+ }
3035
+ /**
3036
+ * Schema operations scoped to this connection
3037
+ */
3038
+ get schema() {
3039
+ const adapter = () => this.getAdapter();
3040
+ const service = this.service;
3041
+ return {
3042
+ create: async (name, definition, options) => {
3043
+ var _a;
3044
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3045
+ const fields = service.convertToFieldDefinitions(definition, options === null || options === void 0 ? void 0 : options.timestamps);
3046
+ const indexes = (_a = options === null || options === void 0 ? void 0 : options.indexes) === null || _a === void 0 ? void 0 : _a.map(idx => ({
3047
+ name: idx.name || `idx_${name}_${Array.isArray(idx.fields) ? (typeof idx.fields[0] === 'string' ? idx.fields.join('_') : idx.fields.map((f) => f.name).join('_')) : idx.fields}`,
3048
+ fields: service.normalizeIndexFields(idx.fields),
3049
+ unique: idx.unique,
3050
+ }));
3051
+ return schemaManager.createCollection(name, fields, {
3052
+ autoApply: true,
3053
+ indexes,
3054
+ sqlOptions: options === null || options === void 0 ? void 0 : options.sqlOptions,
3055
+ mongoOptions: options === null || options === void 0 ? void 0 : options.mongoOptions,
3056
+ dynamoOptions: options === null || options === void 0 ? void 0 : options.dynamoOptions,
3057
+ cassandraOptions: options === null || options === void 0 ? void 0 : options.cassandraOptions,
3058
+ });
3059
+ },
3060
+ drop: async (name, options) => {
3061
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3062
+ return schemaManager.dropCollection(name, {
3063
+ autoApply: true,
3064
+ ifExists: options === null || options === void 0 ? void 0 : options.ifExists,
3065
+ cascade: options === null || options === void 0 ? void 0 : options.cascade,
3066
+ });
3067
+ },
3068
+ addField: async (collection, fieldName, definition) => {
3069
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3070
+ const field = service.convertFieldDefinition(fieldName, definition);
3071
+ return schemaManager.addField(collection, field, { autoApply: true });
3072
+ },
3073
+ dropField: async (collection, fieldName) => {
3074
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3075
+ return schemaManager.dropField(collection, fieldName, { autoApply: true });
3076
+ },
3077
+ renameField: async (collection, oldName, newName) => {
3078
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3079
+ return schemaManager.renameField(collection, oldName, newName, { autoApply: true });
3080
+ },
3081
+ modifyField: async (collection, fieldName, changes) => {
3082
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3083
+ const fieldChanges = {};
3084
+ if (changes.type)
3085
+ fieldChanges.type = service.normalizeFieldType(changes.type);
3086
+ if (changes.minLength !== undefined)
3087
+ fieldChanges.minLength = changes.minLength;
3088
+ if (changes.maxLength !== undefined)
3089
+ fieldChanges.maxLength = changes.maxLength;
3090
+ if (changes.precision !== undefined)
3091
+ fieldChanges.precision = changes.precision;
3092
+ if (changes.scale !== undefined)
3093
+ fieldChanges.scale = changes.scale;
3094
+ if (changes.required !== undefined)
3095
+ fieldChanges.nullable = !changes.required;
3096
+ if (changes.unique !== undefined)
3097
+ fieldChanges.unique = changes.unique;
3098
+ if (changes.default !== undefined)
3099
+ fieldChanges.defaultValue = changes.default;
3100
+ if (changes.enum !== undefined)
3101
+ fieldChanges.enumValues = changes.enum;
3102
+ return schemaManager.modifyField(collection, fieldName, fieldChanges, { autoApply: true });
3103
+ },
3104
+ createIndex: async (collection, fields, options) => {
3105
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3106
+ const normalizedFields = service.normalizeIndexFields(fields);
3107
+ const indexName = (options === null || options === void 0 ? void 0 : options.name) || `idx_${collection}_${normalizedFields.map((f) => f.name).join('_')}`;
3108
+ return schemaManager.createIndex(collection, indexName, normalizedFields, {
3109
+ autoApply: true,
3110
+ unique: options === null || options === void 0 ? void 0 : options.unique,
3111
+ sparse: options === null || options === void 0 ? void 0 : options.sparse,
3112
+ sqlOptions: (options === null || options === void 0 ? void 0 : options.where) ? { where: options.where } : undefined,
3113
+ mongoOptions: (options === null || options === void 0 ? void 0 : options.expireAfterSeconds) ? { expireAfterSeconds: options.expireAfterSeconds } : undefined,
3114
+ });
3115
+ },
3116
+ dropIndex: async (collection, indexName) => {
3117
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3118
+ return schemaManager.dropIndex(collection, indexName, { autoApply: true, ifExists: true });
3119
+ },
3120
+ addConstraint: async (collection, constraint) => {
3121
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3122
+ return schemaManager.addConstraint(collection, constraint, { autoApply: true });
3123
+ },
3124
+ dropConstraint: async (collection, constraintName) => {
3125
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3126
+ return schemaManager.dropConstraint(collection, constraintName, { autoApply: true });
3127
+ },
3128
+ rename: async (oldName, newName) => {
3129
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3130
+ return schemaManager.renameCollection(oldName, newName, { autoApply: true });
3131
+ },
3132
+ exists: async (name) => {
3133
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3134
+ return schemaManager.collectionExists(name);
3135
+ },
3136
+ list: async (schemaName) => {
3137
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3138
+ return schemaManager.listCollections(schemaName);
3139
+ },
3140
+ describe: async (name) => {
3141
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3142
+ return schemaManager.getCollectionSchema(name);
3143
+ },
3144
+ indexes: async (collection) => {
3145
+ const schemaManager = new schema_manager_1.SchemaManager(adapter());
3146
+ return schemaManager.listIndexes(collection);
3147
+ },
3148
+ };
3149
+ }
3150
+ // Query operations scoped to this connection
3151
+ query(options) {
3152
+ return this.service.query(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3153
+ }
3154
+ insert(options) {
3155
+ return this.service.insert(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3156
+ }
3157
+ update(options) {
3158
+ return this.service.update(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3159
+ }
3160
+ delete(options) {
3161
+ return this.service.delete(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3162
+ }
3163
+ upsert(options) {
3164
+ return this.service.upsert(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3165
+ }
3166
+ raw(options) {
3167
+ return this.service.raw(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3168
+ }
3169
+ // Aggregation operations scoped to this connection
3170
+ count(options) {
3171
+ return this.service.count(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3172
+ }
3173
+ sum(options) {
3174
+ return this.service.sum(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3175
+ }
3176
+ avg(options) {
3177
+ return this.service.avg(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3178
+ }
3179
+ min(options) {
3180
+ return this.service.min(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3181
+ }
3182
+ max(options) {
3183
+ return this.service.max(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3184
+ }
3185
+ aggregate(options) {
3186
+ return this.service.aggregate(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3187
+ }
3188
+ groupBy(options) {
3189
+ return this.service.groupBy(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3190
+ }
3191
+ /**
3192
+ * Trigger operations scoped to this connection
3193
+ */
3194
+ get triggers() {
3195
+ const connection = this;
3196
+ return {
3197
+ /**
3198
+ * Create a trigger and store it on the backend
3199
+ * @param data - Trigger configuration (tag should be just the trigger name, database tag is added automatically)
3200
+ */
3201
+ create: async (data) => {
3202
+ var _a;
3203
+ if (!connection._product) {
3204
+ throw new Error('Product tag is required to create triggers. Use connect() with product parameter.');
3205
+ }
3206
+ // Auto-prefix with database tag if not already prefixed
3207
+ const tag = ((_a = data.tag) === null || _a === void 0 ? void 0 : _a.includes(':')) ? data.tag : `${connection._database}:${data.tag}`;
3208
+ return connection.service.createTrigger(connection._product, Object.assign(Object.assign({}, data), { tag }));
3209
+ },
3210
+ /**
3211
+ * Update an existing trigger on the backend
3212
+ * @param data - Trigger configuration
3213
+ */
3214
+ update: async (data) => {
3215
+ var _a;
3216
+ if (!connection._product) {
3217
+ throw new Error('Product tag is required to update triggers. Use connect() with product parameter.');
3218
+ }
3219
+ const tag = ((_a = data.tag) === null || _a === void 0 ? void 0 : _a.includes(':')) ? data.tag : `${connection._database}:${data.tag}`;
3220
+ return connection.service.updateTrigger(connection._product, Object.assign(Object.assign({}, data), { tag }));
3221
+ },
3222
+ /**
3223
+ * Fetch a specific trigger from the backend
3224
+ * @param triggerTag - The trigger tag (without database prefix)
3225
+ */
3226
+ fetch: async (triggerTag) => {
3227
+ if (!connection._product) {
3228
+ throw new Error('Product tag is required to fetch triggers. Use connect() with product parameter.');
3229
+ }
3230
+ const tag = triggerTag.includes(':') ? triggerTag : `${connection._database}:${triggerTag}`;
3231
+ return connection.service.fetchTrigger(connection._product, tag);
3232
+ },
3233
+ /**
3234
+ * Fetch all triggers for this database from the backend
3235
+ * @deprecated Use list() instead
3236
+ */
3237
+ fetchAll: async () => {
3238
+ if (!connection._product) {
3239
+ throw new Error('Product tag is required to fetch triggers. Use connect() with product parameter.');
3240
+ }
3241
+ return connection.service.fetchTriggers(connection._product, connection._database);
3242
+ },
3243
+ /**
3244
+ * List all triggers for this database from the backend
3245
+ * @param options - Optional filters (table, event, enabled)
3246
+ */
3247
+ list: async (options) => {
3248
+ if (!connection._product) {
3249
+ throw new Error('Product tag is required to list triggers. Use connect() with product parameter.');
3250
+ }
3251
+ let triggers = await connection.service.fetchTriggers(connection._product, connection._database);
3252
+ // Apply filters if provided
3253
+ if (options === null || options === void 0 ? void 0 : options.table) {
3254
+ triggers = triggers.filter(t => { var _a; return (_a = t.tables) === null || _a === void 0 ? void 0 : _a.includes(options.table); });
3255
+ }
3256
+ if (options === null || options === void 0 ? void 0 : options.event) {
3257
+ triggers = triggers.filter(t => { var _a; return (_a = t.events) === null || _a === void 0 ? void 0 : _a.includes(options.event); });
3258
+ }
3259
+ if ((options === null || options === void 0 ? void 0 : options.enabled) !== undefined) {
3260
+ triggers = triggers.filter(t => t.enabled === options.enabled);
3261
+ }
3262
+ return triggers;
3263
+ },
3264
+ /**
3265
+ * Delete a trigger from the backend
3266
+ * @param triggerTag - The trigger tag (without database prefix)
3267
+ */
3268
+ delete: async (triggerTag) => {
3269
+ if (!connection._product) {
3270
+ throw new Error('Product tag is required to delete triggers. Use connect() with product parameter.');
3271
+ }
3272
+ const tag = triggerTag.includes(':') ? triggerTag : `${connection._database}:${triggerTag}`;
3273
+ await connection.service.deleteTrigger(connection._product, tag);
3274
+ return true;
3275
+ },
3276
+ /**
3277
+ * Register a trigger in memory for the current session (does not persist to backend)
3278
+ * @deprecated Use create() for persistent triggers
3279
+ */
3280
+ register: (table, trigger) => {
3281
+ connection.triggerProcessor.register(table, trigger);
3282
+ },
3283
+ /**
3284
+ * Register multiple triggers in memory (does not persist to backend)
3285
+ * @deprecated Use create() for persistent triggers
3286
+ */
3287
+ registerAll: (triggers) => {
3288
+ connection.triggerProcessor.registerAll(triggers);
3289
+ },
3290
+ /**
3291
+ * Unregister a trigger from memory
3292
+ */
3293
+ unregister: (table, triggerName) => {
3294
+ return connection.triggerProcessor.unregister(table, triggerName);
3295
+ },
3296
+ /**
3297
+ * Get all triggers for a table and event
3298
+ */
3299
+ getTriggersForEvent: (table, event) => {
3300
+ return connection.triggerProcessor.getTriggersForEvent(table, event);
3301
+ },
3302
+ /**
3303
+ * Execute all triggers for an event
3304
+ */
3305
+ execute: async (event, context) => {
3306
+ return connection.triggerProcessor.executeTriggers(event, Object.assign(Object.assign({}, context), { database: connection._database, env: connection._env }));
3307
+ },
3308
+ /**
3309
+ * Load triggers from the backend and register them in memory
3310
+ */
3311
+ load: async () => {
3312
+ if (!connection._product) {
3313
+ throw new Error('Product tag is required to load triggers. Use connect() with product parameter.');
3314
+ }
3315
+ const backendTriggers = await connection.service.fetchTriggers(connection._product, connection._database);
3316
+ for (const trigger of backendTriggers) {
3317
+ // Convert backend trigger format to ITriggerDefinition
3318
+ const definition = {
3319
+ name: trigger.tag,
3320
+ description: trigger.description,
3321
+ events: trigger.events, // TriggerEventType maps to TriggerEvent
3322
+ tables: trigger.tables,
3323
+ condition: trigger.condition,
3324
+ actions: trigger.actions.map(action => (Object.assign(Object.assign({}, action.config), { type: action.type, name: action.name, condition: action.condition, timing: action.timing, retry: action.retry, timeout: action.timeout, continueOnError: action.continueOnError }))),
3325
+ enabled: trigger.enabled,
3326
+ priority: trigger.priority,
3327
+ tags: trigger.tags,
3328
+ };
3329
+ // Register for all tables specified, or use '*' for all
3330
+ const tables = trigger.tables && trigger.tables.length > 0 ? trigger.tables : ['*'];
3331
+ for (const table of tables) {
3332
+ connection.triggerProcessor.register(table, definition);
3333
+ }
3334
+ }
3335
+ },
3336
+ /**
3337
+ * Set the Ductape instance for trigger actions
3338
+ */
3339
+ setDuctapeInstance: (instance) => {
3340
+ connection.triggerProcessor.setDuctapeInstance(instance);
3341
+ },
3342
+ /**
3343
+ * Get the trigger processor instance
3344
+ */
3345
+ getProcessor: () => {
3346
+ return connection.triggerProcessor;
3347
+ },
3348
+ /**
3349
+ * Trigger action builders
3350
+ */
3351
+ Trigger: trigger_processor_1.Trigger,
3352
+ /**
3353
+ * Trigger events enum
3354
+ */
3355
+ TriggerEvent: trigger_interface_1.TriggerEvent,
3356
+ /**
3357
+ * Trigger timing enum
3358
+ */
3359
+ TriggerTiming: trigger_interface_1.TriggerTiming,
3360
+ /**
3361
+ * Trigger action types enum
3362
+ */
3363
+ TriggerActionType: trigger_interface_1.TriggerActionType,
3364
+ };
3365
+ }
3366
+ }
3367
+ exports.DatabaseConnection = DatabaseConnection;
3368
+ // Export singleton instance for convenience
3369
+ exports.databaseService = new DatabaseService();
3370
+ //# sourceMappingURL=databases.service.js.map