monsqlize 2.0.5 → 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,634 @@
1
+ import type { BookmarkClearResult, BookmarkListResult, BookmarkPrewarmResult, DeleteBatchResult, DeleteResult, IncrementOneResult, IndexCreateResult, InsertBatchResult, InsertManyResult, InsertOneResult, UpdateBatchResult, UpdateResult } from './collection.mjs';
2
+
3
+ /**
4
+ * Schema DSL transformer function.
5
+ * Receives a raw DSL descriptor and returns a transformed schema object.
6
+ * @since v1.0.0
7
+ */
8
+ export type SchemaDSL = (dsl: unknown) => unknown;
9
+
10
+ /**
11
+ * Default value for a model field — either a static value or a factory function.
12
+ * @template T Field value type
13
+ * @since v1.0.0
14
+ */
15
+ export type DefaultValue<T = unknown> = T | ((context?: unknown, doc?: unknown) => T);
16
+
17
+ export interface ValidationResult {
18
+ valid: boolean;
19
+ errors?: Array<{
20
+ field: string;
21
+ message: string;
22
+ value?: unknown;
23
+ }>;
24
+ data?: unknown;
25
+ }
26
+
27
+ export interface HookContext {
28
+ operation: string;
29
+ collection: string;
30
+ data?: unknown;
31
+ filter?: unknown;
32
+ update?: unknown;
33
+ result?: unknown;
34
+ error?: Error;
35
+ [key: string]: unknown;
36
+ }
37
+
38
+ export interface ModelConnection {
39
+ pool?: string;
40
+ database?: string;
41
+ }
42
+
43
+ export interface RelationConfig {
44
+ from: string;
45
+ localField: string;
46
+ foreignField: string;
47
+ single?: boolean;
48
+ }
49
+
50
+ export interface PopulateConfig {
51
+ path: string;
52
+ select?: string | string[];
53
+ match?: Record<string, unknown>;
54
+ sort?: Record<string, 1 | -1>;
55
+ limit?: number;
56
+ skip?: number;
57
+ populate?: string | PopulateConfig | Array<string | PopulateConfig>;
58
+ }
59
+
60
+ export interface VirtualConfig {
61
+ get: (this: Record<string, unknown>) => unknown;
62
+ set?: (this: Record<string, unknown>, value: unknown) => void;
63
+ }
64
+
65
+ export type ModelAutoIndexOptions = boolean | {
66
+ /** Enable automatic model index creation. Defaults to true for backward compatibility. */
67
+ enabled?: boolean;
68
+ /** Emit `model-index-error` when automatic index creation fails. Defaults to true. */
69
+ emitEvents?: boolean;
70
+ };
71
+
72
+ export type ModelIndexSource = 'definition' | 'softDelete';
73
+
74
+ export interface ModelDeclaredIndex {
75
+ source: ModelIndexSource;
76
+ key: unknown;
77
+ options: Record<string, unknown>;
78
+ name?: string;
79
+ fingerprint: string;
80
+ }
81
+
82
+ export interface ModelIndexNamespace {
83
+ db: string;
84
+ collection: string;
85
+ poolName: string;
86
+ }
87
+
88
+ export interface ModelIndexErrorSummary {
89
+ name?: string;
90
+ message: string;
91
+ code?: unknown;
92
+ }
93
+
94
+ export interface ModelIndexEnsureExisting {
95
+ declared: ModelDeclaredIndex;
96
+ existing: Record<string, unknown>;
97
+ }
98
+
99
+ export interface ModelIndexConflict {
100
+ declared: ModelDeclaredIndex;
101
+ existing?: Record<string, unknown>;
102
+ reason: string;
103
+ }
104
+
105
+ export interface ModelIndexCreated {
106
+ declared: ModelDeclaredIndex;
107
+ name?: string;
108
+ result?: unknown;
109
+ }
110
+
111
+ export interface ModelIndexFailure {
112
+ declared: ModelDeclaredIndex;
113
+ error: ModelIndexErrorSummary;
114
+ }
115
+
116
+ export interface ModelIndexSkipped {
117
+ declared: ModelDeclaredIndex;
118
+ reason: string;
119
+ }
120
+
121
+ export interface ModelEnsureIndexesOptions {
122
+ /** Return the index diff without creating missing indexes. */
123
+ dryRun?: boolean;
124
+ /** Throw a MonSQLize `MONGODB_ERROR` when conflicts or creation failures are found. */
125
+ throwOnError?: boolean;
126
+ }
127
+
128
+ export interface ModelEnsureAllIndexesOptions extends ModelEnsureIndexesOptions {
129
+ /** Limit the operation to specific registered model names. Defaults to all models. */
130
+ models?: string[];
131
+ /** Optional database scope for models without their own connection override. */
132
+ database?: string;
133
+ /** Optional pool scope for models without their own connection override. */
134
+ pool?: string;
135
+ }
136
+
137
+ export interface ModelIndexEnsureResult {
138
+ dryRun: boolean;
139
+ namespace: ModelIndexNamespace;
140
+ declared: ModelDeclaredIndex[];
141
+ existing: ModelIndexEnsureExisting[];
142
+ missing: ModelDeclaredIndex[];
143
+ created: ModelIndexCreated[];
144
+ conflicts: ModelIndexConflict[];
145
+ failed: ModelIndexFailure[];
146
+ skipped: ModelIndexSkipped[];
147
+ }
148
+
149
+ export interface ModelIndexEnsureSummary {
150
+ dryRun: boolean;
151
+ models: Array<{ name: string; result: ModelIndexEnsureResult }>;
152
+ totals: {
153
+ declared: number;
154
+ existing: number;
155
+ missing: number;
156
+ created: number;
157
+ conflicts: number;
158
+ failed: number;
159
+ skipped: number;
160
+ };
161
+ }
162
+
163
+ /** v1 hooks factory format */
164
+ export type V1HooksFactory<TDocument = Record<string, unknown>> = (
165
+ model: ModelInstance<TDocument>,
166
+ ) => {
167
+ find?: {
168
+ before?: (ctx: Record<string, unknown>, ...args: unknown[]) => unknown;
169
+ after?: (ctx: Record<string, unknown>, result: unknown) => unknown;
170
+ };
171
+ insert?: {
172
+ before?: (ctx: Record<string, unknown>, ...args: unknown[]) => unknown;
173
+ after?: (ctx: Record<string, unknown>, result: unknown) => unknown;
174
+ };
175
+ update?: {
176
+ before?: (ctx: Record<string, unknown>, ...args: unknown[]) => unknown;
177
+ after?: (ctx: Record<string, unknown>, result: unknown) => unknown;
178
+ };
179
+ delete?: {
180
+ before?: (ctx: Record<string, unknown>, ...args: unknown[]) => unknown;
181
+ after?: (ctx: Record<string, unknown>, result: unknown) => unknown;
182
+ };
183
+ };
184
+
185
+ /** v1 methods factory format */
186
+ export type V1MethodsFactory<TDocument = Record<string, unknown>> = (
187
+ model: ModelInstance<TDocument>,
188
+ ) => {
189
+ instance?: Record<string, (this: TDocument & Record<string, unknown>, ...args: unknown[]) => unknown>;
190
+ static?: Record<string, (...args: unknown[]) => unknown>;
191
+ };
192
+
193
+ export interface ModelDefinitionOptions {
194
+ timestamps?: boolean | { createdAt?: string | boolean; updatedAt?: string | boolean };
195
+ validate?: boolean;
196
+ autoIndex?: ModelAutoIndexOptions;
197
+ softDelete?: boolean | {
198
+ enabled?: boolean;
199
+ field?: string;
200
+ type?: string;
201
+ ttl?: number | null;
202
+ };
203
+ version?: boolean | {
204
+ enabled?: boolean;
205
+ field?: string;
206
+ };
207
+ }
208
+
209
+ export interface ModelDefinition<TDocument = Record<string, unknown>> {
210
+ /** Actual MongoDB collection name; falls back to `name` and then the `Model.define()` registration name. */
211
+ collection?: string;
212
+ /** Compatibility collection name used by model auto-loading files; `collection` has higher priority. */
213
+ name?: string;
214
+ enums?: Record<string, string>;
215
+ schema?: ((dsl: unknown) => unknown) | Record<string, unknown>;
216
+ defaults?: Record<string, unknown | ((context?: unknown, doc?: TDocument) => unknown)>;
217
+ hooks?:
218
+ | {
219
+ beforeCreate?: (context: HookContext) => Promise<void> | void;
220
+ afterCreate?: (context: HookContext) => Promise<void> | void;
221
+ beforeInsert?: (context: HookContext) => Promise<void> | void;
222
+ afterInsert?: (context: HookContext) => Promise<void> | void;
223
+ beforeUpdate?: (context: HookContext) => Promise<void> | void;
224
+ afterUpdate?: (context: HookContext) => Promise<void> | void;
225
+ beforeDelete?: (context: HookContext) => Promise<void> | void;
226
+ afterDelete?: (context: HookContext) => Promise<void> | void;
227
+ beforeFind?: (context: HookContext) => Promise<void> | void;
228
+ afterFind?: (context: HookContext) => Promise<void> | void;
229
+ }
230
+ | V1HooksFactory<TDocument>;
231
+ methods?:
232
+ | Record<string, (this: TDocument & Record<string, unknown>, ...args: unknown[]) => unknown>
233
+ | V1MethodsFactory<TDocument>;
234
+ statics?: Record<string, (...args: unknown[]) => unknown>;
235
+ relations?: Record<string, RelationConfig>;
236
+ virtuals?: Record<string, VirtualConfig>;
237
+ connection?: ModelConnection;
238
+ indexes?: Array<{ key: unknown } & Record<string, unknown>>;
239
+ options?: ModelDefinitionOptions;
240
+ }
241
+
242
+ export interface RegisteredModel<TDocument = Record<string, unknown>> {
243
+ collectionName: string;
244
+ definition: ModelDefinition<TDocument>;
245
+ }
246
+
247
+ export interface ModelScopeOptions {
248
+ database?: string;
249
+ pool?: string;
250
+ }
251
+
252
+ export interface PopulateProxy<T = unknown> extends Promise<T> {
253
+ populate(path: string | PopulateConfig | Array<string | PopulateConfig>, options?: Partial<Omit<PopulateConfig, 'path'>>): PopulateProxy<T>;
254
+ exec(): Promise<T>;
255
+ }
256
+
257
+ type LegacyModelPageInfo<TDocument = any> = unknown extends TDocument ? any : {
258
+ hasNext: boolean;
259
+ hasPrev: boolean;
260
+ startCursor: string | null;
261
+ endCursor: string | null;
262
+ currentPage?: number;
263
+ };
264
+ type LegacyModelTotalsInfo<TDocument = any> = unknown extends TDocument ? any : import('./collection.mjs').TotalsInfo;
265
+ type LegacyModelSyncTotalsInfo<TDocument = any> = unknown extends TDocument ? any : (import('./collection.mjs').TotalsInfo & {
266
+ mode: 'sync';
267
+ total: number;
268
+ totalPages: number;
269
+ });
270
+ export type RestoreResult = Pick<UpdateResult, 'modifiedCount'> & Partial<UpdateResult>;
271
+
272
+ export type ModelDocument<TDocument = any> = TDocument & Record<string, unknown> & {
273
+ save(): Promise<ModelDocument<TDocument>>;
274
+ remove(): Promise<boolean>;
275
+ validate(): Promise<ValidationResult>;
276
+ populate(path: string | PopulateConfig | Array<string | PopulateConfig>): PopulateProxy<ModelDocument<TDocument> | null>;
277
+ toObject(): TDocument & Record<string, unknown>;
278
+ toJSON(): TDocument & Record<string, unknown>;
279
+ };
280
+
281
+ export interface ModelInstance<TDocument = any> {
282
+ readonly collectionName: string;
283
+ readonly dbName: string;
284
+ readonly poolName?: string;
285
+ readonly definition: ModelDefinition<TDocument>;
286
+ /** Returns namespace metadata for the current model, including instance ID, type, database, and collection. */
287
+ getNamespace(): { iid: string; type: 'mongodb'; db: string; collection: string; };
288
+ /** Returns the relation config map declared by the current model. */
289
+ getRelations(): Record<string, RelationConfig>;
290
+ /** Returns the enum value map declared by the current model. */
291
+ getEnums(): Record<string, string>;
292
+ /** Returns the underlying native MongoDB Collection for raw operations not wrapped by the framework. */
293
+ raw(): unknown;
294
+ /**
295
+ * Finds documents matching the query.
296
+ * @param query Optional filter.
297
+ * @param options Optional query options such as projection, sort, and limit.
298
+ * @returns Document array with chainable `.populate()` support.
299
+ */
300
+ find(query?: unknown, options?: unknown): PopulateProxy<Array<ModelDocument<TDocument>>>;
301
+ /**
302
+ * Finds the first document matching the query.
303
+ * @param query Optional filter.
304
+ * @param options Optional query options.
305
+ * @returns The matching document, or `null` when none is found.
306
+ */
307
+ findOne(query?: unknown, options?: unknown): PopulateProxy<ModelDocument<TDocument> | null>;
308
+ /**
309
+ * Finds a single document by primary ID, as an ID shortcut for `findOne`.
310
+ * @param id Document primary key value.
311
+ * @param options Optional query options.
312
+ * @returns The matching document, or `null` when none is found.
313
+ */
314
+ findOneById(id: unknown, options?: unknown): PopulateProxy<ModelDocument<TDocument> | null>;
315
+ /**
316
+ * Finds a single document by primary ID; alias of `findOneById`.
317
+ * @param id Document primary key value.
318
+ * @param options Optional query options.
319
+ * @returns The matching document, or `null` when none is found.
320
+ */
321
+ findById(id: unknown, options?: unknown): PopulateProxy<ModelDocument<TDocument> | null>;
322
+ /**
323
+ * Finds documents by multiple primary IDs.
324
+ * @param ids Primary key values.
325
+ * @param options Optional query options.
326
+ * @returns Matching documents.
327
+ */
328
+ findByIds(ids: unknown[], options?: unknown): PopulateProxy<Array<ModelDocument<TDocument>>>;
329
+ /**
330
+ * Finds documents with cursor-based or page-number pagination.
331
+ * @param options Pagination options including `limit`, `cursor`/`page`, `filter`, and `sort`.
332
+ * @returns Result object containing items, page information, and optional totals.
333
+ */
334
+ findPage(options: { totals: { mode: 'sync'; } & Record<string, unknown>; } & Record<string, unknown>): PopulateProxy<{
335
+ items: Array<ModelDocument<TDocument>>;
336
+ pageInfo: LegacyModelPageInfo<TDocument>;
337
+ totals: LegacyModelSyncTotalsInfo<TDocument>;
338
+ meta?: import('./collection.mjs').MetaInfo;
339
+ }>;
340
+ findPage(options?: unknown): PopulateProxy<{
341
+ items: Array<ModelDocument<TDocument>>;
342
+ pageInfo: LegacyModelPageInfo<TDocument>;
343
+ totals?: LegacyModelTotalsInfo<TDocument>;
344
+ meta?: import('./collection.mjs').MetaInfo;
345
+ }>;
346
+ /**
347
+ * Finds documents and returns the unpaginated total count.
348
+ * @param query Optional filter.
349
+ * @param options Optional query options.
350
+ * @returns Object containing documents and total count.
351
+ */
352
+ findAndCount(query?: unknown, options?: unknown): PopulateProxy<{
353
+ data: Array<ModelDocument<TDocument>>;
354
+ total: number;
355
+ }>;
356
+ /**
357
+ * Counts documents matching the query.
358
+ * @param query Optional filter.
359
+ * @param options Optional count options.
360
+ * @returns Number of matching documents.
361
+ */
362
+ count(query?: unknown, options?: unknown): Promise<number>;
363
+ /**
364
+ * Inserts a single document.
365
+ * @param document Document data to insert.
366
+ * @param options Optional write options.
367
+ * @returns Result object containing the inserted ID.
368
+ */
369
+ insertOne(document?: unknown, options?: unknown): Promise<InsertOneResult>;
370
+ /**
371
+ * Inserts multiple documents in order, stopping on the first error.
372
+ * @param documents Documents to insert.
373
+ * @param options Optional write options.
374
+ */
375
+ insertMany(documents?: unknown[], options?: unknown): Promise<InsertManyResult>;
376
+ /**
377
+ * Updates the first document matching the filter.
378
+ * @param filter Filter.
379
+ * @param update Update operator document, such as `$set` or `$inc`.
380
+ * @param options Optional update options.
381
+ */
382
+ updateOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
383
+ /**
384
+ * Updates all documents matching the filter.
385
+ * @param filter Filter.
386
+ * @param update Update operator document.
387
+ * @param options Optional update options.
388
+ */
389
+ updateMany(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
390
+ /**
391
+ * Replaces the first document matching the filter with a full replacement document.
392
+ * @param filter Filter.
393
+ * @param replacement Full replacement document.
394
+ * @param options Optional replacement options.
395
+ */
396
+ replaceOne(filter?: unknown, replacement?: unknown, options?: unknown): Promise<UpdateResult>;
397
+ /**
398
+ * Atomically finds and updates one document.
399
+ * @param filter Filter.
400
+ * @param update Update operator document.
401
+ * @param options Optional options such as `returnDocument: 'after'`.
402
+ * @returns Updated document, or `null` when none is found.
403
+ */
404
+ findOneAndUpdate(filter?: unknown, update?: unknown, options?: unknown): Promise<TDocument | null>;
405
+ /**
406
+ * Atomically finds and replaces one document.
407
+ * @param filter Filter.
408
+ * @param replacement Full replacement document.
409
+ * @param options Optional options.
410
+ * @returns Replaced document, or `null` when none is found.
411
+ */
412
+ findOneAndReplace(filter?: unknown, replacement?: unknown, options?: unknown): Promise<TDocument | null>;
413
+ /**
414
+ * Atomically finds and deletes one document.
415
+ * @param filter Filter.
416
+ * @param options Optional options.
417
+ * @returns Deleted document, or `null` when none is found.
418
+ */
419
+ findOneAndDelete(filter?: unknown, options?: unknown): Promise<TDocument | null>;
420
+ /**
421
+ * Updates an existing document or inserts one when none matches.
422
+ * @param filter Filter.
423
+ * @param update Update operator document.
424
+ * @param options Optional update options.
425
+ * @returns Standard `UpdateResult` object.
426
+ */
427
+ upsertOne(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateResult>;
428
+ /**
429
+ * Atomically increments a field on one matching document.
430
+ * @param filter Filter.
431
+ * @param field Field name or field-increment map.
432
+ * @param increment Increment value used when `field` is a string.
433
+ * @param options Optional update options.
434
+ */
435
+ incrementOne(filter?: unknown, field?: string | Record<string, number>, increment?: number, options?: unknown): Promise<IncrementOneResult<TDocument>>;
436
+ /**
437
+ * Deletes the first document matching the filter.
438
+ * @param filter Filter.
439
+ * @param options Optional delete options.
440
+ * @returns Standard `DeleteResult` object.
441
+ */
442
+ deleteOne(filter?: unknown, options?: unknown): Promise<DeleteResult>;
443
+ /**
444
+ * Deletes all documents matching the filter.
445
+ * @param filter Filter.
446
+ * @param options Optional delete options.
447
+ * @returns Standard `DeleteResult` object.
448
+ */
449
+ deleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
450
+ // soft-delete extended methods
451
+ /**
452
+ * Finds matching documents, including soft-deleted documents.
453
+ * @param query Optional filter.
454
+ * @param options Optional query options.
455
+ */
456
+ findWithDeleted(query?: unknown, options?: unknown): PopulateProxy<Array<ModelDocument<TDocument>>>;
457
+ /**
458
+ * Finds only soft-deleted documents.
459
+ * @param query Optional filter.
460
+ * @param options Optional query options.
461
+ */
462
+ findOnlyDeleted(query?: unknown, options?: unknown): PopulateProxy<Array<ModelDocument<TDocument>>>;
463
+ /**
464
+ * Finds the first matching document, including soft-deleted documents.
465
+ * @param query Optional filter.
466
+ * @param options Optional query options.
467
+ * @returns Matching document, or `null` when none is found.
468
+ */
469
+ findOneWithDeleted(query?: unknown, options?: unknown): PopulateProxy<ModelDocument<TDocument> | null>;
470
+ /**
471
+ * Restores the first soft-deleted document matching the filter.
472
+ * @param filter Filter.
473
+ * @param options Optional update options.
474
+ */
475
+ restore(filter?: unknown, options?: unknown): Promise<RestoreResult>;
476
+ /**
477
+ * Restores all soft-deleted documents matching the filter.
478
+ * @param filter Filter.
479
+ * @param options Optional update options.
480
+ */
481
+ restoreMany(filter?: unknown, options?: unknown): Promise<RestoreResult>;
482
+ /**
483
+ * Physically deletes the first matching document, bypassing soft-delete.
484
+ * @param filter Filter.
485
+ * @param options Optional delete options.
486
+ * @returns Standard `DeleteResult` object.
487
+ */
488
+ forceDelete(filter?: unknown, options?: unknown): Promise<DeleteResult>;
489
+ /**
490
+ * Physically deletes all matching documents, bypassing soft-delete.
491
+ * @param filter Filter.
492
+ * @param options Optional delete options.
493
+ * @returns Standard `DeleteResult` object.
494
+ */
495
+ forceDeleteMany(filter?: unknown, options?: unknown): Promise<DeleteResult>;
496
+ /**
497
+ * Finds the first matching document from only the soft-deleted set.
498
+ * @param query Optional filter.
499
+ * @param options Optional query options.
500
+ * @returns Matching deleted document, or `null` when none is found.
501
+ */
502
+ findOneOnlyDeleted(query?: unknown, options?: unknown): PopulateProxy<ModelDocument<TDocument> | null>;
503
+ /**
504
+ * Counts matching documents, including soft-deleted documents.
505
+ * @param query Optional filter.
506
+ * @param options Optional count options.
507
+ */
508
+ countWithDeleted(query?: unknown, options?: unknown): Promise<number>;
509
+ /**
510
+ * Counts soft-deleted documents matching the query.
511
+ * @param query Optional filter.
512
+ * @param options Optional count options.
513
+ */
514
+ countOnlyDeleted(query?: unknown, options?: unknown): Promise<number>;
515
+ /**
516
+ * Inserts a large document batch through the write queue.
517
+ * @param docs Documents to insert.
518
+ * @param options Optional batch write options.
519
+ */
520
+ insertBatch(docs: unknown[], options?: unknown): Promise<InsertBatchResult>;
521
+ /**
522
+ * Batch-updates matching documents using `bulkWrite`.
523
+ * @param filter Filter.
524
+ * @param update Update operator document.
525
+ * @param options Optional batch write options.
526
+ */
527
+ updateBatch(filter?: unknown, update?: unknown, options?: unknown): Promise<UpdateBatchResult>;
528
+ /** Batch-deletes matching documents. */
529
+ deleteBatch(filter?: unknown, options?: unknown): Promise<DeleteBatchResult>;
530
+ /**
531
+ * Creates a single index on the collection.
532
+ * @param keys Index key specification.
533
+ * @param options Optional index options such as `unique` or `sparse`.
534
+ * @returns Index creation result.
535
+ */
536
+ createIndex(keys: unknown, options?: unknown): Promise<IndexCreateResult>;
537
+ /**
538
+ * Creates multiple indexes.
539
+ * @param specs Index specifications, each containing `key` and optional index options.
540
+ * @returns Names of created indexes.
541
+ */
542
+ createIndexes(specs: Array<{ key: unknown; } & Record<string, unknown>>): Promise<string[]>;
543
+ /** Lists all existing index definitions on the collection. */
544
+ listIndexes(): Promise<Record<string, unknown>[]>;
545
+ /**
546
+ * Compares declared model indexes with the database and optionally creates missing indexes.
547
+ * Does not drop, rename, or rebuild conflicting indexes.
548
+ */
549
+ ensureIndexes(options?: ModelEnsureIndexesOptions): Promise<ModelIndexEnsureResult>;
550
+ /**
551
+ * Drops the specified index by name.
552
+ * @param name Index name.
553
+ */
554
+ dropIndex(name: string): Promise<unknown>;
555
+ /** Drops all non-`_id` indexes on the collection. */
556
+ dropIndexes(): Promise<unknown>;
557
+ /** Prewarms cursor pagination bookmark cache. */
558
+ prewarmBookmarks(keyDims?: unknown, pages?: number[]): Promise<BookmarkPrewarmResult>;
559
+ /** Lists cursor pagination bookmark cache entries. */
560
+ listBookmarks(keyDims?: unknown): Promise<BookmarkListResult>;
561
+ /** Clears cursor pagination bookmark cache entries. */
562
+ clearBookmarks(keyDims?: unknown): Promise<BookmarkClearResult>;
563
+ /**
564
+ * Gets distinct values for a field from matching documents.
565
+ * @param key Target field name.
566
+ * @param query Optional filter.
567
+ * @param options Optional driver-level options.
568
+ * @returns Distinct values.
569
+ */
570
+ distinct(key: string, query?: unknown, options?: unknown): Promise<unknown[]>;
571
+ /**
572
+ * Executes an aggregation pipeline and returns result documents.
573
+ * @param pipeline Aggregation stages.
574
+ * @param options Optional aggregation options such as `allowDiskUse`.
575
+ * @returns Aggregation result documents.
576
+ */
577
+ aggregate(pipeline?: unknown[], options?: unknown): Promise<unknown[]>;
578
+ /** Returns a readable stream for matching query results. */
579
+ stream(query?: unknown, options?: unknown): NodeJS.ReadableStream;
580
+ /** Returns the MongoDB query execution plan. */
581
+ explain(query?: unknown, options?: unknown): Promise<unknown>;
582
+ /** Manually invalidates read cache for the current model collection. */
583
+ invalidate(op?: 'find' | 'findOne' | 'count' | 'findPage' | 'aggregate' | 'distinct'): Promise<number>;
584
+ /** Drops the collection for the current model. */
585
+ dropCollection(): Promise<boolean>;
586
+ /** Creates the current collection or a collection with the specified name. */
587
+ createCollection(name?: string, options?: Record<string, unknown>): Promise<boolean>;
588
+ /** Creates a MongoDB view. */
589
+ createView(name: string, source: string, pipeline?: unknown[]): Promise<boolean>;
590
+ /** Returns index usage statistics. */
591
+ indexStats(): Promise<unknown[]>;
592
+ /** Sets the collection JSON Schema validator. */
593
+ setValidator(validator: unknown, options?: { validationLevel?: string; validationAction?: string }): Promise<{ ok: number; collection: string }>;
594
+ /** Sets the collection validation level. */
595
+ setValidationLevel(level: 'off' | 'moderate' | 'strict' | string): Promise<{ ok: number; validationLevel: string }>;
596
+ /** Sets the collection validation action. */
597
+ setValidationAction(action: 'error' | 'warn' | string): Promise<{ ok: number; validationAction: string }>;
598
+ /** Reads the collection validator and validation settings. */
599
+ getValidator(): Promise<{ validator: Record<string, unknown> | null; validationLevel: string; validationAction: string }>;
600
+ /** Returns collection storage and index statistics. */
601
+ stats(options?: { scale?: number }): Promise<{ ns: string; count: number; size: number; storageSize: number; totalIndexSize: number; nindexes: number; avgObjSize?: number; scaleFactor?: number }>;
602
+ /** Renames the collection for the current model. */
603
+ renameCollection(newName: string, options?: { dropTarget?: boolean }): Promise<{ renamed: boolean; from: string; to: string }>;
604
+ /** Executes a collMod management command. */
605
+ collMod(modifications: Record<string, unknown>): Promise<Record<string, unknown>>;
606
+ /** Converts the collection to a capped collection. */
607
+ convertToCapped(size: number, options?: { max?: number }): Promise<{ ok: number; collection: string; capped: boolean; size: number }>;
608
+ /**
609
+ * Opens a ChangeStream on the collection.
610
+ * @param pipeline Optional aggregation filter pipeline.
611
+ * @param options Optional ChangeStream options.
612
+ * @returns Native MongoDB ChangeStream object.
613
+ */
614
+ watch(pipeline?: unknown[], options?: unknown): import('mongodb').ChangeStream;
615
+ /**
616
+ * Validates document data against the model schema definition.
617
+ * @param document Document to validate.
618
+ * @returns Validation result containing the `valid` flag and error details.
619
+ */
620
+ validate(document?: unknown): ValidationResult;
621
+ }
622
+
623
+ export declare class Model {
624
+ static define<TDocument = Record<string, unknown>>(collectionName: string, definition: ModelDefinition<TDocument>): void;
625
+ static get<TDocument = Record<string, unknown>>(collectionName: string): RegisteredModel<TDocument> | undefined;
626
+ static has(collectionName: string): boolean;
627
+ static list(): string[];
628
+ static undefine(collectionName: string): boolean;
629
+ static redefine<TDocument = Record<string, unknown>>(collectionName: string, definition: ModelDefinition<TDocument>): void;
630
+ static _clear(): void;
631
+ }
632
+
633
+
634
+
@@ -0,0 +1,56 @@
1
+ import type { Db, MongoClient, MongoClientOptions } from 'mongodb';
2
+ import type { SSHConfig } from './monsqlize.mjs';
3
+
4
+ export interface MongoConnectConfig {
5
+ uri?: string;
6
+ options?: MongoClientOptions;
7
+ /** v1 compat: read preference shortcut merged into MongoClient options. */
8
+ readPreference?: MongoClientOptions['readPreference'];
9
+ /**
10
+ * v1 compat: when true, automatically starts mongodb-memory-server without requiring a uri.
11
+ * For testing only.
12
+ */
13
+ useMemoryServer?: boolean;
14
+ /** Instance/binary configuration options for mongodb-memory-server. */
15
+ memoryServerOptions?: {
16
+ instance?: {
17
+ port?: number;
18
+ dbName?: string;
19
+ storageEngine?: string;
20
+ replSet?: string;
21
+ dbPath?: string;
22
+ launchTimeout?: number;
23
+ };
24
+ binary?: { version?: string };
25
+ [key: string]: unknown;
26
+ };
27
+ /**
28
+ * SSH tunnel configuration. When provided, monSQLize establishes an SSH port-forward
29
+ * through the specified bastion host before connecting to MongoDB.
30
+ * The remote host/port are auto-parsed from `uri` unless overridden by `remoteHost`/`remotePort`.
31
+ * @since v1.3.0
32
+ */
33
+ ssh?: SSHConfig;
34
+ /**
35
+ * Explicit remote MongoDB host visible from the SSH server.
36
+ * Overrides the host auto-parsed from `uri` when `ssh` is set.
37
+ * @since v1.3.0
38
+ */
39
+ remoteHost?: string;
40
+ /**
41
+ * Explicit remote MongoDB port visible from the SSH server.
42
+ * Overrides the port auto-parsed from `uri` when `ssh` is set.
43
+ * @since v1.3.0
44
+ */
45
+ remotePort?: number;
46
+ /** @alias remoteHost — v1 SSH config field */
47
+ mongoHost?: string;
48
+ /** @alias remotePort — v1 SSH config field */
49
+ mongoPort?: number;
50
+ }
51
+
52
+ export interface MongoConnectionState {
53
+ client: MongoClient;
54
+ db: Db;
55
+ }
56
+