@treatwell/moleculer-essentials 1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/context-factory-BWO3xPWE.d.cts +520 -0
  4. package/dist/context-factory-BWO3xPWE.d.mts +520 -0
  5. package/dist/index-82e1CXJX.cjs +11 -0
  6. package/dist/index-BV1ZqQrU.mjs +351 -0
  7. package/dist/index-DNJWwcZu.mjs +8 -0
  8. package/dist/index-rZl77S1z.cjs +375 -0
  9. package/dist/index.cjs +1570 -0
  10. package/dist/index.d.cts +373 -0
  11. package/dist/index.d.mts +373 -0
  12. package/dist/index.mjs +1535 -0
  13. package/dist/mixins/database.mixin.cjs +1673 -0
  14. package/dist/mixins/database.mixin.d.cts +958 -0
  15. package/dist/mixins/database.mixin.d.mts +958 -0
  16. package/dist/mixins/database.mixin.mjs +1645 -0
  17. package/dist/mixins/encryptor.mixin.cjs +84 -0
  18. package/dist/mixins/encryptor.mixin.d.cts +31 -0
  19. package/dist/mixins/encryptor.mixin.d.mts +31 -0
  20. package/dist/mixins/encryptor.mixin.mjs +81 -0
  21. package/dist/mixins/global-store.mixin.cjs +56 -0
  22. package/dist/mixins/global-store.mixin.d.cts +39 -0
  23. package/dist/mixins/global-store.mixin.d.mts +39 -0
  24. package/dist/mixins/global-store.mixin.mjs +54 -0
  25. package/dist/mixins/jwt.mixin.cjs +118 -0
  26. package/dist/mixins/jwt.mixin.d.cts +43 -0
  27. package/dist/mixins/jwt.mixin.d.mts +43 -0
  28. package/dist/mixins/jwt.mixin.mjs +115 -0
  29. package/dist/mixins/queue.mixin.cjs +420 -0
  30. package/dist/mixins/queue.mixin.d.cts +150 -0
  31. package/dist/mixins/queue.mixin.d.mts +150 -0
  32. package/dist/mixins/queue.mixin.mjs +414 -0
  33. package/dist/mixins/redis.mixin.cjs +50 -0
  34. package/dist/mixins/redis.mixin.d.cts +27 -0
  35. package/dist/mixins/redis.mixin.d.mts +27 -0
  36. package/dist/mixins/redis.mixin.mjs +48 -0
  37. package/dist/mixins/redlock.mixin.cjs +76 -0
  38. package/dist/mixins/redlock.mixin.d.cts +30 -0
  39. package/dist/mixins/redlock.mixin.d.mts +30 -0
  40. package/dist/mixins/redlock.mixin.mjs +74 -0
  41. package/package.json +181 -0
