monsqlize 2.0.5 → 3.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 (39) hide show
  1. package/CHANGELOG.md +14 -5
  2. package/MIGRATION.md +105 -0
  3. package/README.md +183 -189
  4. package/SECURITY.md +21 -0
  5. package/changelogs/README.md +16 -4
  6. package/changelogs/v2.0.6.md +16 -0
  7. package/changelogs/v2.0.7.md +63 -0
  8. package/changelogs/v3.0.0.md +97 -0
  9. package/dist/cjs/cli/data-task.cjs +17768 -0
  10. package/dist/cjs/index.cjs +12166 -5505
  11. package/dist/cjs/transaction/Transaction.cjs +151 -19
  12. package/dist/cjs/transaction/TransactionManager.cjs +152 -20
  13. package/dist/esm/index.mjs +12171 -5509
  14. package/dist/types/base.d.mts +81 -0
  15. package/dist/types/collection.d.mts +1156 -0
  16. package/dist/types/collection.d.ts +138 -15
  17. package/dist/types/data-tasks.d.mts +221 -0
  18. package/dist/types/data-tasks.d.ts +221 -0
  19. package/dist/types/expression.d.mts +115 -0
  20. package/dist/types/index.d.mts +24 -0
  21. package/dist/types/index.d.ts +1 -0
  22. package/dist/types/lock.d.mts +77 -0
  23. package/dist/types/lock.d.ts +7 -4
  24. package/dist/types/model.d.mts +666 -0
  25. package/dist/types/model.d.ts +46 -14
  26. package/dist/types/mongodb.d.mts +56 -0
  27. package/dist/types/monsqlize.d.mts +638 -0
  28. package/dist/types/monsqlize.d.ts +130 -16
  29. package/dist/types/pool.d.mts +84 -0
  30. package/dist/types/runtime.d.mts +400 -0
  31. package/dist/types/runtime.d.ts +18 -5
  32. package/dist/types/saga.d.mts +148 -0
  33. package/dist/types/saga.d.ts +11 -6
  34. package/dist/types/slow-query-log.d.mts +126 -0
  35. package/dist/types/sync.d.mts +149 -0
  36. package/dist/types/sync.d.ts +47 -1
  37. package/dist/types/transaction.d.mts +152 -0
  38. package/dist/types/transaction.d.ts +8 -0
  39. package/package.json +32 -14
