@ambiten/core 1.0.0

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 (304) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -0
  3. package/bin/bootstrap.js +26 -0
  4. package/dist/ambiten-cache/ambitenCache.d.ts +64 -0
  5. package/dist/ambiten-cache/ambitenCache.d.ts.map +1 -0
  6. package/dist/ambiten-cache/ambitenCache.js +127 -0
  7. package/dist/ambiten-cache/index.d.ts +2 -0
  8. package/dist/ambiten-cache/index.d.ts.map +1 -0
  9. package/dist/ambiten-cache/index.js +4 -0
  10. package/dist/browser.d.ts +32 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +37 -0
  13. package/dist/cli/ambiten-core-cli.d.ts +4 -0
  14. package/dist/cli/ambiten-core-cli.d.ts.map +1 -0
  15. package/dist/cli/ambiten-core-cli.js +41 -0
  16. package/dist/cli/buildInteractiveConfig.d.ts +4 -0
  17. package/dist/cli/buildInteractiveConfig.d.ts.map +1 -0
  18. package/dist/cli/buildInteractiveConfig.js +198 -0
  19. package/dist/cli/index.d.ts +5 -0
  20. package/dist/cli/index.d.ts.map +1 -0
  21. package/dist/cli/index.js +7 -0
  22. package/dist/cli/prompt.d.ts +10 -0
  23. package/dist/cli/prompt.d.ts.map +1 -0
  24. package/dist/cli/prompt.js +48 -0
  25. package/dist/cli/types.d.ts +11 -0
  26. package/dist/cli/types.d.ts.map +1 -0
  27. package/dist/cli/types.js +2 -0
  28. package/dist/config/ambiten.config.schema.json +278 -0
  29. package/dist/config/index.d.ts +2 -0
  30. package/dist/config/index.d.ts.map +1 -0
  31. package/dist/config/index.js +4 -0
  32. package/dist/config/loadAmbitenConfig.d.ts +3 -0
  33. package/dist/config/loadAmbitenConfig.d.ts.map +1 -0
  34. package/dist/config/loadAmbitenConfig.js +131 -0
  35. package/dist/context/ambitenContext.d.ts +35 -0
  36. package/dist/context/ambitenContext.d.ts.map +1 -0
  37. package/dist/context/ambitenContext.js +147 -0
  38. package/dist/context/helpers/runManualTransaction.d.ts +3 -0
  39. package/dist/context/helpers/runManualTransaction.d.ts.map +1 -0
  40. package/dist/context/helpers/runManualTransaction.js +22 -0
  41. package/dist/context/helpers/transactionSession.d.ts +9 -0
  42. package/dist/context/helpers/transactionSession.d.ts.map +1 -0
  43. package/dist/context/helpers/transactionSession.js +8 -0
  44. package/dist/context/index.d.ts +4 -0
  45. package/dist/context/index.d.ts.map +1 -0
  46. package/dist/context/index.js +6 -0
  47. package/dist/debug/debugLog.d.ts +2 -0
  48. package/dist/debug/debugLog.d.ts.map +1 -0
  49. package/dist/debug/debugLog.js +23 -0
  50. package/dist/debug/index.d.ts +2 -0
  51. package/dist/debug/index.d.ts.map +1 -0
  52. package/dist/debug/index.js +4 -0
  53. package/dist/gc/ambitenGC.d.ts +49 -0
  54. package/dist/gc/ambitenGC.d.ts.map +1 -0
  55. package/dist/gc/ambitenGC.js +138 -0
  56. package/dist/gc/gcCron.browser.d.ts +2 -0
  57. package/dist/gc/gcCron.browser.d.ts.map +1 -0
  58. package/dist/gc/gcCron.browser.js +9 -0
  59. package/dist/gc/gcCron.node.d.ts +19 -0
  60. package/dist/gc/gcCron.node.d.ts.map +1 -0
  61. package/dist/gc/gcCron.node.js +47 -0
  62. package/dist/gc/gcManager.d.ts +37 -0
  63. package/dist/gc/gcManager.d.ts.map +1 -0
  64. package/dist/gc/gcManager.js +62 -0
  65. package/dist/gc/index.d.ts +5 -0
  66. package/dist/gc/index.d.ts.map +1 -0
  67. package/dist/gc/index.js +7 -0
  68. package/dist/graphql/ambitenGraphQL.d.ts +24 -0
  69. package/dist/graphql/ambitenGraphQL.d.ts.map +1 -0
  70. package/dist/graphql/ambitenGraphQL.js +215 -0
  71. package/dist/graphql/index.d.ts +2 -0
  72. package/dist/graphql/index.d.ts.map +1 -0
  73. package/dist/graphql/index.js +4 -0
  74. package/dist/index-browser.js +25 -0
  75. package/dist/index-browser.js.map +1 -0
  76. package/dist/index-cli.js +26 -0
  77. package/dist/index-cli.js.map +1 -0
  78. package/dist/index.d.ts +30 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +25 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/init-cli/generate.project.d.ts +9 -0
  83. package/dist/init-cli/generate.project.d.ts.map +1 -0
  84. package/dist/init-cli/generate.project.js +38 -0
  85. package/dist/instrumentation/index.d.ts +3 -0
  86. package/dist/instrumentation/index.d.ts.map +1 -0
  87. package/dist/instrumentation/index.js +5 -0
  88. package/dist/instrumentation/measureQuery.browser.d.ts +3 -0
  89. package/dist/instrumentation/measureQuery.browser.d.ts.map +1 -0
  90. package/dist/instrumentation/measureQuery.browser.js +6 -0
  91. package/dist/instrumentation/measureQueryWithErrors.d.ts +11 -0
  92. package/dist/instrumentation/measureQueryWithErrors.d.ts.map +1 -0
  93. package/dist/instrumentation/measureQueryWithErrors.js +90 -0
  94. package/dist/lib-core/ambitenClient.d.ts +115 -0
  95. package/dist/lib-core/ambitenClient.d.ts.map +1 -0
  96. package/dist/lib-core/ambitenClient.js +537 -0
  97. package/dist/lib-core/ambitenModelFactory.d.ts +979 -0
  98. package/dist/lib-core/ambitenModelFactory.d.ts.map +1 -0
  99. package/dist/lib-core/ambitenModelFactory.js +3984 -0
  100. package/dist/lib-core/ambitenSchema.d.ts +126 -0
  101. package/dist/lib-core/ambitenSchema.d.ts.map +1 -0
  102. package/dist/lib-core/ambitenSchema.js +247 -0
  103. package/dist/lib-core/bootstrap/ambitenBootstrap.d.ts +38 -0
  104. package/dist/lib-core/bootstrap/ambitenBootstrap.d.ts.map +1 -0
  105. package/dist/lib-core/bootstrap/ambitenBootstrap.js +381 -0
  106. package/dist/lib-core/bootstrap/index.d.ts +2 -0
  107. package/dist/lib-core/bootstrap/index.d.ts.map +1 -0
  108. package/dist/lib-core/bootstrap/index.js +4 -0
  109. package/dist/lib-core/index.d.ts +5 -0
  110. package/dist/lib-core/index.d.ts.map +1 -0
  111. package/dist/lib-core/index.js +7 -0
  112. package/dist/middleware/authorization/auth.d.ts +22 -0
  113. package/dist/middleware/authorization/auth.d.ts.map +1 -0
  114. package/dist/middleware/authorization/auth.js +37 -0
  115. package/dist/middleware/index.d.ts +4 -0
  116. package/dist/middleware/index.d.ts.map +1 -0
  117. package/dist/middleware/index.js +6 -0
  118. package/dist/middleware/rbac/rbacMiddleware.d.ts +103 -0
  119. package/dist/middleware/rbac/rbacMiddleware.d.ts.map +1 -0
  120. package/dist/middleware/rbac/rbacMiddleware.js +246 -0
  121. package/dist/middleware/rbac/rbacTypes.d.ts +4 -0
  122. package/dist/middleware/rbac/rbacTypes.d.ts.map +1 -0
  123. package/dist/middleware/rbac/rbacTypes.js +8 -0
  124. package/dist/plugins/index.d.ts +3 -0
  125. package/dist/plugins/index.d.ts.map +1 -0
  126. package/dist/plugins/index.js +5 -0
  127. package/dist/plugins/softDelete/applySoftDelete.d.ts +5 -0
  128. package/dist/plugins/softDelete/applySoftDelete.d.ts.map +1 -0
  129. package/dist/plugins/softDelete/applySoftDelete.js +139 -0
  130. package/dist/plugins/softDelete/types.d.ts +14 -0
  131. package/dist/plugins/softDelete/types.d.ts.map +1 -0
  132. package/dist/plugins/softDelete/types.js +2 -0
  133. package/dist/redis-manager/index.d.ts +2 -0
  134. package/dist/redis-manager/index.d.ts.map +1 -0
  135. package/dist/redis-manager/index.js +4 -0
  136. package/dist/redis-manager/redisClient.d.ts +32 -0
  137. package/dist/redis-manager/redisClient.d.ts.map +1 -0
  138. package/dist/redis-manager/redisClient.js +146 -0
  139. package/dist/tanancy/MultiTenantManager.d.ts +98 -0
  140. package/dist/tanancy/MultiTenantManager.d.ts.map +1 -0
  141. package/dist/tanancy/MultiTenantManager.js +190 -0
  142. package/dist/tanancy/TenantContext.d.ts +31 -0
  143. package/dist/tanancy/TenantContext.d.ts.map +1 -0
  144. package/dist/tanancy/TenantContext.js +59 -0
  145. package/dist/tanancy/TenantModelResolver.d.ts +10 -0
  146. package/dist/tanancy/TenantModelResolver.d.ts.map +1 -0
  147. package/dist/tanancy/TenantModelResolver.js +114 -0
  148. package/dist/tanancy/index.d.ts +5 -0
  149. package/dist/tanancy/index.d.ts.map +1 -0
  150. package/dist/tanancy/index.js +7 -0
  151. package/dist/tanancy/init/initMultiTenancy.d.ts +29 -0
  152. package/dist/tanancy/init/initMultiTenancy.d.ts.map +1 -0
  153. package/dist/tanancy/init/initMultiTenancy.js +62 -0
  154. package/dist/templates/generateDefaultConfigContent.d.ts +10 -0
  155. package/dist/templates/generateDefaultConfigContent.d.ts.map +1 -0
  156. package/dist/templates/generateDefaultConfigContent.js +108 -0
  157. package/dist/templates/generateGCManagerFile.d.ts +2 -0
  158. package/dist/templates/generateGCManagerFile.d.ts.map +1 -0
  159. package/dist/templates/generateGCManagerFile.js +39 -0
  160. package/dist/templates/generateGCRunnerFile.d.ts +2 -0
  161. package/dist/templates/generateGCRunnerFile.d.ts.map +1 -0
  162. package/dist/templates/generateGCRunnerFile.js +25 -0
  163. package/dist/templates/generateMainEntry.d.ts +3 -0
  164. package/dist/templates/generateMainEntry.d.ts.map +1 -0
  165. package/dist/templates/generateMainEntry.js +24 -0
  166. package/dist/templates/index.d.ts +6 -0
  167. package/dist/templates/index.d.ts.map +1 -0
  168. package/dist/templates/index.js +8 -0
  169. package/dist/templates/scaffold/structureGenerator.d.ts +4 -0
  170. package/dist/templates/scaffold/structureGenerator.d.ts.map +1 -0
  171. package/dist/templates/scaffold/structureGenerator.js +193 -0
  172. package/dist/types/GCConfig.d.ts +7 -0
  173. package/dist/types/GCConfig.d.ts.map +1 -0
  174. package/dist/types/GCConfig.js +2 -0
  175. package/dist/types/ambiten-runtime-type.d.ts +24 -0
  176. package/dist/types/ambiten-runtime-type.d.ts.map +1 -0
  177. package/dist/types/ambiten-runtime-type.js +2 -0
  178. package/dist/types/ambiten.client.type.d.ts +136 -0
  179. package/dist/types/ambiten.client.type.d.ts.map +1 -0
  180. package/dist/types/ambiten.client.type.js +3 -0
  181. package/dist/types/ambiten.model.type.d.ts +135 -0
  182. package/dist/types/ambiten.model.type.d.ts.map +1 -0
  183. package/dist/types/ambiten.model.type.js +4 -0
  184. package/dist/types/ambitenConfig.d.ts +103 -0
  185. package/dist/types/ambitenConfig.d.ts.map +1 -0
  186. package/dist/types/ambitenConfig.js +3 -0
  187. package/dist/types/bootstrapClient.type.d.ts +11 -0
  188. package/dist/types/bootstrapClient.type.d.ts.map +1 -0
  189. package/dist/types/bootstrapClient.type.js +2 -0
  190. package/dist/types/db.provider.d.ts +66 -0
  191. package/dist/types/db.provider.d.ts.map +1 -0
  192. package/dist/types/db.provider.js +2 -0
  193. package/dist/types/document.d.ts +7 -0
  194. package/dist/types/document.d.ts.map +1 -0
  195. package/dist/types/document.js +2 -0
  196. package/dist/types/event.type.d.ts +6 -0
  197. package/dist/types/event.type.d.ts.map +1 -0
  198. package/dist/types/event.type.js +27 -0
  199. package/dist/types/graphql.type.d.ts +22 -0
  200. package/dist/types/graphql.type.d.ts.map +1 -0
  201. package/dist/types/graphql.type.js +2 -0
  202. package/dist/types/index.d.ts +15 -0
  203. package/dist/types/index.d.ts.map +1 -0
  204. package/dist/types/index.js +17 -0
  205. package/dist/types/logger.types.d.ts +15 -0
  206. package/dist/types/logger.types.d.ts.map +1 -0
  207. package/dist/types/logger.types.js +3 -0
  208. package/dist/types/middleware/types.d.ts +28 -0
  209. package/dist/types/middleware/types.d.ts.map +1 -0
  210. package/dist/types/middleware/types.js +2 -0
  211. package/dist/types/result.utils.types.d.ts +7 -0
  212. package/dist/types/result.utils.types.d.ts.map +1 -0
  213. package/dist/types/result.utils.types.js +2 -0
  214. package/dist/types/schema.type.d.ts +23 -0
  215. package/dist/types/schema.type.d.ts.map +1 -0
  216. package/dist/types/schema.type.js +10 -0
  217. package/dist/types/user.type.d.ts +11 -0
  218. package/dist/types/user.type.d.ts.map +1 -0
  219. package/dist/types/user.type.js +2 -0
  220. package/dist/utils/AuthUtils.d.ts +15 -0
  221. package/dist/utils/AuthUtils.d.ts.map +1 -0
  222. package/dist/utils/AuthUtils.js +26 -0
  223. package/dist/utils/ModelRegistry.d.ts +15 -0
  224. package/dist/utils/ModelRegistry.d.ts.map +1 -0
  225. package/dist/utils/ModelRegistry.js +35 -0
  226. package/dist/utils/banner.d.ts +2 -0
  227. package/dist/utils/banner.d.ts.map +1 -0
  228. package/dist/utils/banner.js +20 -0
  229. package/dist/utils/builders/createModel.d.ts +37 -0
  230. package/dist/utils/builders/createModel.d.ts.map +1 -0
  231. package/dist/utils/builders/createModel.js +38 -0
  232. package/dist/utils/builders/getTenantDb.d.ts +12 -0
  233. package/dist/utils/builders/getTenantDb.d.ts.map +1 -0
  234. package/dist/utils/builders/getTenantDb.js +25 -0
  235. package/dist/utils/builders/index.d.ts +4 -0
  236. package/dist/utils/builders/index.d.ts.map +1 -0
  237. package/dist/utils/builders/index.js +6 -0
  238. package/dist/utils/builders/schema.d.ts +22 -0
  239. package/dist/utils/builders/schema.d.ts.map +1 -0
  240. package/dist/utils/builders/schema.js +26 -0
  241. package/dist/utils/cacheWithRedis.d.ts +27 -0
  242. package/dist/utils/cacheWithRedis.d.ts.map +1 -0
  243. package/dist/utils/cacheWithRedis.js +22 -0
  244. package/dist/utils/castId.d.ts +5 -0
  245. package/dist/utils/castId.d.ts.map +1 -0
  246. package/dist/utils/castId.js +52 -0
  247. package/dist/utils/color-palatte.d.ts +4 -0
  248. package/dist/utils/color-palatte.d.ts.map +1 -0
  249. package/dist/utils/color-palatte.js +24 -0
  250. package/dist/utils/configureAmbitenContext.d.ts +13 -0
  251. package/dist/utils/configureAmbitenContext.d.ts.map +1 -0
  252. package/dist/utils/configureAmbitenContext.js +35 -0
  253. package/dist/utils/detect-package-manager.d.ts +5 -0
  254. package/dist/utils/detect-package-manager.d.ts.map +1 -0
  255. package/dist/utils/detect-package-manager.js +59 -0
  256. package/dist/utils/ensureModelNameSafe.d.ts +12 -0
  257. package/dist/utils/ensureModelNameSafe.d.ts.map +1 -0
  258. package/dist/utils/ensureModelNameSafe.js +28 -0
  259. package/dist/utils/ensureRedis.d.ts +7 -0
  260. package/dist/utils/ensureRedis.d.ts.map +1 -0
  261. package/dist/utils/ensureRedis.js +40 -0
  262. package/dist/utils/error/ambitenError-handler.d.ts +24 -0
  263. package/dist/utils/error/ambitenError-handler.d.ts.map +1 -0
  264. package/dist/utils/error/ambitenError-handler.js +39 -0
  265. package/dist/utils/error/errorTypes.d.ts +27 -0
  266. package/dist/utils/error/errorTypes.d.ts.map +1 -0
  267. package/dist/utils/error/errorTypes.js +30 -0
  268. package/dist/utils/error/index.d.ts +3 -0
  269. package/dist/utils/error/index.d.ts.map +1 -0
  270. package/dist/utils/error/index.js +5 -0
  271. package/dist/utils/eventOptions.d.ts +38 -0
  272. package/dist/utils/eventOptions.d.ts.map +1 -0
  273. package/dist/utils/eventOptions.js +130 -0
  274. package/dist/utils/events.d.ts +5 -0
  275. package/dist/utils/events.d.ts.map +1 -0
  276. package/dist/utils/events.js +7 -0
  277. package/dist/utils/index.d.ts +23 -0
  278. package/dist/utils/index.d.ts.map +1 -0
  279. package/dist/utils/index.js +25 -0
  280. package/dist/utils/invalidateTenantCache.d.ts +18 -0
  281. package/dist/utils/invalidateTenantCache.d.ts.map +1 -0
  282. package/dist/utils/invalidateTenantCache.js +27 -0
  283. package/dist/utils/logger.d.ts +3 -0
  284. package/dist/utils/logger.d.ts.map +1 -0
  285. package/dist/utils/logger.js +27 -0
  286. package/dist/utils/modelLoader.d.ts +3 -0
  287. package/dist/utils/modelLoader.d.ts.map +1 -0
  288. package/dist/utils/modelLoader.js +41 -0
  289. package/dist/utils/resolveAmbitenOption.d.ts +2 -0
  290. package/dist/utils/resolveAmbitenOption.d.ts.map +1 -0
  291. package/dist/utils/resolveAmbitenOption.js +10 -0
  292. package/dist/utils/resolveRuntimeConfig.d.ts +22 -0
  293. package/dist/utils/resolveRuntimeConfig.d.ts.map +1 -0
  294. package/dist/utils/resolveRuntimeConfig.js +33 -0
  295. package/dist/utils/scaffoldLoger.d.ts +11 -0
  296. package/dist/utils/scaffoldLoger.d.ts.map +1 -0
  297. package/dist/utils/scaffoldLoger.js +68 -0
  298. package/dist/utils/symbols.d.ts +4 -0
  299. package/dist/utils/symbols.d.ts.map +1 -0
  300. package/dist/utils/symbols.js +6 -0
  301. package/dist/utils/time.d.ts +5 -0
  302. package/dist/utils/time.d.ts.map +1 -0
  303. package/dist/utils/time.js +39 -0
  304. package/package.json +180 -0