@@ -0,0 +1,958 @@
1
+ import { Document, WithoutId, InferIdType, ObjectId, Filter, WithId, OptionalId, FindOptions, CountDocumentsOptions, FindOneAndUpdateOptions, BulkWriteOptions, UpdateOptions, FindOneAndReplaceOptions, FindOneAndDeleteOptions, DeleteOptions, CollationOptions, CreateCollectionOptions, MongoClient, CollectionOptions, Collection, UpdateFilter, FindCursor, UpdateResult } from 'mongodb';
2
+ import { ActionVisibility, BaseValidator, Errors, Context } from 'moleculer';
3
+ import { ZodType, ZodObject } from 'zod/v4';
4
+ import { V as ValidationSchema, J as JSONSchemaType, C as CustomActionSchema, a as CustomServiceSchema } from '../context-factory-BWO3xPWE.cjs';
5
+ import { Readable } from 'stream';
6
+ import 'bson';
7
+ import 'ajv/dist/2019.js';
8
+
9
+ declare enum QueryOp {
10
+ GT = "$gt",
11
+ GTE = "$gte",
12
+ LT = "$lt",
13
+ LTE = "$lte",
14
+ IN = "$in",
15
+ EQ = "$eq",
16
+ NE = "$ne"
17
+ }
18
+ type ActionGetParamsOptions = {
19
+ allowFields?: boolean;
20
+ };
21
+ type ActionCountParamsOptions = {
22
+ queryType: 'object' | 'stringified';
23
+ };
24
+ type ActionListParamsOptions = {
25
+ queryType: 'object' | 'stringified';
26
+ maxPageSize?: number;
27
+ };
28
+ type ActionCreateParamsOptions = {
29
+ allowClientId?: boolean;
30
+ };
31
+ type ActionSchemaFactoryOptions<S, TSchema extends Document> = {
32
+ schemaName?: string;
33
+ schema?: S;
34
+ timestamps: boolean;
35
+ softDelete: boolean;
36
+ tenantField: KeyString<TSchema> | false;
37
+ };
38
+ interface ActionSchemaFactory<S extends ValidationSchema | ZodType = ValidationSchema | ZodType> {
39
+ hasIdField(): boolean;
40
+ hasTenantIdField(): boolean;
41
+ /**
42
+ * Function that make auto generated fields mandatory.
43
+ */
44
+ createSchemaWithDbFields(): S;
45
+ /**
46
+ * Create the params for the find action.
47
+ */
48
+ createFindParams(): S;
49
+ /**
50
+ * Create get AND getInternal action params.
51
+ */
52
+ createGetParams(params: ActionGetParamsOptions): S;
53
+ /**
54
+ * Create count AND countInternal action params.
55
+ */
56
+ createCountParams(params: ActionCountParamsOptions): S;
57
+ /**
58
+ * Create list action params.
59
+ */
60
+ createListParams(params: ActionListParamsOptions): S;
61
+ /**
62
+ * Create list action result JSON schema.
63
+ */
64
+ createListResponse(): S;
65
+ /**
66
+ * Create 'create' action params.
67
+ */
68
+ createCreateParams(params: ActionCreateParamsOptions): S;
69
+ /**
70
+ * Create 'update' action params.
71
+ */
72
+ createUpdateParams(): S;
73
+ /**
74
+ * Create 'remove' action params.
75
+ */
76
+ createRemoveParams(): S;
77
+ }
78
+
79
+ /**
80
+ * Utility type to extract the string keys of a type.
81
+ */
82
+ type KeyString<T> = Extract<keyof T, string>;
83
+ type TenantParams<TSchema extends Document, TenantField extends KeyString<TSchema> | false> = (TenantField extends KeyString<TSchema> ? Pick<TSchema, TenantField> : null) | null;
84
+ type DatabaseMethodsOptions<TSchema extends Document, TenantField extends KeyString<TSchema> | false> = {
85
+ /**
86
+ * Name of the field that will be required to be present in all documents.
87
+ * This will be used in read queries as a filter to ensure that the user
88
+ * can only access documents that belong to the same tenant.
89
+ *
90
+ * This field can only be top-level and should probably be indexed.
91
+ */
92
+ tenantField: TenantField;
93
+ /**
94
+ * Enable soft-delete for the model.
95
+ * The remove method will only set the deletedAt field to NOW.
96
+ * And a new `scope` field will be read to be able to read deleted documents.
97
+ *
98
+ * Note that if schema has a deletedAt field, you are required to set this option to true.
99
+ */
100
+ softDelete: TSchema extends {
101
+ deletedAt?: Date;
102
+ } ? true : false;
103
+ /**
104
+ * Enable timestamps for the model.
105
+ * Will automatically set the createdAt and updatedAt fields on write operations.
106
+ *
107
+ * Note that if schema has both createdAt and updatedAt field, you are required to set this option to true.
108
+ */
109
+ timestamps: TSchema extends {
110
+ createdAt?: Date;
111
+ } ? TSchema extends {
112
+ updatedAt?: Date;
113
+ } ? true : false : false;
114
+ /**
115
+ * Note that this function will be applied ONLY on insert operations.
116
+ */
117
+ idGenerator?: (doc: WithoutId<TSchema>) => InferIdType<TSchema>;
118
+ /**
119
+ * Prefix used for events.
120
+ * If not specified, will disable events.
121
+ *
122
+ * Here is the list of events:
123
+ * - `${eventPrefix}.created`: Sent on insertOne and insertMany
124
+ * - `${eventPrefix}.updated`: Sent on updateOne and replaceOne
125
+ * - `${eventPrefix}.deleted`: Sent on deleteOne
126
+ */
127
+ eventPrefix?: string;
128
+ /**
129
+ * The sQuerySchema variable is an optional parameter used for validation.
130
+ * This is used to parse the sQuery parameter on list and count actions.
131
+ * If omitted, sQuery will be silently discarded.
132
+ * It uses the same validator than on actions.
133
+ * The schema will not be published on the openAPI.
134
+ * See addQueryOps for easy support of some mongo operators.
135
+ */
136
+ sQuerySchema?: ValidationSchema | ZodType;
137
+ /**
138
+ * Create the actions for the database mixin.
139
+ * Read operations:
140
+ * - find (max public)
141
+ * - findStream (max public)
142
+ * - getInternal (max public)
143
+ * - get
144
+ * - countInternal (max public)
145
+ * - count
146
+ * - list
147
+ *
148
+ * Write operations:
149
+ * - create
150
+ * - update
151
+ * - remove
152
+ *
153
+ * If some actions are not provided here, it probably means that they are not necessary.
154
+ * For example, there is no `findAllStream` or `updateMany` actions. This is because they are not used
155
+ * often and is quite specific to the related service.
156
+ */
157
+ actions?: DatabaseActionOptions<TSchema>;
158
+ };
159
+ type DatabaseActionVisibility<T extends DatabaseActionNames> = T extends DatabaseActionInternalNames ? Exclude<ActionVisibility, 'published'> : ActionVisibility;
160
+ type DatabaseActionOptions<TSchema extends Document & {
161
+ _id?: ObjectId | string;
162
+ }> = {
163
+ [key in DatabaseActionNames]?: {
164
+ visibility: DatabaseActionVisibility<key>;
165
+ } & (key extends 'list' ? {
166
+ maxPageSize?: number;
167
+ defaultPageSize?: number;
168
+ defaultSort?: string[];
169
+ } : NonNullable<unknown>) & (key extends 'create' ? {
170
+ allowClientId?: boolean;
171
+ } : NonNullable<unknown>);
172
+ } & {
173
+ schema?: JSONSchemaType<TSchema> | ZodObject;
174
+ schemaFactory?: ActionSchemaFactory;
175
+ schemaName?: string;
176
+ };
177
+ type DatabaseActionInternalNames = 'find' | 'findStream' | 'getInternal' | 'countInternal';
178
+ type DatabaseActionPublishedNames = 'count' | 'list' | 'get' | 'create' | 'update' | 'remove';
179
+ type DatabaseActionNames = DatabaseActionInternalNames | DatabaseActionPublishedNames;
180
+
181
+ /**
182
+ * Create the actions for the database mixin.
183
+ * Read operations:
184
+ * - find (max public)
185
+ * - findStream (max public)
186
+ * - getInternal (max public)
187
+ * - get
188
+ * - countInternal (max public)
189
+ * - count
190
+ * - list
191
+ *
192
+ * Write operations:
193
+ * - create
194
+ * - update
195
+ * - remove
196
+ *
197
+ * If some actions are not provided here, it probably means that they are not necessary.
198
+ * For example, there is no `findAllStream` or `updateMany` actions. This is because they are not used
199
+ * often and is quite specific to the related service.
200
+ */
201
+ declare function createActions<TSchema extends Document & {
202
+ _id: ObjectId | string;
203
+ }, TenantField extends KeyString<TSchema> | false = false>(opts: DatabaseMethodsOptions<TSchema, TenantField>): Partial<Record<DatabaseActionNames, CustomActionSchema>>;
204
+
205
+ declare class AjvActionSchemaFactory<TSchema extends Document> implements ActionSchemaFactory<ValidationSchema> {
206
+ private opts;
207
+ private readonly tenantFieldType;
208
+ private readonly _idFieldType;
209
+ constructor(opts: ActionSchemaFactoryOptions<JSONSchemaType<TSchema>, TSchema>);
210
+ hasIdField(): boolean;
211
+ hasTenantIdField(): boolean;
212
+ createSchemaWithDbFields(): ValidationSchema;
213
+ createFindParams(): ValidationSchema;
214
+ createGetParams(params: ActionGetParamsOptions): ValidationSchema;
215
+ createCountParams(params: ActionCountParamsOptions): ValidationSchema;
216
+ createListParams(params: ActionListParamsOptions): ValidationSchema;
217
+ createListResponse(): ValidationSchema;
218
+ createCreateParams(params: ActionCreateParamsOptions): ValidationSchema;
219
+ createUpdateParams(): ValidationSchema;
220
+ createRemoveParams(): ValidationSchema;
221
+ }
222
+ declare function addQueryOps<T>(schema: JSONSchemaType<T>, queryOps: QueryOp[]): JSONSchemaType<unknown>;
223
+
224
+ declare function parseStringifiedQuery<TSchema extends Document>(sQuery?: string): Filter<TSchema>;
225
+ declare function parseAndValidateQuery<TSchema extends Document>(validator: BaseValidator, schema: ValidationSchema | ZodType | undefined, sQuery: string | undefined): Filter<TSchema>;
226
+
227
+ type DatabaseSoftDeleteScope = 'include-deleted' | 'only-deleted' | 'no-deleted';
228
+ /**
229
+ * Options used on read only operations on the database mixin.
230
+ * Wrapper around mongodb's FindOptions that is easier for us to use.
231
+ */
232
+ type DatabaseFindOptions = Omit<FindOptions, 'projection' | 'sort'> & {
233
+ fields?: string[];
234
+ sort?: string[];
235
+ scope?: DatabaseSoftDeleteScope;
236
+ strictTenantFilter?: boolean;
237
+ };
238
+ /**
239
+ * Options used on count operations on the database mixin.
240
+ */
241
+ type DatabaseCountOptions = CountDocumentsOptions & {
242
+ scope?: DatabaseSoftDeleteScope;
243
+ strictTenantFilter?: boolean;
244
+ };
245
+ /**
246
+ * Options used on insertOne operations.
247
+ * Wrapper around findOneAndUpdate options as we don't use insertOne directly but findOneAndUpdate with upsert.
248
+ */
249
+ type DatabaseInsertOneOptions = Omit<FindOneAndUpdateOptions, 'upsert' | 'returnDocument' | 'sort' | 'hint' | 'projection' | 'arrayFilters'> & {
250
+ fields?: string[];
251
+ skipCreateEvent?: boolean;
252
+ };
253
+ /**
254
+ * Options used on insertMany operations.
255
+ */
256
+ type DatabaseInsertManyOptions = BulkWriteOptions & {
257
+ skipCreateEvent?: boolean;
258
+ };
259
+ /**
260
+ * Options used on updateOne operations.
261
+ */
262
+ type DatabaseUpdateOneOptions = Omit<FindOneAndUpdateOptions, 'sort' | 'projection'> & {
263
+ fields?: string[];
264
+ sort?: string[];
265
+ strictTenantFilter?: boolean;
266
+ skipUpdateEvent?: boolean;
267
+ };
268
+ /**
269
+ * Options used on updateMany operations.
270
+ */
271
+ type DatabaseUpdateManyOptions = UpdateOptions & {
272
+ strictTenantFilter?: boolean;
273
+ };
274
+ /**
275
+ * Options used on deleteOne operations.
276
+ * If soft delete is enabled, the document will be updated with a deletedAt field.
277
+ */
278
+ type DatabaseReplaceOneOptions = Omit<FindOneAndReplaceOptions, 'projection' | 'sort'> & {
279
+ fields?: string[];
280
+ sort?: string[];
281
+ strictTenantFilter?: boolean;
282
+ skipUpdateEvent?: boolean;
283
+ };
284
+ /**
285
+ * Options used on deleteOne operations.
286
+ * If soft delete is enabled, the document will be updated with a deletedAt field.
287
+ */
288
+ type DatabaseDeleteOneOptions = Omit<FindOneAndDeleteOptions, 'projection' | 'sort'> & {
289
+ fields?: string[];
290
+ sort?: string[];
291
+ strictTenantFilter?: boolean;
292
+ skipDeleteEvent?: boolean;
293
+ };
294
+ /**
295
+ * Options used on deleteMany operations.
296
+ * If soft delete is enabled, the document will be updated with a deletedAt field.
297
+ */
298
+ type DatabaseDeleteManyOptions = DeleteOptions & {
299
+ strictTenantFilter?: boolean;
300
+ };
301
+ /**
302
+ * Type of the event sent by the database mixin on insert.
303
+ * For insertMany, it will be sent once per document.
304
+ */
305
+ type DatabaseEventInsert<TSchema extends Document> = {
306
+ type: 'insert';
307
+ document: WithDbFields<TSchema>;
308
+ };
309
+ /**
310
+ * Type of the event sent by the database mixin on update.
311
+ * No event is sent on updateMany.
312
+ */
313
+ type DatabaseEventUpdate<TSchema extends Document> = {
314
+ type: 'update' | 'replace';
315
+ document: WithDbFields<TSchema>;
316
+ };
317
+ /**
318
+ * Type of the event sent by the database mixin on update.
319
+ * No event is sent on deleteMany.
320
+ */
321
+ type DatabaseEventDelete<TSchema extends Document> = {
322
+ type: 'delete';
323
+ document: WithDbFields<TSchema>;
324
+ };
325
+ /**
326
+ * Helper function that gives the type of document returned from the database.
327
+ * It will add _id, createdAt and updatedAt fields if they are not already present.
328
+ */
329
+ type WithDbFields<TSchema extends Document> = TSchema & WithId<TSchema> & (TSchema extends {
330
+ createdAt?: Date;
331
+ } ? TSchema extends {
332
+ updatedAt?: Date;
333
+ } ? {
334
+ createdAt: Date;
335
+ updatedAt: Date;
336
+ } : NonNullable<unknown> : NonNullable<unknown>);
337
+ type WithOptionalId<T> = OptionalId<T>;
338
+
339
+ type DatabaseActionFindParams<TSchema extends Document & {
340
+ _id: ObjectId | string;
341
+ }, TenantField extends KeyString<TSchema> | false = false> = {
342
+ query?: Filter<TSchema>;
343
+ fields?: string[];
344
+ sort?: string[];
345
+ limit?: number;
346
+ offset?: number;
347
+ collation?: CollationOptions;
348
+ } & (TSchema extends {
349
+ deletedAt?: Date;
350
+ } ? {
351
+ scope?: DatabaseSoftDeleteScope;
352
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
353
+ [key in TenantField]: TSchema[TenantField];
354
+ } : NonNullable<unknown>);
355
+ type DatabaseActionFindResult<TSchema extends Document> = Array<WithDbFields<TSchema>>;
356
+ type DatabaseActionGetInternalParams<TSchema extends Document & {
357
+ _id: ObjectId | string;
358
+ }, TenantField extends KeyString<TSchema> | false = false> = {
359
+ _id: InferIdType<TSchema>;
360
+ fields?: string[];
361
+ } & (TSchema extends {
362
+ deletedAt?: Date;
363
+ } ? {
364
+ scope?: DatabaseSoftDeleteScope;
365
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
366
+ [key in TenantField]: TSchema[TenantField];
367
+ } : NonNullable<unknown>);
368
+ type DatabaseActionEntityResult<TSchema extends Document> = WithDbFields<TSchema>;
369
+ type DatabaseActionGetParams<TSchema extends Document & {
370
+ _id: ObjectId | string;
371
+ }, TenantField extends KeyString<TSchema> | false = false> = {
372
+ _id: InferIdType<TSchema>;
373
+ } & (TSchema extends {
374
+ deletedAt?: Date;
375
+ } ? {
376
+ scope?: DatabaseSoftDeleteScope;
377
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
378
+ [key in TenantField]: TSchema[TenantField];
379
+ } : NonNullable<unknown>);
380
+ type DatabaseActionCountInternalParams<TSchema extends Document & {
381
+ _id: ObjectId | string;
382
+ }, TenantField extends KeyString<TSchema> | false = false> = {
383
+ query?: Filter<TSchema>;
384
+ } & (TSchema extends {
385
+ deletedAt?: Date;
386
+ } ? {
387
+ scope?: DatabaseSoftDeleteScope;
388
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
389
+ [key in TenantField]: TSchema[TenantField];
390
+ } : NonNullable<unknown>);
391
+ type DatabaseActionCountParams<TSchema extends Document & {
392
+ _id: ObjectId | string;
393
+ }, TenantField extends KeyString<TSchema> | false = false> = {
394
+ sQuery?: string;
395
+ } & (TSchema extends {
396
+ deletedAt?: Date;
397
+ } ? {
398
+ scope?: DatabaseSoftDeleteScope;
399
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
400
+ [key in TenantField]: TSchema[TenantField];
401
+ } : NonNullable<unknown>);
402
+ type DatabaseActionListParams<TSchema extends Document & {
403
+ _id: ObjectId | string;
404
+ }, TenantField extends KeyString<TSchema> | false = false> = {
405
+ sQuery?: string;
406
+ sort?: string[];
407
+ page?: number;
408
+ pageSize?: number;
409
+ collation?: CollationOptions;
410
+ } & (TSchema extends {
411
+ deletedAt?: Date;
412
+ } ? {
413
+ scope?: DatabaseSoftDeleteScope;
414
+ } : NonNullable<unknown>) & (TenantField extends KeyString<TSchema> ? {
415
+ [key in TenantField]: TSchema[TenantField];
416
+ } : NonNullable<unknown>);
417
+ type DatabaseActionListResult<TSchema extends Document> = {
418
+ rows: Array<TSchema>;
419
+ page: number;
420
+ pageSize: number;
421
+ total: number;
422
+ totalPages: number;
423
+ };
424
+ type DatabaseActionCreateParams<TSchema extends Document & {
425
+ _id: ObjectId | string;
426
+ }> = WithOptionalId<TSchema>;
427
+ type DatabaseActionUpdateParams<TSchema extends Document & {
428
+ _id: ObjectId | string;
429
+ }, TenantField extends KeyString<TSchema> | false = false> = Partial<TSchema> & (TenantField extends KeyString<TSchema> ? {
430
+ [key in TenantField]: TSchema[TenantField];
431
+ } : NonNullable<unknown>);
432
+ type DatabaseActionRemoveParams<TSchema extends Document & {
433
+ _id: ObjectId | string;
434
+ }, TenantField extends KeyString<TSchema> | false = false> = {
435
+ _id: InferIdType<TSchema>;
436
+ } & (TenantField extends KeyString<TSchema> ? {
437
+ [key in TenantField]: TSchema[TenantField];
438
+ } : NonNullable<unknown>);
439
+
440
+ declare class ZodActionSchemaFactory<TSchema extends Document> implements ActionSchemaFactory<ZodType> {
441
+ private opts;
442
+ private readonly tenantFieldType;
443
+ private readonly _idFieldType;
444
+ private schemaWithDbFields;
445
+ constructor(opts: ActionSchemaFactoryOptions<ZodType, TSchema>);
446
+ hasIdField(): boolean;
447
+ hasTenantIdField(): boolean;
448
+ createSchemaWithDbFields(): ZodType;
449
+ createFindParams(): ZodType;
450
+ createGetParams(params: ActionGetParamsOptions): ZodType;
451
+ createCountParams(params: ActionCountParamsOptions): ZodType;
452
+ createListParams(params: ActionListParamsOptions): ZodType;
453
+ createListResponse(): ZodType;
454
+ createCreateParams(params: ActionCreateParamsOptions): ZodType;
455
+ createUpdateParams(): ZodType;
456
+ createRemoveParams(): ZodType;
457
+ }
458
+ declare function addZodQueryOps(fieldValue: ZodType, queryOps: QueryOp[]): ZodType;
459
+
460
+ declare global {
461
+ var __MONGO_URI__: string | undefined;
462
+ var __MONGO_DB_NAME__: string | undefined;
463
+ }
464
+ type DatabaseConnectionOptions = {
465
+ /**
466
+ * Name of the database to use.
467
+ * If not specified, will use the default one (inferred from uri).
468
+ *
469
+ * OVERRIDDEN by globalThis.__MONGO_DB_NAME__ if set, which is useful for tests.
470
+ */
471
+ databaseName?: string;
472
+ /**
473
+ * Name of the collection in the DB.
474
+ */
475
+ collectionName: string;
476
+ /**
477
+ * Collection creation options.
478
+ * If not specified, will use the default one.
479
+ * Note that it shouldn't be changed without being sure of what you are doing.
480
+ */
481
+ createCollectionOptions?: CreateCollectionOptions;
482
+ /**
483
+ * URI of the MongoDB server.
484
+ * If not specified, will try to use one from environment:
485
+ * - process.env.MONGO_URL
486
+ * - process.env.MONGODB_URL
487
+ * - 'mongodb://localhost:27017' (default)
488
+ *
489
+ * OVERRIDDEN by globalThis.__MONGO_URI__ if set, which is useful for tests.
490
+ */
491
+ uri?: string;
492
+ };
493
+ declare function DatabaseConnectionMixin<TSchema extends Record<string, unknown> = never>(opts: DatabaseConnectionOptions): Partial<CustomServiceSchema<unknown, {
494
+ getMongoClient(): MongoClient;
495
+ getCollection(options?: CollectionOptions): Collection<TSchema>;
496
+ }, Partial<CustomServiceSchema<unknown, {
497
+ getStore(storeName: string): Map<string, {
498
+ services: Set<unknown>;
499
+ client: MongoClient;
500
+ onClose: () => Promise<void> | void;
501
+ }>;
502
+ getFromStore(storeName: string, key: string): MongoClient | null;
503
+ removeServiceFromStore(storeName: string, key: string): Promise<boolean>;
504
+ setClientToStore(storeName: string, key: string, client: MongoClient, onClose: () => Promise<void> | void): void;
505
+ }, unknown, unknown>>[], unknown>>;
506
+
507
+ declare const MoleculerClientError: typeof Errors.MoleculerClientError;
508
+ declare class EntityNotFoundError extends MoleculerClientError {
509
+ constructor(id: string | string[]);
510
+ }
511
+
512
+ type MongoIndex = {
513
+ key: Record<string, 1 | -1>;
514
+ name?: string;
515
+ expireAfterSeconds?: number;
516
+ partialFilterExpression?: Record<string, unknown>;
517
+ sparse?: boolean;
518
+ unique?: boolean;
519
+ collation?: CollationOptions;
520
+ };
521
+ type IndexTuple = [MongoIndex['key'], Omit<MongoIndex, 'key'>?];
522
+ type SearchIndexCharFilter = {
523
+ type: 'htmlStrip';
524
+ ignoredTags?: string[];
525
+ } | {
526
+ type: 'icuNormalize';
527
+ } | {
528
+ type: 'mapping';
529
+ mappings: Record<string, string>;
530
+ } | {
531
+ type: 'persian';
532
+ };
533
+ type SearchIndexTokenizer = {
534
+ type: 'edgeGram';
535
+ minGram: number;
536
+ maxGram: number;
537
+ } | {
538
+ type: 'keyword';
539
+ } | {
540
+ type: 'nGram';
541
+ minGram: number;
542
+ maxGram: number;
543
+ } | {
544
+ type: 'regexCaptureGroup';
545
+ pattern: string;
546
+ group: number;
547
+ } | {
548
+ type: 'regexSplit';
549
+ pattern: string;
550
+ } | {
551
+ type: 'standard';
552
+ maxTokenLength?: number;
553
+ } | {
554
+ type: 'uaxUrlEmail';
555
+ maxTokenLength?: number;
556
+ } | {
557
+ type: 'whitespace';
558
+ maxTokenLength?: number;
559
+ };
560
+ type SearchIndexTokenFilter = {
561
+ type: 'asciiFolding';
562
+ originalTokens?: 'include' | 'omit';
563
+ } | {
564
+ type: 'daitchMokotoffSoundex';
565
+ originalTokens?: 'include' | 'omit';
566
+ } | {
567
+ type: 'edgeGram';
568
+ minGram: number;
569
+ maxGram: number;
570
+ termNotInBounds?: 'include' | 'omit';
571
+ } | {
572
+ type: 'englishPossessive';
573
+ } | {
574
+ type: 'flattenGraph';
575
+ } | {
576
+ type: 'icuFolding';
577
+ } | {
578
+ type: 'icuNormalizer';
579
+ normalizationForm?: 'nfd' | 'nfc' | 'nfkd' | 'nfkc';
580
+ } | {
581
+ type: 'kStemming';
582
+ } | {
583
+ type: 'length';
584
+ min?: number;
585
+ max?: number;
586
+ } | {
587
+ type: 'lowercase';
588
+ } | {
589
+ type: 'nGram';
590
+ minGram: number;
591
+ maxGram: number;
592
+ termNotInBounds?: 'include' | 'omit';
593
+ } | {
594
+ type: 'porterStemming';
595
+ } | {
596
+ type: 'regex';
597
+ pattern: string;
598
+ replacement: string;
599
+ matches: 'all' | 'first';
600
+ } | {
601
+ type: 'reverse';
602
+ } | {
603
+ type: 'shingle';
604
+ minShingleSize: number;
605
+ maxShingleSize: number;
606
+ } | {
607
+ type: 'snowballStemming';
608
+ stemmerName: string;
609
+ } | {
610
+ type: 'spanishPluralStemming';
611
+ } | {
612
+ type: 'stempel';
613
+ } | {
614
+ type: 'stopword';
615
+ tokens: string[];
616
+ ignoreCase?: boolean;
617
+ } | {
618
+ type: 'trim';
619
+ } | {
620
+ type: 'wordDelimiterGraph';
621
+ delimiterOptions?: {
622
+ generateWordParts?: boolean;
623
+ generateNumberParts?: boolean;
624
+ concatenateWords?: boolean;
625
+ concatenateNumbers?: boolean;
626
+ concatenateAll?: boolean;
627
+ preserveOriginal?: boolean;
628
+ splitOnCaseChange?: boolean;
629
+ splitOnNumerics?: boolean;
630
+ stemEnglishPossessive?: boolean;
631
+ ignoreKeywords?: boolean;
632
+ };
633
+ protectedWords?: {
634
+ words: string[];
635
+ ignoreCase?: boolean;
636
+ };
637
+ };
638
+ /**
639
+ * Definition of a custom atlas search analyzer.
640
+ * See https://www.mongodb.com/docs/atlas/atlas-search/analyzers/custom/#std-label-custom-analyzers
641
+ */
642
+ type SearchIndexCustomAnalyzers = {
643
+ name: string;
644
+ charFilters?: Array<SearchIndexCharFilter>;
645
+ tokenizer: SearchIndexTokenizer;
646
+ tokenFilters?: Array<SearchIndexTokenFilter>;
647
+ };
648
+ type SearchIndexFieldString = {
649
+ type: 'string';
650
+ analyzer?: string;
651
+ searchAnalyzer?: string;
652
+ indexOptions?: 'docs' | 'freqs' | 'positions' | 'offsets';
653
+ store?: boolean;
654
+ ignoreAbove?: number;
655
+ multi?: Record<string, SearchIndexFieldString>;
656
+ norms?: 'include' | 'omit';
657
+ };
658
+ /**
659
+ * Definition of a field in a search index.
660
+ * See https://www.mongodb.com/docs/atlas/atlas-search/define-field-mappings/
661
+ */
662
+ type SearchIndexField = {
663
+ type: 'autocomplete';
664
+ analyzer?: string;
665
+ maxGrams?: number;
666
+ minGrams?: number;
667
+ tokenization?: 'edgeGram' | 'rightEdgeGram' | 'nGram';
668
+ foldDiacritics?: boolean;
669
+ } | {
670
+ type: 'boolean';
671
+ } | {
672
+ type: 'date';
673
+ } | {
674
+ type: 'dateFacet';
675
+ } | {
676
+ type: 'document';
677
+ dynamic?: boolean;
678
+ fields?: Record<string, SearchIndexField | SearchIndexField[]>;
679
+ } | {
680
+ type: 'embeddedDocuments';
681
+ dynamic?: boolean;
682
+ fields?: Record<string, SearchIndexField | SearchIndexField[]>;
683
+ } | {
684
+ type: 'geo';
685
+ indexShapes?: boolean;
686
+ } | {
687
+ type: 'number';
688
+ representation?: 'double' | 'int64';
689
+ indexIntegers?: boolean;
690
+ indexDoubles?: boolean;
691
+ } | {
692
+ type: 'numberFacet';
693
+ representation?: 'double' | 'int64';
694
+ indexIntegers?: boolean;
695
+ indexDoubles?: boolean;
696
+ } | {
697
+ type: 'objectId';
698
+ } | SearchIndexFieldString | {
699
+ type: 'stringFacet';
700
+ } | {
701
+ type: 'token';
702
+ normalizer?: 'lowercase' | 'none';
703
+ };
704
+ type SearchIndexDefinition = {
705
+ analyzer?: string;
706
+ searchAnalyzer?: string;
707
+ mappings?: {
708
+ dynamic?: boolean;
709
+ fields?: Record<string, SearchIndexField | SearchIndexField[]>;
710
+ };
711
+ analyzers?: Array<SearchIndexCustomAnalyzers>;
712
+ storedSource?: boolean | {
713
+ include: string[];
714
+ } | {
715
+ exclude: string[];
716
+ };
717
+ synonyms?: Array<{
718
+ analyzer: string;
719
+ name: string;
720
+ source: {
721
+ collection: string;
722
+ };
723
+ }>;
724
+ };
725
+ /**
726
+ * Type of what is returned by listSearchIndexes.
727
+ * See https://www.mongodb.com/docs/manual/reference/operator/aggregation/listSearchIndexes/#output
728
+ */
729
+ type ListSearchIndex = {
730
+ id: string;
731
+ name: string;
732
+ status: 'BUILDING' | 'FAILED' | 'PENDING' | 'READY' | 'STALE';
733
+ queryable: boolean;
734
+ latestDefinitionVersion: {
735
+ version: number;
736
+ createdAt: Date;
737
+ };
738
+ latestDefinition: SearchIndexDefinition;
739
+ statusDetail: Array<{
740
+ hostname: string;
741
+ status: string;
742
+ queryable: boolean;
743
+ mainIndex: Document;
744
+ stagedIndex: Document;
745
+ }>;
746
+ synonymMappingStatus: 'BUILDING' | 'FAILED' | 'READY';
747
+ synonymMappingStatusDetail: Array<{
748
+ status: string;
749
+ queryable: boolean;
750
+ }>;
751
+ message: string;
752
+ };
753
+ declare enum IndexStatus {
754
+ OK = "OK",
755
+ MISSING = "MISSING",
756
+ OUTDATED = "OUTDATED",
757
+ NOT_DECLARED = "NOT_DECLARED"
758
+ }
759
+ type IndexState = {
760
+ type: 'index';
761
+ status: IndexStatus.OK | IndexStatus.OUTDATED;
762
+ index: MongoIndex;
763
+ declaredIndex: IndexTuple;
764
+ } | {
765
+ type: 'index';
766
+ status: IndexStatus.MISSING;
767
+ declaredIndex: IndexTuple;
768
+ } | {
769
+ type: 'index';
770
+ status: IndexStatus.NOT_DECLARED;
771
+ index: MongoIndex;
772
+ } | {
773
+ type: 'searchIndex';
774
+ status: IndexStatus.OK | IndexStatus.OUTDATED;
775
+ name: string;
776
+ searchIndex: SearchIndexDefinition;
777
+ declaredSearchIndex: SearchIndexDefinition;
778
+ } | {
779
+ type: 'searchIndex';
780
+ status: IndexStatus.MISSING;
781
+ name: string;
782
+ declaredSearchIndex: SearchIndexDefinition;
783
+ } | {
784
+ type: 'searchIndex';
785
+ status: IndexStatus.NOT_DECLARED;
786
+ name: string;
787
+ searchIndex: SearchIndexDefinition;
788
+ };
789
+
790
+ type DatabaseIndexesOptions = {
791
+ indexes?: IndexTuple[];
792
+ searchIndexes?: Record<string, SearchIndexDefinition>;
793
+ };
794
+ type SyncIndexesOptions = {
795
+ createIndexes: boolean;
796
+ dropIndexes: boolean;
797
+ };
798
+ declare const DATABASE_INDEXES_MIXIN_SYNC_EVENT = "database-indexes-mixin.sync";
799
+ declare function DatabaseIndexesMixin(opts: DatabaseIndexesOptions): Partial<CustomServiceSchema<unknown, {
800
+ _syncIndexes({ dropIndexes, createIndexes, }: SyncIndexesOptions): Promise<void>;
801
+ _createIndexFromState(col: Collection, state: IndexState): Promise<void>;
802
+ }, unknown, unknown>>;
803
+
804
+ declare function getDefaultIndexName(key: Record<string, 1 | -1>): string;
805
+ declare function isIndexNameEqual(dbIdx: MongoIndex, idx: IndexTuple): boolean;
806
+ declare function isIndexEqual(dbIdx: MongoIndex, idx: IndexTuple): boolean;
807
+ declare function isOnAtlas(): boolean;
808
+ /**
809
+ * Rule for auto synchronise indexes is, in that order to not be hosted in MongoDB Atlas
810
+ * 1. check for specific operation env variable
811
+ * 2. check for force operation env variable
812
+ * 3. check if we're hosted on MongoDB Atlas
813
+ * or to force sync with the SYNC_MONGO_INDEX = 'yes'.
814
+ */
815
+ declare function shouldAutoCreateIndexes(): boolean;
816
+ declare function shouldAutoDropIndexes(): boolean;
817
+ declare function getIndexesDifference({ collection, declaredIdxs, }: {
818
+ collection: Collection<any>;
819
+ declaredIdxs: IndexTuple[];
820
+ }): Promise<{
821
+ idxsToCreate: MongoIndex[];
822
+ idxsToUpdate: MongoIndex[];
823
+ idxsToDelete: Required<MongoIndex>[];
824
+ synced: boolean;
825
+ }>;
826
+
827
+ declare function removeMongoId<T>(schema: JSONSchemaType<WithId<T>>, refName?: string): JSONSchemaType<Omit<T, '_id'>>;
828
+ declare function optionalMongoId<T>(schema: JSONSchemaType<WithId<T>>, refName?: string): JSONSchemaType<WithOptionalId<T>>;
829
+ /**
830
+ * Optimize query index usage for $or queries.
831
+ * This is particularly useful in case of partial indexes.
832
+ * This distributes the original condition in all $or conditions.
833
+ * @param query the query to optimize
834
+ */
835
+ declare function optimizeQuery<T extends Record<string, unknown>>(query: Filter<T>): Filter<T>;
836
+
837
+ declare function DatabaseMethodsMixin<TSchema extends Document & {
838
+ _id: ObjectId | string;
839
+ }, TenantField extends KeyString<TSchema> | false = false>(opts: DatabaseMethodsOptions<TSchema, TenantField>): Partial<CustomServiceSchema<unknown, {
840
+ /**
841
+ * Helper function that clean an update aggregation pipeline from createdAt changes.
842
+ * Note: This method mutate the array.
843
+ */
844
+ _removeCreatedAtFromUpdateAggregationPipeline(changes: UpdateFilter<TSchema>): void;
845
+ /**
846
+ * This method will automatically set the needed operators for our features (timestamps).
847
+ *
848
+ * Limitations of this method:
849
+ * - Dates are generated on the mongo server, except for `update` type with upsert.
850
+ * - It doesn't support $replaceWith/$replaceRoot in an aggregation pipeline except when using type `replace`.
851
+ * - Replaces (`replace` type) can only be done with an aggregation pipeline with a single $replaceWith stage.
852
+ * - Update aggregation pipelines will be modified to let the createdAt field stay the same.
853
+ */
854
+ _prepareUpdateFilter(changes: UpdateFilter<TSchema>, type: "create" | "update" | "replace"): UpdateFilter<TSchema>;
855
+ /**
856
+ * Will get the tenant filter from params.
857
+ * This filter should be used in all read queries to ensure that the user
858
+ * can only access documents that belong to the same tenant.
859
+ */
860
+ _getTenantFilter(params: TenantParams<TSchema, TenantField>, strict?: boolean): Filter<TSchema>;
861
+ /**
862
+ * Will get the soft delete filter from params.
863
+ * This filter should be used in all read queries.
864
+ *
865
+ * Indexes should also index the deleted field to ensure optimal performance.
866
+ * Note that in order to support partial indexes, a non deleted field is checked
867
+ * for `false` and `null` values.
868
+ */
869
+ _getSoftDeleteFilter(scope?: DatabaseSoftDeleteScope): Filter<TSchema>;
870
+ /**
871
+ * Get a query filter optimized ($or problem) with additional filters applied:
872
+ * - Tenant filter
873
+ * - Soft delete filter
874
+ */
875
+ _getQueryFilter(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, scope?: DatabaseSoftDeleteScope, strictTenantFilter?: boolean): Filter<TSchema>;
876
+ /**
877
+ * INTERNAL, DO NOT USE.
878
+ * Simple wrapper around the DatabaseConnectionMixin.getCollection method to have typed collection.
879
+ */
880
+ _getDatabaseMixinCollection(options?: CollectionOptions): Collection<TSchema>;
881
+ /**
882
+ * Create a find cursor with database mixin options applied.
883
+ */
884
+ _createFindCursor(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseFindOptions): FindCursor<WithDbFields<TSchema>>;
885
+ _findOne(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: Omit<DatabaseFindOptions, "limit" | "batchSize">): Promise<WithDbFields<TSchema> | null>;
886
+ _find(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseFindOptions): Promise<WithDbFields<TSchema>[]>;
887
+ _findStream(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseFindOptions): Readable;
888
+ _countDocuments(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseCountOptions): Promise<number>;
889
+ /**
890
+ * Insert one document and return it.
891
+ *
892
+ * It differs from the driver's insertOne as it returns the inserted document and
893
+ * send an event with the new document.
894
+ */
895
+ _insertOne(ctx: Context, doc: OptionalId<TSchema>, options?: DatabaseInsertOneOptions): Promise<WithDbFields<TSchema>>;
896
+ /**
897
+ * Insert many documents and return the list of inserted ids in the same order.
898
+ */
899
+ _insertMany(ctx: Context, docs: OptionalId<TSchema>[], options?: DatabaseInsertManyOptions): Promise<TSchema["_id"][]>;
900
+ /**
901
+ * Update one document and return the after version by default.
902
+ * To have the before version, use the `returnDocument` option.
903
+ *
904
+ * WARNING: Only send an event if returnDocument is 'after'.If returnDocument is 'before',
905
+ * you MUST pass skipUpdateEvent: true and optionally send the event yourself.
906
+ */
907
+ _updateOne(ctx: Context, query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, changes: UpdateFilter<TSchema>, options?: DatabaseUpdateOneOptions): Promise<WithDbFields<TSchema> | null>;
908
+ /**
909
+ * Update many documents and return the number of updated documents.
910
+ *
911
+ * WARNING: Do not send any events. You'll have to send an event yourself.
912
+ */
913
+ _updateMany(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, changes: UpdateFilter<TSchema>, options?: DatabaseUpdateManyOptions): Promise<UpdateResult<TSchema>>;
914
+ /**
915
+ * Replace one document and return the after version by default.
916
+ * To have the before version, use the `returnDocument` option.
917
+ *
918
+ * WARNING: Only send an event if returnDocument is 'after'.If returnDocument is 'before',
919
+ * you MUST pass skipUpdateEvent: true and optionally send the event yourself.
920
+ */
921
+ _replaceOne(ctx: Context, query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, doc: TSchema, options?: DatabaseReplaceOneOptions): Promise<WithDbFields<TSchema> | null>;
922
+ /**
923
+ * Delete one document and return it.
924
+ * If soft delete is enabled, it will only set the deleted field to true (hiding it from future requests).
925
+ */
926
+ _deleteOne(ctx: Context, query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseDeleteOneOptions): Promise<WithDbFields<TSchema> | null>;
927
+ /**
928
+ * Delete many documents and return the number of deleted documents.
929
+ * If soft delete is enabled, it will only set the deleted field to true (hiding it from future requests).
930
+ *
931
+ * WARNING: Do not send any events. You'll have to send an event yourself.
932
+ */
933
+ _deleteMany(query: Filter<TSchema>, params: TenantParams<TSchema, TenantField>, options?: DatabaseDeleteManyOptions): Promise<number>;
934
+ }, unknown, unknown>>;
935
+
936
+ /**
937
+ * This function is here to prevent accessing private (secure) fields.
938
+ *
939
+ * It removes any unauthorized fields from the query if it is an
940
+ * "allowed list" mode. In "deny list" mode or if no list,
941
+ * it adds secure fields to the list.
942
+ *
943
+ * If a query is a mixed of both mode, it throws an error.
944
+ */
945
+ declare function filterFields(fields: string[] | undefined, secureFields: string[] | undefined): string[] | undefined;
946
+ /**
947
+ * Filter an objects following a fields array.
948
+ * A simpler version of mongo projection logic.
949
+ */
950
+ declare function filterObjectFields<T extends Record<string, unknown>>(obj: Record<string, unknown>, fields?: string[]): T;
951
+ /**
952
+ * Return an object with each list item as key and 1/0/-1 as value
953
+ * to be used in mongo projection or sort.
954
+ */
955
+ declare function getQueryFromList<T extends 'sort' | 'projection', NotOp extends T extends 'sort' ? -1 : 0>(type: T, list?: string[]): Record<string, 1 | NotOp> | undefined;
956
+
957
+ export { AjvActionSchemaFactory, DATABASE_INDEXES_MIXIN_SYNC_EVENT, DatabaseConnectionMixin, DatabaseIndexesMixin, DatabaseMethodsMixin, EntityNotFoundError, IndexStatus, QueryOp, ZodActionSchemaFactory, addQueryOps, addZodQueryOps, createActions, filterFields, filterObjectFields, getDefaultIndexName, getIndexesDifference, getQueryFromList, isIndexEqual, isIndexNameEqual, isOnAtlas, optimizeQuery, optionalMongoId, parseAndValidateQuery, parseStringifiedQuery, removeMongoId, shouldAutoCreateIndexes, shouldAutoDropIndexes };
958
+ export type { ActionCountParamsOptions, ActionCreateParamsOptions, ActionGetParamsOptions, ActionListParamsOptions, ActionSchemaFactory, ActionSchemaFactoryOptions, DatabaseActionCountInternalParams, DatabaseActionCountParams, DatabaseActionCreateParams, DatabaseActionEntityResult, DatabaseActionFindParams, DatabaseActionFindResult, DatabaseActionGetInternalParams, DatabaseActionGetParams, DatabaseActionInternalNames, DatabaseActionListParams, DatabaseActionListResult, DatabaseActionNames, DatabaseActionOptions, DatabaseActionPublishedNames, DatabaseActionRemoveParams, DatabaseActionUpdateParams, DatabaseConnectionOptions, DatabaseCountOptions, DatabaseDeleteManyOptions, DatabaseDeleteOneOptions, DatabaseEventDelete, DatabaseEventInsert, DatabaseEventUpdate, DatabaseFindOptions, DatabaseIndexesOptions, DatabaseInsertManyOptions, DatabaseInsertOneOptions, DatabaseMethodsOptions, DatabaseReplaceOneOptions, DatabaseSoftDeleteScope, DatabaseUpdateManyOptions, DatabaseUpdateOneOptions, IndexState, IndexTuple, KeyString, ListSearchIndex, MongoIndex, SearchIndexCustomAnalyzers, SearchIndexDefinition, SearchIndexField, SearchIndexFieldString, SyncIndexesOptions, TenantParams, WithDbFields, WithOptionalId };