@@ -0,0 +1,400 @@
1
+ import type { BookmarkClearResult, BookmarkListResult, BookmarkPrewarmResult, DeleteBatchResult, DeleteResult, IncrementOneResult, IndexCreateResult, InsertBatchResult, InsertManyResult, UpdateBatchResult, UpdateResult } from './collection.mjs';
2
+ import type { LoggerLike, ExpressionFunction, ExpressionObject } from './base.mjs';
3
+ import type { ModelDefinition, ModelEnsureIndexesOptions, ModelIndexEnsureResult, ModelInstance as ModelInstanceContract, RegisteredModel, RelationConfig } from './model.mjs';
4
+ import type { LockOptions, LockStats } from './lock.mjs';
5
+ import type { ConnectionPoolManagerOptions, FallbackStrategy, PoolConfig, PoolHealthStatus, PoolRole, PoolStats, PoolStrategy } from './pool.mjs';
6
+ import type { SagaDefinition, SagaOrchestratorOptions, SagaResult, SagaStats, SagaStep } from './saga.mjs';
7
+ import type { SlowQueryLogConfig, SlowQueryLogConfigInput, SlowQueryLogEntry, SlowQueryLogFilter, SlowQueryLogQueryOptions, SlowQueryLogRecord, SlowQueryLogStorageConfig } from './slow-query-log.mjs';
8
+ import type { ResumeTokenConfig, SyncChangeEvent, SyncConfig, SyncStats, SyncTargetConfig, SyncTargetHealthCheckConfig } from './sync.mjs';
9
+ import type { MongoSession, TransactionOptions, TransactionStats } from './transaction.mjs';
10
+ import type {
11
+ CacheLike as HubCacheLike,
12
+ CacheRemainingTtl as HubCacheRemainingTtl,
13
+ CacheSetOptions as HubCacheSetOptions,
14
+ CacheStats as HubCacheStats,
15
+ LockManager as HubCacheLockLike,
16
+ MemoryCacheOptions as HubMemoryCacheOptions,
17
+ } from 'cache-hub' with { "resolution-mode": "import" };
18
+ import type {
19
+ RedisCacheAdapter as HubRedisCacheAdapter,
20
+ RedisCacheAdapterOptions as HubRedisCacheAdapterOptions,
21
+ } from 'cache-hub/redis' with { "resolution-mode": "import" };
22
+ import type {
23
+ DistributedInvalidatorOptions as HubDistributedInvalidatorOptions,
24
+ InvalidatorStats as HubInvalidatorStats,
25
+ } from 'cache-hub/distributed' with { "resolution-mode": "import" };
26
+ import type {
27
+ FunctionCacheOptions as HubFunctionCacheOptions,
28
+ FunctionCacheStats as HubFunctionCacheStats,
29
+ WithCacheOptions as HubWithCacheOptions,
30
+ WithCacheStats as HubWithCacheStats,
31
+ WrappedFunction as HubWrappedFunction,
32
+ } from 'cache-hub/function-cache' with { "resolution-mode": "import" };
33
+
34
+ export { Lock, LockAcquireError, LockTimeoutError, LockManager } from './lock.mjs';
35
+ export { ConnectionPoolManager } from './pool.mjs';
36
+ export { SagaOrchestrator } from './saga.mjs';
37
+ export { BatchQueue, SlowQueryLogConfigManager, SlowQueryLogManager, SlowQueryLogMemoryStorage, MongoDBSlowQueryLogStorage } from './slow-query-log.mjs';
38
+ export { ChangeStreamSyncManager, ResumeTokenStore } from './sync.mjs';
39
+ export { CacheLockManager, Transaction, TransactionManager } from './transaction.mjs';
40
+
41
+ export declare class Logger {
42
+ constructor(logger?: LoggerLike | null);
43
+ debug(...args: unknown[]): void;
44
+ info(...args: unknown[]): void;
45
+ warn(...args: unknown[]): void;
46
+ error(...args: unknown[]): void;
47
+ static create(logger?: LoggerLike | null): Logger;
48
+ }
49
+
50
+ export type CacheLockLike = HubCacheLockLike;
51
+ export type CacheLike = HubCacheLike;
52
+ export type CacheRemainingTtl = HubCacheRemainingTtl;
53
+ export type CacheSetOptions = HubCacheSetOptions;
54
+ export type MemoryCacheOptions = HubMemoryCacheOptions;
55
+
56
+ /**
57
+ * Multi-level cache write policy.
58
+ * - `both`: write to both local and remote simultaneously (waits for remote to complete)
59
+ * - `local-first-async-remote`: return after local write; remote write is asynchronous (reduces tail latency)
60
+ * @since v1.1.0
61
+ */
62
+ export type WritePolicy = 'both' | 'local-first-async-remote';
63
+
64
+ /**
65
+ * Multi-level cache policy configuration.
66
+ * @since v1.1.0
67
+ */
68
+ export interface MultiLevelCachePolicy {
69
+ /** Write policy; defaults to `both`. */
70
+ writePolicy?: WritePolicy;
71
+ /** Whether to backfill the local cache on a remote hit; defaults to true. */
72
+ backfillLocalOnRemoteHit?: boolean;
73
+ }
74
+
75
+ /**
76
+ * Multi-level cache configuration object (declarative two-tier cache setup).
77
+ *
78
+ * When passed to `MonSQLizeOptions.cache`, the framework automatically creates a MultiLevelCache:
79
+ * - `local`: always uses the built-in memory cache (accepts MemoryCacheOptions only)
80
+ * - `remote`: accepts a CacheLike instance (recommended for production) or a config object
81
+ * that degrades to an in-memory placeholder
82
+ * - `policy`: write policy and backfill policy configuration
83
+ * @since v1.1.0
84
+ */
85
+ export interface MultiLevelCacheOptions {
86
+ multiLevel: true;
87
+ local?: MemoryCacheOptions;
88
+ remote?: CacheLike | (MemoryCacheOptions & { timeoutMs?: number });
89
+ policy?: MultiLevelCachePolicy;
90
+ publish?: MultiLevelPublish;
91
+ }
92
+
93
+ export type MultiLevelInvalidationMessage = {
94
+ type: 'del' | 'delete' | 'invalidateKey';
95
+ key: string;
96
+ ts: number;
97
+ } | {
98
+ type: 'delPattern';
99
+ pattern: string;
100
+ ts: number;
101
+ } | {
102
+ type: 'invalidateTag';
103
+ tag: string;
104
+ ts: number;
105
+ };
106
+
107
+ export type MultiLevelPublish = (msg: MultiLevelInvalidationMessage) => void;
108
+
109
+ export declare class MemoryCache {
110
+ constructor(options?: MemoryCacheOptions);
111
+ setLockManager(lockManager: CacheLockLike): void;
112
+ getLockManager(): CacheLockLike | null;
113
+ get<T = unknown>(key: string): T | undefined;
114
+ set(key: string, value: unknown, ttl?: number, options?: CacheSetOptions): void;
115
+ del(key: string): boolean;
116
+ exists(key: string): boolean;
117
+ has(key: string): boolean;
118
+ getMany(keys: string[]): Record<string, unknown>;
119
+ setMany(values: Record<string, unknown>, ttl?: number): boolean;
120
+ delMany(keys: string[]): number;
121
+ clear(): void;
122
+ keys(pattern?: string): string[];
123
+ delPattern(pattern: string): number;
124
+ getRemainingTtl(key: string): CacheRemainingTtl | undefined;
125
+ getRemainingTtlMany(keys: string[]): Record<string, CacheRemainingTtl>;
126
+ getStats(): CacheStats;
127
+ resetStats(): void;
128
+ invalidateByTag(tag: string): void;
129
+ destroy(): void;
130
+ }
131
+
132
+ export declare class MultiLevelCache {
133
+ constructor(options: {
134
+ local: CacheLike;
135
+ remote?: CacheLike;
136
+ writePolicy?: 'both' | 'local-first-async-remote';
137
+ backfillOnRemoteHit?: boolean;
138
+ remoteTimeoutMs?: number;
139
+ publish?: MultiLevelPublish;
140
+ remoteInvalidationErrors?: 'ignore' | 'throw';
141
+ });
142
+ get<T = unknown>(key: string): Promise<T | undefined>;
143
+ set(key: string, value: unknown, ttl?: number, options?: CacheSetOptions): Promise<void>;
144
+ del(key: string): Promise<boolean>;
145
+ exists(key: string): Promise<boolean>;
146
+ has(key: string): Promise<boolean>;
147
+ clear(): Promise<void>;
148
+ getMany(keys: string[]): Promise<Record<string, unknown>>;
149
+ setMany(values: Record<string, unknown>, ttl?: number): Promise<boolean>;
150
+ delMany(keys: string[]): Promise<number>;
151
+ delPattern(pattern: string): Promise<number>;
152
+ keys(pattern?: string): Promise<string[]>;
153
+ invalidateByTag(tag: string): void | Promise<void>;
154
+ setPublish(publish: MultiLevelPublish): void;
155
+ setLockManager(lockManager: CacheLockLike): void;
156
+ getStats(): CacheStats;
157
+ resetStats(): void;
158
+ destroy(): void;
159
+ }
160
+
161
+ export type RedisCacheAdapterOptions = HubRedisCacheAdapterOptions;
162
+ export type RedisLike = object;
163
+
164
+ /**
165
+ * Adapts a v1-style CacheLike object to the v2 CacheLike interface.
166
+ *
167
+ * v2 requires a `has()` method that was absent in v1. This helper adds it
168
+ * by delegating to the existing `exists()`. All other methods are forwarded as-is.
169
+ *
170
+ * @param v1Cache - A v1 custom cache implementation missing `has()`.
171
+ * @returns A fully v2-compatible `CacheLike` instance.
172
+ * @example
173
+ * ```ts
174
+ * const v2Cache = adaptLegacyCacheLike(myV1Cache);
175
+ * const msq = new MonSQLize({ cache: v2Cache });
176
+ * ```
177
+ */
178
+ export declare function adaptLegacyCacheLike(v1Cache: Omit<CacheLike, 'has'>): CacheLike;
179
+
180
+ /** Re-exported alias so consumers can type the return value of `createRedisCacheAdapter`. */
181
+ export type RedisCacheAdapter = HubRedisCacheAdapter;
182
+
183
+ export declare function createRedisCacheAdapter(
184
+ redisUrlOrInstance: string | object | undefined,
185
+ options?: RedisCacheAdapterOptions,
186
+ ): HubRedisCacheAdapter;
187
+
188
+ export type { LockOptions, LockStats, MongoSession, TransactionOptions, TransactionStats };
189
+
190
+ export type DistributedCacheInvalidatorOptions = HubDistributedInvalidatorOptions;
191
+ export type DistributedCacheInvalidatorStats = HubInvalidatorStats;
192
+
193
+ export declare class DistributedCacheInvalidator {
194
+ constructor(options: DistributedCacheInvalidatorOptions);
195
+ invalidate(pattern: string): Promise<void>;
196
+ invalidateKey(key: string): Promise<void>;
197
+ getStats(): HubInvalidatorStats;
198
+ close(): Promise<void>;
199
+ }
200
+
201
+ export type {
202
+ ConnectionPoolManagerOptions,
203
+ FallbackStrategy,
204
+ PoolConfig,
205
+ PoolHealthStatus,
206
+ PoolRole,
207
+ PoolStats,
208
+ PoolStrategy,
209
+ ResumeTokenConfig,
210
+ SagaDefinition,
211
+ SagaOrchestratorOptions,
212
+ SagaResult,
213
+ SagaStats,
214
+ SagaStep,
215
+ SlowQueryLogConfig,
216
+ SlowQueryLogConfigInput,
217
+ SlowQueryLogEntry,
218
+ SlowQueryLogFilter,
219
+ SlowQueryLogQueryOptions,
220
+ SlowQueryLogRecord,
221
+ SlowQueryLogStorageConfig,
222
+ SyncChangeEvent,
223
+ SyncConfig,
224
+ SyncStats,
225
+ SyncTargetConfig,
226
+ SyncTargetHealthCheckConfig,
227
+ };
228
+
229
+ export declare function validateSyncConfig(config: SyncConfig): void;
230
+ export declare function generateQueryHash(input: unknown): string;
231
+
232
+ export type WithCacheOptions<
233
+ T extends (...args: any[]) => Promise<any> = (...args: unknown[]) => Promise<unknown>,
234
+ > = HubWithCacheOptions<T>;
235
+
236
+ export type CacheStats = HubCacheStats;
237
+
238
+ export interface WithCacheStats extends HubWithCacheStats {
239
+ calls: number;
240
+ totalTime: number;
241
+ avgTime: number;
242
+ }
243
+
244
+ export interface FunctionCacheStats extends HubFunctionCacheStats {
245
+ calls: number;
246
+ totalTime: number;
247
+ avgTime: number;
248
+ }
249
+
250
+ export type CachedFunction<TArgs extends unknown[] = unknown[], TResult = unknown> = HubWrappedFunction<(...args: TArgs) => Promise<TResult>> & {
251
+ /** @deprecated Use `stats()`. v1 backward-compat alias. */
252
+ getCacheStats(): WithCacheStats;
253
+ stats(): WithCacheStats;
254
+ };
255
+
256
+ export interface FunctionCacheOptions extends HubFunctionCacheOptions {
257
+ /** @deprecated v1 alias for `ttl`. Use `ttl` instead. */
258
+ defaultTTL?: number;
259
+ }
260
+
261
+ /**
262
+ * @deprecated Retained for v1 compatibility. Non-database function caching is no longer a recommended monSQLize feature path;
263
+ * use `cache-hub` directly or an application-owned cache layer for new generic function-cache usage.
264
+ */
265
+ export declare function withCache<TArgs extends unknown[], TResult>(
266
+ fn: (...args: TArgs) => Promise<TResult>,
267
+ options?: WithCacheOptions<(...args: TArgs) => Promise<TResult>>,
268
+ ): CachedFunction<TArgs, TResult>;
269
+
270
+ /**
271
+ * @deprecated Retained for v1 compatibility. Non-database function caching is no longer a recommended monSQLize feature path;
272
+ * use `cache-hub` directly or an application-owned cache layer for new generic function-cache usage.
273
+ */
274
+ export declare class FunctionCache {
275
+ constructor(cacheOrDb?: CacheLike | { getCache(): CacheLike; }, options?: FunctionCacheOptions);
276
+ register(name: string, fn: (...args: unknown[]) => Promise<unknown>, options?: {
277
+ ttl?: number;
278
+ keyBuilder?: (...args: unknown[]) => string;
279
+ namespace?: string;
280
+ condition?: (result: unknown) => boolean;
281
+ }): Promise<void>;
282
+ execute(name: string, ...args: unknown[]): Promise<unknown>;
283
+ invalidate(name: string, ...args: unknown[]): Promise<void>;
284
+ invalidatePattern(pattern: string): Promise<number>;
285
+ getStats(name?: string): FunctionCacheStats | Record<string, FunctionCacheStats> | null;
286
+ list(): string[];
287
+ resetStats(name?: string): void;
288
+ clear(): void;
289
+ }
290
+
291
+ export declare class Model {
292
+ static define<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
293
+ static get<TDocument = any>(name: string): RegisteredModel<TDocument> | undefined;
294
+ static has(name: string): boolean;
295
+ static list(): string[];
296
+ static undefine(name: string): boolean;
297
+ static redefine<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
298
+ static _clear(): void;
299
+ }
300
+
301
+ export declare class ModelInstance<TDocument = any> implements ModelInstanceContract<TDocument> {
302
+ private constructor(...args: unknown[]);
303
+ readonly collectionName: string;
304
+ readonly dbName: string;
305
+ readonly poolName?: string;
306
+ readonly definition: ModelDefinition<TDocument>;
307
+ getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; pool?: string; };
308
+ getRelations(): Record<string, RelationConfig>;
309
+ getEnums(): Record<string, string>;
310
+ raw(): unknown;
311
+ find(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
312
+ findOne(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
313
+ findOneById(id: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
314
+ findById(id: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
315
+ findByIds(ids: unknown[], options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
316
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model.mjs').PopulateProxy<{
317
+ items: Array<import('./model.mjs').ModelDocument<TDocument>>;
318
+ pageInfo: import('./model.mjs').ModelInstance<TDocument> extends {
319
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
320
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
321
+ totals: import('./model.mjs').ModelInstance<TDocument> extends {
322
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model.mjs').PopulateProxy<infer TResult>;
323
+ } ? TResult extends { totals: infer TTotals } ? TTotals : never : never;
324
+ meta?: import('./collection.mjs').MetaInfo;
325
+ }>;
326
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<{
327
+ items: Array<import('./model.mjs').ModelDocument<TDocument>>;
328
+ pageInfo: import('./model.mjs').ModelInstance<TDocument> extends {
329
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
330
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
331
+ totals?: import('./model.mjs').ModelInstance<TDocument> extends {
332
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
333
+ } ? TResult extends { totals?: infer TTotals } ? TTotals : never : never;
334
+ meta?: import('./collection.mjs').MetaInfo;
335
+ }>;
336
+ findAndCount(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<{ data: Array<import('./model.mjs').ModelDocument<TDocument>>; total: number; }>;
337
+ count(query?: unknown, options?: unknown): Promise<number>;
338
+ insertOne(document?: unknown, options?: unknown): Promise<{ acknowledged: boolean; insertedId: any; }>;
339
+ insertMany(documents?: unknown[], options?: unknown): Promise<InsertManyResult>;
340
+ updateOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
341
+ updateMany(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
342
+ replaceOne(filter?: unknown, replacement?: unknown, options?: unknown): Promise<UpdateResult>;
343
+ findOneAndUpdate(filter?: unknown, update?: unknown, options?: unknown): Promise<TDocument | null>;
344
+ findOneAndDelete(filter?: unknown, options?: unknown): Promise<TDocument | null>;
345
+ upsertOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
346
+ deleteOne(filter?: unknown, options?: unknown): Promise<DeleteResult>;
347
+ deleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
348
+ createIndex(keys: unknown, options?: unknown): Promise<IndexCreateResult>;
349
+ createIndexes(specs: Array<{ key: unknown; } & Record<string, unknown>>): Promise<string[]>;
350
+ listIndexes(): Promise<Record<string, unknown>[]>;
351
+ ensureIndexes(options?: ModelEnsureIndexesOptions): Promise<ModelIndexEnsureResult>;
352
+ dropIndex(name: string): Promise<unknown>;
353
+ dropIndexes(): Promise<unknown>;
354
+ prewarmBookmarks(keyDims?: unknown, pages?: number[]): Promise<BookmarkPrewarmResult>;
355
+ listBookmarks(keyDims?: unknown): Promise<BookmarkListResult>;
356
+ clearBookmarks(keyDims?: unknown): Promise<BookmarkClearResult>;
357
+ distinct(key: string, query?: unknown, options?: unknown): Promise<unknown[]>;
358
+ aggregate(pipeline?: unknown[], options?: unknown): Promise<unknown[]>;
359
+ stream(query?: unknown, options?: unknown): NodeJS.ReadableStream;
360
+ explain(query?: unknown, options?: unknown): Promise<unknown>;
361
+ invalidate(op?: 'find' | 'findOne' | 'count' | 'findPage' | 'aggregate' | 'distinct'): Promise<number>;
362
+ dropCollection(): Promise<boolean>;
363
+ createCollection(name?: string, options?: Record<string, unknown>): Promise<boolean>;
364
+ createView(name: string, source: string, pipeline?: unknown[]): Promise<boolean>;
365
+ indexStats(): Promise<unknown[]>;
366
+ setValidator(validator: unknown, options?: { validationLevel?: string; validationAction?: string }): Promise<{ ok: number; collection: string }>;
367
+ setValidationLevel(level: 'off' | 'moderate' | 'strict' | string): Promise<{ ok: number; validationLevel: string }>;
368
+ setValidationAction(action: 'error' | 'warn' | string): Promise<{ ok: number; validationAction: string }>;
369
+ getValidator(): Promise<{ validator: Record<string, unknown> | null; validationLevel: string; validationAction: string }>;
370
+ stats(options?: { scale?: number }): Promise<{ ns: string; count: number; size: number; storageSize: number; totalIndexSize: number; nindexes: number; avgObjSize?: number; scaleFactor?: number }>;
371
+ renameCollection(newName: string, options?: { dropTarget?: boolean }): Promise<{ renamed: boolean; from: string; to: string }>;
372
+ collMod(modifications: Record<string, unknown>): Promise<Record<string, unknown>>;
373
+ convertToCapped(size: number, options?: { max?: number }): Promise<{ ok: number; collection: string; capped: boolean; size: number }>;
374
+ watch(pipeline?: unknown[], options?: unknown): import('mongodb').ChangeStream;
375
+ validate(document?: unknown): import('./model.mjs').ValidationResult;
376
+ findOneAndReplace(filter?: unknown, replacement?: unknown, options?: unknown): Promise<TDocument | null>;
377
+ incrementOne(filter?: unknown, field?: string | Record<string, number>, increment?: number, options?: unknown): Promise<IncrementOneResult<TDocument>>;
378
+ findWithDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
379
+ findOnlyDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
380
+ findOneWithDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
381
+ restore(filter?: unknown, options?: unknown): Promise<import('./model.mjs').RestoreResult>;
382
+ restoreMany(filter?: unknown, options?: unknown): Promise<import('./model.mjs').RestoreResult>;
383
+ forceDelete(filter?: unknown, options?: unknown): Promise<DeleteResult>;
384
+ forceDeleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
385
+ findOneOnlyDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
386
+ countWithDeleted(query?: unknown, options?: unknown): Promise<number>;
387
+ countOnlyDeleted(query?: unknown, options?: unknown): Promise<number>;
388
+ insertBatch(docs: unknown[], options?: unknown): Promise<InsertBatchResult>;
389
+ updateBatch(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateBatchResult>;
390
+ deleteBatch(filter?: unknown, options?: unknown): Promise<DeleteBatchResult>;
391
+ }
392
+
393
+ export declare const expr: ExpressionFunction;
394
+ export declare const createExpression: ExpressionFunction;
395
+ export declare function isExpressionObject(value: unknown): value is ExpressionObject;
396
+ export declare function hasExpressionInObject(value: unknown): boolean;
397
+ export declare function hasExpressionInPipeline(pipeline: unknown): boolean;
398
+ /** Compile expression objects in a MongoDB pipeline into real operators. */
399
+ export declare function compilePipelineExpressions<TPipeline>(pipeline: TPipeline): TPipeline;
400
+
@@ -14,22 +14,22 @@ import type {
14
14
  CacheStats as HubCacheStats,
15
15
  LockManager as HubCacheLockLike,
16
16
  MemoryCacheOptions as HubMemoryCacheOptions,
17
- } from 'cache-hub';
17
+ } from 'cache-hub' with { "resolution-mode": "import" };
18
18
  import type {
19
19
  RedisCacheAdapter as HubRedisCacheAdapter,
20
20
  RedisCacheAdapterOptions as HubRedisCacheAdapterOptions,
21
- } from 'cache-hub/redis';
21
+ } from 'cache-hub/redis' with { "resolution-mode": "import" };
22
22
  import type {
23
23
  DistributedInvalidatorOptions as HubDistributedInvalidatorOptions,
24
24
  InvalidatorStats as HubInvalidatorStats,
25
- } from 'cache-hub/distributed';
25
+ } from 'cache-hub/distributed' with { "resolution-mode": "import" };
26
26
  import type {
27
27
  FunctionCacheOptions as HubFunctionCacheOptions,
28
28
  FunctionCacheStats as HubFunctionCacheStats,
29
29
  WithCacheOptions as HubWithCacheOptions,
30
30
  WithCacheStats as HubWithCacheStats,
31
31
  WrappedFunction as HubWrappedFunction,
32
- } from 'cache-hub/function-cache';
32
+ } from 'cache-hub/function-cache' with { "resolution-mode": "import" };
33
33
 
34
34
  export { Lock, LockAcquireError, LockTimeoutError, LockManager } from './lock';
35
35
  export { ConnectionPoolManager } from './pool';
@@ -91,6 +91,10 @@ export interface MultiLevelCacheOptions {
91
91
  }
92
92
 
93
93
  export type MultiLevelInvalidationMessage = {
94
+ type: 'del' | 'delete' | 'invalidateKey';
95
+ key: string;
96
+ ts: number;
97
+ } | {
94
98
  type: 'delPattern';
95
99
  pattern: string;
96
100
  ts: number;
@@ -189,6 +193,7 @@ export type DistributedCacheInvalidatorStats = HubInvalidatorStats;
189
193
  export declare class DistributedCacheInvalidator {
190
194
  constructor(options: DistributedCacheInvalidatorOptions);
191
195
  invalidate(pattern: string): Promise<void>;
196
+ invalidateKey(key: string): Promise<void>;
192
197
  getStats(): HubInvalidatorStats;
193
198
  close(): Promise<void>;
194
199
  }
@@ -253,11 +258,19 @@ export interface FunctionCacheOptions extends HubFunctionCacheOptions {
253
258
  defaultTTL?: number;
254
259
  }
255
260
 
261
+ /**
262
+ * @deprecated Retained for v1 compatibility. Non-database function caching is no longer a recommended monSQLize feature path;
263
+ * use `cache-hub` directly or an application-owned cache layer for new generic function-cache usage.
264
+ */
256
265
  export declare function withCache<TArgs extends unknown[], TResult>(
257
266
  fn: (...args: TArgs) => Promise<TResult>,
258
267
  options?: WithCacheOptions<(...args: TArgs) => Promise<TResult>>,
259
268
  ): CachedFunction<TArgs, TResult>;
260
269
 
270
+ /**
271
+ * @deprecated Retained for v1 compatibility. Non-database function caching is no longer a recommended monSQLize feature path;
272
+ * use `cache-hub` directly or an application-owned cache layer for new generic function-cache usage.
273
+ */
261
274
  export declare class FunctionCache {
262
275
  constructor(cacheOrDb?: CacheLike | { getCache(): CacheLike; }, options?: FunctionCacheOptions);
263
276
  register(name: string, fn: (...args: unknown[]) => Promise<unknown>, options?: {
@@ -291,7 +304,7 @@ export declare class ModelInstance<TDocument = any> implements ModelInstanceCont
291
304
  readonly dbName: string;
292
305
  readonly poolName?: string;
293
306
  readonly definition: ModelDefinition<TDocument>;
294
- getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; };
307
+ getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; pool?: string; };
295
308
  getRelations(): Record<string, RelationConfig>;
296
309
  getEnums(): Record<string, string>;
297
310
  raw(): unknown;
@@ -0,0 +1,148 @@
1
+ import type { LoggerLike } from './base.mjs';
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
+ /** Abort signal for the current step. Timeout cancellation is cooperative; the step must observe this signal. */
18
+ readonly signal?: AbortSignal;
19
+ /** Store a value in the shared step context. */
20
+ set(key: string, value: any): void;
21
+ /** Retrieve a previously stored value. v1 compat — default generic is `any` to match v1 callers that did not annotate. */
22
+ get<T = any>(key: string): T | undefined;
23
+ /** Return `true` if a value exists for `key`. */
24
+ has(key: string): boolean;
25
+ /** Return all stored key-value pairs. */
26
+ getAll(): Record<string, any>;
27
+ /**
28
+ * Ordered list of completed step names.
29
+ * @deprecated v1 compat — populated automatically by the orchestrator.
30
+ */
31
+ readonly completedSteps: string[];
32
+ /**
33
+ * Mark a step as completed and record its result.
34
+ * @deprecated v1 compat — called automatically by the orchestrator. Use `ctx.get(stepName)` to retrieve step results.
35
+ */
36
+ markStepCompleted(stepName: string, result: unknown): void;
37
+ /**
38
+ * Return the result of a previously completed step.
39
+ * @deprecated v1 compat — use `ctx.get(stepName)` instead.
40
+ */
41
+ getStepResult(stepName: string): unknown;
42
+ /**
43
+ * Return an ordered copy of completed step names.
44
+ * @deprecated v1 compat — use `ctx.getAll()` instead.
45
+ */
46
+ getCompletedSteps(): string[];
47
+ }
48
+
49
+ /** A single step within a Saga, consisting of a forward action and an optional compensation handler. */
50
+ export interface SagaStep {
51
+ name: string;
52
+ execute: (context: SagaContext) => Promise<any>;
53
+ /** 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. */
54
+ compensate: (context: SagaContext, result?: any) => Promise<void>;
55
+ /** Per-step timeout in milliseconds (overrides Saga-level timeout). */
56
+ timeout?: number;
57
+ /** Number of retry attempts on ordinary step failure. Timed-out attempts are never retried. */
58
+ retries?: number;
59
+ }
60
+
61
+ /** Definition of a Saga, including its ordered steps and execution configuration. */
62
+ export interface SagaDefinition {
63
+ name: string;
64
+ steps: SagaStep[];
65
+ /** Default timeout for each step in milliseconds; a step-level timeout overrides it. */
66
+ timeout?: number;
67
+ /** Whether to emit detailed execution logs. */
68
+ logging?: boolean;
69
+ }
70
+
71
+ /** Result returned after a Saga execution (success or failure). */
72
+ export interface SagaResult {
73
+ /** v2 field — present when emitted by v2 runtime; v1 fixtures may omit. */
74
+ sagaId?: string;
75
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
76
+ executionId: string;
77
+ /** v2 field — present when emitted by v2 runtime; v1 fixtures may omit. */
78
+ sagaName?: string;
79
+ success: boolean;
80
+ /** The return value of the last completed step (success path). */
81
+ result?: any;
82
+ /** v1-compatible Error object (set when success is false). */
83
+ error?: Error;
84
+ /** v2 compatibility alias for message-only consumers. */
85
+ errorMessage?: string;
86
+ /** Ordered list of completed step names. */
87
+ completedSteps: string[];
88
+ /** v2 compatibility alias for count-only consumers. */
89
+ completedStepCount?: number;
90
+ /** @deprecated Alias of `completedSteps` retained for v2 callers. */
91
+ completedStepNames?: string[];
92
+ /** Names of steps whose compensation handlers were invoked. v1 compat — runtime always populates an array (empty on success). */
93
+ compensatedSteps: string[];
94
+ /** Total execution duration in milliseconds. */
95
+ duration: number;
96
+ /** Original Error object (failure path only). v1 compat — `error` field is a string in v2. */
97
+ errorCause?: any;
98
+ /** Present on the failure path when at least one completed step has a compensate function. */
99
+ compensation?: {
100
+ success: boolean;
101
+ results: Array<{ stepName: string; success: boolean; reason?: string; error?: string; duration?: number; }>;
102
+ };
103
+ }
104
+
105
+ /** Options for constructing a `SagaOrchestrator`. */
106
+ export interface SagaOrchestratorOptions {
107
+ logger?: LoggerLike | null;
108
+ cache?: SagaMetadataCache | null;
109
+ }
110
+
111
+ /** Aggregate statistics for a `SagaOrchestrator` instance. */
112
+ export interface SagaStats {
113
+ totalExecutions: number;
114
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
115
+ successfulExecutions?: number;
116
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
117
+ failedExecutions?: number;
118
+ /** @since v1.0.8 — v2 extension; v1 fixtures may omit. */
119
+ compensatedExecutions?: number;
120
+ successRate?: string;
121
+ storageMode?: string;
122
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
123
+ successCount: number;
124
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
125
+ failureCount: number;
126
+ /** Primary v1 field — always present in both v1 and v2 runtime output. */
127
+ compensationCount: number;
128
+ }
129
+
130
+ /**
131
+ * Legacy-compatible in-process Saga orchestrator with compensation support.
132
+ * @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration.
133
+ */
134
+ export declare class SagaOrchestrator {
135
+ constructor(options?: SagaOrchestratorOptions);
136
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
137
+ define(definition: SagaDefinition): void;
138
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
139
+ defineSaga(definition: SagaDefinition): Promise<SagaDefinition>;
140
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
141
+ execute(name: string, data: any): Promise<SagaResult>;
142
+ /** Return the definition for a registered Saga by name. */
143
+ getSaga(name: string): SagaDefinition | undefined;
144
+ /** Return the names of all registered Sagas. */
145
+ listSagas(): string[];
146
+ /** Return aggregate execution statistics. */
147
+ getStats(): SagaStats;
148
+ }
@@ -14,6 +14,8 @@ export interface SagaContext {
14
14
  readonly sagaId?: string;
15
15
  /** Initial data passed to `executeSaga`. */
16
16
  readonly data: any;
17
+ /** Abort signal for the current step. Timeout cancellation is cooperative; the step must observe this signal. */
18
+ readonly signal?: AbortSignal;
17
19
  /** Store a value in the shared step context. */
18
20
  set(key: string, value: any): void;
19
21
  /** Retrieve a previously stored value. v1 compat — default generic is `any` to match v1 callers that did not annotate. */
@@ -52,7 +54,7 @@ export interface SagaStep {
52
54
  compensate: (context: SagaContext, result?: any) => Promise<void>;
53
55
  /** Per-step timeout in milliseconds (overrides Saga-level timeout). */
54
56
  timeout?: number;
55
- /** Number of retry attempts on step failure. */
57
+ /** Number of retry attempts on ordinary step failure. Timed-out attempts are never retried. */
56
58
  retries?: number;
57
59
  }
58
60
 
@@ -60,7 +62,7 @@ export interface SagaStep {
60
62
  export interface SagaDefinition {
61
63
  name: string;
62
64
  steps: SagaStep[];
63
- /** Overall Saga timeout in milliseconds. */
65
+ /** Default timeout for each step in milliseconds; a step-level timeout overrides it. */
64
66
  timeout?: number;
65
67
  /** Whether to emit detailed execution logs. */
66
68
  logging?: boolean;
@@ -125,14 +127,17 @@ export interface SagaStats {
125
127
  compensationCount: number;
126
128
  }
127
129
 
128
- /** Orchestrates the execution and compensation of multi-step Saga workflows. */
130
+ /**
131
+ * Legacy-compatible in-process Saga orchestrator with compensation support.
132
+ * @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration.
133
+ */
129
134
  export declare class SagaOrchestrator {
130
135
  constructor(options?: SagaOrchestratorOptions);
131
- /** Register a Saga definition (sync). */
136
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
132
137
  define(definition: SagaDefinition): void;
133
- /** Register a Saga definition (async; returns the registered definition). */
138
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
134
139
  defineSaga(definition: SagaDefinition): Promise<SagaDefinition>;
135
- /** Execute the named Saga with the given initial data. */
140
+ /** @deprecated Saga APIs are retained for compatibility. Prefer application/framework-level workflow orchestration. */
136
141
  execute(name: string, data: any): Promise<SagaResult>;
137
142
  /** Return the definition for a registered Saga by name. */
138
143
  getSaga(name: string): SagaDefinition | undefined;