@classytic/mongokit 3.2.0 → 3.2.2

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 (48) hide show
  1. package/README.md +470 -193
  2. package/dist/actions/index.d.mts +9 -0
  3. package/dist/actions/index.mjs +15 -0
  4. package/dist/aggregate-BAi4Do-X.mjs +767 -0
  5. package/dist/aggregate-CCHI7F51.d.mts +269 -0
  6. package/dist/ai/index.d.mts +125 -0
  7. package/dist/ai/index.mjs +203 -0
  8. package/dist/cache-keys-C8Z9B5sw.mjs +204 -0
  9. package/dist/chunk-DQk6qfdC.mjs +18 -0
  10. package/dist/create-BuO6xt0v.mjs +55 -0
  11. package/dist/custom-id.plugin-B_zIs6gE.mjs +1818 -0
  12. package/dist/custom-id.plugin-BzZI4gnE.d.mts +893 -0
  13. package/dist/index.d.mts +1012 -0
  14. package/dist/index.mjs +1906 -0
  15. package/dist/limits-DsNeCx4D.mjs +299 -0
  16. package/dist/logger-D8ily-PP.mjs +51 -0
  17. package/dist/mongooseToJsonSchema-COdDEkIJ.mjs +317 -0
  18. package/dist/{mongooseToJsonSchema-CaRF_bCN.d.ts → mongooseToJsonSchema-Wbvjfwkn.d.mts} +16 -89
  19. package/dist/pagination/PaginationEngine.d.mts +93 -0
  20. package/dist/pagination/PaginationEngine.mjs +196 -0
  21. package/dist/plugins/index.d.mts +3 -0
  22. package/dist/plugins/index.mjs +3 -0
  23. package/dist/types-D-gploPr.d.mts +1241 -0
  24. package/dist/utils/{index.d.ts → index.d.mts} +14 -21
  25. package/dist/utils/index.mjs +5 -0
  26. package/package.json +21 -21
  27. package/dist/actions/index.d.ts +0 -3
  28. package/dist/actions/index.js +0 -5
  29. package/dist/ai/index.d.ts +0 -175
  30. package/dist/ai/index.js +0 -206
  31. package/dist/chunks/chunk-2ZN65ZOP.js +0 -93
  32. package/dist/chunks/chunk-44KXLGPO.js +0 -388
  33. package/dist/chunks/chunk-DEVXDBRL.js +0 -1226
  34. package/dist/chunks/chunk-I7CWNAJB.js +0 -46
  35. package/dist/chunks/chunk-JWUAVZ3L.js +0 -8
  36. package/dist/chunks/chunk-UE2IEXZJ.js +0 -306
  37. package/dist/chunks/chunk-URLJFIR7.js +0 -22
  38. package/dist/chunks/chunk-VWKIKZYF.js +0 -737
  39. package/dist/chunks/chunk-WSFCRVEQ.js +0 -7
  40. package/dist/index-BDn5fSTE.d.ts +0 -516
  41. package/dist/index.d.ts +0 -1422
  42. package/dist/index.js +0 -1893
  43. package/dist/pagination/PaginationEngine.d.ts +0 -117
  44. package/dist/pagination/PaginationEngine.js +0 -3
  45. package/dist/plugins/index.d.ts +0 -922
  46. package/dist/plugins/index.js +0 -6
  47. package/dist/types-Jni1KgkP.d.ts +0 -780
  48. package/dist/utils/index.js +0 -5