@@ -0,0 +1,979 @@
1
+ import 'dotenv/config';
2
+ import { Filter, OptionalUnlessRequiredId, UpdateFilter, AggregateOptions, ClientSession, AnyBulkWriteOperation, ChangeStreamDocument, ChangeStream, BulkWriteOptions, BulkWriteResult } from 'mongodb';
3
+ import type { User, Document, AmbitenModelOptions, EventType, ModelContext, ModelResult, ModelResultArray, AmbitenMiddlewareOperation, AmbitenMiddlewareHandler, QueryOptions, AmbitenCacheStats } from '../types';
4
+ import { AmbitenSchema } from './ambitenSchema';
5
+ /**
6
+ * A MongoDB-backed model with schema validation, middleware, multi-tenancy,
7
+ * transactions, caching, soft-delete support, and query instrumentation.
8
+ *
9
+ * @typeParam T - The MongoDB document shape handled by this model.
10
+ */
11
+ export declare class AmbitenModel<T extends Document> {
12
+ private _provider;
13
+ private _collectionName;
14
+ private _collectionOverride?;
15
+ private _schema;
16
+ private _initialized;
17
+ private _defaultCtx?;
18
+ private readonly _modelGCConfig?;
19
+ private readonly _gcConfig?;
20
+ private _gcTimer?;
21
+ private eventEmitter;
22
+ private beforeMiddlewares;
23
+ private afterMiddlewares;
24
+ private _softDeleteConfig?;
25
+ /**
26
+ * Creates a new model instance.
27
+ *
28
+ * @param options - Model configuration including collection, schema, provider,
29
+ * default context, and optional GC configuration.
30
+ */
31
+ constructor(options: AmbitenModelOptions<T>);
32
+ /**
33
+ * Merges an explicit operation context with the model default context and the
34
+ * current runtime context.
35
+ *
36
+ * @param ctx - Optional operation context.
37
+ * @returns A merged context or `undefined` when no context values are present.
38
+ */
39
+ private mergeCtx;
40
+ /**
41
+ * Ensures a runtime Ambiten context exists before executing an instrumented action.
42
+ *
43
+ * This allows model methods to remain safe when invoked outside adapter-managed
44
+ * request lifecycles while still preserving tenant-aware instrumentation.
45
+ *
46
+ * @param ctx - Optional model context.
47
+ * @param action - The action to execute inside a runtime context.
48
+ * @returns The action result.
49
+ */
50
+ private runWithModelContext;
51
+ private isGCEnabled;
52
+ private resolveSchemaGCConfig;
53
+ /**
54
+ * Resolves the MongoDB collection for the current model and context.
55
+ *
56
+ * @param ctx - Optional model context.
57
+ * @returns The resolved MongoDB collection.
58
+ */
59
+ private getCollection;
60
+ /**
61
+ * Resolves a registered tenant configuration.
62
+ *
63
+ * @param tenantId - The tenant identifier.
64
+ * @returns The tenant configuration.
65
+ */
66
+ private getResolvedTenant;
67
+ /**
68
+ * Resolves the MongoDB database for the current operation.
69
+ *
70
+ * @param ctx - Optional model context.
71
+ * @returns The resolved MongoDB database instance.
72
+ */
73
+ private resolveDb;
74
+ /**
75
+ * Resolves the collection name for the current operation.
76
+ *
77
+ * @param ctx - Optional model context.
78
+ * @returns The collection name.
79
+ */
80
+ private resolveCollectionName;
81
+ /**
82
+ * Resolves the client session for the current operation.
83
+ *
84
+ * @param ctx - Optional model context.
85
+ * @returns The MongoDB client session if available.
86
+ */
87
+ private resolveSession;
88
+ /**
89
+ * Resolves the MongoDB client session to use for an operation.
90
+ *
91
+ * Precedence order:
92
+ * 1. Explicit externally supplied session
93
+ * 2. Per-call model context session
94
+ * 3. Active runtime session from AmbitenContext
95
+ *
96
+ * This ensures explicit caller intent always overrides implicit runtime state.
97
+ *
98
+ * @param ctx - Optional model execution context.
99
+ * @param externalSession - Optional explicit session supplied by the caller.
100
+ * @returns The resolved MongoDB client session, or `undefined` when no session is available.
101
+ */
102
+ private resolveSessionStrict;
103
+ /**
104
+ * Subscribes to a model event.
105
+ *
106
+ * @param event - Event type.
107
+ * @param listener - Event listener callback.
108
+ */
109
+ on(event: EventType, listener: (...args: any[]) => void): void;
110
+ /**
111
+ * Subscribes to a model event once.
112
+ *
113
+ * @param event - Event type.
114
+ * @param listener - Event listener callback.
115
+ */
116
+ once(event: EventType, listener: (...args: any[]) => void): void;
117
+ /**
118
+ * Removes a subscribed event listener.
119
+ *
120
+ * @param event - Event type.
121
+ * @param listener - Event listener callback.
122
+ */
123
+ off(event: EventType, listener: (...args: any[]) => void): void;
124
+ /**
125
+ * Removes a specific event listener.
126
+ *
127
+ * @param event - Event type.
128
+ * @param listener - Event listener callback.
129
+ */
130
+ removeListener(event: EventType, listener: (...args: any[]) => void): void;
131
+ /**
132
+ * Ensures the model has the minimum configuration required to operate.
133
+ */
134
+ private ensureConfigured;
135
+ /**
136
+ * Initializes the model by validating configuration, resolving the collection,
137
+ * and creating the GC TTL index when enabled.
138
+ */
139
+ init(): Promise<void>;
140
+ /**
141
+ * Returns a model instance bound to a default context.
142
+ *
143
+ * @param ctx - Context to bind to the cloned model.
144
+ * @returns A cloned model instance with merged default context.
145
+ */
146
+ bind(ctx: ModelContext): AmbitenModel<T>;
147
+ /**
148
+ * Registers or reconfigures the model.
149
+ *
150
+ * @param options - Model registration options.
151
+ */
152
+ registerModel(options: AmbitenModelOptions<T>): Promise<void>;
153
+ /**
154
+ * Ensures the TTL index used by the garbage collector exists.
155
+ *
156
+ * @param gc - GC configuration.
157
+ */
158
+ private ensureGCIndex;
159
+ /**
160
+ * Returns the schema attached to this model.
161
+ */
162
+ get schema(): AmbitenSchema<T>;
163
+ /**
164
+ * Returns the schema attached to this model.
165
+ */
166
+ getSchema(): AmbitenSchema<T>;
167
+ /**
168
+ * Validates a document against the model schema.
169
+ * Throws an error if validation fails.
170
+ * @param doc - Document to validate.
171
+ */
172
+ private validate;
173
+ /**
174
+ * Validates a document asynchronously against the model schema.
175
+ * Useful for schemas that perform async validation, such as checking uniqueness
176
+ * @param doc - Document to validate.
177
+ * @returns The validated document.
178
+ */
179
+ validateAsync(doc: OptionalUnlessRequiredId<T>): Promise<T>;
180
+ /**
181
+ * Initializes internal schema middleware for relationships, aggregation, and
182
+ * change notifications. This is called during model initialization and ensures that all registered
183
+ * middleware is set up before any operations are performed.
184
+ */
185
+ private initMiddleware;
186
+ /**
187
+ * Creates a new document in the model collection.
188
+ *
189
+ * This operation runs inside the active Ambiten runtime context, is instrumented
190
+ * through {@link measureQuery}, executes registered create middlewares,
191
+ * validates the incoming document against the model schema, triggers schema
192
+ * create hooks, invalidates relevant cache patterns, and publishes a database
193
+ * change event after successful insertion.
194
+ *
195
+ * @param doc - The document to insert.
196
+ * @param ctx - Optional model execution context for tenant, database,
197
+ * collection, session, and related runtime overrides.
198
+ * @returns The created document as a normalized model result.
199
+ * @throws {Error} When the provided document is missing or invalid.
200
+ */
201
+ create(doc: OptionalUnlessRequiredId<T>, ctx?: ModelContext): Promise<ModelResult<T>>;
202
+ /**
203
+ * Finds documents matching the provided filter.
204
+ *
205
+ * This operation runs inside the active Ambiten runtime context, is instrumented
206
+ * through {@link measureQuery}, executes registered find middlewares, supports
207
+ * optional result caching, triggers schema find hooks, and returns normalized
208
+ * model results.
209
+ *
210
+ * @param filter - MongoDB filter used to match documents.
211
+ * @param ctx - Optional model execution context for tenant, database,
212
+ * collection, session, and related runtime overrides.
213
+ * @param options - Optional query-level features such as caching.
214
+ * @returns An array of normalized model results.
215
+ * @throws {Error} When the filter is invalid.
216
+ */
217
+ find(filter?: Filter<T>, ctx?: ModelContext, options?: QueryOptions): Promise<ModelResultArray<T>>;
218
+ /**
219
+ * Finds a single document matching the provided filter.
220
+ *
221
+ * This operation runs inside the active Ambiten runtime context, is instrumented
222
+ * through {@link measureQuery}, executes registered findOne middlewares,
223
+ * supports optional result caching, triggers schema find hooks, and returns a
224
+ * normalized model result when a document is found.
225
+ *
226
+ * @param filter - MongoDB filter used to match the document.
227
+ * @param ctx - Optional model execution context for tenant, database,
228
+ * collection, session, and related runtime overrides.
229
+ * @param options - Optional query-level features such as caching.
230
+ * @returns The matched document as a normalized model result, or `null` if no document matched.
231
+ * @throws {Error} When the filter is missing or invalid.
232
+ */
233
+ findOne(filter: Filter<T>, ctx?: ModelContext, options?: QueryOptions): Promise<ModelResult<T> | null>;
234
+ /**
235
+ * Updates a single document matching the provided filter.
236
+ *
237
+ * This operation runs inside the active Ambiten runtime context, is instrumented
238
+ * through {@link measureQuery}, executes registered update middlewares,
239
+ * triggers schema update hooks, invalidates relevant cache patterns, and
240
+ * publishes a database change event after completion.
241
+ *
242
+ * @param filter - MongoDB filter used to identify the document to update.
243
+ * @param update - MongoDB update document to apply.
244
+ * @param ctx - Optional model execution context for tenant, database,
245
+ * collection, session, and related runtime overrides.
246
+ * @returns A promise that resolves when the operation completes.
247
+ * @throws {Error} When the filter is missing or invalid.
248
+ * @throws {Error} When the update document is missing or invalid.
249
+ */
250
+ updateOne(filter: Filter<T>, update: UpdateFilter<T>, ctx?: ModelContext): Promise<void>;
251
+ /**
252
+ * Inserts multiple documents into the model collection.
253
+ *
254
+ * This operation runs inside the active Ambiten runtime context, is instrumented
255
+ * through {@link measureQuery}, executes registered bulkInsert middlewares,
256
+ * validates each incoming document against the model schema, triggers schema
257
+ * bulk insert hooks, invalidates relevant cache patterns, and publishes a
258
+ * database change event after successful insertion.
259
+ *
260
+ * @param docs - The documents to insert.
261
+ * @param ctx - Optional model execution context for tenant, database,
262
+ * collection, session, and related runtime overrides.
263
+ * @returns A promise that resolves when the operation completes.
264
+ */
265
+ bulkInsert(docs: OptionalUnlessRequiredId<T>[], ctx?: ModelContext): Promise<void>;
266
+ /**
267
+ * Updates multiple documents using MongoDB bulk write semantics.
268
+ *
269
+ * This operation runs inside the active Ambiten runtime context, is instrumented
270
+ * through {@link measureQuery}, executes registered bulkUpdate middlewares,
271
+ * triggers schema bulk update hooks, invalidates relevant cache patterns, and
272
+ * publishes a database change event after completion.
273
+ *
274
+ * Each update entry is translated into an `updateOne` bulk operation using
275
+ * `$set` with the provided partial update document.
276
+ *
277
+ * @param updates - Array of filter/update pairs to execute as bulk updates.
278
+ * @param ctx - Optional model execution context for tenant, database,
279
+ * collection, session, and related runtime overrides.
280
+ * @returns A promise that resolves when the operation completes.
281
+ * @throws {Error} When the updates payload is invalid.
282
+ */
283
+ bulkUpdate(updates: {
284
+ filter: Partial<T>;
285
+ update: Partial<T>;
286
+ }[], ctx?: ModelContext): Promise<void>;
287
+ /**
288
+ * Deletes a single document matching the provided filter.
289
+ *
290
+ * This operation runs inside the active Ambiten runtime context, is instrumented
291
+ * through {@link measureQuery}, executes registered delete middlewares,
292
+ * supports middleware-driven soft delete flows, triggers schema delete or
293
+ * update hooks as appropriate, invalidates relevant cache patterns, and
294
+ * publishes a database change event after completion.
295
+ *
296
+ * When middleware metadata enables soft delete, the matched document is updated
297
+ * instead of being physically removed from the collection.
298
+ *
299
+ * @param filter - MongoDB filter used to identify the document to delete.
300
+ * @param ctx - Optional model execution context for tenant, database,
301
+ * collection, session, and related runtime overrides.
302
+ * @returns A promise that resolves when the operation completes.
303
+ * @throws {Error} When the filter is missing or invalid.
304
+ * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.
305
+ */
306
+ deleteOne(filter: Filter<T>, ctx?: ModelContext): Promise<void>;
307
+ /**
308
+ * Deletes multiple documents matching the provided filter.
309
+ *
310
+ * This operation runs inside the active Ambiten runtime context, is instrumented
311
+ * through {@link measureQuery}, executes registered deleteMany middlewares,
312
+ * supports middleware-driven soft delete flows, triggers schema delete or
313
+ * update hooks as appropriate, invalidates relevant cache patterns, and
314
+ * publishes a database change event after completion.
315
+ *
316
+ * When middleware metadata enables soft delete, matched documents are updated
317
+ * instead of being physically removed from the collection.
318
+ *
319
+ * @param filter - MongoDB filter used to identify the documents to delete.
320
+ * @param ctx - Optional model execution context for tenant, database,
321
+ * collection, session, and related runtime overrides.
322
+ * @returns A promise that resolves when the operation completes.
323
+ * @throws {Error} When the filter is missing or invalid.
324
+ * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.
325
+ */
326
+ deleteMany(filter: Filter<T>, ctx?: ModelContext): Promise<void>;
327
+ /**
328
+ * Populates a single reference field on a document by resolving the related
329
+ * document from another model.
330
+ *
331
+ * This helper performs a follow-up lookup using the referenced field value as
332
+ * the `_id` of the related document. If the target field is empty or
333
+ * undefined, the original document is returned unchanged.
334
+ *
335
+ * @typeParam K - The related model document type.
336
+ * @param doc - The source document containing the reference field.
337
+ * @param field - The field on the source document that stores the related document identifier.
338
+ * @param relatedModel - The model used to resolve the related document.
339
+ * @returns The source document with the populated field replaced by the related
340
+ * document result, or `null` when the input document is invalid.
341
+ */
342
+ populateOne<K extends Document>(doc: T, field: keyof T, relatedModel: AmbitenModel<K>): Promise<(T & Record<string, unknown>) | null>;
343
+ /**
344
+ * Populates an array reference field on a document by resolving the related
345
+ * documents from another model.
346
+ *
347
+ * This helper performs a follow-up lookup using the referenced field values as
348
+ * `_id` values of the related documents. If the target field is empty,
349
+ * undefined, or not an array, the original document is returned unchanged.
350
+ *
351
+ * @typeParam K - The related model document type.
352
+ * @param doc - The source document containing the reference array field.
353
+ * @param field - The field on the source document that stores related document identifiers.
354
+ * @param relatedModel - The model used to resolve the related documents.
355
+ * @returns The source document with the populated field replaced by the related
356
+ * document results, or `null` when the input document is invalid.
357
+ */
358
+ populateMany<K extends Document>(doc: T, field: keyof T, relatedModel: AmbitenModel<K>): Promise<(T & Record<string, unknown>) | null>;
359
+ /**
360
+ * Creates a new document inside a transaction-aware runtime context.
361
+ *
362
+ * This transactional variant runs within the active Ambiten runtime context,
363
+ * executes registered create middlewares, validates the incoming document,
364
+ * triggers schema create hooks with transactional metadata, invalidates
365
+ * relevant cache patterns, and publishes a database change event after
366
+ * successful insertion.
367
+ *
368
+ * @param doc - The document to insert.
369
+ * @param ctx - Optional model execution context for tenant, database,
370
+ * collection, session, and transaction-aware runtime overrides.
371
+ * @returns The created document as a normalized model result.
372
+ * @throws {Error} When the provided document is missing or invalid.
373
+ */
374
+ createWithTransaction(doc: OptionalUnlessRequiredId<T>, ctx?: ModelContext): Promise<ModelResult<T>>;
375
+ /**
376
+ * Executes multiple MongoDB bulk write operations inside a transaction-aware
377
+ * runtime context.
378
+ *
379
+ * This transactional variant runs within the active Ambiten runtime context,
380
+ * executes registered bulk update middlewares, triggers schema bulk update
381
+ * hooks with transactional metadata, invalidates relevant cache patterns, and
382
+ * publishes a database change event after completion.
383
+ *
384
+ * @param operations - MongoDB bulk write operations to execute.
385
+ * @param options - Optional MongoDB bulk write options.
386
+ * @param ctx - Optional model execution context for tenant, database,
387
+ * collection, session, and transaction-aware runtime overrides.
388
+ * @returns The MongoDB bulk write result.
389
+ * @throws {Error} When the operations payload is missing or invalid.
390
+ */
391
+ bulkWriteWithTransaction(operations: AnyBulkWriteOperation<T>[], options?: BulkWriteOptions, ctx?: ModelContext): Promise<BulkWriteResult>;
392
+ /**
393
+ * Deletes a single document inside a transaction-aware runtime context.
394
+ *
395
+ * This transactional variant runs within the active Ambiten runtime context,
396
+ * executes registered delete middlewares, triggers schema delete hooks with
397
+ * transactional metadata, invalidates relevant cache patterns, and publishes a
398
+ * database change event after completion.
399
+ *
400
+ * @param filter - MongoDB filter used to identify the document to delete.
401
+ * @param ctx - Optional model execution context for tenant, database,
402
+ * collection, session, and transaction-aware runtime overrides.
403
+ * @returns `true` when a document was deleted, otherwise `false`.
404
+ * @throws {Error} When the filter is missing or invalid.
405
+ */
406
+ deleteWithTransaction(filter: Filter<T>, ctx?: ModelContext): Promise<boolean>;
407
+ /**
408
+ * Updates a single document inside a transaction-aware runtime context.
409
+ *
410
+ * This transactional variant runs within the active Ambiten runtime context,
411
+ * executes registered update middlewares, validates the projected updated
412
+ * document, triggers schema update hooks with transactional metadata,
413
+ * invalidates relevant cache patterns, and publishes a database change event
414
+ * after completion.
415
+ *
416
+ * @param filter - MongoDB filter used to identify the document to update.
417
+ * @param update - MongoDB update document to apply.
418
+ * @param ctx - Optional model execution context for tenant, database,
419
+ * collection, session, and transaction-aware runtime overrides.
420
+ * @returns The updated document as a normalized model result, or `null` if no
421
+ * document matched the filter.
422
+ * @throws {Error} When the filter is missing or invalid.
423
+ * @throws {Error} When the update document is missing or invalid.
424
+ */
425
+ updateWithTransaction(filter: Filter<T>, update: UpdateFilter<T>, ctx?: ModelContext): Promise<ModelResult<T> | null>;
426
+ /**
427
+ * Finds a single document matching the provided filter and updates it.
428
+ *
429
+ * This operation runs inside the active Ambiten runtime context, is instrumented
430
+ * through {@link measureQuery}, executes registered findOneAndUpdate
431
+ * middlewares, triggers schema update hooks, invalidates relevant cache
432
+ * patterns, and publishes a database change event after completion.
433
+ *
434
+ * The updated document is returned in its post-update state when a matching
435
+ * document is found.
436
+ *
437
+ * @param filter - MongoDB filter used to identify the document to update.
438
+ * @param update - MongoDB update document to apply.
439
+ * @param ctx - Optional model execution context for tenant, database,
440
+ * collection, session, and related runtime overrides.
441
+ * @returns The updated document as a normalized model result, or `null` if no
442
+ * document matched the filter.
443
+ * @throws {Error} When the filter is missing or invalid.
444
+ * @throws {Error} When the update document is missing or invalid.
445
+ */
446
+ findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, ctx?: ModelContext): Promise<ModelResult<T> | null>;
447
+ /**
448
+ * Finds a single document matching the provided filter and deletes it.
449
+ *
450
+ * Supports both hard delete and middleware-driven soft delete flows.
451
+ * When soft delete is enabled via middleware metadata, the matched document
452
+ * is updated using the provided soft-delete update operation instead of being
453
+ * physically removed from the collection.
454
+ *
455
+ * The operation:
456
+ * - runs within the active Ambiten runtime context
457
+ * - is instrumented through {@link measureQuery}
458
+ * - executes registered before/after model middlewares
459
+ * - triggers schema delete/update hooks as appropriate
460
+ * - invalidates relevant cache patterns after mutation
461
+ * - publishes a database change event through PubSub
462
+ *
463
+ * @param filter - MongoDB filter used to identify the document to delete.
464
+ * @param ctx - Optional model execution context for tenant, database,
465
+ * session, cache, and collection overrides.
466
+ * @returns The deleted document as a model result, or `null` if no document matched.
467
+ * @throws {Error} When the filter is missing or invalid.
468
+ */
469
+ findOneAndDelete(filter: Filter<T>, ctx?: ModelContext): Promise<ModelResult<T> | null>;
470
+ /**
471
+ * Finds a single document matching the provided filter and replaces it with the
472
+ * supplied replacement document.
473
+ *
474
+ * This operation runs inside the active Ambiten runtime context, executes model
475
+ * middlewares, triggers schema update hooks, invalidates relevant cache entries,
476
+ * and publishes a database change event after a successful replacement.
477
+ *
478
+ * The replacement document is fully validated before being persisted.
479
+ *
480
+ * @param filter - MongoDB filter used to identify the document to replace.
481
+ * @param replacement - The full replacement document that will overwrite the matched document.
482
+ * @param ctx - Optional model execution context for tenant, database,
483
+ * collection, session, and related runtime overrides.
484
+ * @returns The replaced document in its updated form, or `null` if no document matched the filter.
485
+ * @throws {Error} When the filter is missing or invalid.
486
+ * @throws {Error} When the replacement document fails validation.
487
+ */
488
+ findOneAndReplace(filter: Filter<T>, replacement: T, ctx?: ModelContext): Promise<ModelResult<T> | null>;
489
+ /**
490
+ * Finds a single document matching the provided filter and updates it. If no
491
+ * matching document exists, a new one is inserted using MongoDB upsert
492
+ * semantics.
493
+ *
494
+ * This operation runs within the active Ambiten runtime context, is instrumented
495
+ * through {@link measureQuery}, executes registered model middlewares, triggers
496
+ * schema update hooks, invalidates relevant cache patterns, and publishes a
497
+ * database change event after completion.
498
+ *
499
+ * @param filter - MongoDB filter used to identify the document to update or insert.
500
+ * @param update - MongoDB update document applied to the matched document or to the inserted document during upsert.
501
+ * @param ctx - Optional model execution context for tenant, database,
502
+ * collection, session, and related runtime overrides.
503
+ * @returns The updated or newly upserted document in its final state, or `null`
504
+ * if no document could be resolved from the operation result.
505
+ * @throws {Error} When the filter is missing or invalid.
506
+ * @throws {Error} When the update document is missing or invalid.
507
+ */
508
+ findOneAndUpsert(filter: Filter<T>, update: UpdateFilter<T>, ctx?: ModelContext): Promise<ModelResult<T> | null>;
509
+ /**
510
+ * Finds a single document matching the provided filter and updates it inside a
511
+ * transaction. If no document matches, a new one is inserted using MongoDB
512
+ * upsert semantics.
513
+ *
514
+ * This transactional variant runs inside the active Ambiten runtime context,
515
+ * executes registered model middlewares, triggers schema update hooks with
516
+ * transactional metadata, invalidates relevant cache patterns, and publishes a
517
+ * database change event after completion.
518
+ *
519
+ * @param filter - MongoDB filter used to identify the document to update or insert.
520
+ * @param update - MongoDB update document applied to the matched document or inserted document.
521
+ * @param ctx - Optional model execution context for tenant, database,
522
+ * collection, session, and transaction-aware runtime overrides.
523
+ * @returns The updated or newly inserted document in its final state, or `null`
524
+ * if no document could be resolved from the operation result.
525
+ * @throws {Error} When the filter is missing or invalid.
526
+ * @throws {Error} When the update document is missing or invalid.
527
+ */
528
+ findOneAndUpsertWithTransaction(filter: Filter<T>, update: UpdateFilter<T>, ctx?: ModelContext): Promise<ModelResult<T> | null>;
529
+ /**
530
+ * Finds a single document matching the provided filter and updates it inside a
531
+ * secure transaction. If no document matches, a new one is inserted using
532
+ * MongoDB upsert semantics.
533
+ *
534
+ * This secure transactional variant enforces an admin-only authorization rule
535
+ * before performing the operation. It runs inside the active Ambiten runtime
536
+ * context, executes registered model middlewares, triggers schema update hooks
537
+ * with transactional and security metadata, invalidates relevant cache patterns,
538
+ * and publishes a database change event after completion.
539
+ *
540
+ * @param filter - MongoDB filter used to identify the document to update or insert.
541
+ * @param update - MongoDB update document applied to the matched document or inserted document.
542
+ * @param user - Authenticated user performing the operation. Must have the `admin` role.
543
+ * @param ctx - Optional model execution context for tenant, database,
544
+ * collection, session, and transaction-aware runtime overrides.
545
+ * @returns The updated or newly inserted document in its final state, or `null`
546
+ * if no document could be resolved from the operation result.
547
+ * @throws {Error} When the user is not authorized to perform the operation.
548
+ * @throws {Error} When the filter is missing or invalid.
549
+ * @throws {Error} When the update document is missing or invalid.
550
+ */
551
+ findOneAndUpsertWithTransactionSecure(filter: Filter<T>, update: UpdateFilter<T>, user: User, ctx?: ModelContext): Promise<ModelResult<T> | null>;
552
+ /**
553
+ * Deletes a single document matching the provided filter using an admin-only
554
+ * secure operation.
555
+ *
556
+ * This method enforces authorization before executing the delete flow. It runs
557
+ * inside the active Ambiten runtime context, is instrumented through
558
+ * {@link measureQuery}, executes registered model middlewares, triggers schema
559
+ * delete hooks with security metadata, invalidates relevant cache patterns, and
560
+ * publishes a database change event after a successful deletion.
561
+ *
562
+ * @param filter - MongoDB filter used to identify the document to delete.
563
+ * @param user - Authenticated user performing the operation. Must have the `admin` role.
564
+ * @param ctx - Optional model execution context for tenant, database,
565
+ * collection, session, and related runtime overrides.
566
+ * @returns A promise that resolves when the operation completes.
567
+ * @throws {Error} When the user is not authorized to perform the operation.
568
+ * @throws {Error} When the filter is missing or invalid.
569
+ * @throws {Error} When the user payload is missing.
570
+ */
571
+ deleteSecure(filter: Filter<T>, user: User, ctx?: ModelContext): Promise<void>;
572
+ /**
573
+ * Executes an aggregation pipeline against the model collection.
574
+ *
575
+ * This operation runs inside the active Ambiten runtime context, is instrumented
576
+ * through {@link measureQuery}, executes registered aggregate middlewares,
577
+ * supports optional query-result caching, and publishes a database change event
578
+ * after execution.
579
+ *
580
+ * When caching is enabled through {@link QueryOptions}, the aggregation result
581
+ * is stored and reused using a tenant-aware cache key derived from the
582
+ * collection, pipeline, options, and runtime context.
583
+ *
584
+ * @typeParam U - The aggregation result document shape.
585
+ * @param pipeline - MongoDB aggregation pipeline stages.
586
+ * @param options - Optional MongoDB aggregation options.
587
+ * @param externalSession - Optional explicit client session to use for the aggregation.
588
+ * @param ctx - Optional model execution context for tenant, database,
589
+ * collection, session, and related runtime overrides.
590
+ * @param queryOptions - Optional query-level features such as caching.
591
+ * @returns The aggregation result array.
592
+ * @throws {Error} When the pipeline is missing or invalid.
593
+ */
594
+ aggregate<U extends Document>(pipeline: object[], options?: AggregateOptions, externalSession?: ClientSession, ctx?: ModelContext, queryOptions?: QueryOptions): Promise<U[]>;
595
+ /**
596
+ * Executes an aggregation pipeline inside a transaction-aware runtime context.
597
+ *
598
+ * This transactional variant runs within the active Ambiten runtime context,
599
+ * executes registered aggregate middlewares, triggers schema aggregate hooks,
600
+ * instruments the query through {@link measureQuery}, and publishes a database
601
+ * change event after execution.
602
+ *
603
+ * @typeParam U - The aggregation result document shape.
604
+ * @param pipeline - MongoDB aggregation pipeline stages.
605
+ * @param options - Optional MongoDB aggregation options.
606
+ * @param ctx - Optional model execution context for tenant, database,
607
+ * collection, session, and transaction-aware runtime overrides.
608
+ * @returns The aggregation result array.
609
+ * @throws {Error} When the pipeline is missing or invalid.
610
+ */
611
+ aggregateWithTransaction<U extends Document>(pipeline: object[], options?: AggregateOptions, ctx?: ModelContext): Promise<U[]>;
612
+ /**
613
+ * Executes the provided operation within a transaction-aware runtime context.
614
+ *
615
+ * Resolution order:
616
+ * 1. Reuse an existing session from the merged model context when available.
617
+ * 2. Start a provider-managed session when the active database provider
618
+ * exposes a session factory.
619
+ * 3. Fall back to {@link AmbitenContext.withTransaction} to resolve a client
620
+ * and execute the operation inside a transaction.
621
+ *
622
+ * When an existing session is supplied, the current transaction boundary is
623
+ * reused and no new transaction is started.
624
+ *
625
+ * @typeParam R - The operation result type.
626
+ * @param operation - Callback executed with the resolved MongoDB client session.
627
+ * @param ctx - Optional model execution context used to resolve tenant,
628
+ * database, collection, and session overrides.
629
+ * @returns The resolved operation result.
630
+ */
631
+ private withTransaction;
632
+ /**
633
+ * Executes the provided operation inside a transaction-aware Ambiten runtime context.
634
+ *
635
+ * This helper ensures the operation runs with a resolved MongoDB client session
636
+ * and within the active Ambiten runtime context for the current tenant,
637
+ * database, and collection. If a session already exists in the merged model
638
+ * context, that session is reused and no new transaction boundary is created.
639
+ *
640
+ * Use this method when multiple model operations must be executed atomically
641
+ * within a single transactional unit of work.
642
+ *
643
+ * @typeParam R - The operation result type.
644
+ * @param operation - Callback executed with the resolved MongoDB client session.
645
+ * @param ctx - Optional model execution context for tenant, database,
646
+ * collection, and session overrides.
647
+ * @returns The resolved result of the transactional operation.
648
+ */
649
+ runInTransaction<R>(operation: (session: ClientSession) => Promise<R>, ctx?: ModelContext): Promise<R>;
650
+ private getSession;
651
+ /**
652
+ * Creates a readable stream for an aggregation pipeline.
653
+ *
654
+ * This method runs inside the active Ambiten runtime context, is instrumented
655
+ * through {@link measureQuery}, executes registered aggregate middlewares,
656
+ * triggers schema aggregate hooks, and publishes a database change event after
657
+ * the aggregation stream is created.
658
+ *
659
+ * This method instruments stream creation only. It does not track the full
660
+ * lifecycle of stream consumption unless additional listeners are attached by
661
+ * the caller or by a higher-level observability layer.
662
+ *
663
+ * @typeParam U - The aggregation result document shape.
664
+ * @param pipeline - MongoDB aggregation pipeline stages.
665
+ * @param options - Optional MongoDB aggregation options.
666
+ * @param ctx - Optional model execution context for tenant, database,
667
+ * collection, session, and related runtime overrides.
668
+ * @returns A readable stream for the aggregation result set.
669
+ * @throws {Error} When the pipeline is missing or invalid.
670
+ */
671
+ streamAggregation<U extends Document>(pipeline: object[], options?: AggregateOptions, ctx?: ModelContext): Promise<import("stream").Readable & AsyncIterable<U>>;
672
+ /**
673
+ * Aggregates documents in the collection using a pipeline with caching.
674
+ * @param {object[]} pipeline - The aggregation pipeline.
675
+ * @param {string} cacheKey - The cache key.
676
+ * @param {number} [cacheDuration=300] - The cache duration in seconds.
677
+ * @returns {Promise<T[]>} The aggregation result as an array.
678
+ * @throws {Error} If the pipeline is not valid or the cache key is not a string.
679
+ */
680
+ aggregateWithCache(pipeline: object[], cacheKey: string, cacheDuration?: number): Promise<T[]>;
681
+ /**
682
+ * Cursor-based pagination using _id comparison instead of skip.
683
+ * @param filter - The filter for documents.
684
+ * @param pageSize - Number of documents per page.
685
+ * @param lastId - Last document _id from the previous page.
686
+ * @returns {Promise<T[]>} Array of documents for the current page.
687
+ * This method uses the _id field for pagination, which is more efficient than using skip.
688
+ *
689
+ */
690
+ paginatedFind(filter: Partial<T>, pageSize: number, lastId?: string): Promise<T[]>;
691
+ /**
692
+ * Opens a MongoDB change stream on the model collection and registers a change
693
+ * callback.
694
+ *
695
+ * This helper initializes the model, resolves the collection within the active
696
+ * Ambiten runtime context, creates a change stream, and subscribes the provided
697
+ * callback to `"change"` events.
698
+ *
699
+ * The method is intentionally lightweight: it manages change stream creation,
700
+ * but does not yet instrument the full lifecycle of emitted change events. That
701
+ * can be added later by higher-level observability or evidence collection
702
+ * layers.
703
+ *
704
+ * @param callback - Function invoked whenever a change event is emitted by the collection change stream.
705
+ * @param ctx - Optional model execution context for tenant, database,
706
+ * collection, session, and related runtime overrides.
707
+ * @returns The active MongoDB change stream.
708
+ * @throws {Error} When the callback is not a valid function.
709
+ */
710
+ watchChanges(callback: (change: ChangeStreamDocument<T>) => void, ctx?: ModelContext): Promise<ChangeStream<T>>;
711
+ /**
712
+ * Creates an index on the model collection.
713
+ *
714
+ * @param fields - Index field specification where each key maps to ascending
715
+ * (`1`) or descending (`-1`) index order.
716
+ * @param ctx - Optional model execution context for tenant, database,
717
+ * collection, session, and related runtime overrides.
718
+ * @returns A promise that resolves when the index has been created.
719
+ * @throws {Error} When the field specification is missing or invalid.
720
+ */
721
+ createIndex(fields: Partial<Record<keyof T, 1 | -1>>, ctx?: ModelContext): Promise<void>;
722
+ /**
723
+ * Drops an index from the collection by its name.
724
+ * @param {string} indexName - The name of the index to drop.
725
+ * @returns {Promise<void>} Resolves when the index is dropped.
726
+ */
727
+ dropIndex(indexName: string): Promise<void>;
728
+ private invalidateCachePatterns;
729
+ /**
730
+ * Invalidates all cache entries matching the provided Redis key pattern.
731
+ *
732
+ * This method uses Redis `SCAN` to iterate over matching keys in batches and
733
+ * deletes them using a pipelined multi-operation for better efficiency.
734
+ *
735
+ * @param pattern - Redis key pattern to invalidate.
736
+ * @returns The number of successfully deleted keys.
737
+ * @throws {Error} When the pattern is invalid or cache invalidation fails.
738
+ */
739
+ static invalidatePattern(pattern: string): Promise<number>;
740
+ getContext(): {
741
+ ctx: ModelContext;
742
+ };
743
+ /**
744
+ * Invalidates cache entries for the current model scope using a pattern.
745
+ *
746
+ * This helper resolves tenant, database, and collection scope from the
747
+ * provided context and applies the pattern within the Ambiten cache namespace.
748
+ *
749
+ * @param pattern - Partial cache pattern (e.g. "find:*", "aggregate:*").
750
+ * @param ctx - Optional model execution context.
751
+ * @returns Number of deleted cache entries.
752
+ * @throws {Error} When the pattern is invalid.
753
+ */
754
+ invalidateModelPattern(pattern: string, ctx?: ModelContext): Promise<number>;
755
+ /**
756
+ * Invalidates cache entries related to a specific document within the current
757
+ * model scope.
758
+ *
759
+ * This helper is useful only when document-specific cache keys are part of the
760
+ * active cache strategy.
761
+ *
762
+ * @param doc - The document whose cache entries should be invalidated.
763
+ * @param ctx - Optional model execution context.
764
+ * @returns A promise that resolves when invalidation completes.
765
+ * @throws {Error} When the document is missing a valid `_id`.
766
+ */
767
+ invalidateDocumentCache(doc: T, ctx?: ModelContext): Promise<number>;
768
+ /**
769
+ * Returns cache statistics for the active Redis cache backend.
770
+ *
771
+ * This helper retrieves Redis memory and keyspace statistics, along with Ambiten
772
+ * cache hit/miss counters. When a tenant identifier is provided, it also counts
773
+ * cache keys scoped to that tenant within the Ambiten cache namespace.
774
+ *
775
+ * @param tenantId - Optional tenant identifier used to count tenant-scoped cache keys.
776
+ * @returns Cache statistics for the current Redis backend.
777
+ * @throws {Error} When cache statistics cannot be retrieved.
778
+ */
779
+ static getCacheStats(tenantId?: string): Promise<AmbitenCacheStats>;
780
+ /**
781
+ * Runs a custom command on the collection.
782
+ * @param {string} command - The command to run.
783
+ * @param {...any} args - The arguments for the command.
784
+ * @returns {Promise<any>} The result of the command.
785
+ */
786
+ runCommand(command: string, ...args: any[]): Promise<any>;
787
+ /**
788
+ * Runs garbage collection for expired documents in the model collection.
789
+ *
790
+ * This operation uses the model GC configuration to locate expired documents
791
+ * and either soft-delete them or permanently delete them. When configured,
792
+ * expired documents may be archived before deletion.
793
+ *
794
+ * The operation runs inside the active Ambiten runtime context, is instrumented
795
+ * through {@link measureQuery}, executes registered GC-related middlewares,
796
+ * triggers schema update/delete hooks as appropriate, invalidates relevant
797
+ * cache patterns, and publishes a garbage collection event after completion.
798
+ *
799
+ * @param ctx - Optional model execution context for tenant, database,
800
+ * collection, session, and related runtime overrides.
801
+ * @returns A promise that resolves when garbage collection completes.
802
+ */
803
+ runGC(ctx?: ModelContext): Promise<void>;
804
+ /**
805
+ * Starts the automatic garbage collection process.
806
+ * @param {number} intervalMs - The interval in milliseconds for the garbage collection to run.
807
+ */
808
+ startAutoGC(intervalMs?: number): void;
809
+ /**
810
+ * Resolves instrumentation context for model operations by combining explicit
811
+ * model context with the active runtime context.
812
+ *
813
+ * This helper is used to provide stable metadata for logging, observers,
814
+ * tracing, and query instrumentation.
815
+ *
816
+ * @param ctx - Optional model execution context.
817
+ * @returns Resolved instrumentation metadata for the current operation.
818
+ */
819
+ private resolveInstrumentationContext;
820
+ /**
821
+ * Builds normalized operation metadata by merging existing middleware metadata
822
+ * with operation-specific overrides.
823
+ *
824
+ * @param base - Existing operation metadata.
825
+ * @param overrides - Additional metadata flags or values to apply.
826
+ * @returns Normalized operation metadata.
827
+ */
828
+ private buildOperationMeta;
829
+ /**
830
+ * Builds a normalized hook payload for schema middleware and instrumentation.
831
+ *
832
+ * @param operation - Operation name.
833
+ * @param ctx - Optional model execution context.
834
+ * @param payload - Additional hook payload fields.
835
+ * @returns Normalized hook payload.
836
+ */
837
+ private buildHookPayload;
838
+ /**
839
+ * Resolves a cache adapter for the current query options.
840
+ *
841
+ * This helper returns a lightweight Redis-backed cache interface when caching
842
+ * is enabled in the provided query options. Cache failures are treated as
843
+ * non-fatal so query execution can continue even when Redis is unavailable or
844
+ * a cache payload is invalid.
845
+ *
846
+ * @param options - Optional query options that may enable caching.
847
+ * @returns A cache adapter when caching is enabled, otherwise `null`.
848
+ */
849
+ private resolveCache;
850
+ /**
851
+ * Builds a deterministic cache key for a query operation.
852
+ *
853
+ * The cache key is scoped by tenant, database, collection, and operation, and
854
+ * uses a normalized serialized payload to ensure stable cache identity across
855
+ * semantically equivalent query inputs.
856
+ *
857
+ * @param operation - Query operation name.
858
+ * @param payload - Cache identity payload for the operation.
859
+ * @returns A deterministic tenant-aware cache key.
860
+ */
861
+ private buildCacheKey;
862
+ private static trackCacheMiss;
863
+ private static trackCacheHit;
864
+ static cacheResult<R>(key: string, data: R, ttl?: number): Promise<void>;
865
+ /**
866
+ * Clears a cached result by its key.
867
+ * @param {string} key - The cache key.
868
+ * @returns {Promise<void>} Resolves when the cache is cleared.
869
+ */
870
+ static clearCache(key: string): Promise<void>;
871
+ /**
872
+ * Warms cache entries for selected model queries.
873
+ *
874
+ * When query definitions are provided, this helper executes the corresponding
875
+ * `find` operations and stores the results using Ambiten's scoped cache key
876
+ * strategy. When no queries are provided, it warms a default collection-wide
877
+ * `find({})` cache entry, subject to a safety threshold for large collections.
878
+ *
879
+ * This helper is best suited for controlled cache priming scenarios such as
880
+ * startup warmup, scheduled maintenance, or high-traffic query preparation.
881
+ *
882
+ * @param queries - Optional list of query definitions to warm.
883
+ * @param defaultTtl - Default TTL in seconds for warmed entries.
884
+ * @param ctx - Optional model execution context for tenant, database,
885
+ * collection, session, and related runtime overrides.
886
+ * @returns A promise that resolves when cache warming completes.
887
+ * @throws {Error} When cache warming fails.
888
+ */
889
+ warmCache(queries?: {
890
+ filter?: Partial<T>;
891
+ ttl?: number;
892
+ }[], defaultTtl?: number, ctx?: ModelContext): Promise<void>;
893
+ private sortObjectDeep;
894
+ private toModelResult;
895
+ private toModelResults;
896
+ /**
897
+ * Restores a single soft-deleted document matching the provided filter.
898
+ *
899
+ * This operation runs inside the active Ambiten runtime context, is instrumented
900
+ * through {@link measureQuery}, executes registered restore middlewares,
901
+ * triggers schema update hooks, invalidates relevant cache patterns, and
902
+ * publishes a document restoration event after completion.
903
+ *
904
+ * The actual restore behavior is driven by the update document returned from
905
+ * {@link buildRestoreUpdate}.
906
+ *
907
+ * @param filter - MongoDB filter used to identify the document to restore.
908
+ * @param ctx - Optional model execution context for tenant, database,
909
+ * collection, session, and related runtime overrides.
910
+ * @returns A promise that resolves when the operation completes.
911
+ * @throws {Error} When the filter is missing or invalid.
912
+ */
913
+ restoreOne(filter: Filter<T>, ctx?: ModelContext): Promise<void>;
914
+ /**
915
+ * Restores multiple soft-deleted documents matching the provided filter.
916
+ *
917
+ * This operation runs inside the active Ambiten runtime context, is instrumented
918
+ * through {@link measureQuery}, executes registered restore middlewares,
919
+ * triggers schema update hooks, invalidates relevant cache patterns, and
920
+ * publishes a document restoration event after completion.
921
+ *
922
+ * The actual restore behavior is driven by the update document returned from
923
+ * {@link buildRestoreUpdate}.
924
+ *
925
+ * @param filter - MongoDB filter used to identify the documents to restore.
926
+ * @param ctx - Optional model execution context for tenant, database,
927
+ * collection, session, and related runtime overrides.
928
+ * @returns A promise that resolves when the operation completes.
929
+ * @throws {Error} When the filter is missing or invalid.
930
+ */
931
+ restoreMany(filter: Filter<T>, ctx?: ModelContext): Promise<void>;
932
+ private buildRestoreUpdate;
933
+ private buildMiddlewareContext;
934
+ setSoftDeleteConfig(config: {
935
+ deletedAtField: string;
936
+ isDeletedField: string;
937
+ }): void;
938
+ /**
939
+ * Builds the update document used for soft delete operations.
940
+ *
941
+ * The generated update sets the configured deleted timestamp field and
942
+ * deleted-state flag field to mark the document as logically deleted without
943
+ * physically removing it from the collection.
944
+ *
945
+ * @returns MongoDB update document for soft delete flows.
946
+ */
947
+ private buildSoftDeleteUpdate;
948
+ private runBeforeMiddlewares;
949
+ private runAfterMiddlewares;
950
+ before(operation: AmbitenMiddlewareOperation, handler: AmbitenMiddlewareHandler<T>): this;
951
+ after(operation: AmbitenMiddlewareOperation, handler: AmbitenMiddlewareHandler<T>): this;
952
+ beforeFind(handler: AmbitenMiddlewareHandler<T>): this;
953
+ afterFind(handler: AmbitenMiddlewareHandler<T>): this;
954
+ beforeFindOne(handler: AmbitenMiddlewareHandler<T>): this;
955
+ afterFindOne(handler: AmbitenMiddlewareHandler<T>): this;
956
+ beforeSave(handler: AmbitenMiddlewareHandler<T>): this;
957
+ afterSave(handler: AmbitenMiddlewareHandler<T>): this;
958
+ beforeUpdateOne(handler: AmbitenMiddlewareHandler<T>): this;
959
+ afterUpdateOne(handler: AmbitenMiddlewareHandler<T>): this;
960
+ beforeDeleteOne(handler: AmbitenMiddlewareHandler<T>): this;
961
+ afterDeleteOne(handler: AmbitenMiddlewareHandler<T>): this;
962
+ beforeDeleteMany(handler: AmbitenMiddlewareHandler<T>): this;
963
+ afterDeleteMany(handler: AmbitenMiddlewareHandler<T>): this;
964
+ beforeBulkInsert(handler: AmbitenMiddlewareHandler<T>): this;
965
+ afterBulkInsert(handler: AmbitenMiddlewareHandler<T>): this;
966
+ beforeBulkUpdate(handler: AmbitenMiddlewareHandler<T>): this;
967
+ afterBulkUpdate(handler: AmbitenMiddlewareHandler<T>): this;
968
+ beforeAggregate(handler: AmbitenMiddlewareHandler<T>): this;
969
+ afterAggregate(handler: AmbitenMiddlewareHandler<T>): this;
970
+ beforeFindOneAndUpdate(handler: AmbitenMiddlewareHandler<T>): this;
971
+ afterFindOneAndUpdate(handler: AmbitenMiddlewareHandler<T>): this;
972
+ beforeFindOneAndDelete(handler: AmbitenMiddlewareHandler<T>): this;
973
+ afterFindOneAndDelete(handler: AmbitenMiddlewareHandler<T>): this;
974
+ beforeFindOneAndReplace(handler: AmbitenMiddlewareHandler<T>): this;
975
+ afterFindOneAndReplace(handler: AmbitenMiddlewareHandler<T>): this;
976
+ beforeFindOneAndUpsert(handler: AmbitenMiddlewareHandler<T>): this;
977
+ afterFindOneAndUpsert(handler: AmbitenMiddlewareHandler<T>): this;
978
+ }
979
+ //# sourceMappingURL=ambitenModelFactory.d.ts.map