@classytic/mongokit 2.0.0 → 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 (105) hide show
  1. package/README.md +221 -7
  2. package/dist/actions/index.d.ts +3 -0
  3. package/dist/actions/index.js +473 -0
  4. package/dist/actions/index.js.map +1 -0
  5. package/dist/index-CgOJ2pqz.d.ts +337 -0
  6. package/dist/index.d.ts +239 -0
  7. package/dist/index.js +2108 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/memory-cache-DG2oSSbx.d.ts +142 -0
  10. package/dist/pagination/PaginationEngine.d.ts +117 -0
  11. package/dist/pagination/PaginationEngine.js +369 -0
  12. package/dist/pagination/PaginationEngine.js.map +1 -0
  13. package/dist/plugins/index.d.ts +275 -0
  14. package/dist/plugins/index.js +857 -0
  15. package/dist/plugins/index.js.map +1 -0
  16. package/dist/types-Nxhmi1aI.d.ts +510 -0
  17. package/dist/utils/index.d.ts +189 -0
  18. package/dist/utils/index.js +643 -0
  19. package/dist/utils/index.js.map +1 -0
  20. package/package.json +38 -21
  21. package/src/Repository.js +0 -296
  22. package/src/actions/aggregate.js +0 -266
  23. package/src/actions/create.js +0 -59
  24. package/src/actions/delete.js +0 -88
  25. package/src/actions/index.js +0 -11
  26. package/src/actions/read.js +0 -188
  27. package/src/actions/update.js +0 -176
  28. package/src/hooks/lifecycle.js +0 -146
  29. package/src/index.js +0 -71
  30. package/src/pagination/PaginationEngine.js +0 -348
  31. package/src/pagination/utils/cursor.js +0 -119
  32. package/src/pagination/utils/filter.js +0 -42
  33. package/src/pagination/utils/limits.js +0 -82
  34. package/src/pagination/utils/sort.js +0 -101
  35. package/src/plugins/aggregate-helpers.plugin.js +0 -71
  36. package/src/plugins/audit-log.plugin.js +0 -60
  37. package/src/plugins/batch-operations.plugin.js +0 -66
  38. package/src/plugins/field-filter.plugin.js +0 -27
  39. package/src/plugins/index.js +0 -19
  40. package/src/plugins/method-registry.plugin.js +0 -140
  41. package/src/plugins/mongo-operations.plugin.js +0 -317
  42. package/src/plugins/soft-delete.plugin.js +0 -46
  43. package/src/plugins/subdocument.plugin.js +0 -66
  44. package/src/plugins/timestamp.plugin.js +0 -19
  45. package/src/plugins/validation-chain.plugin.js +0 -145
  46. package/src/types.d.ts +0 -87
  47. package/src/utils/error.js +0 -12
  48. package/src/utils/field-selection.js +0 -156
  49. package/src/utils/index.js +0 -12
  50. package/types/Repository.d.ts +0 -95
  51. package/types/Repository.d.ts.map +0 -1
  52. package/types/actions/aggregate.d.ts +0 -112
  53. package/types/actions/aggregate.d.ts.map +0 -1
  54. package/types/actions/create.d.ts +0 -21
  55. package/types/actions/create.d.ts.map +0 -1
  56. package/types/actions/delete.d.ts +0 -37
  57. package/types/actions/delete.d.ts.map +0 -1
  58. package/types/actions/index.d.ts +0 -6
  59. package/types/actions/index.d.ts.map +0 -1
  60. package/types/actions/read.d.ts +0 -135
  61. package/types/actions/read.d.ts.map +0 -1
  62. package/types/actions/update.d.ts +0 -58
  63. package/types/actions/update.d.ts.map +0 -1
  64. package/types/hooks/lifecycle.d.ts +0 -44
  65. package/types/hooks/lifecycle.d.ts.map +0 -1
  66. package/types/index.d.ts +0 -25
  67. package/types/index.d.ts.map +0 -1
  68. package/types/pagination/PaginationEngine.d.ts +0 -386
  69. package/types/pagination/PaginationEngine.d.ts.map +0 -1
  70. package/types/pagination/utils/cursor.d.ts +0 -40
  71. package/types/pagination/utils/cursor.d.ts.map +0 -1
  72. package/types/pagination/utils/filter.d.ts +0 -28
  73. package/types/pagination/utils/filter.d.ts.map +0 -1
  74. package/types/pagination/utils/limits.d.ts +0 -64
  75. package/types/pagination/utils/limits.d.ts.map +0 -1
  76. package/types/pagination/utils/sort.d.ts +0 -41
  77. package/types/pagination/utils/sort.d.ts.map +0 -1
  78. package/types/plugins/aggregate-helpers.plugin.d.ts +0 -6
  79. package/types/plugins/aggregate-helpers.plugin.d.ts.map +0 -1
  80. package/types/plugins/audit-log.plugin.d.ts +0 -6
  81. package/types/plugins/audit-log.plugin.d.ts.map +0 -1
  82. package/types/plugins/batch-operations.plugin.d.ts +0 -6
  83. package/types/plugins/batch-operations.plugin.d.ts.map +0 -1
  84. package/types/plugins/field-filter.plugin.d.ts +0 -6
  85. package/types/plugins/field-filter.plugin.d.ts.map +0 -1
  86. package/types/plugins/index.d.ts +0 -11
  87. package/types/plugins/index.d.ts.map +0 -1
  88. package/types/plugins/method-registry.plugin.d.ts +0 -3
  89. package/types/plugins/method-registry.plugin.d.ts.map +0 -1
  90. package/types/plugins/mongo-operations.plugin.d.ts +0 -4
  91. package/types/plugins/mongo-operations.plugin.d.ts.map +0 -1
  92. package/types/plugins/soft-delete.plugin.d.ts +0 -6
  93. package/types/plugins/soft-delete.plugin.d.ts.map +0 -1
  94. package/types/plugins/subdocument.plugin.d.ts +0 -6
  95. package/types/plugins/subdocument.plugin.d.ts.map +0 -1
  96. package/types/plugins/timestamp.plugin.d.ts +0 -6
  97. package/types/plugins/timestamp.plugin.d.ts.map +0 -1
  98. package/types/plugins/validation-chain.plugin.d.ts +0 -31
  99. package/types/plugins/validation-chain.plugin.d.ts.map +0 -1
  100. package/types/utils/error.d.ts +0 -11
  101. package/types/utils/error.d.ts.map +0 -1
  102. package/types/utils/field-selection.d.ts +0 -9
  103. package/types/utils/field-selection.d.ts.map +0 -1
  104. package/types/utils/index.d.ts +0 -2
  105. package/types/utils/index.d.ts.map +0 -1