@@ -1,780 +0,0 @@
1
- import * as mongoose from 'mongoose';
2
- import { Document, PopulateOptions, ClientSession, PipelineStage, Model, Types } from 'mongoose';
3
-
4
- /** Re-export mongoose ObjectId */
5
- type ObjectId = Types.ObjectId;
6
- /** Generic document type */
7
- type AnyDocument = Document & Record<string, unknown>;
8
- /** Generic model type */
9
- type AnyModel = Model<AnyDocument>;
10
- /** Sort direction */
11
- type SortDirection = 1 | -1;
12
- /** Sort specification for MongoDB queries */
13
- type SortSpec = Record<string, SortDirection>;
14
- /** Populate specification */
15
- type PopulateSpec = string | string[] | PopulateOptions | PopulateOptions[];
16
- /** Select specification */
17
- type SelectSpec = string | string[] | Record<string, 0 | 1>;
18
- /** Filter query type for MongoDB queries (compatible with Mongoose 8 & 9) */
19
- type FilterQuery<_T = unknown> = Record<string, unknown>;
20
- /**
21
- * Infer document type from a Mongoose Model
22
- * @example
23
- * type UserDoc = InferDocument<typeof UserModel>;
24
- */
25
- type InferDocument<TModel> = TModel extends Model<infer TDoc> ? TDoc : never;
26
- /**
27
- * Infer raw document shape (without Mongoose Document methods)
28
- * @example
29
- * type User = InferRawDoc<typeof UserModel>;
30
- */
31
- type InferRawDoc<TModel> = TModel extends Model<infer TDoc> ? TDoc extends Document ? Omit<TDoc, keyof Document> : TDoc : never;
32
- /**
33
- * Make specific fields optional
34
- * @example
35
- * type CreateUser = PartialBy<User, 'createdAt' | 'updatedAt'>;
36
- */
37
- type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
38
- /**
39
- * Make specific fields required
40
- * @example
41
- * type UserWithId = RequiredBy<User, '_id'>;
42
- */
43
- type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
44
- /**
45
- * Extract keys of type T that have values of type V
46
- * @example
47
- * type StringFields = KeysOfType<User, string>; // 'name' | 'email'
48
- */
49
- type KeysOfType<T, V> = {
50
- [K in keyof T]: T[K] extends V ? K : never;
51
- }[keyof T];
52
- /**
53
- * Deep partial - makes all nested properties optional
54
- */
55
- type DeepPartial<T> = T extends object ? {
56
- [P in keyof T]?: DeepPartial<T[P]>;
57
- } : T;
58
- /**
59
- * Strict object type - prevents excess properties
60
- * Use with `satisfies` for compile-time validation
61
- */
62
- type Strict<T> = T & {
63
- [K in Exclude<string, keyof T>]?: never;
64
- };
65
- /**
66
- * NonNullable fields extractor
67
- */
68
- type NonNullableFields<T> = {
69
- [K in keyof T]: NonNullable<T[K]>;
70
- };
71
- /**
72
- * Create/Update input types from document
73
- */
74
- type CreateInput<TDoc> = Omit<TDoc, '_id' | 'createdAt' | 'updatedAt' | '__v'>;
75
- type UpdateInput<TDoc> = Partial<Omit<TDoc, '_id' | 'createdAt' | '__v'>>;
76
- /** Hook execution mode */
77
- type HookMode = 'sync' | 'async';
78
- /** Repository options */
79
- interface RepositoryOptions {
80
- /** Whether repository event hooks are awaited */
81
- hooks?: HookMode;
82
- }
83
- /** Pagination configuration */
84
- interface PaginationConfig {
85
- /** Default number of documents per page (default: 10) */
86
- defaultLimit?: number;
87
- /** Maximum allowed limit (default: 100) */
88
- maxLimit?: number;
89
- /** Maximum allowed page number (default: 10000) */
90
- maxPage?: number;
91
- /** Page number that triggers performance warning (default: 100) */
92
- deepPageThreshold?: number;
93
- /** Cursor version for forward compatibility (default: 1) */
94
- cursorVersion?: number;
95
- /** Use estimatedDocumentCount for faster counts on large collections */
96
- useEstimatedCount?: boolean;
97
- }
98
- /** Base pagination options */
99
- interface BasePaginationOptions {
100
- /** MongoDB query filters */
101
- filters?: FilterQuery<AnyDocument>;
102
- /** Sort specification */
103
- sort?: SortSpec;
104
- /** Number of documents per page */
105
- limit?: number;
106
- /** Fields to select */
107
- select?: SelectSpec;
108
- /** Fields to populate */
109
- populate?: PopulateSpec;
110
- /** Return plain JavaScript objects */
111
- lean?: boolean;
112
- /** MongoDB session for transactions */
113
- session?: ClientSession;
114
- }
115
- /** Offset pagination options */
116
- interface OffsetPaginationOptions extends BasePaginationOptions {
117
- /** Page number (1-indexed) */
118
- page?: number;
119
- }
120
- /** Keyset (cursor) pagination options */
121
- interface KeysetPaginationOptions extends BasePaginationOptions {
122
- /** Cursor token for next page */
123
- after?: string;
124
- /** Sort is required for keyset pagination */
125
- sort: SortSpec;
126
- }
127
- /** Aggregate pagination options */
128
- interface AggregatePaginationOptions {
129
- /** Aggregation pipeline stages */
130
- pipeline?: PipelineStage[];
131
- /** Page number (1-indexed) */
132
- page?: number;
133
- /** Number of documents per page */
134
- limit?: number;
135
- /** MongoDB session for transactions */
136
- session?: ClientSession;
137
- }
138
- /** Offset pagination result */
139
- interface OffsetPaginationResult<T = unknown> {
140
- /** Pagination method used */
141
- method: 'offset';
142
- /** Array of documents */
143
- docs: T[];
144
- /** Current page number */
145
- page: number;
146
- /** Documents per page */
147
- limit: number;
148
- /** Total document count */
149
- total: number;
150
- /** Total page count */
151
- pages: number;
152
- /** Whether next page exists */
153
- hasNext: boolean;
154
- /** Whether previous page exists */
155
- hasPrev: boolean;
156
- /** Performance warning for deep pagination */
157
- warning?: string;
158
- }
159
- /** Keyset pagination result */
160
- interface KeysetPaginationResult<T = unknown> {
161
- /** Pagination method used */
162
- method: 'keyset';
163
- /** Array of documents */
164
- docs: T[];
165
- /** Documents per page */
166
- limit: number;
167
- /** Whether more documents exist */
168
- hasMore: boolean;
169
- /** Cursor token for next page */
170
- next: string | null;
171
- }
172
- /** Aggregate pagination result */
173
- interface AggregatePaginationResult<T = unknown> {
174
- /** Pagination method used */
175
- method: 'aggregate';
176
- /** Array of documents */
177
- docs: T[];
178
- /** Current page number */
179
- page: number;
180
- /** Documents per page */
181
- limit: number;
182
- /** Total document count */
183
- total: number;
184
- /** Total page count */
185
- pages: number;
186
- /** Whether next page exists */
187
- hasNext: boolean;
188
- /** Whether previous page exists */
189
- hasPrev: boolean;
190
- /** Performance warning for deep pagination */
191
- warning?: string;
192
- }
193
- /** Union type for all pagination results */
194
- type PaginationResult<T = unknown> = OffsetPaginationResult<T> | KeysetPaginationResult<T> | AggregatePaginationResult<T>;
195
- /** Repository operation options */
196
- interface OperationOptions {
197
- /** MongoDB session for transactions */
198
- session?: ClientSession;
199
- /** Fields to select */
200
- select?: SelectSpec;
201
- /** Fields to populate */
202
- populate?: PopulateSpec;
203
- /** Return plain JavaScript objects */
204
- lean?: boolean;
205
- /** Throw error if document not found (default: true) */
206
- throwOnNotFound?: boolean;
207
- /** Additional query filters (e.g., for soft delete) */
208
- query?: Record<string, unknown>;
209
- }
210
- /** withTransaction options */
211
- interface WithTransactionOptions {
212
- /** Allow non-transactional fallback when transactions are unsupported */
213
- allowFallback?: boolean;
214
- /** Optional hook to observe fallback triggers */
215
- onFallback?: (error: Error) => void;
216
- /** MongoDB transaction options (readConcern, writeConcern, readPreference, maxCommitTimeMS) */
217
- transactionOptions?: mongoose.mongo.TransactionOptions;
218
- }
219
- /** Create operation options */
220
- interface CreateOptions {
221
- /** MongoDB session for transactions */
222
- session?: ClientSession;
223
- /** Keep insertion order on error (default: true) */
224
- ordered?: boolean;
225
- }
226
- /** Update operation options */
227
- interface UpdateOptions extends OperationOptions {
228
- /** Enable update pipeline syntax */
229
- updatePipeline?: boolean;
230
- }
231
- /** Delete result */
232
- interface DeleteResult {
233
- success: boolean;
234
- message: string;
235
- count?: number;
236
- }
237
- /** Update many result */
238
- interface UpdateManyResult {
239
- matchedCount: number;
240
- modifiedCount: number;
241
- }
242
- /** Validation result */
243
- interface ValidationResult {
244
- valid: boolean;
245
- violations?: Array<{
246
- field: string;
247
- reason: string;
248
- }>;
249
- message?: string;
250
- }
251
- /** Update with validation result */
252
- type UpdateWithValidationResult<T> = {
253
- success: true;
254
- data: T;
255
- } | {
256
- success: false;
257
- error: {
258
- code: number;
259
- message: string;
260
- violations?: ValidationResult['violations'];
261
- };
262
- };
263
- /** User context for operations */
264
- interface UserContext {
265
- _id?: ObjectId | string;
266
- id?: string;
267
- roles?: string | string[];
268
- [key: string]: unknown;
269
- }
270
- /** Repository operation context */
271
- interface RepositoryContext {
272
- /** Operation name */
273
- operation: string;
274
- /** Model name */
275
- model: string;
276
- /** Document data (for create/update) */
277
- data?: Record<string, unknown>;
278
- /** Array of documents (for createMany) */
279
- dataArray?: Record<string, unknown>[];
280
- /** Document ID (for update/delete/getById) */
281
- id?: string | ObjectId;
282
- /** Query filters */
283
- query?: FilterQuery<AnyDocument>;
284
- /** User making the request */
285
- user?: UserContext;
286
- /** Organization ID for multi-tenancy */
287
- organizationId?: string | ObjectId;
288
- /** Fields to select */
289
- select?: SelectSpec;
290
- /** Fields to populate */
291
- populate?: PopulateSpec;
292
- /** Return lean documents */
293
- lean?: boolean;
294
- /** MongoDB session */
295
- session?: ClientSession;
296
- /** Pagination filters */
297
- filters?: Record<string, unknown>;
298
- /** Sort specification */
299
- sort?: SortSpec;
300
- /** Page number (offset pagination) */
301
- page?: number;
302
- /** Items per page */
303
- limit?: number;
304
- /** Cursor for next page (keyset pagination) */
305
- after?: string;
306
- /** Search query string */
307
- search?: string;
308
- /** Whether this is a soft delete operation (set by softDeletePlugin) */
309
- softDeleted?: boolean;
310
- /** Include soft-deleted documents in queries */
311
- includeDeleted?: boolean;
312
- /** Skip cache for this operation */
313
- skipCache?: boolean;
314
- /** Custom TTL for this operation (seconds) */
315
- cacheTtl?: number;
316
- /** Whether result was served from cache (internal) */
317
- _cacheHit?: boolean;
318
- /** Cached result (internal) */
319
- _cachedResult?: unknown;
320
- /** IDs to cascade delete (internal) */
321
- _cascadeIds?: unknown[];
322
- /** Custom context data from plugins */
323
- [key: string]: unknown;
324
- }
325
- /** Plugin interface */
326
- interface Plugin {
327
- /** Plugin name */
328
- name: string;
329
- /** Apply plugin to repository */
330
- apply(repo: RepositoryInstance): void;
331
- }
332
- /** Plugin function signature */
333
- type PluginFunction = (repo: RepositoryInstance) => void;
334
- /** Plugin type (object or function) */
335
- type PluginType = Plugin | PluginFunction;
336
- /** Repository instance for plugin type reference */
337
- interface RepositoryInstance {
338
- Model: Model<any>;
339
- model: string;
340
- _hooks: Map<string, Array<(data: any) => void | Promise<void>>>;
341
- _pagination: unknown;
342
- use(plugin: PluginType): this;
343
- on(event: string, listener: (data: any) => void | Promise<void>): this;
344
- off(event: string, listener: (data: any) => void | Promise<void>): this;
345
- removeAllListeners(event?: string): this;
346
- emit(event: string, data: unknown): void;
347
- emitAsync(event: string, data: unknown): Promise<void>;
348
- registerMethod?(name: string, fn: Function): void;
349
- hasMethod?(name: string): boolean;
350
- [key: string]: unknown;
351
- }
352
- /** Repository operation names */
353
- type RepositoryOperation = 'create' | 'createMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany' | 'getById' | 'getByQuery' | 'getAll' | 'aggregatePaginate' | 'lookupPopulate';
354
- /** Event lifecycle phases */
355
- type EventPhase = 'before' | 'after' | 'error';
356
- /** Repository event names (generated from template literals) */
357
- type RepositoryEvent = `${EventPhase}:${RepositoryOperation}` | 'method:registered' | 'error:hook';
358
- /**
359
- * Type-safe event handler map
360
- *
361
- * Hook signature contract:
362
- * - `before:*` — receives `context: RepositoryContext` directly (not wrapped).
363
- * Plugins mutate context in-place to inject filters, data, etc.
364
- * - `after:*` — receives `{ context, result }` where result is the operation output.
365
- * - `error:*` — receives `{ context, error }` where error is the caught Error.
366
- */
367
- type EventHandlers<TDoc = unknown> = {
368
- [K in RepositoryEvent]?: K extends `before:${string}` ? (context: RepositoryContext) => void | Promise<void> : K extends `after:${string}` ? (payload: {
369
- context: RepositoryContext;
370
- result: TDoc | TDoc[];
371
- }) => void | Promise<void> : K extends `error:${string}` ? (payload: {
372
- context: RepositoryContext;
373
- error: Error;
374
- }) => void | Promise<void> : (payload: {
375
- context: RepositoryContext;
376
- }) => void | Promise<void>;
377
- };
378
- /** Event payload */
379
- interface EventPayload {
380
- context: RepositoryContext;
381
- result?: unknown;
382
- error?: Error;
383
- }
384
- /** Field preset configuration */
385
- interface FieldPreset {
386
- /** Fields visible to everyone */
387
- public: string[];
388
- /** Additional fields for authenticated users */
389
- authenticated?: string[];
390
- /** Additional fields for admins */
391
- admin?: string[];
392
- }
393
- /** Field rules for schema building */
394
- interface FieldRules {
395
- [fieldName: string]: {
396
- /** Field cannot be updated */
397
- immutable?: boolean;
398
- /** Alias for immutable */
399
- immutableAfterCreate?: boolean;
400
- /** System-only field (omitted from create/update) */
401
- systemManaged?: boolean;
402
- /** Remove from required array */
403
- optional?: boolean;
404
- };
405
- }
406
- /** Schema builder options */
407
- interface SchemaBuilderOptions {
408
- /** Field rules for create/update */
409
- fieldRules?: FieldRules;
410
- /** Strict additional properties (default: false) */
411
- strictAdditionalProperties?: boolean;
412
- /** Date format: 'date' | 'datetime' */
413
- dateAs?: 'date' | 'datetime';
414
- /** Create schema options */
415
- create?: {
416
- /** Fields to omit from create schema */
417
- omitFields?: string[];
418
- /** Override required status */
419
- requiredOverrides?: Record<string, boolean>;
420
- /** Override optional status */
421
- optionalOverrides?: Record<string, boolean>;
422
- /** Schema overrides */
423
- schemaOverrides?: Record<string, unknown>;
424
- };
425
- /** Update schema options */
426
- update?: {
427
- /** Fields to omit from update schema */
428
- omitFields?: string[];
429
- /** Require at least one field to be provided (default: false) */
430
- requireAtLeastOne?: boolean;
431
- };
432
- /** Query schema options */
433
- query?: {
434
- /** Filterable fields */
435
- filterableFields?: Record<string, {
436
- type: string;
437
- } | unknown>;
438
- };
439
- }
440
- /** JSON Schema type */
441
- interface JsonSchema {
442
- type: string;
443
- properties?: Record<string, unknown>;
444
- required?: string[];
445
- additionalProperties?: boolean | unknown;
446
- items?: unknown;
447
- enum?: string[];
448
- format?: string;
449
- pattern?: string;
450
- minProperties?: number;
451
- maxProperties?: number;
452
- minLength?: number;
453
- maxLength?: number;
454
- minimum?: number;
455
- maximum?: number;
456
- }
457
- /** CRUD schemas result - framework-agnostic JSON schemas */
458
- interface CrudSchemas {
459
- /** JSON Schema for create request body */
460
- createBody: JsonSchema;
461
- /** JSON Schema for update request body */
462
- updateBody: JsonSchema;
463
- /** JSON Schema for route params (id validation) */
464
- params: JsonSchema;
465
- /** JSON Schema for list/query parameters */
466
- listQuery: JsonSchema;
467
- }
468
- /** Decoded cursor */
469
- interface DecodedCursor {
470
- /** Primary sort field value (rehydrated) */
471
- value: unknown;
472
- /** Document ID (rehydrated) */
473
- id: ObjectId | string;
474
- /** Sort specification */
475
- sort: SortSpec;
476
- /** Cursor version */
477
- version: number;
478
- }
479
- /** Validator definition */
480
- interface ValidatorDefinition {
481
- /** Validator name */
482
- name: string;
483
- /** Operations to apply validator to */
484
- operations?: Array<'create' | 'createMany' | 'update' | 'delete'>;
485
- /** Validation function */
486
- validate: (context: RepositoryContext, repo?: RepositoryInstance) => void | Promise<void>;
487
- }
488
- /** Validation chain options */
489
- interface ValidationChainOptions {
490
- /** Stop on first validation error (default: true) */
491
- stopOnFirstError?: boolean;
492
- }
493
- /** Logger interface for audit plugin */
494
- interface Logger {
495
- info?(message: string, meta?: Record<string, unknown>): void;
496
- error?(message: string, meta?: Record<string, unknown>): void;
497
- warn?(message: string, meta?: Record<string, unknown>): void;
498
- debug?(message: string, meta?: Record<string, unknown>): void;
499
- }
500
- /** Filter mode for soft delete queries */
501
- type SoftDeleteFilterMode = 'null' | 'exists';
502
- /** Soft delete plugin options */
503
- interface SoftDeleteOptions {
504
- /** Field name for deletion timestamp (default: 'deletedAt') */
505
- deletedField?: string;
506
- /** Field name for deleting user (default: 'deletedBy') */
507
- deletedByField?: string;
508
- /** Enable soft delete (default: true) */
509
- soft?: boolean;
510
- /**
511
- * Filter mode for excluding deleted documents (default: 'null')
512
- * - 'null': Filters where deletedField is null (works with `default: null` in schema)
513
- * - 'exists': Filters where deletedField does not exist (legacy behavior)
514
- */
515
- filterMode?: SoftDeleteFilterMode;
516
- /** Add restore method to repository (default: true) */
517
- addRestoreMethod?: boolean;
518
- /** Add getDeleted method to repository (default: true) */
519
- addGetDeletedMethod?: boolean;
520
- /**
521
- * TTL in days for auto-cleanup of deleted documents.
522
- * When set, creates a TTL index on the deletedField.
523
- * Documents will be automatically removed after the specified days.
524
- */
525
- ttlDays?: number;
526
- }
527
- /** Repository with soft delete methods */
528
- interface SoftDeleteRepository {
529
- /**
530
- * Restore a soft-deleted document by setting deletedAt to null
531
- * @param id - Document ID to restore
532
- * @param options - Optional session for transactions
533
- * @returns The restored document
534
- */
535
- restore(id: string | ObjectId, options?: {
536
- session?: ClientSession;
537
- }): Promise<unknown>;
538
- /**
539
- * Get all soft-deleted documents
540
- * @param params - Query parameters (filters, pagination, etc.)
541
- * @param options - Query options (select, populate, etc.)
542
- * @returns Paginated result of deleted documents
543
- */
544
- getDeleted(params?: {
545
- filters?: Record<string, unknown>;
546
- sort?: SortSpec | string;
547
- page?: number;
548
- limit?: number;
549
- }, options?: {
550
- select?: SelectSpec;
551
- populate?: PopulateSpec;
552
- lean?: boolean;
553
- session?: ClientSession;
554
- }): Promise<OffsetPaginationResult<unknown>>;
555
- }
556
-
557
- /** Group result */
558
- interface GroupResult {
559
- _id: unknown;
560
- count: number;
561
- }
562
- /** Min/Max result */
563
- interface MinMaxResult {
564
- min: unknown;
565
- max: unknown;
566
- }
567
- /**
568
- * Cache adapter interface - bring your own cache implementation
569
- * Works with Redis, Memcached, in-memory, or any key-value store
570
- *
571
- * @example Redis implementation:
572
- * ```typescript
573
- * const redisCache: CacheAdapter = {
574
- * async get(key) { return JSON.parse(await redis.get(key) || 'null'); },
575
- * async set(key, value, ttl) { await redis.setex(key, ttl, JSON.stringify(value)); },
576
- * async del(key) { await redis.del(key); },
577
- * async clear(pattern) {
578
- * const keys = await redis.keys(pattern || '*');
579
- * if (keys.length) await redis.del(...keys);
580
- * }
581
- * };
582
- * ```
583
- */
584
- interface CacheAdapter {
585
- /** Get value by key, returns null if not found or expired */
586
- get<T = unknown>(key: string): Promise<T | null>;
587
- /** Set value with TTL in seconds */
588
- set<T = unknown>(key: string, value: T, ttl: number): Promise<void>;
589
- /** Delete single key */
590
- del(key: string): Promise<void>;
591
- /** Clear keys matching pattern (optional, used for bulk invalidation) */
592
- clear?(pattern?: string): Promise<void>;
593
- }
594
- /** Cache plugin options */
595
- interface CacheOptions {
596
- /** Cache adapter implementation (required) */
597
- adapter: CacheAdapter;
598
- /** Default TTL in seconds (default: 60) */
599
- ttl?: number;
600
- /** TTL for byId queries in seconds (default: same as ttl) */
601
- byIdTtl?: number;
602
- /** TTL for query/list results in seconds (default: same as ttl) */
603
- queryTtl?: number;
604
- /** Key prefix for namespacing (default: 'mk') */
605
- prefix?: string;
606
- /** Enable debug logging (default: false) */
607
- debug?: boolean;
608
- /**
609
- * Skip caching for queries with these characteristics:
610
- * - largeLimit: Skip if limit > value (default: 100)
611
- */
612
- skipIf?: {
613
- largeLimit?: number;
614
- };
615
- }
616
- /** Options for cache-aware operations */
617
- interface CacheOperationOptions {
618
- /** Skip cache for this operation (read from DB directly) */
619
- skipCache?: boolean;
620
- /** Custom TTL for this operation in seconds */
621
- cacheTtl?: number;
622
- }
623
- /** Cache statistics (for debugging/monitoring) */
624
- interface CacheStats {
625
- hits: number;
626
- misses: number;
627
- sets: number;
628
- invalidations: number;
629
- }
630
- /** Cascade relation definition */
631
- interface CascadeRelation {
632
- /** Model name to cascade delete to */
633
- model: string;
634
- /** Foreign key field in the related model that references the deleted document */
635
- foreignKey: string;
636
- /** Whether to use soft delete if available (default: follows parent behavior) */
637
- softDelete?: boolean;
638
- }
639
- /** Cascade delete plugin options */
640
- interface CascadeOptions {
641
- /** Relations to cascade delete */
642
- relations: CascadeRelation[];
643
- /** Run cascade deletes in parallel (default: true) */
644
- parallel?: boolean;
645
- /** Logger for cascade operations */
646
- logger?: Logger;
647
- }
648
- /** HTTP Error with status code */
649
- interface HttpError extends Error {
650
- status: number;
651
- validationErrors?: Array<{
652
- validator: string;
653
- error: string;
654
- }>;
655
- }
656
- /**
657
- * Combines all plugin method types into a single type
658
- * Useful when you're using all plugins and want full type safety
659
- *
660
- * @example
661
- * ```typescript
662
- * import { Repository } from '@classytic/mongokit';
663
- * import type { AllPluginMethods } from '@classytic/mongokit';
664
- *
665
- * class UserRepo extends Repository<IUser> {}
666
- *
667
- * const repo = new UserRepo(Model, [...allPlugins]) as UserRepo & AllPluginMethods<IUser>;
668
- *
669
- * // TypeScript knows about all plugin methods!
670
- * await repo.increment(id, 'views', 1);
671
- * await repo.restore(id);
672
- * await repo.invalidateCache(id);
673
- * ```
674
- *
675
- * Note: Import the individual plugin method types if you need them:
676
- * ```typescript
677
- * import type {
678
- * MongoOperationsMethods,
679
- * BatchOperationsMethods,
680
- * AggregateHelpersMethods,
681
- * SubdocumentMethods,
682
- * SoftDeleteMethods,
683
- * CacheMethods,
684
- * } from '@classytic/mongokit';
685
- * ```
686
- */
687
- type AllPluginMethods<TDoc> = {
688
- upsert(query: Record<string, unknown>, data: Record<string, unknown>, options?: Record<string, unknown>): Promise<TDoc>;
689
- increment(id: string | ObjectId, field: string, value?: number, options?: Record<string, unknown>): Promise<TDoc>;
690
- decrement(id: string | ObjectId, field: string, value?: number, options?: Record<string, unknown>): Promise<TDoc>;
691
- pushToArray(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
692
- pullFromArray(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
693
- addToSet(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
694
- setField(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
695
- unsetField(id: string | ObjectId, fields: string | string[], options?: Record<string, unknown>): Promise<TDoc>;
696
- renameField(id: string | ObjectId, oldName: string, newName: string, options?: Record<string, unknown>): Promise<TDoc>;
697
- multiplyField(id: string | ObjectId, field: string, multiplier: number, options?: Record<string, unknown>): Promise<TDoc>;
698
- setMin(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
699
- setMax(id: string | ObjectId, field: string, value: unknown, options?: Record<string, unknown>): Promise<TDoc>;
700
- updateMany(query: Record<string, unknown>, data: Record<string, unknown>, options?: {
701
- session?: ClientSession;
702
- updatePipeline?: boolean;
703
- }): Promise<{
704
- acknowledged: boolean;
705
- matchedCount: number;
706
- modifiedCount: number;
707
- upsertedCount: number;
708
- upsertedId: unknown;
709
- }>;
710
- deleteMany(query: Record<string, unknown>, options?: Record<string, unknown>): Promise<{
711
- acknowledged: boolean;
712
- deletedCount: number;
713
- }>;
714
- groupBy(field: string, options?: {
715
- limit?: number;
716
- session?: unknown;
717
- }): Promise<Array<{
718
- _id: unknown;
719
- count: number;
720
- }>>;
721
- sum(field: string, query?: Record<string, unknown>, options?: Record<string, unknown>): Promise<number>;
722
- average(field: string, query?: Record<string, unknown>, options?: Record<string, unknown>): Promise<number>;
723
- min(field: string, query?: Record<string, unknown>, options?: Record<string, unknown>): Promise<number>;
724
- max(field: string, query?: Record<string, unknown>, options?: Record<string, unknown>): Promise<number>;
725
- addSubdocument(parentId: string | ObjectId, arrayPath: string, subData: Record<string, unknown>, options?: Record<string, unknown>): Promise<TDoc>;
726
- getSubdocument(parentId: string | ObjectId, arrayPath: string, subId: string | ObjectId, options?: {
727
- lean?: boolean;
728
- session?: unknown;
729
- }): Promise<Record<string, unknown>>;
730
- updateSubdocument(parentId: string | ObjectId, arrayPath: string, subId: string | ObjectId, updateData: Record<string, unknown>, options?: {
731
- session?: unknown;
732
- }): Promise<TDoc>;
733
- deleteSubdocument(parentId: string | ObjectId, arrayPath: string, subId: string | ObjectId, options?: Record<string, unknown>): Promise<TDoc>;
734
- restore(id: string | ObjectId, options?: {
735
- session?: ClientSession;
736
- }): Promise<TDoc>;
737
- getDeleted(params?: {
738
- filters?: Record<string, unknown>;
739
- sort?: SortSpec | string;
740
- page?: number;
741
- limit?: number;
742
- }, options?: {
743
- select?: SelectSpec;
744
- populate?: PopulateSpec;
745
- lean?: boolean;
746
- session?: ClientSession;
747
- }): Promise<OffsetPaginationResult<TDoc>>;
748
- invalidateCache(id: string): Promise<void>;
749
- invalidateListCache(): Promise<void>;
750
- invalidateAllCache(): Promise<void>;
751
- getCacheStats(): CacheStats;
752
- resetCacheStats(): void;
753
- };
754
- /**
755
- * Helper type to add all plugin methods to a repository class
756
- * Cleaner than manually typing the intersection
757
- *
758
- * @example
759
- * ```typescript
760
- * import { Repository } from '@classytic/mongokit';
761
- * import type { WithPlugins } from '@classytic/mongokit';
762
- *
763
- * class OrderRepo extends Repository<IOrder> {
764
- * async getCustomerOrders(customerId: string) {
765
- * return this.getAll({ filters: { customerId } });
766
- * }
767
- * }
768
- *
769
- * const orderRepo = new OrderRepo(Model, [
770
- * ...allPlugins
771
- * ]) as WithPlugins<IOrder, OrderRepo>;
772
- *
773
- * // Works: custom methods + plugin methods
774
- * await orderRepo.getCustomerOrders('123');
775
- * await orderRepo.increment(orderId, 'total', 100);
776
- * ```
777
- */
778
- type WithPlugins<TDoc, TRepo extends RepositoryInstance = RepositoryInstance> = TRepo & AllPluginMethods<TDoc>;
779
-
780
- export type { ValidatorDefinition as $, AnyDocument as A, PluginFunction as B, CreateInput as C, DeepPartial as D, RepositoryInstance as E, RepositoryOperation as F, EventPhase as G, HttpError as H, InferDocument as I, RepositoryEvent as J, KeysetPaginationOptions as K, EventHandlers as L, EventPayload as M, NonNullableFields as N, OffsetPaginationOptions as O, PaginationConfig as P, FieldPreset as Q, RepositoryOptions as R, SelectSpec as S, FieldRules as T, UpdateOptions as U, ValidationResult as V, WithTransactionOptions as W, SchemaBuilderOptions as X, JsonSchema as Y, CrudSchemas as Z, DecodedCursor as _, OffsetPaginationResult as a, ValidationChainOptions as a0, Logger as a1, SoftDeleteOptions as a2, SoftDeleteFilterMode as a3, SoftDeleteRepository as a4, GroupResult as a5, MinMaxResult as a6, CacheAdapter as a7, CacheOptions as a8, CacheOperationOptions as a9, CacheStats as aa, CascadeRelation as ab, CascadeOptions as ac, AllPluginMethods as ad, WithPlugins as ae, KeysetPaginationResult as b, AggregatePaginationOptions as c, AggregatePaginationResult as d, PopulateSpec as e, SortSpec as f, Plugin as g, PaginationResult as h, PluginType as i, ObjectId as j, RepositoryContext as k, AnyModel as l, SortDirection as m, HookMode as n, InferRawDoc as o, PartialBy as p, RequiredBy as q, KeysOfType as r, Strict as s, UpdateInput as t, OperationOptions as u, CreateOptions as v, DeleteResult as w, UpdateManyResult as x, UpdateWithValidationResult as y, UserContext as z };