monsqlize 2.0.4 → 2.0.6

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.
@@ -0,0 +1,387 @@
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: 'delPattern';
95
+ pattern: string;
96
+ ts: number;
97
+ } | {
98
+ type: 'invalidateTag';
99
+ tag: string;
100
+ ts: number;
101
+ };
102
+
103
+ export type MultiLevelPublish = (msg: MultiLevelInvalidationMessage) => void;
104
+
105
+ export declare class MemoryCache {
106
+ constructor(options?: MemoryCacheOptions);
107
+ setLockManager(lockManager: CacheLockLike): void;
108
+ getLockManager(): CacheLockLike | null;
109
+ get<T = unknown>(key: string): T | undefined;
110
+ set(key: string, value: unknown, ttl?: number, options?: CacheSetOptions): void;
111
+ del(key: string): boolean;
112
+ exists(key: string): boolean;
113
+ has(key: string): boolean;
114
+ getMany(keys: string[]): Record<string, unknown>;
115
+ setMany(values: Record<string, unknown>, ttl?: number): boolean;
116
+ delMany(keys: string[]): number;
117
+ clear(): void;
118
+ keys(pattern?: string): string[];
119
+ delPattern(pattern: string): number;
120
+ getRemainingTtl(key: string): CacheRemainingTtl | undefined;
121
+ getRemainingTtlMany(keys: string[]): Record<string, CacheRemainingTtl>;
122
+ getStats(): CacheStats;
123
+ resetStats(): void;
124
+ invalidateByTag(tag: string): void;
125
+ destroy(): void;
126
+ }
127
+
128
+ export declare class MultiLevelCache {
129
+ constructor(options: {
130
+ local: CacheLike;
131
+ remote?: CacheLike;
132
+ writePolicy?: 'both' | 'local-first-async-remote';
133
+ backfillOnRemoteHit?: boolean;
134
+ remoteTimeoutMs?: number;
135
+ publish?: MultiLevelPublish;
136
+ remoteInvalidationErrors?: 'ignore' | 'throw';
137
+ });
138
+ get<T = unknown>(key: string): Promise<T | undefined>;
139
+ set(key: string, value: unknown, ttl?: number, options?: CacheSetOptions): Promise<void>;
140
+ del(key: string): Promise<boolean>;
141
+ exists(key: string): Promise<boolean>;
142
+ has(key: string): Promise<boolean>;
143
+ clear(): Promise<void>;
144
+ getMany(keys: string[]): Promise<Record<string, unknown>>;
145
+ setMany(values: Record<string, unknown>, ttl?: number): Promise<boolean>;
146
+ delMany(keys: string[]): Promise<number>;
147
+ delPattern(pattern: string): Promise<number>;
148
+ keys(pattern?: string): Promise<string[]>;
149
+ invalidateByTag(tag: string): void | Promise<void>;
150
+ setPublish(publish: MultiLevelPublish): void;
151
+ setLockManager(lockManager: CacheLockLike): void;
152
+ getStats(): CacheStats;
153
+ resetStats(): void;
154
+ destroy(): void;
155
+ }
156
+
157
+ export type RedisCacheAdapterOptions = HubRedisCacheAdapterOptions;
158
+ export type RedisLike = object;
159
+
160
+ /**
161
+ * Adapts a v1-style CacheLike object to the v2 CacheLike interface.
162
+ *
163
+ * v2 requires a `has()` method that was absent in v1. This helper adds it
164
+ * by delegating to the existing `exists()`. All other methods are forwarded as-is.
165
+ *
166
+ * @param v1Cache - A v1 custom cache implementation missing `has()`.
167
+ * @returns A fully v2-compatible `CacheLike` instance.
168
+ * @example
169
+ * ```ts
170
+ * const v2Cache = adaptLegacyCacheLike(myV1Cache);
171
+ * const msq = new MonSQLize({ cache: v2Cache });
172
+ * ```
173
+ */
174
+ export declare function adaptLegacyCacheLike(v1Cache: Omit<CacheLike, 'has'>): CacheLike;
175
+
176
+ /** Re-exported alias so consumers can type the return value of `createRedisCacheAdapter`. */
177
+ export type RedisCacheAdapter = HubRedisCacheAdapter;
178
+
179
+ export declare function createRedisCacheAdapter(
180
+ redisUrlOrInstance: string | object | undefined,
181
+ options?: RedisCacheAdapterOptions,
182
+ ): HubRedisCacheAdapter;
183
+
184
+ export type { LockOptions, LockStats, MongoSession, TransactionOptions, TransactionStats };
185
+
186
+ export type DistributedCacheInvalidatorOptions = HubDistributedInvalidatorOptions;
187
+ export type DistributedCacheInvalidatorStats = HubInvalidatorStats;
188
+
189
+ export declare class DistributedCacheInvalidator {
190
+ constructor(options: DistributedCacheInvalidatorOptions);
191
+ invalidate(pattern: string): Promise<void>;
192
+ getStats(): HubInvalidatorStats;
193
+ close(): Promise<void>;
194
+ }
195
+
196
+ export type {
197
+ ConnectionPoolManagerOptions,
198
+ FallbackStrategy,
199
+ PoolConfig,
200
+ PoolHealthStatus,
201
+ PoolRole,
202
+ PoolStats,
203
+ PoolStrategy,
204
+ ResumeTokenConfig,
205
+ SagaDefinition,
206
+ SagaOrchestratorOptions,
207
+ SagaResult,
208
+ SagaStats,
209
+ SagaStep,
210
+ SlowQueryLogConfig,
211
+ SlowQueryLogConfigInput,
212
+ SlowQueryLogEntry,
213
+ SlowQueryLogFilter,
214
+ SlowQueryLogQueryOptions,
215
+ SlowQueryLogRecord,
216
+ SlowQueryLogStorageConfig,
217
+ SyncChangeEvent,
218
+ SyncConfig,
219
+ SyncStats,
220
+ SyncTargetConfig,
221
+ SyncTargetHealthCheckConfig,
222
+ };
223
+
224
+ export declare function validateSyncConfig(config: SyncConfig): void;
225
+ export declare function generateQueryHash(input: unknown): string;
226
+
227
+ export type WithCacheOptions<
228
+ T extends (...args: any[]) => Promise<any> = (...args: unknown[]) => Promise<unknown>,
229
+ > = HubWithCacheOptions<T>;
230
+
231
+ export type CacheStats = HubCacheStats;
232
+
233
+ export interface WithCacheStats extends HubWithCacheStats {
234
+ calls: number;
235
+ totalTime: number;
236
+ avgTime: number;
237
+ }
238
+
239
+ export interface FunctionCacheStats extends HubFunctionCacheStats {
240
+ calls: number;
241
+ totalTime: number;
242
+ avgTime: number;
243
+ }
244
+
245
+ export type CachedFunction<TArgs extends unknown[] = unknown[], TResult = unknown> = HubWrappedFunction<(...args: TArgs) => Promise<TResult>> & {
246
+ /** @deprecated Use `stats()`. v1 backward-compat alias. */
247
+ getCacheStats(): WithCacheStats;
248
+ stats(): WithCacheStats;
249
+ };
250
+
251
+ export interface FunctionCacheOptions extends HubFunctionCacheOptions {
252
+ /** @deprecated v1 alias for `ttl`. Use `ttl` instead. */
253
+ defaultTTL?: number;
254
+ }
255
+
256
+ export declare function withCache<TArgs extends unknown[], TResult>(
257
+ fn: (...args: TArgs) => Promise<TResult>,
258
+ options?: WithCacheOptions<(...args: TArgs) => Promise<TResult>>,
259
+ ): CachedFunction<TArgs, TResult>;
260
+
261
+ export declare class FunctionCache {
262
+ constructor(cacheOrDb?: CacheLike | { getCache(): CacheLike; }, options?: FunctionCacheOptions);
263
+ register(name: string, fn: (...args: unknown[]) => Promise<unknown>, options?: {
264
+ ttl?: number;
265
+ keyBuilder?: (...args: unknown[]) => string;
266
+ namespace?: string;
267
+ condition?: (result: unknown) => boolean;
268
+ }): Promise<void>;
269
+ execute(name: string, ...args: unknown[]): Promise<unknown>;
270
+ invalidate(name: string, ...args: unknown[]): Promise<void>;
271
+ invalidatePattern(pattern: string): Promise<number>;
272
+ getStats(name?: string): FunctionCacheStats | Record<string, FunctionCacheStats> | null;
273
+ list(): string[];
274
+ resetStats(name?: string): void;
275
+ clear(): void;
276
+ }
277
+
278
+ export declare class Model {
279
+ static define<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
280
+ static get<TDocument = any>(name: string): RegisteredModel<TDocument> | undefined;
281
+ static has(name: string): boolean;
282
+ static list(): string[];
283
+ static undefine(name: string): boolean;
284
+ static redefine<TDocument = any>(name: string, definition: ModelDefinition<TDocument>): void;
285
+ static _clear(): void;
286
+ }
287
+
288
+ export declare class ModelInstance<TDocument = any> implements ModelInstanceContract<TDocument> {
289
+ private constructor(...args: unknown[]);
290
+ readonly collectionName: string;
291
+ readonly dbName: string;
292
+ readonly poolName?: string;
293
+ readonly definition: ModelDefinition<TDocument>;
294
+ getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; };
295
+ getRelations(): Record<string, RelationConfig>;
296
+ getEnums(): Record<string, string>;
297
+ raw(): unknown;
298
+ find(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
299
+ findOne(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
300
+ findOneById(id: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
301
+ findById(id: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
302
+ findByIds(ids: unknown[], options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
303
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model.mjs').PopulateProxy<{
304
+ items: Array<import('./model.mjs').ModelDocument<TDocument>>;
305
+ pageInfo: import('./model.mjs').ModelInstance<TDocument> extends {
306
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
307
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
308
+ totals: import('./model.mjs').ModelInstance<TDocument> extends {
309
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): import('./model.mjs').PopulateProxy<infer TResult>;
310
+ } ? TResult extends { totals: infer TTotals } ? TTotals : never : never;
311
+ meta?: import('./collection.mjs').MetaInfo;
312
+ }>;
313
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<{
314
+ items: Array<import('./model.mjs').ModelDocument<TDocument>>;
315
+ pageInfo: import('./model.mjs').ModelInstance<TDocument> extends {
316
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
317
+ } ? TResult extends { pageInfo: infer TPageInfo } ? TPageInfo : never : never;
318
+ totals?: import('./model.mjs').ModelInstance<TDocument> extends {
319
+ findPage(options?: unknown): import('./model.mjs').PopulateProxy<infer TResult>;
320
+ } ? TResult extends { totals?: infer TTotals } ? TTotals : never : never;
321
+ meta?: import('./collection.mjs').MetaInfo;
322
+ }>;
323
+ findAndCount(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<{ data: Array<import('./model.mjs').ModelDocument<TDocument>>; total: number; }>;
324
+ count(query?: unknown, options?: unknown): Promise<number>;
325
+ insertOne(document?: unknown, options?: unknown): Promise<{ acknowledged: boolean; insertedId: any; }>;
326
+ insertMany(documents?: unknown[], options?: unknown): Promise<InsertManyResult>;
327
+ updateOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
328
+ updateMany(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
329
+ replaceOne(filter?: unknown, replacement?: unknown, options?: unknown): Promise<UpdateResult>;
330
+ findOneAndUpdate(filter?: unknown, update?: unknown, options?: unknown): Promise<TDocument | null>;
331
+ findOneAndDelete(filter?: unknown, options?: unknown): Promise<TDocument | null>;
332
+ upsertOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
333
+ deleteOne(filter?: unknown, options?: unknown): Promise<DeleteResult>;
334
+ deleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
335
+ createIndex(keys: unknown, options?: unknown): Promise<IndexCreateResult>;
336
+ createIndexes(specs: Array<{ key: unknown; } & Record<string, unknown>>): Promise<string[]>;
337
+ listIndexes(): Promise<Record<string, unknown>[]>;
338
+ ensureIndexes(options?: ModelEnsureIndexesOptions): Promise<ModelIndexEnsureResult>;
339
+ dropIndex(name: string): Promise<unknown>;
340
+ dropIndexes(): Promise<unknown>;
341
+ prewarmBookmarks(keyDims?: unknown, pages?: number[]): Promise<BookmarkPrewarmResult>;
342
+ listBookmarks(keyDims?: unknown): Promise<BookmarkListResult>;
343
+ clearBookmarks(keyDims?: unknown): Promise<BookmarkClearResult>;
344
+ distinct(key: string, query?: unknown, options?: unknown): Promise<unknown[]>;
345
+ aggregate(pipeline?: unknown[], options?: unknown): Promise<unknown[]>;
346
+ stream(query?: unknown, options?: unknown): NodeJS.ReadableStream;
347
+ explain(query?: unknown, options?: unknown): Promise<unknown>;
348
+ invalidate(op?: 'find' | 'findOne' | 'count' | 'findPage' | 'aggregate' | 'distinct'): Promise<number>;
349
+ dropCollection(): Promise<boolean>;
350
+ createCollection(name?: string, options?: Record<string, unknown>): Promise<boolean>;
351
+ createView(name: string, source: string, pipeline?: unknown[]): Promise<boolean>;
352
+ indexStats(): Promise<unknown[]>;
353
+ setValidator(validator: unknown, options?: { validationLevel?: string; validationAction?: string }): Promise<{ ok: number; collection: string }>;
354
+ setValidationLevel(level: 'off' | 'moderate' | 'strict' | string): Promise<{ ok: number; validationLevel: string }>;
355
+ setValidationAction(action: 'error' | 'warn' | string): Promise<{ ok: number; validationAction: string }>;
356
+ getValidator(): Promise<{ validator: Record<string, unknown> | null; validationLevel: string; validationAction: string }>;
357
+ stats(options?: { scale?: number }): Promise<{ ns: string; count: number; size: number; storageSize: number; totalIndexSize: number; nindexes: number; avgObjSize?: number; scaleFactor?: number }>;
358
+ renameCollection(newName: string, options?: { dropTarget?: boolean }): Promise<{ renamed: boolean; from: string; to: string }>;
359
+ collMod(modifications: Record<string, unknown>): Promise<Record<string, unknown>>;
360
+ convertToCapped(size: number, options?: { max?: number }): Promise<{ ok: number; collection: string; capped: boolean; size: number }>;
361
+ watch(pipeline?: unknown[], options?: unknown): import('mongodb').ChangeStream;
362
+ validate(document?: unknown): import('./model.mjs').ValidationResult;
363
+ findOneAndReplace(filter?: unknown, replacement?: unknown, options?: unknown): Promise<TDocument | null>;
364
+ incrementOne(filter?: unknown, field?: string | Record<string, number>, increment?: number, options?: unknown): Promise<IncrementOneResult<TDocument>>;
365
+ findWithDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
366
+ findOnlyDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<Array<import('./model.mjs').ModelDocument<TDocument>>>;
367
+ findOneWithDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
368
+ restore(filter?: unknown, options?: unknown): Promise<import('./model.mjs').RestoreResult>;
369
+ restoreMany(filter?: unknown, options?: unknown): Promise<import('./model.mjs').RestoreResult>;
370
+ forceDelete(filter?: unknown, options?: unknown): Promise<DeleteResult>;
371
+ forceDeleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
372
+ findOneOnlyDeleted(query?: unknown, options?: unknown): import('./model.mjs').PopulateProxy<import('./model.mjs').ModelDocument<TDocument> | null>;
373
+ countWithDeleted(query?: unknown, options?: unknown): Promise<number>;
374
+ countOnlyDeleted(query?: unknown, options?: unknown): Promise<number>;
375
+ insertBatch(docs: unknown[], options?: unknown): Promise<InsertBatchResult>;
376
+ updateBatch(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateBatchResult>;
377
+ deleteBatch(filter?: unknown, options?: unknown): Promise<DeleteBatchResult>;
378
+ }
379
+
380
+ export declare const expr: ExpressionFunction;
381
+ export declare const createExpression: ExpressionFunction;
382
+ export declare function isExpressionObject(value: unknown): value is ExpressionObject;
383
+ export declare function hasExpressionInObject(value: unknown): boolean;
384
+ export declare function hasExpressionInPipeline(pipeline: unknown): boolean;
385
+ /** Compile expression objects in a MongoDB pipeline into real operators. */
386
+ export declare function compilePipelineExpressions<TPipeline>(pipeline: TPipeline): TPipeline;
387
+
@@ -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';
@@ -0,0 +1,143 @@
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
+ /** 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
+ }