@@ -0,0 +1,510 @@
1
+ import { Document, PopulateOptions, ClientSession, PipelineStage, Model, Types } from 'mongoose';
2
+
3
+ /**
4
+ * MongoKit Type Definitions
5
+ *
6
+ * Production-grade types for MongoDB repository pattern with TypeScript
7
+ *
8
+ * @module @classytic/mongokit
9
+ */
10
+
11
+ /** Re-export mongoose ObjectId */
12
+ type ObjectId = Types.ObjectId;
13
+ /** Generic document type */
14
+ type AnyDocument = Document & Record<string, unknown>;
15
+ /** Generic model type */
16
+ type AnyModel = Model<AnyDocument>;
17
+ /** Sort direction */
18
+ type SortDirection = 1 | -1;
19
+ /** Sort specification */
20
+ type SortSpec = Record<string, SortDirection>;
21
+ /** Populate specification */
22
+ type PopulateSpec = string | string[] | PopulateOptions | PopulateOptions[];
23
+ /** Select specification */
24
+ type SelectSpec = string | string[] | Record<string, 0 | 1>;
25
+ /** Filter query type for MongoDB queries (compatible with Mongoose 8 & 9) */
26
+ type FilterQuery<T> = Record<string, unknown>;
27
+ /** Pagination configuration */
28
+ interface PaginationConfig {
29
+ /** Default number of documents per page (default: 10) */
30
+ defaultLimit?: number;
31
+ /** Maximum allowed limit (default: 100) */
32
+ maxLimit?: number;
33
+ /** Maximum allowed page number (default: 10000) */
34
+ maxPage?: number;
35
+ /** Page number that triggers performance warning (default: 100) */
36
+ deepPageThreshold?: number;
37
+ /** Cursor version for forward compatibility (default: 1) */
38
+ cursorVersion?: number;
39
+ /** Use estimatedDocumentCount for faster counts on large collections */
40
+ useEstimatedCount?: boolean;
41
+ }
42
+ /** Base pagination options */
43
+ interface BasePaginationOptions {
44
+ /** MongoDB query filters */
45
+ filters?: FilterQuery<AnyDocument>;
46
+ /** Sort specification */
47
+ sort?: SortSpec;
48
+ /** Number of documents per page */
49
+ limit?: number;
50
+ /** Fields to select */
51
+ select?: SelectSpec;
52
+ /** Fields to populate */
53
+ populate?: PopulateSpec;
54
+ /** Return plain JavaScript objects */
55
+ lean?: boolean;
56
+ /** MongoDB session for transactions */
57
+ session?: ClientSession;
58
+ }
59
+ /** Offset pagination options */
60
+ interface OffsetPaginationOptions extends BasePaginationOptions {
61
+ /** Page number (1-indexed) */
62
+ page?: number;
63
+ }
64
+ /** Keyset (cursor) pagination options */
65
+ interface KeysetPaginationOptions extends BasePaginationOptions {
66
+ /** Cursor token for next page */
67
+ after?: string;
68
+ /** Sort is required for keyset pagination */
69
+ sort: SortSpec;
70
+ }
71
+ /** Aggregate pagination options */
72
+ interface AggregatePaginationOptions {
73
+ /** Aggregation pipeline stages */
74
+ pipeline?: PipelineStage[];
75
+ /** Page number (1-indexed) */
76
+ page?: number;
77
+ /** Number of documents per page */
78
+ limit?: number;
79
+ /** MongoDB session for transactions */
80
+ session?: ClientSession;
81
+ }
82
+ /** Offset pagination result */
83
+ interface OffsetPaginationResult<T = unknown> {
84
+ /** Pagination method used */
85
+ method: 'offset';
86
+ /** Array of documents */
87
+ docs: T[];
88
+ /** Current page number */
89
+ page: number;
90
+ /** Documents per page */
91
+ limit: number;
92
+ /** Total document count */
93
+ total: number;
94
+ /** Total page count */
95
+ pages: number;
96
+ /** Whether next page exists */
97
+ hasNext: boolean;
98
+ /** Whether previous page exists */
99
+ hasPrev: boolean;
100
+ /** Performance warning for deep pagination */
101
+ warning?: string;
102
+ }
103
+ /** Keyset pagination result */
104
+ interface KeysetPaginationResult<T = unknown> {
105
+ /** Pagination method used */
106
+ method: 'keyset';
107
+ /** Array of documents */
108
+ docs: T[];
109
+ /** Documents per page */
110
+ limit: number;
111
+ /** Whether more documents exist */
112
+ hasMore: boolean;
113
+ /** Cursor token for next page */
114
+ next: string | null;
115
+ }
116
+ /** Aggregate pagination result */
117
+ interface AggregatePaginationResult<T = unknown> {
118
+ /** Pagination method used */
119
+ method: 'aggregate';
120
+ /** Array of documents */
121
+ docs: T[];
122
+ /** Current page number */
123
+ page: number;
124
+ /** Documents per page */
125
+ limit: number;
126
+ /** Total document count */
127
+ total: number;
128
+ /** Total page count */
129
+ pages: number;
130
+ /** Whether next page exists */
131
+ hasNext: boolean;
132
+ /** Whether previous page exists */
133
+ hasPrev: boolean;
134
+ /** Performance warning for deep pagination */
135
+ warning?: string;
136
+ }
137
+ /** Union type for all pagination results */
138
+ type PaginationResult<T = unknown> = OffsetPaginationResult<T> | KeysetPaginationResult<T> | AggregatePaginationResult<T>;
139
+ /** Repository operation options */
140
+ interface OperationOptions {
141
+ /** MongoDB session for transactions */
142
+ session?: ClientSession;
143
+ /** Fields to select */
144
+ select?: SelectSpec;
145
+ /** Fields to populate */
146
+ populate?: PopulateSpec;
147
+ /** Return plain JavaScript objects */
148
+ lean?: boolean;
149
+ /** Throw error if document not found (default: true) */
150
+ throwOnNotFound?: boolean;
151
+ /** Additional query filters (e.g., for soft delete) */
152
+ query?: Record<string, unknown>;
153
+ }
154
+ /** Create operation options */
155
+ interface CreateOptions {
156
+ /** MongoDB session for transactions */
157
+ session?: ClientSession;
158
+ /** Keep insertion order on error (default: true) */
159
+ ordered?: boolean;
160
+ }
161
+ /** Update operation options */
162
+ interface UpdateOptions extends OperationOptions {
163
+ /** Enable update pipeline syntax */
164
+ updatePipeline?: boolean;
165
+ }
166
+ /** Delete result */
167
+ interface DeleteResult {
168
+ success: boolean;
169
+ message: string;
170
+ count?: number;
171
+ }
172
+ /** Update many result */
173
+ interface UpdateManyResult {
174
+ matchedCount: number;
175
+ modifiedCount: number;
176
+ }
177
+ /** Validation result */
178
+ interface ValidationResult {
179
+ valid: boolean;
180
+ violations?: Array<{
181
+ field: string;
182
+ reason: string;
183
+ }>;
184
+ message?: string;
185
+ }
186
+ /** Update with validation result */
187
+ type UpdateWithValidationResult<T> = {
188
+ success: true;
189
+ data: T;
190
+ } | {
191
+ success: false;
192
+ error: {
193
+ code: number;
194
+ message: string;
195
+ violations?: ValidationResult['violations'];
196
+ };
197
+ };
198
+ /** User context for operations */
199
+ interface UserContext {
200
+ _id?: ObjectId | string;
201
+ id?: string;
202
+ roles?: string | string[];
203
+ [key: string]: unknown;
204
+ }
205
+ /** Repository operation context */
206
+ interface RepositoryContext {
207
+ /** Operation name */
208
+ operation: string;
209
+ /** Model name */
210
+ model: string;
211
+ /** Document data (for create/update) */
212
+ data?: Record<string, unknown>;
213
+ /** Array of documents (for createMany) */
214
+ dataArray?: Record<string, unknown>[];
215
+ /** Document ID (for update/delete/getById) */
216
+ id?: string | ObjectId;
217
+ /** Query filters */
218
+ query?: FilterQuery<AnyDocument>;
219
+ /** User making the request */
220
+ user?: UserContext;
221
+ /** Organization ID for multi-tenancy */
222
+ organizationId?: string | ObjectId;
223
+ /** Fields to select */
224
+ select?: SelectSpec;
225
+ /** Fields to populate */
226
+ populate?: PopulateSpec;
227
+ /** Return lean documents */
228
+ lean?: boolean;
229
+ /** MongoDB session */
230
+ session?: ClientSession;
231
+ /** Include soft-deleted documents */
232
+ includeDeleted?: boolean;
233
+ /** Custom context data from plugins */
234
+ [key: string]: unknown;
235
+ }
236
+ /** Plugin interface */
237
+ interface Plugin {
238
+ /** Plugin name */
239
+ name: string;
240
+ /** Apply plugin to repository */
241
+ apply(repo: RepositoryInstance): void;
242
+ }
243
+ /** Plugin function signature */
244
+ type PluginFunction = (repo: RepositoryInstance) => void;
245
+ /** Plugin type (object or function) */
246
+ type PluginType = Plugin | PluginFunction;
247
+ /** Repository instance for plugin type reference */
248
+ interface RepositoryInstance {
249
+ Model: Model<any>;
250
+ model: string;
251
+ _hooks: Map<string, Array<(data: any) => void | Promise<void>>>;
252
+ _pagination: unknown;
253
+ use(plugin: PluginType): this;
254
+ on(event: string, listener: (data: any) => void | Promise<void>): this;
255
+ emit(event: string, data: unknown): void;
256
+ registerMethod?(name: string, fn: Function): void;
257
+ hasMethod?(name: string): boolean;
258
+ [key: string]: unknown;
259
+ }
260
+ /** Repository event names */
261
+ type RepositoryEvent = 'before:create' | 'after:create' | 'error:create' | 'before:createMany' | 'after:createMany' | 'error:createMany' | 'before:update' | 'after:update' | 'error:update' | 'before:updateMany' | 'after:updateMany' | 'error:updateMany' | 'before:delete' | 'after:delete' | 'error:delete' | 'before:deleteMany' | 'after:deleteMany' | 'error:deleteMany' | 'before:getById' | 'after:getById' | 'before:getByQuery' | 'after:getByQuery' | 'before:getAll' | 'after:getAll' | 'before:aggregatePaginate' | 'method:registered';
262
+ /** Event payload */
263
+ interface EventPayload {
264
+ context: RepositoryContext;
265
+ result?: unknown;
266
+ error?: Error;
267
+ }
268
+ /** Field preset configuration */
269
+ interface FieldPreset {
270
+ /** Fields visible to everyone */
271
+ public: string[];
272
+ /** Additional fields for authenticated users */
273
+ authenticated?: string[];
274
+ /** Additional fields for admins */
275
+ admin?: string[];
276
+ }
277
+ /** Parsed query result */
278
+ interface ParsedQuery {
279
+ filters: FilterQuery<AnyDocument>;
280
+ limit: number;
281
+ sort: SortSpec | undefined;
282
+ populate: string | undefined;
283
+ search: string | undefined;
284
+ page?: number;
285
+ after?: string;
286
+ }
287
+ /** Field rules for schema building */
288
+ interface FieldRules {
289
+ [fieldName: string]: {
290
+ /** Field cannot be updated */
291
+ immutable?: boolean;
292
+ /** Alias for immutable */
293
+ immutableAfterCreate?: boolean;
294
+ /** System-only field (omitted from create/update) */
295
+ systemManaged?: boolean;
296
+ /** Remove from required array */
297
+ optional?: boolean;
298
+ };
299
+ }
300
+ /** Schema builder options */
301
+ interface SchemaBuilderOptions {
302
+ /** Field rules for create/update */
303
+ fieldRules?: FieldRules;
304
+ /** Strict additional properties (default: false) */
305
+ strictAdditionalProperties?: boolean;
306
+ /** Date format: 'date' | 'datetime' */
307
+ dateAs?: 'date' | 'datetime';
308
+ /** Create schema options */
309
+ create?: {
310
+ /** Fields to omit from create schema */
311
+ omitFields?: string[];
312
+ /** Override required status */
313
+ requiredOverrides?: Record<string, boolean>;
314
+ /** Override optional status */
315
+ optionalOverrides?: Record<string, boolean>;
316
+ /** Schema overrides */
317
+ schemaOverrides?: Record<string, unknown>;
318
+ };
319
+ /** Update schema options */
320
+ update?: {
321
+ /** Fields to omit from update schema */
322
+ omitFields?: string[];
323
+ };
324
+ /** Query schema options */
325
+ query?: {
326
+ /** Filterable fields */
327
+ filterableFields?: Record<string, {
328
+ type: string;
329
+ } | unknown>;
330
+ };
331
+ }
332
+ /** JSON Schema type */
333
+ interface JsonSchema {
334
+ type: string;
335
+ properties?: Record<string, unknown>;
336
+ required?: string[];
337
+ additionalProperties?: boolean | unknown;
338
+ items?: unknown;
339
+ enum?: string[];
340
+ format?: string;
341
+ pattern?: string;
342
+ }
343
+ /** CRUD schemas result */
344
+ interface CrudSchemas {
345
+ createBody: JsonSchema;
346
+ updateBody: JsonSchema;
347
+ params: JsonSchema;
348
+ listQuery: JsonSchema;
349
+ crudSchemas: {
350
+ create: {
351
+ body: JsonSchema;
352
+ };
353
+ update: {
354
+ body: JsonSchema;
355
+ params: JsonSchema;
356
+ };
357
+ get: {
358
+ params: JsonSchema;
359
+ };
360
+ list: {
361
+ query: JsonSchema;
362
+ };
363
+ remove: {
364
+ params: JsonSchema;
365
+ };
366
+ };
367
+ }
368
+ /** Decoded cursor */
369
+ interface DecodedCursor {
370
+ /** Primary sort field value (rehydrated) */
371
+ value: unknown;
372
+ /** Document ID (rehydrated) */
373
+ id: ObjectId | string;
374
+ /** Sort specification */
375
+ sort: SortSpec;
376
+ /** Cursor version */
377
+ version: number;
378
+ }
379
+ /** Validator definition */
380
+ interface ValidatorDefinition {
381
+ /** Validator name */
382
+ name: string;
383
+ /** Operations to apply validator to */
384
+ operations?: Array<'create' | 'createMany' | 'update' | 'delete'>;
385
+ /** Validation function */
386
+ validate: (context: RepositoryContext, repo?: RepositoryInstance) => void | Promise<void>;
387
+ }
388
+ /** Validation chain options */
389
+ interface ValidationChainOptions {
390
+ /** Stop on first validation error (default: true) */
391
+ stopOnFirstError?: boolean;
392
+ }
393
+ /** Logger interface for audit plugin */
394
+ interface Logger {
395
+ info?(message: string, meta?: Record<string, unknown>): void;
396
+ error?(message: string, meta?: Record<string, unknown>): void;
397
+ warn?(message: string, meta?: Record<string, unknown>): void;
398
+ debug?(message: string, meta?: Record<string, unknown>): void;
399
+ }
400
+ /** Soft delete plugin options */
401
+ interface SoftDeleteOptions {
402
+ /** Field name for deletion timestamp (default: 'deletedAt') */
403
+ deletedField?: string;
404
+ /** Field name for deleting user (default: 'deletedBy') */
405
+ deletedByField?: string;
406
+ /** Enable soft delete (default: true) */
407
+ soft?: boolean;
408
+ }
409
+ /** Lookup options for aggregate */
410
+ interface LookupOptions {
411
+ /** Collection to join */
412
+ from: string;
413
+ /** Local field to match */
414
+ localField: string;
415
+ /** Foreign field to match */
416
+ foreignField: string;
417
+ /** Output array field name */
418
+ as: string;
419
+ /** Additional pipeline stages */
420
+ pipeline?: PipelineStage[];
421
+ /** Initial match query */
422
+ query?: FilterQuery<AnyDocument>;
423
+ /** Operation options */
424
+ options?: {
425
+ session?: ClientSession;
426
+ };
427
+ }
428
+ /** Group result */
429
+ interface GroupResult {
430
+ _id: unknown;
431
+ count: number;
432
+ }
433
+ /** Min/Max result */
434
+ interface MinMaxResult {
435
+ min: unknown;
436
+ max: unknown;
437
+ }
438
+ /**
439
+ * Cache adapter interface - bring your own cache implementation
440
+ * Works with Redis, Memcached, in-memory, or any key-value store
441
+ *
442
+ * @example Redis implementation:
443
+ * ```typescript
444
+ * const redisCache: CacheAdapter = {
445
+ * async get(key) { return JSON.parse(await redis.get(key) || 'null'); },
446
+ * async set(key, value, ttl) { await redis.setex(key, ttl, JSON.stringify(value)); },
447
+ * async del(key) { await redis.del(key); },
448
+ * async clear(pattern) {
449
+ * const keys = await redis.keys(pattern || '*');
450
+ * if (keys.length) await redis.del(...keys);
451
+ * }
452
+ * };
453
+ * ```
454
+ */
455
+ interface CacheAdapter {
456
+ /** Get value by key, returns null if not found or expired */
457
+ get<T = unknown>(key: string): Promise<T | null>;
458
+ /** Set value with TTL in seconds */
459
+ set<T = unknown>(key: string, value: T, ttl: number): Promise<void>;
460
+ /** Delete single key */
461
+ del(key: string): Promise<void>;
462
+ /** Clear keys matching pattern (optional, used for bulk invalidation) */
463
+ clear?(pattern?: string): Promise<void>;
464
+ }
465
+ /** Cache plugin options */
466
+ interface CacheOptions {
467
+ /** Cache adapter implementation (required) */
468
+ adapter: CacheAdapter;
469
+ /** Default TTL in seconds (default: 60) */
470
+ ttl?: number;
471
+ /** TTL for byId queries in seconds (default: same as ttl) */
472
+ byIdTtl?: number;
473
+ /** TTL for query/list results in seconds (default: same as ttl) */
474
+ queryTtl?: number;
475
+ /** Key prefix for namespacing (default: 'mk') */
476
+ prefix?: string;
477
+ /** Enable debug logging (default: false) */
478
+ debug?: boolean;
479
+ /**
480
+ * Skip caching for queries with these characteristics:
481
+ * - largeLimit: Skip if limit > value (default: 100)
482
+ */
483
+ skipIf?: {
484
+ largeLimit?: number;
485
+ };
486
+ }
487
+ /** Options for cache-aware operations */
488
+ interface CacheOperationOptions {
489
+ /** Skip cache for this operation (read from DB directly) */
490
+ skipCache?: boolean;
491
+ /** Custom TTL for this operation in seconds */
492
+ cacheTtl?: number;
493
+ }
494
+ /** Cache statistics (for debugging/monitoring) */
495
+ interface CacheStats {
496
+ hits: number;
497
+ misses: number;
498
+ sets: number;
499
+ invalidations: number;
500
+ }
501
+ /** HTTP Error with status code */
502
+ interface HttpError extends Error {
503
+ status: number;
504
+ validationErrors?: Array<{
505
+ validator: string;
506
+ error: string;
507
+ }>;
508
+ }
509
+
510
+ export type { AnyDocument as A, SoftDeleteOptions as B, CreateOptions as C, DeleteResult as D, EventPayload as E, FieldPreset as F, LookupOptions as G, HttpError as H, GroupResult as I, JsonSchema as J, KeysetPaginationOptions as K, Logger as L, MinMaxResult as M, CacheAdapter as N, OffsetPaginationOptions as O, PaginationConfig as P, CacheOptions as Q, RepositoryContext as R, SelectSpec as S, CacheOperationOptions as T, UpdateOptions as U, ValidationResult as V, CacheStats as W, OffsetPaginationResult as a, KeysetPaginationResult as b, AggregatePaginationOptions as c, AggregatePaginationResult as d, PluginType as e, PopulateSpec as f, SortSpec as g, ObjectId as h, AnyModel as i, SortDirection as j, PaginationResult as k, OperationOptions as l, UpdateManyResult as m, UpdateWithValidationResult as n, UserContext as o, Plugin as p, PluginFunction as q, RepositoryInstance as r, RepositoryEvent as s, ParsedQuery as t, FieldRules as u, SchemaBuilderOptions as v, CrudSchemas as w, DecodedCursor as x, ValidatorDefinition as y, ValidationChainOptions as z };
@@ -0,0 +1,189 @@
1
+ export { b as createError, c as createFieldPreset, d as createMemoryCache, f as filterResponseData, g as getFieldsForUser, a as getMongooseProjection } from '../memory-cache-DG2oSSbx.js';
2
+ import { t as ParsedQuery, v as SchemaBuilderOptions, w as CrudSchemas, V as ValidationResult, S as SelectSpec, f as PopulateSpec, g as SortSpec } from '../types-Nxhmi1aI.js';
3
+ import mongoose__default, { Schema } from 'mongoose';
4
+
5
+ /**
6
+ * Query Parser
7
+ *
8
+ * Parses HTTP query parameters into MongoDB-compatible query objects.
9
+ * Supports operators, pagination, sorting, and filtering.
10
+ */
11
+
12
+ declare class QueryParser {
13
+ private operators;
14
+ /**
15
+ * Dangerous MongoDB operators that should never be accepted from user input
16
+ * Security: Prevent NoSQL injection attacks
17
+ */
18
+ private dangerousOperators;
19
+ /**
20
+ * Parse query parameters into MongoDB query format
21
+ */
22
+ parseQuery(query: Record<string, unknown> | null | undefined): ParsedQuery;
23
+ /**
24
+ * Parse sort parameter
25
+ * Converts string like '-createdAt' to { createdAt: -1 }
26
+ * Handles multiple sorts: '-createdAt,name' → { createdAt: -1, name: 1 }
27
+ */
28
+ private _parseSort;
29
+ /**
30
+ * Parse standard filter parameter (filter[field]=value)
31
+ */
32
+ private _parseFilters;
33
+ /**
34
+ * Handle operator syntax: field[operator]=value
35
+ */
36
+ private _handleOperatorSyntax;
37
+ /**
38
+ * Handle bracket syntax with object value
39
+ */
40
+ private _handleBracketSyntax;
41
+ /**
42
+ * Convert operator to MongoDB format
43
+ */
44
+ private _toMongoOperator;
45
+ /**
46
+ * Convert values based on operator type
47
+ */
48
+ private _convertValue;
49
+ /**
50
+ * Parse $or conditions
51
+ */
52
+ private _parseOr;
53
+ /**
54
+ * Enhance filters with between operator
55
+ */
56
+ private _enhanceWithBetween;
57
+ }
58
+ declare const _default: QueryParser;
59
+
60
+ /**
61
+ * Mongoose to JSON Schema Converter with Field Rules
62
+ *
63
+ * Generates Fastify JSON schemas from Mongoose models with declarative field rules.
64
+ *
65
+ * Field Rules (options.fieldRules):
66
+ * - immutable: Field cannot be updated (omitted from update schema)
67
+ * - immutableAfterCreate: Alias for immutable
68
+ * - systemManaged: System-only field (omitted from create/update)
69
+ * - optional: Remove from required array
70
+ *
71
+ * Additional Options:
72
+ * - strictAdditionalProperties: Set to true to add "additionalProperties: false" to schemas
73
+ * This makes Fastify reject unknown fields at validation level (default: false for backward compatibility)
74
+ *
75
+ * @example
76
+ * buildCrudSchemasFromModel(Model, {
77
+ * strictAdditionalProperties: true, // Reject unknown fields
78
+ * fieldRules: {
79
+ * organizationId: { immutable: true },
80
+ * status: { systemManaged: true },
81
+ * },
82
+ * create: { omitFields: ['verifiedAt'] },
83
+ * update: { omitFields: ['customerId'] }
84
+ * })
85
+ */
86
+
87
+ /**
88
+ * Build CRUD schemas from Mongoose schema
89
+ */
90
+ declare function buildCrudSchemasFromMongooseSchema(mongooseSchema: Schema, options?: SchemaBuilderOptions): CrudSchemas;
91
+ /**
92
+ * Build CRUD schemas from Mongoose model
93
+ */
94
+ declare function buildCrudSchemasFromModel(mongooseModel: mongoose__default.Model<unknown>, options?: SchemaBuilderOptions): CrudSchemas;
95
+ /**
96
+ * Get fields that are immutable (cannot be updated)
97
+ */
98
+ declare function getImmutableFields(options?: SchemaBuilderOptions): string[];
99
+ /**
100
+ * Get fields that are system-managed (cannot be set by users)
101
+ */
102
+ declare function getSystemManagedFields(options?: SchemaBuilderOptions): string[];
103
+ /**
104
+ * Check if field is allowed in update
105
+ */
106
+ declare function isFieldUpdateAllowed(fieldName: string, options?: SchemaBuilderOptions): boolean;
107
+ /**
108
+ * Validate update body against field rules
109
+ */
110
+ declare function validateUpdateBody(body?: Record<string, unknown>, options?: SchemaBuilderOptions): ValidationResult;
111
+
112
+ /**
113
+ * Cache Key Utilities
114
+ *
115
+ * Generates deterministic, collision-free cache keys for MongoDB queries.
116
+ * Key design inspired by Next.js cache tags and best practices from Stripe/Meta.
117
+ */
118
+
119
+ /**
120
+ * Generate cache key for getById operations
121
+ *
122
+ * Format: {prefix}:id:{model}:{documentId}
123
+ *
124
+ * @example
125
+ * byIdKey('mk', 'User', '507f1f77bcf86cd799439011')
126
+ * // => 'mk:id:User:507f1f77bcf86cd799439011'
127
+ */
128
+ declare function byIdKey(prefix: string, model: string, id: string): string;
129
+ /**
130
+ * Generate cache key for single-document queries
131
+ *
132
+ * Format: {prefix}:one:{model}:{queryHash}
133
+ *
134
+ * @example
135
+ * byQueryKey('mk', 'User', { email: 'john@example.com' })
136
+ * // => 'mk:one:User:a1b2c3d4'
137
+ */
138
+ declare function byQueryKey(prefix: string, model: string, query: Record<string, unknown>, options?: {
139
+ select?: SelectSpec;
140
+ populate?: PopulateSpec;
141
+ }): string;
142
+ /**
143
+ * Generate cache key for paginated list queries
144
+ *
145
+ * Format: {prefix}:list:{model}:{version}:{queryHash}
146
+ *
147
+ * The version component enables efficient bulk invalidation:
148
+ * - On any mutation, bump the version
149
+ * - All list cache keys become invalid without scanning/deleting each
150
+ *
151
+ * @example
152
+ * listQueryKey('mk', 'User', 1, { filters: { status: 'active' }, page: 1, limit: 20 })
153
+ * // => 'mk:list:User:1:e5f6g7h8'
154
+ */
155
+ declare function listQueryKey(prefix: string, model: string, version: number, params: {
156
+ filters?: Record<string, unknown>;
157
+ sort?: SortSpec;
158
+ page?: number;
159
+ limit?: number;
160
+ after?: string;
161
+ select?: SelectSpec;
162
+ populate?: PopulateSpec;
163
+ }): string;
164
+ /**
165
+ * Generate cache key for collection version tag
166
+ *
167
+ * Format: {prefix}:ver:{model}
168
+ *
169
+ * Used to track mutation version for list invalidation
170
+ */
171
+ declare function versionKey(prefix: string, model: string): string;
172
+ /**
173
+ * Generate pattern for clearing all cache keys for a model
174
+ *
175
+ * Format: {prefix}:*:{model}:*
176
+ *
177
+ * @example
178
+ * modelPattern('mk', 'User')
179
+ * // => 'mk:*:User:*'
180
+ */
181
+ declare function modelPattern(prefix: string, model: string): string;
182
+ /**
183
+ * Generate pattern for clearing all list cache keys for a model
184
+ *
185
+ * Format: {prefix}:list:{model}:*
186
+ */
187
+ declare function listPattern(prefix: string, model: string): string;
188
+
189
+ export { buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, byIdKey, byQueryKey, getImmutableFields, getSystemManagedFields, isFieldUpdateAllowed, listPattern, listQueryKey, modelPattern, _default as queryParser, validateUpdateBody, versionKey };