monsqlize 1.3.0 → 2.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 (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  4. package/changelogs/README.md +160 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/dist/cjs/index.cjs +10600 -0
  7. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  8. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  9. package/dist/cjs/transaction/Transaction.cjs +158 -0
  10. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  11. package/dist/esm/index.mjs +10650 -0
  12. package/dist/types/base.d.ts +81 -0
  13. package/dist/types/collection.d.ts +1031 -0
  14. package/dist/types/expression.d.ts +115 -0
  15. package/dist/types/index.d.ts +23 -0
  16. package/dist/types/lock.d.ts +74 -0
  17. package/dist/types/model.d.ts +526 -0
  18. package/dist/types/mongodb.d.ts +49 -0
  19. package/dist/types/monsqlize.d.ts +491 -0
  20. package/dist/types/pool.d.ts +84 -0
  21. package/dist/types/runtime.d.ts +362 -0
  22. package/dist/types/saga.d.ts +143 -0
  23. package/dist/types/slow-query-log.d.ts +126 -0
  24. package/dist/types/sync.d.ts +103 -0
  25. package/dist/types/transaction.d.ts +132 -0
  26. package/package.json +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -0,0 +1,362 @@
1
+ import type { BookmarkClearResult, BookmarkListResult, BookmarkPrewarmResult, DeleteBatchResult, DeleteResult, IncrementOneResult, IndexCreateResult, InsertBatchResult, InsertManyResult, UpdateBatchResult, UpdateResult } from './collection';
2
+ import type { LoggerLike, ExpressionFunction, ExpressionObject } from './base';
3
+ import type { ModelDefinition, ModelInstance as ModelInstanceContract, RegisteredModel, RelationConfig } from './model';
4
+ import type { LockOptions, LockStats } from './lock';
5
+ import type { ConnectionPoolManagerOptions, FallbackStrategy, PoolConfig, PoolHealthStatus, PoolRole, PoolStats, PoolStrategy } from './pool';
6
+ import type { SagaDefinition, SagaOrchestratorOptions, SagaResult, SagaStats, SagaStep } from './saga';
7
+ import type { SlowQueryLogConfig, SlowQueryLogConfigInput, SlowQueryLogEntry, SlowQueryLogFilter, SlowQueryLogQueryOptions, SlowQueryLogRecord, SlowQueryLogStorageConfig } from './slow-query-log';
8
+ import type { ResumeTokenConfig, SyncChangeEvent, SyncConfig, SyncStats, SyncTargetConfig, SyncTargetHealthCheckConfig } from './sync';
9
+ import type { MongoSession, TransactionOptions, TransactionStats } from './transaction';
10
+ import type {
11
+ CacheLike as HubCacheLike,
12
+ CacheStats as HubCacheStats,
13
+ LockManager as HubCacheLockLike,
14
+ MemoryCacheOptions as HubMemoryCacheOptions,
15
+ } from 'cache-hub';
16
+ import type { RedisCacheAdapter as HubRedisCacheAdapter } from 'cache-hub/redis';
17
+ import type {
18
+ DistributedInvalidatorOptions as HubDistributedInvalidatorOptions,
19
+ InvalidatorStats as HubInvalidatorStats,
20
+ } from 'cache-hub/distributed';
21
+ import type {
22
+ FunctionCacheOptions as HubFunctionCacheOptions,
23
+ FunctionCacheStats as HubFunctionCacheStats,
24
+ WithCacheOptions as HubWithCacheOptions,
25
+ WithCacheStats as HubWithCacheStats,
26
+ WrappedFunction as HubWrappedFunction,
27
+ } from 'cache-hub/function-cache';
28
+
29
+ export { Lock, LockAcquireError, LockTimeoutError, LockManager } from './lock';
30
+ export { ConnectionPoolManager } from './pool';
31
+ export { SagaOrchestrator } from './saga';
32
+ export { BatchQueue, SlowQueryLogConfigManager, SlowQueryLogManager, SlowQueryLogMemoryStorage, MongoDBSlowQueryLogStorage } from './slow-query-log';
33
+ export { ChangeStreamSyncManager, ResumeTokenStore } from './sync';
34
+ export { CacheLockManager, Transaction, TransactionManager } from './transaction';
35
+
36
+ export declare class Logger {
37
+ constructor(logger?: LoggerLike | null);
38
+ debug(...args: unknown[]): void;
39
+ info(...args: unknown[]): void;
40
+ warn(...args: unknown[]): void;
41
+ error(...args: unknown[]): void;
42
+ static create(logger?: LoggerLike | null): Logger;
43
+ }
44
+
45
+ export type CacheLockLike = HubCacheLockLike;
46
+ export type CacheLike = HubCacheLike;
47
+ export type MemoryCacheOptions = HubMemoryCacheOptions;
48
+
49
+ /**
50
+ * Multi-level cache write policy.
51
+ * - `both`: write to both local and remote simultaneously (waits for remote to complete)
52
+ * - `local-first-async-remote`: return after local write; remote write is asynchronous (reduces tail latency)
53
+ * @since v1.1.0
54
+ */
55
+ export type WritePolicy = 'both' | 'local-first-async-remote';
56
+
57
+ /**
58
+ * Multi-level cache policy configuration.
59
+ * @since v1.1.0
60
+ */
61
+ export interface MultiLevelCachePolicy {
62
+ /** Write policy; defaults to `both`. */
63
+ writePolicy?: WritePolicy;
64
+ /** Whether to backfill the local cache on a remote hit; defaults to true. */
65
+ backfillLocalOnRemoteHit?: boolean;
66
+ }
67
+
68
+ /**
69
+ * Multi-level cache configuration object (declarative two-tier cache setup).
70
+ *
71
+ * When passed to `MonSQLizeOptions.cache`, the framework automatically creates a MultiLevelCache:
72
+ * - `local`: always uses the built-in memory cache (accepts MemoryCacheOptions only)
73
+ * - `remote`: accepts a CacheLike instance (recommended for production) or a config object
74
+ * that degrades to an in-memory placeholder
75
+ * - `policy`: write policy and backfill policy configuration
76
+ * @since v1.1.0
77
+ */
78
+ export interface MultiLevelCacheOptions {
79
+ multiLevel: true;
80
+ local?: MemoryCacheOptions;
81
+ remote?: CacheLike | (MemoryCacheOptions & { timeoutMs?: number });
82
+ policy?: MultiLevelCachePolicy;
83
+ publish?: (msg: unknown) => void;
84
+ }
85
+
86
+ export declare class MemoryCache {
87
+ constructor(options?: MemoryCacheOptions);
88
+ setLockManager(lockManager: CacheLockLike): void;
89
+ getLockManager(): CacheLockLike | null;
90
+ get<T = unknown>(key: string): T | undefined;
91
+ set(key: string, value: unknown, ttl?: number): void;
92
+ del(key: string): boolean;
93
+ exists(key: string): boolean;
94
+ has(key: string): boolean;
95
+ getMany(keys: string[]): Record<string, unknown>;
96
+ setMany(values: Record<string, unknown>, ttl?: number): boolean;
97
+ delMany(keys: string[]): number;
98
+ clear(): void;
99
+ keys(pattern?: string): string[];
100
+ delPattern(pattern: string): number;
101
+ getStats(): CacheStats;
102
+ resetStats(): void;
103
+ invalidateByTag(tag: string): void;
104
+ destroy(): void;
105
+ }
106
+
107
+ export declare class MultiLevelCache {
108
+ constructor(options: {
109
+ local: CacheLike;
110
+ remote?: CacheLike;
111
+ writePolicy?: 'both' | 'local-first-async-remote';
112
+ backfillOnRemoteHit?: boolean;
113
+ remoteTimeoutMs?: number;
114
+ publish?: (msg: { type: string; pattern: string; ts: number }) => void;
115
+ });
116
+ get<T = unknown>(key: string): Promise<T | undefined>;
117
+ set(key: string, value: unknown, ttl?: number): Promise<void>;
118
+ del(key: string): Promise<boolean>;
119
+ exists(key: string): Promise<boolean>;
120
+ has(key: string): Promise<boolean>;
121
+ clear(): Promise<void>;
122
+ getMany(keys: string[]): Promise<Record<string, unknown>>;
123
+ setMany(values: Record<string, unknown>, ttl?: number): Promise<boolean>;
124
+ delMany(keys: string[]): Promise<number>;
125
+ delPattern(pattern: string): Promise<number>;
126
+ keys(pattern?: string): Promise<string[]>;
127
+ invalidateByTag(tag: string): void | Promise<void>;
128
+ setPublish(publish: (msg: { type: string; pattern: string; ts: number }) => void): void;
129
+ setLockManager(lockManager: CacheLockLike): void;
130
+ getStats(): CacheStats;
131
+ resetStats(): void;
132
+ destroy(): void;
133
+ }
134
+
135
+ export type RedisCacheAdapterOptions = never;
136
+ export type RedisLike = object;
137
+
138
+ /**
139
+ * Adapts a v1-style CacheLike object to the v2 CacheLike interface.
140
+ *
141
+ * v2 requires a `has()` method that was absent in v1. This helper adds it
142
+ * by delegating to the existing `exists()`. All other methods are forwarded as-is.
143
+ *
144
+ * @param v1Cache - A v1 custom cache implementation missing `has()`.
145
+ * @returns A fully v2-compatible `CacheLike` instance.
146
+ * @example
147
+ * ```ts
148
+ * const v2Cache = adaptLegacyCacheLike(myV1Cache);
149
+ * const msq = new MonSQLize({ cache: v2Cache });
150
+ * ```
151
+ */
152
+ export declare function adaptLegacyCacheLike(v1Cache: Omit<CacheLike, 'has'>): CacheLike;
153
+
154
+ /** Re-exported alias so consumers can type the return value of `createRedisCacheAdapter`. */
155
+ export type RedisCacheAdapter = HubRedisCacheAdapter;
156
+
157
+ export declare function createRedisCacheAdapter(
158
+ redisUrlOrInstance: string | object | undefined,
159
+ ): HubRedisCacheAdapter;
160
+
161
+ export type { LockOptions, LockStats, MongoSession, TransactionOptions, TransactionStats };
162
+
163
+ export type DistributedCacheInvalidatorOptions = HubDistributedInvalidatorOptions;
164
+
165
+ export declare class DistributedCacheInvalidator {
166
+ constructor(options: DistributedCacheInvalidatorOptions);
167
+ invalidate(pattern: string): Promise<void>;
168
+ getStats(): HubInvalidatorStats;
169
+ close(): Promise<void>;
170
+ }
171
+
172
+ export type {
173
+ ConnectionPoolManagerOptions,
174
+ FallbackStrategy,
175
+ PoolConfig,
176
+ PoolHealthStatus,
177
+ PoolRole,
178
+ PoolStats,
179
+ PoolStrategy,
180
+ ResumeTokenConfig,
181
+ SagaDefinition,
182
+ SagaOrchestratorOptions,
183
+ SagaResult,
184
+ SagaStats,
185
+ SagaStep,
186
+ SlowQueryLogConfig,
187
+ SlowQueryLogConfigInput,
188
+ SlowQueryLogEntry,
189
+ SlowQueryLogFilter,
190
+ SlowQueryLogQueryOptions,
191
+ SlowQueryLogRecord,
192
+ SlowQueryLogStorageConfig,
193
+ SyncChangeEvent,
194
+ SyncConfig,
195
+ SyncStats,
196
+ SyncTargetConfig,
197
+ SyncTargetHealthCheckConfig,
198
+ };
199
+
200
+ export declare function validateSyncConfig(config: SyncConfig): void;
201
+ export declare function generateQueryHash(input: unknown): string;
202
+
203
+ export type WithCacheOptions<
204
+ T extends (...args: any[]) => Promise<any> = (...args: unknown[]) => Promise<unknown>,
205
+ > = HubWithCacheOptions<T>;
206
+
207
+ export type CacheStats = HubCacheStats;
208
+
209
+ export interface WithCacheStats extends HubWithCacheStats {
210
+ calls: number;
211
+ totalTime: number;
212
+ avgTime: number;
213
+ }
214
+
215
+ export interface FunctionCacheStats extends HubFunctionCacheStats {
216
+ calls: number;
217
+ totalTime: number;
218
+ avgTime: number;
219
+ }
220
+
221
+ export type CachedFunction<TArgs extends unknown[] = unknown[], TResult = unknown> = HubWrappedFunction<(...args: TArgs) => Promise<TResult>> & {
222
+ /** @deprecated Use `stats()`. v1 backward-compat alias. */
223
+ getCacheStats(): WithCacheStats;
224
+ stats(): WithCacheStats;
225
+ };
226
+
227
+ export interface FunctionCacheOptions extends HubFunctionCacheOptions {
228
+ /** @deprecated v1 alias for `ttl`. Use `ttl` instead. */
229
+ defaultTTL?: number;
230
+ }
231
+
232
+ export declare function withCache<TArgs extends unknown[], TResult>(
233
+ fn: (...args: TArgs) => Promise<TResult>,
234
+ options?: WithCacheOptions<(...args: TArgs) => Promise<TResult>>,
235
+ ): CachedFunction<TArgs, TResult>;
236
+
237
+ export declare class FunctionCache {
238
+ constructor(cacheOrDb?: CacheLike | { getCache(): CacheLike; }, options?: FunctionCacheOptions);
239
+ register(name: string, fn: (...args: unknown[]) => Promise<unknown>, options?: {
240
+ ttl?: number;
241
+ keyBuilder?: (...args: unknown[]) => string;
242
+ namespace?: string;
243
+ condition?: (result: unknown) => boolean;
244
+ }): Promise<void>;
245
+ execute(name: string, ...args: unknown[]): Promise<unknown>;
246
+ invalidate(name: string, ...args: unknown[]): Promise<void>;
247
+ invalidatePattern(pattern: string): Promise<number>;
248
+ getStats(name?: string): FunctionCacheStats | Record<string, FunctionCacheStats> | null;
249
+ list(): string[];
250
+ resetStats(name?: string): void;
251
+ clear(): void;
252
+ }
253
+
254
+ export declare class Model {
255
+ static define<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
256
+ static get<TDocument = any>(name: string): RegisteredModel<TDocument> | undefined;
257
+ static has(name: string): boolean;
258
+ static list(): string[];
259
+ static undefine(name: string): boolean;
260
+ static redefine<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
261
+ static _clear(): void;
262
+ }
263
+
264
+ export declare class ModelInstance<TDocument = any> implements ModelInstanceContract<TDocument> {
265
+ private constructor(...args: unknown[]);
266
+ readonly collectionName: string;
267
+ readonly dbName: string;
268
+ readonly poolName?: string;
269
+ readonly definition: ModelDefinition<TDocument>;
270
+ getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; };
271
+ getRelations(): Record<string, RelationConfig>;
272
+ getEnums(): Record<string, string>;
273
+ raw(): unknown;
274
+ find(query?: unknown, options?: unknown): import('./model').PopulateProxy<Array<import('./model').ModelDocument<TDocument>>>;
275
+ findOne(query?: unknown, options?: unknown): import('./model').PopulateProxy<import('./model').ModelDocument<TDocument> | null>;
276
+ findOneById(id: unknown, options?: unknown): import('./model').PopulateProxy<import('./model').ModelDocument<TDocument> | null>;
277
+ findById(id: unknown, options?: unknown): import('./model').PopulateProxy<import('./model').ModelDocument<TDocument> | null>;
278
+ findByIds(ids: unknown[], options?: unknown): import('./model').PopulateProxy<Array<import('./model').ModelDocument<TDocument>>>;
279
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model').PopulateProxy<{
280
+ items: Array<import('./model').ModelDocument<TDocument>>;
281
+ pageInfo: import('./model').ModelInstance<TDocument> extends {
282
+ findPage(options?: unknown): import('./model').PopulateProxy<infer TResult>;
283
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
284
+ totals: import('./model').ModelInstance<TDocument> extends {
285
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model').PopulateProxy<infer TResult>;
286
+ } ? TResult extends { totals: infer TTotals } ? TTotals : never : never;
287
+ meta?: import('./collection').MetaInfo;
288
+ }>;
289
+ findPage(options?: unknown): import('./model').PopulateProxy<{
290
+ items: Array<import('./model').ModelDocument<TDocument>>;
291
+ pageInfo: import('./model').ModelInstance<TDocument> extends {
292
+ findPage(options?: unknown): import('./model').PopulateProxy<infer TResult>;
293
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
294
+ totals?: import('./model').ModelInstance<TDocument> extends {
295
+ findPage(options?: unknown): import('./model').PopulateProxy<infer TResult>;
296
+ } ? TResult extends { totals?: infer TTotals } ? TTotals : never : never;
297
+ meta?: import('./collection').MetaInfo;
298
+ }>;
299
+ findAndCount(query?: unknown, options?: unknown): import('./model').PopulateProxy<{ data: Array<import('./model').ModelDocument<TDocument>>; total: number; }>;
300
+ count(query?: unknown, options?: unknown): Promise<number>;
301
+ insertOne(document?: unknown, options?: unknown): Promise<{ acknowledged: boolean; insertedId: any; }>;
302
+ insertMany(documents?: unknown[], options?: unknown): Promise<InsertManyResult>;
303
+ updateOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
304
+ updateMany(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
305
+ replaceOne(filter?: unknown, replacement?: unknown, options?: unknown): Promise<UpdateResult>;
306
+ findOneAndUpdate(filter?: unknown, update?: unknown, options?: unknown): Promise<TDocument | null>;
307
+ findOneAndDelete(filter?: unknown, options?: unknown): Promise<TDocument | null>;
308
+ upsertOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
309
+ deleteOne(filter?: unknown, options?: unknown): Promise<DeleteResult>;
310
+ deleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
311
+ createIndex(keys: unknown, options?: unknown): Promise<IndexCreateResult>;
312
+ createIndexes(specs: Array<{ key: unknown; } & Record<string, unknown>>): Promise<string[]>;
313
+ listIndexes(): Promise<Record<string, unknown>[]>;
314
+ dropIndex(name: string): Promise<unknown>;
315
+ dropIndexes(): Promise<unknown>;
316
+ prewarmBookmarks(keyDims?: unknown, pages?: number[]): Promise<BookmarkPrewarmResult>;
317
+ listBookmarks(keyDims?: unknown): Promise<BookmarkListResult>;
318
+ clearBookmarks(keyDims?: unknown): Promise<BookmarkClearResult>;
319
+ distinct(key: string, query?: unknown, options?: unknown): Promise<unknown[]>;
320
+ aggregate(pipeline?: unknown[], options?: unknown): Promise<unknown[]>;
321
+ stream(query?: unknown, options?: unknown): NodeJS.ReadableStream;
322
+ explain(query?: unknown, options?: unknown): Promise<unknown>;
323
+ invalidate(op?: 'find' | 'findOne' | 'count' | 'findPage' | 'aggregate' | 'distinct'): Promise<number>;
324
+ dropCollection(): Promise<boolean>;
325
+ createCollection(name?: string, options?: Record<string, unknown>): Promise<boolean>;
326
+ createView(name: string, source: string, pipeline?: unknown[]): Promise<boolean>;
327
+ indexStats(): Promise<unknown[]>;
328
+ setValidator(validator: unknown, options?: { validationLevel?: string; validationAction?: string }): Promise<{ ok: number; collection: string }>;
329
+ setValidationLevel(level: 'off' | 'moderate' | 'strict' | string): Promise<{ ok: number; validationLevel: string }>;
330
+ setValidationAction(action: 'error' | 'warn' | string): Promise<{ ok: number; validationAction: string }>;
331
+ getValidator(): Promise<{ validator: Record<string, unknown> | null; validationLevel: string; validationAction: string }>;
332
+ stats(options?: { scale?: number }): Promise<{ ns: string; count: number; size: number; storageSize: number; totalIndexSize: number; nindexes: number; avgObjSize?: number; scaleFactor?: number }>;
333
+ renameCollection(newName: string, options?: { dropTarget?: boolean }): Promise<{ renamed: boolean; from: string; to: string }>;
334
+ collMod(modifications: Record<string, unknown>): Promise<Record<string, unknown>>;
335
+ convertToCapped(size: number, options?: { max?: number }): Promise<{ ok: number; collection: string; capped: boolean; size: number }>;
336
+ watch(pipeline?: unknown[], options?: unknown): import('mongodb').ChangeStream;
337
+ validate(document?: unknown): import('./model').ValidationResult;
338
+ findOneAndReplace(filter?: unknown, replacement?: unknown, options?: unknown): Promise<TDocument | null>;
339
+ incrementOne(filter?: unknown, field?: string | Record<string, number>, increment?: number, options?: unknown): Promise<IncrementOneResult<TDocument>>;
340
+ findWithDeleted(query?: unknown, options?: unknown): import('./model').PopulateProxy<Array<import('./model').ModelDocument<TDocument>>>;
341
+ findOnlyDeleted(query?: unknown, options?: unknown): import('./model').PopulateProxy<Array<import('./model').ModelDocument<TDocument>>>;
342
+ findOneWithDeleted(query?: unknown, options?: unknown): import('./model').PopulateProxy<import('./model').ModelDocument<TDocument> | null>;
343
+ restore(filter?: unknown, options?: unknown): Promise<import('./model').RestoreResult>;
344
+ restoreMany(filter?: unknown, options?: unknown): Promise<import('./model').RestoreResult>;
345
+ forceDelete(filter?: unknown, options?: unknown): Promise<DeleteResult>;
346
+ forceDeleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
347
+ findOneOnlyDeleted(query?: unknown, options?: unknown): import('./model').PopulateProxy<import('./model').ModelDocument<TDocument> | null>;
348
+ countWithDeleted(query?: unknown, options?: unknown): Promise<number>;
349
+ countOnlyDeleted(query?: unknown, options?: unknown): Promise<number>;
350
+ insertBatch(docs: unknown[], options?: unknown): Promise<InsertBatchResult>;
351
+ updateBatch(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateBatchResult>;
352
+ deleteBatch(filter?: unknown, options?: unknown): Promise<DeleteBatchResult>;
353
+ }
354
+
355
+ export declare const expr: ExpressionFunction;
356
+ export declare const createExpression: ExpressionFunction;
357
+ export declare function isExpressionObject(value: unknown): value is ExpressionObject;
358
+ export declare function hasExpressionInObject(value: unknown): boolean;
359
+ export declare function hasExpressionInPipeline(pipeline: unknown): boolean;
360
+ /** Compile expression objects in a MongoDB pipeline into real operators. */
361
+ export declare function compilePipelineExpressions<TPipeline>(pipeline: TPipeline): TPipeline;
362
+
@@ -0,0 +1,143 @@
1
+ import type { LoggerLike } from './base';
2
+
3
+ export interface SagaMetadataCache {
4
+ set(key: string, value: any, ttl?: number): void | Promise<void>;
5
+ keys?(pattern?: string): string[] | Promise<string[]>;
6
+ publish?(channel: string, message: string): void | Promise<unknown>;
7
+ }
8
+
9
+ /** Execution context passed to each Saga step; provides data sharing between steps. */
10
+ export interface SagaContext {
11
+ /** Unique ID for this Saga execution run. */
12
+ readonly executionId: string;
13
+ /** @deprecated Use `executionId` — v1 compatibility alias. */
14
+ readonly sagaId?: string;
15
+ /** Initial data passed to `executeSaga`. */
16
+ readonly data: any;
17
+ /** Store a value in the shared step context. */
18
+ set(key: string, value: any): void;
19
+ /** Retrieve a previously stored value. v1 compat — default generic is `any` to match v1 callers that did not annotate. */
20
+ get<T = any>(key: string): T | undefined;
21
+ /** Return `true` if a value exists for `key`. */
22
+ has(key: string): boolean;
23
+ /** Return all stored key-value pairs. */
24
+ getAll(): Record<string, any>;
25
+ /**
26
+ * Ordered list of completed step names.
27
+ * @deprecated v1 compat — populated automatically by the orchestrator.
28
+ */
29
+ readonly completedSteps: string[];
30
+ /**
31
+ * Mark a step as completed and record its result.
32
+ * @deprecated v1 compat — called automatically by the orchestrator. Use `ctx.get(stepName)` to retrieve step results.
33
+ */
34
+ markStepCompleted(stepName: string, result: unknown): void;
35
+ /**
36
+ * Return the result of a previously completed step.
37
+ * @deprecated v1 compat — use `ctx.get(stepName)` instead.
38
+ */
39
+ getStepResult(stepName: string): unknown;
40
+ /**
41
+ * Return an ordered copy of completed step names.
42
+ * @deprecated v1 compat — use `ctx.getAll()` instead.
43
+ */
44
+ getCompletedSteps(): string[];
45
+ }
46
+
47
+ /** A single step within a Saga, consisting of a forward action and an optional compensation handler. */
48
+ export interface SagaStep {
49
+ name: string;
50
+ execute: (context: SagaContext) => Promise<any>;
51
+ /** Compensation handler — receives the context and the step's own execute result. v1 compat — required so callers may invoke `step.compensate(ctx)` without optional-chaining. */
52
+ compensate: (context: SagaContext, result?: any) => Promise<void>;
53
+ /** Per-step timeout in milliseconds (overrides Saga-level timeout). */
54
+ timeout?: number;
55
+ /** Number of retry attempts on step failure. */
56
+ retries?: number;
57
+ }
58
+
59
+ /** Definition of a Saga, including its ordered steps and execution configuration. */
60
+ export interface SagaDefinition {
61
+ name: string;
62
+ steps: SagaStep[];
63
+ /** Overall Saga timeout in milliseconds. */
64
+ timeout?: number;
65
+ /** Whether to emit detailed execution logs. */
66
+ logging?: boolean;
67
+ }
68
+
69
+ /** Result returned after a Saga execution (success or failure). */
70
+ export interface SagaResult {
71
+ /** v2 field — present when emitted by v2 runtime; v1 fixtures may omit. */
72
+ sagaId?: string;
73
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
74
+ executionId: string;
75
+ /** v2 field — present when emitted by v2 runtime; v1 fixtures may omit. */
76
+ sagaName?: string;
77
+ success: boolean;
78
+ /** The return value of the last completed step (success path). */
79
+ result?: any;
80
+ /** v1-compatible Error object (set when success is false). */
81
+ error?: Error;
82
+ /** v2 compatibility alias for message-only consumers. */
83
+ errorMessage?: string;
84
+ /** Ordered list of completed step names. */
85
+ completedSteps: string[];
86
+ /** v2 compatibility alias for count-only consumers. */
87
+ completedStepCount?: number;
88
+ /** @deprecated Alias of `completedSteps` retained for v2 callers. */
89
+ completedStepNames?: string[];
90
+ /** Names of steps whose compensation handlers were invoked. v1 compat — runtime always populates an array (empty on success). */
91
+ compensatedSteps: string[];
92
+ /** Total execution duration in milliseconds. */
93
+ duration: number;
94
+ /** Original Error object (failure path only). v1 compat — `error` field is a string in v2. */
95
+ errorCause?: any;
96
+ /** Present on the failure path when at least one completed step has a compensate function. */
97
+ compensation?: {
98
+ success: boolean;
99
+ results: Array<{ stepName: string; success: boolean; reason?: string; error?: string; duration?: number; }>;
100
+ };
101
+ }
102
+
103
+ /** Options for constructing a `SagaOrchestrator`. */
104
+ export interface SagaOrchestratorOptions {
105
+ logger?: LoggerLike | null;
106
+ cache?: SagaMetadataCache | null;
107
+ }
108
+
109
+ /** Aggregate statistics for a `SagaOrchestrator` instance. */
110
+ export interface SagaStats {
111
+ totalExecutions: number;
112
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
113
+ successfulExecutions?: number;
114
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
115
+ failedExecutions?: number;
116
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
117
+ compensatedExecutions?: number;
118
+ successRate?: string;
119
+ storageMode?: string;
120
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
121
+ successCount: number;
122
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
123
+ failureCount: number;
124
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
125
+ compensationCount: number;
126
+ }
127
+
128
+ /** Orchestrates the execution and compensation of multi-step Saga workflows. */
129
+ export declare class SagaOrchestrator {
130
+ constructor(options?: SagaOrchestratorOptions);
131
+ /** Register a Saga definition (sync). */
132
+ define(definition: SagaDefinition): void;
133
+ /** Register a Saga definition (async; returns the registered definition). */
134
+ defineSaga(definition: SagaDefinition): Promise<SagaDefinition>;
135
+ /** Execute the named Saga with the given initial data. */
136
+ execute(name: string, data: any): Promise<SagaResult>;
137
+ /** Return the definition for a registered Saga by name. */
138
+ getSaga(name: string): SagaDefinition | undefined;
139
+ /** Return the names of all registered Sagas. */
140
+ listSagas(): string[];
141
+ /** Return aggregate execution statistics. */
142
+ getStats(): SagaStats;
143
+ }
@@ -0,0 +1,126 @@
1
+ import type { LoggerLike } from './base';
2
+
3
+ export interface SlowQueryLogEntry {
4
+ database: string;
5
+ collection: string;
6
+ operation: string;
7
+ durationMs: number;
8
+ query?: unknown;
9
+ timestamp?: Date;
10
+ queryHash?: string;
11
+ metadata?: Record<string, unknown>;
12
+ }
13
+
14
+ export interface SlowQueryLogRecord {
15
+ queryHash: string;
16
+ database: string;
17
+ collection: string;
18
+ operation: string;
19
+ count: number;
20
+ totalTimeMs: number;
21
+ avgTimeMs: number;
22
+ maxTimeMs: number;
23
+ minTimeMs: number;
24
+ firstSeen: Date;
25
+ lastSeen: Date;
26
+ sampleQuery?: unknown;
27
+ metadata?: Record<string, unknown>;
28
+ }
29
+
30
+ export interface SlowQueryLogFilter {
31
+ database?: string;
32
+ collection?: string;
33
+ operation?: string;
34
+ queryHash?: string;
35
+ }
36
+
37
+ export interface SlowQueryLogQueryOptions {
38
+ sort?: Record<string, 1 | -1>;
39
+ limit?: number;
40
+ skip?: number;
41
+ }
42
+
43
+ export interface SlowQueryLogStorageConfig {
44
+ type?: 'memory' | 'mongodb';
45
+ useBusinessConnection?: boolean;
46
+ uri?: string | null;
47
+ database?: string;
48
+ collection?: string;
49
+ ttl?: number;
50
+ options?: Record<string, unknown>;
51
+ }
52
+
53
+ export interface SlowQueryLogConfig {
54
+ enabled: boolean;
55
+ storage: SlowQueryLogStorageConfig;
56
+ batch: {
57
+ enabled: boolean;
58
+ size: number;
59
+ interval: number;
60
+ maxBufferSize: number;
61
+ };
62
+ filter: {
63
+ excludeDatabases: string[];
64
+ excludeCollections: string[];
65
+ excludeOperations: string[];
66
+ minExecutionTimeMs: number;
67
+ };
68
+ advanced: {
69
+ errorHandling: 'log' | 'throw' | 'silent';
70
+ autoCreateIndexes: boolean;
71
+ };
72
+ }
73
+
74
+ export type SlowQueryLogConfigInput = boolean | Partial<SlowQueryLogConfig>;
75
+
76
+ export interface SlowQueryLogStorage {
77
+ initialize(): Promise<void>;
78
+ save(log: SlowQueryLogEntry): Promise<void>;
79
+ saveBatch(logs: SlowQueryLogEntry[]): Promise<void>;
80
+ query(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
81
+ close(): Promise<void>;
82
+ }
83
+
84
+ export declare const DEFAULT_SLOW_QUERY_LOG_CONFIG: SlowQueryLogConfig;
85
+ export declare function generateQueryHash(input: unknown): string;
86
+
87
+ export declare class BatchQueue {
88
+ constructor(storage: Pick<SlowQueryLogStorage, 'saveBatch'>, options?: Partial<SlowQueryLogConfig['batch']>, logger?: LoggerLike | null);
89
+ add(log: SlowQueryLogEntry): Promise<void>;
90
+ flush(): Promise<void>;
91
+ close(): Promise<void>;
92
+ }
93
+
94
+ export declare class SlowQueryLogMemoryStorage implements SlowQueryLogStorage {
95
+ initialize(): Promise<void>;
96
+ save(log: SlowQueryLogEntry): Promise<void>;
97
+ saveBatch(logs: SlowQueryLogEntry[]): Promise<void>;
98
+ query(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
99
+ close(): Promise<void>;
100
+ }
101
+
102
+ export declare class MongoDBSlowQueryLogStorage implements SlowQueryLogStorage {
103
+ constructor(config?: SlowQueryLogStorageConfig, businessClient?: unknown, logger?: LoggerLike | null);
104
+ initialize(): Promise<void>;
105
+ save(log: SlowQueryLogEntry): Promise<void>;
106
+ saveBatch(logs: SlowQueryLogEntry[]): Promise<void>;
107
+ query(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
108
+ close(): Promise<void>;
109
+ }
110
+
111
+ export declare class SlowQueryLogConfigManager {
112
+ static mergeConfig(userConfig?: SlowQueryLogConfigInput, businessType?: string): SlowQueryLogConfig;
113
+ static validate(config: SlowQueryLogConfig, businessType?: string): boolean;
114
+ }
115
+
116
+ export declare class SlowQueryLogManager {
117
+ readonly config: SlowQueryLogConfig;
118
+ readonly storage: SlowQueryLogStorage;
119
+ readonly queue: BatchQueue | null;
120
+ constructor(userConfig?: SlowQueryLogConfigInput, businessClient?: unknown, businessType?: string, logger?: LoggerLike | null);
121
+ initialize(): Promise<void>;
122
+ save(log: SlowQueryLogEntry): Promise<void>;
123
+ query(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
124
+ close(): Promise<void>;
125
+ }
126
+