@classytic/mongokit 3.17.0 → 3.19.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 (32) hide show
  1. package/README.md +68 -1
  2. package/dist/PaginationEngine-4SjzfBQE.d.mts +103 -0
  3. package/dist/actions/index.d.mts +1 -1
  4. package/dist/adapter/index.mjs +1 -1
  5. package/dist/ai/index.d.mts +1 -1
  6. package/dist/better-auth/index.mjs +1 -1
  7. package/dist/create-repository-D5YX0wGs.mjs +29 -0
  8. package/dist/create-repository-K0yft2ht.d.mts +1663 -0
  9. package/dist/{index-fi91ycQc.d.mts → index-BgSBwlWu.d.mts} +1 -1
  10. package/dist/index.d.mts +11 -1665
  11. package/dist/index.mjs +5 -29
  12. package/dist/{mongooseToJsonSchema-BdQJU39w.d.mts → mongooseToJsonSchema-Bz47aMfH.d.mts} +1 -1
  13. package/dist/multi-tenant.plugin-D6lw3BsI.d.mts +487 -0
  14. package/dist/pagination/PaginationEngine.d.mts +1 -102
  15. package/dist/plugins/index.d.mts +19 -2
  16. package/dist/plugins/index.mjs +73 -2
  17. package/dist/query/primitives/coercion.d.mts +1 -1
  18. package/dist/query/primitives/indexes.d.mts +1 -1
  19. package/dist/testkit/index.d.mts +129 -0
  20. package/dist/testkit/index.mjs +139 -0
  21. package/dist/{validation-chain.plugin-DJtC0KJ-.mjs → timestamp.plugin-B1A9U-P7.mjs} +1 -1052
  22. package/dist/utils/index.d.mts +1 -1
  23. package/dist/utils/index.mjs +2 -2
  24. package/dist/{validation-chain.plugin-BpMfy18N.d.mts → validation-chain.plugin-CYOPfFGF.d.mts} +2 -486
  25. package/dist/validation-chain.plugin-DHZbpb4t.mjs +1056 -0
  26. package/package.json +16 -4
  27. /package/dist/{adapter-DYEMkLwK.mjs → adapter-BSxhT0Ip.mjs} +0 -0
  28. /package/dist/{coercion-TRMmR49h.d.mts → coercion-BxxHyLjP.d.mts} +0 -0
  29. /package/dist/{field-selection-CQW3WBiK.mjs → field-selection-d1qdRiMr.mjs} +0 -0
  30. /package/dist/{indexes-CgOF7Wjd.d.mts → indexes-3eHBWNZ2.d.mts} +0 -0
  31. /package/dist/{mongooseToJsonSchema-CBEQmeEa.mjs → mongooseToJsonSchema-ChtXSrLT.mjs} +0 -0
  32. /package/dist/{types-CU3SEDbD.d.mts → types-BA8oXjFe.d.mts} +0 -0
@@ -0,0 +1,1056 @@
1
+ import { s as ALL_OPERATIONS } from "./Repository-B01VW_fU.mjs";
2
+ import { _ as upsert } from "./update-CvCMv5Cl.mjs";
3
+ import { n as warn } from "./logger-B8wf-Mtb.mjs";
4
+ import { t as createError } from "./error-BTeepSNL.mjs";
5
+ import { r as getFieldsForUser } from "./field-selection-d1qdRiMr.mjs";
6
+ import mongoose from "mongoose";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ //#region src/plugins/aggregate-helpers.plugin.ts
9
+ /**
10
+ * Aggregate helpers plugin
11
+ *
12
+ * @example
13
+ * const repo = new Repository(Model, [
14
+ * methodRegistryPlugin(),
15
+ * aggregateHelpersPlugin(),
16
+ * ]);
17
+ *
18
+ * const groups = await repo.groupBy('category');
19
+ * const total = await repo.sum('amount', { status: 'completed' });
20
+ */
21
+ function aggregateHelpersPlugin() {
22
+ return {
23
+ name: "aggregate-helpers",
24
+ apply(repo) {
25
+ if (!repo.registerMethod) throw new Error("aggregateHelpersPlugin requires methodRegistryPlugin");
26
+ /**
27
+ * Group by field
28
+ */
29
+ repo.registerMethod("groupBy", async function(field, options = {}) {
30
+ const pipeline = [{ $group: {
31
+ _id: `$${field}`,
32
+ count: { $sum: 1 }
33
+ } }, { $sort: { count: -1 } }];
34
+ if (options.limit) pipeline.push({ $limit: options.limit });
35
+ return this.aggregatePipeline(pipeline, options);
36
+ });
37
+ const aggregateOperation = async function(field, operator, resultKey, query = {}, options = {}) {
38
+ const pipeline = [{ $match: query }, { $group: {
39
+ _id: null,
40
+ [resultKey]: { [operator]: `$${field}` }
41
+ } }];
42
+ return (await this.aggregatePipeline(pipeline, options))[0]?.[resultKey] || 0;
43
+ };
44
+ /**
45
+ * Sum field values
46
+ */
47
+ repo.registerMethod("sum", async function(field, query = {}, options = {}) {
48
+ return aggregateOperation.call(this, field, "$sum", "total", query, options);
49
+ });
50
+ /**
51
+ * Average field values
52
+ */
53
+ repo.registerMethod("average", async function(field, query = {}, options = {}) {
54
+ return aggregateOperation.call(this, field, "$avg", "avg", query, options);
55
+ });
56
+ /**
57
+ * Get minimum value
58
+ */
59
+ repo.registerMethod("min", async function(field, query = {}, options = {}) {
60
+ return aggregateOperation.call(this, field, "$min", "min", query, options);
61
+ });
62
+ /**
63
+ * Get maximum value
64
+ */
65
+ repo.registerMethod("max", async function(field, query = {}, options = {}) {
66
+ return aggregateOperation.call(this, field, "$max", "max", query, options);
67
+ });
68
+ }
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region src/plugins/cascade.plugin.ts
73
+ /**
74
+ * Cascade Delete Plugin
75
+ *
76
+ * Automatically deletes related documents when a parent document is deleted.
77
+ *
78
+ * Two routing modes per relation:
79
+ *
80
+ * 1. **Repo-routed (preferred)** — pass `repo: targetRepo` on the relation.
81
+ * Cascade calls `targetRepo.delete(id, { mode })` / `targetRepo.deleteMany(
82
+ * query, { mode })`, so the target's `before:delete` / `before:deleteMany`
83
+ * hooks fire. Multi-tenant scoping, audit logging, cache invalidation,
84
+ * and the target's own `softDeletePlugin` (with its configured
85
+ * `deletedField`) all run correctly.
86
+ *
87
+ * 2. **Model-routed (legacy)** — pass `model: 'TargetModelName'`. Cascade
88
+ * writes directly via `mongoose.models[name].updateMany / deleteMany`,
89
+ * **bypassing** the target's hooks. Safe only for trivial targets with
90
+ * no policy plugins. Retained for backwards compatibility — prefer the
91
+ * repo-routed form for new code.
92
+ *
93
+ * The parent's delete mode propagates: a hard-deleted parent cascades hard,
94
+ * a soft-deleted parent cascades soft — unless `relation.softDelete` overrides
95
+ * the decision per-relation.
96
+ *
97
+ * @example Repo-routed (new)
98
+ * ```ts
99
+ * const productRepo = new Repository(Product, [
100
+ * methodRegistryPlugin(),
101
+ * cascadePlugin({
102
+ * relations: [
103
+ * { repo: stockEntryRepo, foreignKey: 'product' },
104
+ * { repo: stockMovementRepo, foreignKey: 'product' },
105
+ * ],
106
+ * }),
107
+ * ]);
108
+ * ```
109
+ *
110
+ * @example Model-routed (legacy)
111
+ * ```ts
112
+ * cascadePlugin({
113
+ * relations: [
114
+ * { model: 'StockEntry', foreignKey: 'product' },
115
+ * ],
116
+ * });
117
+ * ```
118
+ */
119
+ /**
120
+ * Collect top-level parent-context fields that a target plugin (multi-tenant,
121
+ * audit) will likely need. We can't know the target's contextKey, so we
122
+ * forward a well-known allow-list: `organizationId`, `tenantId`, and `user`.
123
+ * These are the conventions enforced by the built-in plugins.
124
+ */
125
+ function collectScopeForward(context) {
126
+ const out = {};
127
+ if (context.organizationId !== void 0) out.organizationId = context.organizationId;
128
+ if (context.tenantId !== void 0) out.tenantId = context.tenantId;
129
+ if (context.user !== void 0) out.user = context.user;
130
+ return out;
131
+ }
132
+ /**
133
+ * Cascade delete plugin.
134
+ */
135
+ function cascadePlugin(options) {
136
+ const { relations, parallel = true, logger } = options;
137
+ if (!relations || relations.length === 0) throw new Error("cascadePlugin requires at least one relation");
138
+ for (const rel of relations) {
139
+ if (!rel.repo && !rel.model) throw new Error("cascadePlugin: each relation needs either `repo` (preferred) or `model` (legacy)");
140
+ if (!rel.foreignKey) throw new Error("cascadePlugin: each relation needs `foreignKey`");
141
+ }
142
+ return {
143
+ name: "cascade",
144
+ apply(repo) {
145
+ repo.on("after:delete", async (payload) => {
146
+ const { context } = payload;
147
+ const deletedId = context.id;
148
+ if (!deletedId) {
149
+ logger?.warn?.("Cascade delete skipped: no document ID in context", { model: context.model });
150
+ return;
151
+ }
152
+ const isSoftParent = context.softDeleted === true;
153
+ const scopeForward = collectScopeForward(context);
154
+ const cascadeOne = async (relation) => {
155
+ const shouldSoftDelete = relation.softDelete ?? isSoftParent;
156
+ const cascadeCtx = {
157
+ targetModelName: relation.repo ? relation.repo.Model?.modelName ?? "<unknown>" : relation.model ?? "<unknown>",
158
+ session: context.session,
159
+ shouldSoftDelete,
160
+ user: context.user,
161
+ scopeForward
162
+ };
163
+ try {
164
+ if (relation.repo) await cascadeViaRepoBulk(relation, deletedId, cascadeCtx);
165
+ else await cascadeViaLegacyModel(relation, deletedId, cascadeCtx, logger);
166
+ } catch (error) {
167
+ logger?.error?.(`Cascade delete failed for '${cascadeCtx.targetModelName}'`, {
168
+ parentModel: context.model,
169
+ parentId: String(deletedId),
170
+ relatedModel: cascadeCtx.targetModelName,
171
+ foreignKey: relation.foreignKey,
172
+ error: error.message
173
+ });
174
+ throw error;
175
+ }
176
+ };
177
+ await runCascades(relations, cascadeOne, parallel);
178
+ });
179
+ repo.on("before:deleteMany", async (context) => {
180
+ const query = context.query;
181
+ if (!query || Object.keys(query).length === 0) return;
182
+ const idField = repo.idField || "_id";
183
+ context._cascadeIds = (await repo.Model.find(query, { [idField]: 1 }).lean().session(context.session ?? null)).map((doc) => doc[idField]);
184
+ });
185
+ repo.on("after:deleteMany", async (payload) => {
186
+ const { context } = payload;
187
+ const ids = context._cascadeIds;
188
+ if (!ids || ids.length === 0) return;
189
+ const isSoftParent = context.softDeleted === true;
190
+ const scopeForward = collectScopeForward(context);
191
+ const cascadeBulk = async (relation) => {
192
+ const shouldSoftDelete = relation.softDelete ?? isSoftParent;
193
+ const cascadeCtx = {
194
+ targetModelName: relation.repo ? relation.repo.Model?.modelName ?? "<unknown>" : relation.model ?? "<unknown>",
195
+ session: context.session,
196
+ shouldSoftDelete,
197
+ user: context.user,
198
+ scopeForward
199
+ };
200
+ try {
201
+ if (relation.repo) await cascadeViaRepoBulkMany(relation, ids, cascadeCtx);
202
+ else await cascadeViaLegacyModelMany(relation, ids, cascadeCtx, logger);
203
+ } catch (error) {
204
+ logger?.error?.(`Cascade deleteMany failed for '${cascadeCtx.targetModelName}'`, {
205
+ parentModel: context.model,
206
+ relatedModel: cascadeCtx.targetModelName,
207
+ foreignKey: relation.foreignKey,
208
+ error: error.message
209
+ });
210
+ throw error;
211
+ }
212
+ };
213
+ await runCascades(relations, cascadeBulk, parallel);
214
+ });
215
+ }
216
+ };
217
+ }
218
+ /**
219
+ * Repo-routed cascade for a single parent delete.
220
+ * Calls `repo.deleteMany({ [fk]: parentId }, { mode })` — respects all target
221
+ * hooks (multi-tenant, audit, target's own soft-delete plugin).
222
+ */
223
+ async function cascadeViaRepoBulk(relation, parentId, ctx) {
224
+ const targetRepo = relation.repo;
225
+ if (typeof targetRepo.deleteMany !== "function") throw new Error(`cascadePlugin: target repo for '${ctx.targetModelName}' is missing deleteMany(). Ensure the target is a mongokit Repository or implements the StandardRepo deleteMany contract.`);
226
+ await targetRepo.deleteMany({ [relation.foreignKey]: parentId }, {
227
+ ...ctx.scopeForward,
228
+ mode: ctx.shouldSoftDelete ? "soft" : "hard",
229
+ session: ctx.session
230
+ });
231
+ }
232
+ /**
233
+ * Repo-routed cascade for a bulk parent deleteMany — `$in` over snapshot ids.
234
+ */
235
+ async function cascadeViaRepoBulkMany(relation, parentIds, ctx) {
236
+ const targetRepo = relation.repo;
237
+ if (typeof targetRepo.deleteMany !== "function") throw new Error(`cascadePlugin: target repo for '${ctx.targetModelName}' is missing deleteMany(). Ensure the target is a mongokit Repository or implements the StandardRepo deleteMany contract.`);
238
+ await targetRepo.deleteMany({ [relation.foreignKey]: { $in: parentIds } }, {
239
+ ...ctx.scopeForward,
240
+ mode: ctx.shouldSoftDelete ? "soft" : "hard",
241
+ session: ctx.session
242
+ });
243
+ }
244
+ /**
245
+ * Legacy cascade via `mongoose.models[name]`. Bypasses target hooks.
246
+ * Retained for backwards compatibility with existing cascadePlugin consumers.
247
+ */
248
+ async function cascadeViaLegacyModel(relation, parentId, ctx, logger) {
249
+ const RelatedModel = mongoose.models[relation.model];
250
+ if (!RelatedModel) {
251
+ logger?.warn?.(`Cascade delete skipped: model '${relation.model}' not found`);
252
+ return;
253
+ }
254
+ const query = { [relation.foreignKey]: parentId };
255
+ if (ctx.shouldSoftDelete) await RelatedModel.updateMany(query, {
256
+ deletedAt: /* @__PURE__ */ new Date(),
257
+ ...ctx.user ? { deletedBy: ctx.user._id || ctx.user.id } : {}
258
+ }, { session: ctx.session });
259
+ else await RelatedModel.deleteMany(query, { session: ctx.session });
260
+ }
261
+ async function cascadeViaLegacyModelMany(relation, parentIds, ctx, logger) {
262
+ const RelatedModel = mongoose.models[relation.model];
263
+ if (!RelatedModel) {
264
+ logger?.warn?.(`Cascade deleteMany skipped: model '${relation.model}' not found`);
265
+ return;
266
+ }
267
+ const query = { [relation.foreignKey]: { $in: parentIds } };
268
+ if (ctx.shouldSoftDelete) await RelatedModel.updateMany(query, {
269
+ deletedAt: /* @__PURE__ */ new Date(),
270
+ ...ctx.user ? { deletedBy: ctx.user._id || ctx.user.id } : {}
271
+ }, { session: ctx.session });
272
+ else await RelatedModel.deleteMany(query, { session: ctx.session });
273
+ }
274
+ /**
275
+ * Execute a list of cascade operations, honoring the `parallel` flag.
276
+ * Uses `allSettled` so one failure doesn't abort siblings; throws the first
277
+ * rejection (with a composite message if several failed) after all complete.
278
+ */
279
+ async function runCascades(relations, fn, parallel) {
280
+ if (parallel) {
281
+ const failures = (await Promise.allSettled(relations.map(fn))).filter((r) => r.status === "rejected");
282
+ if (failures.length) {
283
+ const err = failures[0].reason;
284
+ if (failures.length > 1) err.message = `${failures.length} cascade deletes failed. First: ${err.message}`;
285
+ throw err;
286
+ }
287
+ } else for (const relation of relations) await fn(relation);
288
+ }
289
+ //#endregion
290
+ //#region src/plugins/elastic.plugin.ts
291
+ function elasticSearchPlugin(options) {
292
+ return {
293
+ name: "elastic-search",
294
+ apply(repo) {
295
+ if (!repo.registerMethod) throw new Error("[mongokit] elasticSearchPlugin requires methodRegistryPlugin to be registered first. Add methodRegistryPlugin() before elasticSearchPlugin() in your repository plugins array.");
296
+ repo.registerMethod("search", async function(searchQuery, searchOptions = {}) {
297
+ const { client, index, idField = "_id" } = options;
298
+ const limit = Math.min(Math.max(searchOptions.limit || 20, 1), 1e3);
299
+ const from = Math.max(searchOptions.from || 0, 0);
300
+ const esResponse = await client.search({
301
+ index,
302
+ body: {
303
+ query: searchQuery,
304
+ size: limit,
305
+ from
306
+ }
307
+ });
308
+ const hits = esResponse.hits?.hits || esResponse.body?.hits?.hits || [];
309
+ if (hits.length === 0) return {
310
+ data: [],
311
+ total: 0,
312
+ limit,
313
+ from
314
+ };
315
+ const totalValue = esResponse.hits?.total?.value ?? esResponse.hits?.total ?? esResponse.body?.hits?.total?.value ?? esResponse.body?.hits?.total ?? 0;
316
+ const total = typeof totalValue === "number" ? totalValue : 0;
317
+ const docsOrder = /* @__PURE__ */ new Map();
318
+ const scores = /* @__PURE__ */ new Map();
319
+ const ids = [];
320
+ hits.forEach((hit, idx) => {
321
+ const docId = hit._source?.[idField] || hit[idField] || hit._id;
322
+ if (docId) {
323
+ const strId = String(docId);
324
+ docsOrder.set(strId, idx);
325
+ if (hit._score !== void 0) scores.set(strId, hit._score);
326
+ ids.push(strId);
327
+ }
328
+ });
329
+ if (ids.length === 0) return {
330
+ data: [],
331
+ total,
332
+ limit,
333
+ from
334
+ };
335
+ const mongoIdField = repo.idField || "_id";
336
+ const mongoQuery = this.Model.find({ [mongoIdField]: { $in: ids } });
337
+ if (searchOptions.mongoOptions?.select) mongoQuery.select(searchOptions.mongoOptions.select);
338
+ if (searchOptions.mongoOptions?.populate) mongoQuery.populate(searchOptions.mongoOptions.populate);
339
+ if (searchOptions.mongoOptions?.lean !== false) mongoQuery.lean();
340
+ return {
341
+ data: (await mongoQuery.exec()).sort((a, b) => {
342
+ const aId = String(a[mongoIdField]);
343
+ const bId = String(b[mongoIdField]);
344
+ return (docsOrder.get(aId) ?? Number.MAX_SAFE_INTEGER) - (docsOrder.get(bId) ?? Number.MAX_SAFE_INTEGER);
345
+ }).map((doc) => {
346
+ const strId = String(doc[mongoIdField]);
347
+ if (searchOptions.mongoOptions?.lean !== false) return {
348
+ ...doc,
349
+ _score: scores.get(strId)
350
+ };
351
+ return doc;
352
+ }),
353
+ total,
354
+ limit,
355
+ from
356
+ };
357
+ });
358
+ }
359
+ };
360
+ }
361
+ //#endregion
362
+ //#region src/plugins/field-filter.plugin.ts
363
+ /**
364
+ * Field filter plugin that restricts fields based on user context
365
+ *
366
+ * @example
367
+ * const fieldPreset = {
368
+ * public: ['id', 'name'],
369
+ * authenticated: ['email'],
370
+ * admin: ['createdAt', 'internalNotes']
371
+ * };
372
+ *
373
+ * const repo = new Repository(Model, [fieldFilterPlugin(fieldPreset)]);
374
+ */
375
+ function fieldFilterPlugin(fieldPreset) {
376
+ return {
377
+ name: "fieldFilter",
378
+ apply(repo) {
379
+ const applyFieldFiltering = (context) => {
380
+ if (!fieldPreset) return;
381
+ const presetSelect = getFieldsForUser(context.context?.user || context.user, fieldPreset).join(" ");
382
+ if (context.select) context.select = `${presetSelect} ${context.select}`;
383
+ else context.select = presetSelect;
384
+ };
385
+ repo.on("before:getAll", applyFieldFiltering);
386
+ repo.on("before:findAll", applyFieldFiltering);
387
+ repo.on("before:getById", applyFieldFiltering);
388
+ repo.on("before:getByQuery", applyFieldFiltering);
389
+ repo.on("before:getOne", applyFieldFiltering);
390
+ }
391
+ };
392
+ }
393
+ //#endregion
394
+ //#region src/plugins/lease.plugin.ts
395
+ function leasePlugin(options = {}) {
396
+ const statusField = options.statusField ?? "status";
397
+ const leasedByField = options.leasedByField ?? "leasedBy";
398
+ const leaseExpiresAtField = options.leaseExpiresAtField ?? "leaseExpiresAt";
399
+ const pendingStatus = options.pendingStatus ?? "pending";
400
+ const processingStatus = options.processingStatus ?? "processing";
401
+ const doneStatus = options.doneStatus ?? "done";
402
+ const sort = options.sort ?? { createdAt: 1 };
403
+ return {
404
+ name: "lease",
405
+ apply(repo) {
406
+ if (!repo.registerMethod) throw new Error("leasePlugin requires methodRegistryPlugin. Add methodRegistryPlugin() before leasePlugin().");
407
+ /**
408
+ * Atomic FIFO lease claim — the canonical
409
+ * findOneAndUpdate({ status: pending, OR leaseExpiresAt < now },
410
+ * { $set: { status: processing, leasedBy, leaseExpiresAt } },
411
+ * { sort })
412
+ * pattern, distilled.
413
+ */
414
+ repo.registerMethod("lease", async function(opts) {
415
+ if (typeof opts?.leaseFor !== "number" || opts.leaseFor <= 0) throw createError(400, "leasePlugin.lease: leaseFor must be a positive number (ms)");
416
+ if (typeof opts.leasedBy !== "string" || opts.leasedBy.length === 0) throw createError(400, "leasePlugin.lease: leasedBy must be a non-empty string");
417
+ const now = /* @__PURE__ */ new Date();
418
+ const leaseUntil = new Date(now.getTime() + opts.leaseFor);
419
+ const claimFilter = {
420
+ ...opts.filter ?? {},
421
+ $or: [{ [statusField]: pendingStatus }, { [leaseExpiresAtField]: { $lt: now } }]
422
+ };
423
+ return this.findOneAndUpdate(claimFilter, { $set: {
424
+ [statusField]: processingStatus,
425
+ [leasedByField]: opts.leasedBy,
426
+ [leaseExpiresAtField]: leaseUntil
427
+ } }, {
428
+ ...opts.options ?? {},
429
+ sort,
430
+ returnDocument: "after"
431
+ });
432
+ });
433
+ repo.registerMethod("extend", async function(id, opts) {
434
+ if (typeof opts?.leaseFor !== "number" || opts.leaseFor <= 0) throw createError(400, "leasePlugin.extend: leaseFor must be a positive number (ms)");
435
+ const now = /* @__PURE__ */ new Date();
436
+ const leaseUntil = new Date(now.getTime() + opts.leaseFor);
437
+ const idField = this.idField || "_id";
438
+ return this.findOneAndUpdate({
439
+ [idField]: id,
440
+ [leasedByField]: opts.leasedBy,
441
+ [leaseExpiresAtField]: { $gt: now }
442
+ }, { $set: { [leaseExpiresAtField]: leaseUntil } }, {
443
+ ...opts.options ?? {},
444
+ returnDocument: "after"
445
+ });
446
+ });
447
+ repo.registerMethod("release", async function(id, opts) {
448
+ if (typeof opts?.leasedBy !== "string" || opts.leasedBy.length === 0) throw createError(400, "leasePlugin.release: leasedBy must be a non-empty string (the holder finalising the lease)");
449
+ const finalStatus = opts.finalStatus ?? doneStatus;
450
+ const now = /* @__PURE__ */ new Date();
451
+ const idField = this.idField || "_id";
452
+ return this.findOneAndUpdate({
453
+ [idField]: id,
454
+ [leasedByField]: opts.leasedBy,
455
+ [leaseExpiresAtField]: { $gt: now }
456
+ }, {
457
+ $set: { [statusField]: finalStatus },
458
+ $unset: {
459
+ [leasedByField]: "",
460
+ [leaseExpiresAtField]: ""
461
+ }
462
+ }, {
463
+ ...opts.options ?? {},
464
+ returnDocument: "after"
465
+ });
466
+ });
467
+ }
468
+ };
469
+ }
470
+ //#endregion
471
+ //#region src/plugins/mongo-operations.plugin.ts
472
+ /**
473
+ * MongoDB Operations Plugin
474
+ *
475
+ * Adds MongoDB-specific operations to repositories.
476
+ * Requires method-registry.plugin.js to be loaded first.
477
+ */
478
+ /**
479
+ * MongoDB operations plugin
480
+ *
481
+ * Adds MongoDB-specific atomic operations to repositories:
482
+ * - upsert: Create or update document
483
+ * - increment/decrement: Atomic numeric operations
484
+ * - pushToArray/pullFromArray/addToSet: Array operations
485
+ * - setField/unsetField/renameField: Field operations
486
+ * - multiplyField: Multiply numeric field
487
+ * - setMin/setMax: Conditional min/max updates
488
+ *
489
+ * @example Basic usage (no TypeScript autocomplete)
490
+ * ```typescript
491
+ * const repo = new Repository(ProductModel, [
492
+ * methodRegistryPlugin(),
493
+ * mongoOperationsPlugin(),
494
+ * ]);
495
+ *
496
+ * // Works at runtime but TypeScript doesn't know about these methods
497
+ * await (repo as any).increment(productId, 'views', 1);
498
+ * await (repo as any).pushToArray(productId, 'tags', 'featured');
499
+ * ```
500
+ *
501
+ * @example With TypeScript type safety (recommended)
502
+ * ```typescript
503
+ * import { Repository, mongoOperationsPlugin, methodRegistryPlugin } from '@classytic/mongokit';
504
+ * import type { MongoOperationsMethods } from '@classytic/mongokit';
505
+ *
506
+ * class ProductRepo extends Repository<IProduct> {
507
+ * // Add your custom methods here
508
+ * }
509
+ *
510
+ * // Create with type assertion to get autocomplete for plugin methods
511
+ * type ProductRepoWithPlugins = ProductRepo & MongoOperationsMethods<IProduct>;
512
+ *
513
+ * const repo = new ProductRepo(ProductModel, [
514
+ * methodRegistryPlugin(),
515
+ * mongoOperationsPlugin(),
516
+ * ]) as ProductRepoWithPlugins;
517
+ *
518
+ * // Now TypeScript provides autocomplete and type checking!
519
+ * await repo.increment(productId, 'views', 1);
520
+ * await repo.upsert({ sku: 'ABC' }, { name: 'Product', price: 99 });
521
+ * await repo.pushToArray(productId, 'tags', 'featured');
522
+ * ```
523
+ */
524
+ function mongoOperationsPlugin() {
525
+ return {
526
+ name: "mongo-operations",
527
+ apply(repo) {
528
+ if (!repo.registerMethod) throw new Error("mongoOperationsPlugin requires methodRegistryPlugin. Add methodRegistryPlugin() before mongoOperationsPlugin() in plugins array.");
529
+ /**
530
+ * Update existing document or insert new one
531
+ */
532
+ repo.registerMethod("upsert", async function(query, data, options = {}) {
533
+ return upsert(this.Model, query, data, options);
534
+ });
535
+ const validateAndUpdateNumeric = async function(id, field, value, operator, operationName, options) {
536
+ if (typeof value !== "number") throw createError(400, `${operationName} value must be a number`);
537
+ return this.update(id, { [operator]: { [field]: value } }, options);
538
+ };
539
+ /**
540
+ * Atomically increment numeric field
541
+ */
542
+ repo.registerMethod("increment", async function(id, field, value = 1, options = {}) {
543
+ return validateAndUpdateNumeric.call(this, id, field, value, "$inc", "Increment", options);
544
+ });
545
+ /**
546
+ * Atomically decrement numeric field
547
+ */
548
+ repo.registerMethod("decrement", async function(id, field, value = 1, options = {}) {
549
+ return validateAndUpdateNumeric.call(this, id, field, -value, "$inc", "Decrement", options);
550
+ });
551
+ const applyOperator = function(id, field, value, operator, options) {
552
+ return this.update(id, { [operator]: { [field]: value } }, options);
553
+ };
554
+ /**
555
+ * Push value to array field
556
+ */
557
+ repo.registerMethod("pushToArray", async function(id, field, value, options = {}) {
558
+ return applyOperator.call(this, id, field, value, "$push", options);
559
+ });
560
+ /**
561
+ * Remove value from array field
562
+ */
563
+ repo.registerMethod("pullFromArray", async function(id, field, value, options = {}) {
564
+ return applyOperator.call(this, id, field, value, "$pull", options);
565
+ });
566
+ /**
567
+ * Add value to array only if not already present (unique)
568
+ */
569
+ repo.registerMethod("addToSet", async function(id, field, value, options = {}) {
570
+ return applyOperator.call(this, id, field, value, "$addToSet", options);
571
+ });
572
+ /**
573
+ * Set field value (alias for update with $set)
574
+ */
575
+ repo.registerMethod("setField", async function(id, field, value, options = {}) {
576
+ return applyOperator.call(this, id, field, value, "$set", options);
577
+ });
578
+ /**
579
+ * Unset (remove) field from document
580
+ */
581
+ repo.registerMethod("unsetField", async function(id, fields, options = {}) {
582
+ const unsetObj = (Array.isArray(fields) ? fields : [fields]).reduce((acc, field) => {
583
+ acc[field] = "";
584
+ return acc;
585
+ }, {});
586
+ return this.update(id, { $unset: unsetObj }, options);
587
+ });
588
+ /**
589
+ * Rename field in document
590
+ */
591
+ repo.registerMethod("renameField", async function(id, oldName, newName, options = {}) {
592
+ return this.update(id, { $rename: { [oldName]: newName } }, options);
593
+ });
594
+ /**
595
+ * Multiply numeric field by value
596
+ */
597
+ repo.registerMethod("multiplyField", async function(id, field, multiplier, options = {}) {
598
+ return validateAndUpdateNumeric.call(this, id, field, multiplier, "$mul", "Multiplier", options);
599
+ });
600
+ /**
601
+ * Set field to minimum value (only if current value is greater)
602
+ */
603
+ repo.registerMethod("setMin", async function(id, field, value, options = {}) {
604
+ return applyOperator.call(this, id, field, value, "$min", options);
605
+ });
606
+ /**
607
+ * Set field to maximum value (only if current value is less)
608
+ */
609
+ repo.registerMethod("setMax", async function(id, field, value, options = {}) {
610
+ return applyOperator.call(this, id, field, value, "$max", options);
611
+ });
612
+ /**
613
+ * Atomic conditional increment — only increments when the current
614
+ * value is strictly below `ceiling`. Returns the updated document
615
+ * on success, or `null` when the row is already at/above the
616
+ * ceiling (or the id doesn't match).
617
+ *
618
+ * Single round-trip via `findOneAndUpdate({ _id, [field]: { $lt:
619
+ * ceiling } }, { $inc: { [field]: by } })` — race-free across
620
+ * concurrent callers. The standard pattern for per-document
621
+ * concurrency limits / quotas / capacity caps that would
622
+ * otherwise need a 150-line lease loop.
623
+ *
624
+ * @example streamline strict-concurrency: claim a worker slot
625
+ * ```ts
626
+ * const claimed = await repo.incrementIfBelow(
627
+ * tenantId,
628
+ * 'activeRuns',
629
+ * maxConcurrent,
630
+ * );
631
+ * if (!claimed) return; // already at limit; another caller won
632
+ * ```
633
+ */
634
+ repo.registerMethod("incrementIfBelow", async function(id, field, ceiling, by = 1, options = {}) {
635
+ if (typeof ceiling !== "number") throw createError(400, "incrementIfBelow ceiling must be a number");
636
+ if (typeof by !== "number") throw createError(400, "incrementIfBelow `by` must be a number");
637
+ if (typeof field !== "string" || field.length === 0) throw createError(400, "incrementIfBelow field must be a non-empty string");
638
+ for (const segment of field.split(".")) {
639
+ if (segment.length === 0) throw createError(400, `incrementIfBelow field has an empty segment ("${field}")`);
640
+ if (segment.startsWith("$")) throw createError(400, `incrementIfBelow field segment cannot start with '$' ("${segment}") — Mongo would treat it as an operator`);
641
+ if (segment === "__proto__" || segment === "constructor" || segment === "prototype") throw createError(400, `incrementIfBelow field segment "${segment}" is reserved (prototype-pollution guard)`);
642
+ }
643
+ const idField = this.idField || "_id";
644
+ return this.findOneAndUpdate({
645
+ [idField]: id,
646
+ [field]: { $lt: ceiling }
647
+ }, { $inc: { [field]: by } }, {
648
+ ...options,
649
+ returnDocument: "after"
650
+ });
651
+ });
652
+ /**
653
+ * Atomic update with multiple MongoDB operators in a single call
654
+ *
655
+ * Combines $inc, $set, $push, $pull, $addToSet, $unset, $setOnInsert, $min, $max, $mul, $rename
656
+ * into one atomic database operation.
657
+ *
658
+ * @example
659
+ * // Combine $inc + $set in one atomic call
660
+ * await repo.atomicUpdate(id, {
661
+ * $inc: { views: 1, commentCount: 1 },
662
+ * $set: { lastActiveAt: new Date() }
663
+ * });
664
+ *
665
+ * // Multiple operators: $inc + $set + $push
666
+ * await repo.atomicUpdate(id, {
667
+ * $inc: { 'metrics.total': 1 },
668
+ * $set: { updatedAt: new Date() },
669
+ * $push: { history: { action: 'update', at: new Date() } }
670
+ * });
671
+ *
672
+ * // $push with $each modifier
673
+ * await repo.atomicUpdate(id, {
674
+ * $push: { tags: { $each: ['featured', 'popular'] } },
675
+ * $inc: { tagCount: 2 }
676
+ * });
677
+ *
678
+ * // With arrayFilters for positional updates
679
+ * await repo.atomicUpdate(id, {
680
+ * $set: { 'items.$[elem].quantity': 5 }
681
+ * }, { arrayFilters: [{ 'elem._id': itemId }] });
682
+ */
683
+ repo.registerMethod("atomicUpdate", async function(id, operators, options = {}) {
684
+ const validOperators = new Set([
685
+ "$inc",
686
+ "$set",
687
+ "$unset",
688
+ "$push",
689
+ "$pull",
690
+ "$addToSet",
691
+ "$pop",
692
+ "$rename",
693
+ "$min",
694
+ "$max",
695
+ "$mul",
696
+ "$setOnInsert",
697
+ "$bit",
698
+ "$currentDate"
699
+ ]);
700
+ const keys = Object.keys(operators);
701
+ if (keys.length === 0) throw createError(400, "atomicUpdate requires at least one operator");
702
+ for (const key of keys) if (!validOperators.has(key)) throw createError(400, `Invalid update operator: '${key}'. Valid operators: ${[...validOperators].join(", ")}`);
703
+ return this.update(id, operators, options);
704
+ });
705
+ }
706
+ };
707
+ }
708
+ //#endregion
709
+ //#region src/plugins/observability.plugin.ts
710
+ /**
711
+ * Observability Plugin
712
+ *
713
+ * Adds operation timing, structured metrics, and APM hook points.
714
+ * Works with any monitoring system — just provide an onMetric callback.
715
+ *
716
+ * @example
717
+ * ```typescript
718
+ * const repo = new Repository(User, [
719
+ * observabilityPlugin({
720
+ * onMetric: (metric) => {
721
+ * // Send to DataDog, New Relic, OpenTelemetry, or console
722
+ * console.log(`${metric.operation} took ${metric.durationMs}ms`);
723
+ * statsd.histogram('mongokit.operation', metric.durationMs, { op: metric.operation });
724
+ * },
725
+ * }),
726
+ * ]);
727
+ * ```
728
+ */
729
+ const DEFAULT_OPS = ALL_OPERATIONS;
730
+ const timers = /* @__PURE__ */ new WeakMap();
731
+ function observabilityPlugin(options) {
732
+ const { onMetric, slowThresholdMs } = options;
733
+ const ops = options.operations ?? DEFAULT_OPS;
734
+ const isSkipped = (context) => {
735
+ const list = context.skipPlugins;
736
+ return Array.isArray(list) && list.includes("observability");
737
+ };
738
+ return {
739
+ name: "observability",
740
+ apply(repo) {
741
+ for (const op of ops) {
742
+ repo.on(`before:${op}`, (context) => {
743
+ if (isSkipped(context)) return;
744
+ timers.set(context, performance.now());
745
+ }, { priority: 300 });
746
+ repo.on(`after:${op}`, ({ context }) => {
747
+ if (isSkipped(context)) return;
748
+ const start = timers.get(context);
749
+ if (start == null) return;
750
+ const durationMs = Math.round((performance.now() - start) * 100) / 100;
751
+ timers.delete(context);
752
+ if (slowThresholdMs != null && durationMs < slowThresholdMs) return;
753
+ onMetric({
754
+ operation: op,
755
+ model: context.model || repo.model,
756
+ durationMs,
757
+ success: true,
758
+ startedAt: new Date(Date.now() - durationMs),
759
+ userId: context.user?._id?.toString() || context.user?.id?.toString(),
760
+ organizationId: context.organizationId?.toString()
761
+ });
762
+ });
763
+ repo.on(`error:${op}`, ({ context, error }) => {
764
+ if (isSkipped(context)) return;
765
+ const start = timers.get(context);
766
+ if (start == null) return;
767
+ const durationMs = Math.round((performance.now() - start) * 100) / 100;
768
+ timers.delete(context);
769
+ onMetric({
770
+ operation: op,
771
+ model: context.model || repo.model,
772
+ durationMs,
773
+ success: false,
774
+ error: error.message,
775
+ startedAt: new Date(Date.now() - durationMs),
776
+ userId: context.user?._id?.toString() || context.user?.id?.toString(),
777
+ organizationId: context.organizationId?.toString()
778
+ });
779
+ });
780
+ }
781
+ }
782
+ };
783
+ }
784
+ //#endregion
785
+ //#region src/plugins/subdocument.plugin.ts
786
+ /**
787
+ * Subdocument plugin for managing nested arrays
788
+ *
789
+ * @example
790
+ * const repo = new Repository(Model, [
791
+ * methodRegistryPlugin(),
792
+ * subdocumentPlugin(),
793
+ * ]);
794
+ *
795
+ * await repo.addSubdocument(parentId, 'items', { name: 'Item 1' });
796
+ * await repo.updateSubdocument(parentId, 'items', itemId, { name: 'Updated Item' });
797
+ */
798
+ function subdocumentPlugin() {
799
+ return {
800
+ name: "subdocument",
801
+ apply(repo) {
802
+ if (!repo.registerMethod) throw new Error("subdocumentPlugin requires methodRegistryPlugin");
803
+ /**
804
+ * Add subdocument to array
805
+ */
806
+ repo.registerMethod("addSubdocument", async function(parentId, arrayPath, subData, options = {}) {
807
+ return this.update(parentId, { $push: { [arrayPath]: subData } }, options);
808
+ });
809
+ /**
810
+ * Get subdocument from array
811
+ */
812
+ repo.registerMethod("getSubdocument", async function(parentId, arrayPath, subId, options = {}) {
813
+ return this._executeQuery(async (Model) => {
814
+ const parent = await Model.findById(parentId).session(options.session).exec();
815
+ if (!parent) throw createError(404, "Parent not found");
816
+ const arrayField = parent[arrayPath];
817
+ if (!arrayField || typeof arrayField.id !== "function") throw createError(404, "Array field not found");
818
+ const sub = arrayField.id(subId);
819
+ if (!sub) throw createError(404, "Subdocument not found");
820
+ return options.lean && typeof sub.toObject === "function" ? sub.toObject() : sub;
821
+ });
822
+ });
823
+ /**
824
+ * Update subdocument in array
825
+ */
826
+ repo.registerMethod("updateSubdocument", async function(parentId, arrayPath, subId, updateData, options = {}) {
827
+ return this._executeQuery(async (Model) => {
828
+ const query = {
829
+ _id: parentId,
830
+ [`${arrayPath}._id`]: subId
831
+ };
832
+ const update = { $set: { [`${arrayPath}.$`]: {
833
+ ...updateData,
834
+ _id: subId
835
+ } } };
836
+ const result = await Model.findOneAndUpdate(query, update, {
837
+ returnDocument: "after",
838
+ runValidators: true,
839
+ session: options.session
840
+ }).exec();
841
+ if (!result) throw createError(404, "Parent or subdocument not found");
842
+ return result;
843
+ });
844
+ });
845
+ /**
846
+ * Delete subdocument from array
847
+ */
848
+ repo.registerMethod("deleteSubdocument", async function(parentId, arrayPath, subId, options = {}) {
849
+ return this.update(parentId, { $pull: { [arrayPath]: { _id: subId } } }, options);
850
+ });
851
+ }
852
+ };
853
+ }
854
+ //#endregion
855
+ //#region src/plugins/tenant-context.ts
856
+ /**
857
+ * Request-scoped tenant context via AsyncLocalStorage.
858
+ *
859
+ * The multi-tenant plugin already accepts a `resolveContext` callback for
860
+ * reading tenant ID from an external store. This helper wraps Node's
861
+ * `AsyncLocalStorage` into a tiny, batteries-included API so apps don't need
862
+ * to wire the plumbing by hand — a common source of cross-tenant leaks.
863
+ *
864
+ * @example
865
+ * import { createTenantContext, multiTenantPlugin } from '@classytic/mongokit';
866
+ *
867
+ * const tenantContext = createTenantContext();
868
+ *
869
+ * // In your HTTP middleware (Express / Fastify / NestJS):
870
+ * app.use((req, _res, next) => {
871
+ * tenantContext.run({ tenantId: req.auth.organizationId }, next);
872
+ * });
873
+ *
874
+ * // In your repository definition:
875
+ * const repo = new Repository(Invoice, [
876
+ * multiTenantPlugin({
877
+ * tenantField: 'organizationId',
878
+ * resolveContext: () => tenantContext.getTenantId(),
879
+ * }),
880
+ * ]);
881
+ *
882
+ * // In your handler — no need to pass organizationId manually:
883
+ * await repo.getAll({ filters: { status: 'paid' } });
884
+ */
885
+ function createTenantContext() {
886
+ const storage = new AsyncLocalStorage();
887
+ return {
888
+ storage,
889
+ run(store, fn) {
890
+ return storage.run(store, fn);
891
+ },
892
+ getStore() {
893
+ return storage.getStore();
894
+ },
895
+ getTenantId() {
896
+ return storage.getStore()?.tenantId;
897
+ },
898
+ requireTenantId() {
899
+ const id = storage.getStore()?.tenantId;
900
+ if (!id) throw new Error("[mongokit] No tenant context active. Wrap the request in tenantContext.run({ tenantId }, fn).");
901
+ return id;
902
+ }
903
+ };
904
+ }
905
+ //#endregion
906
+ //#region src/plugins/validation-chain.plugin.ts
907
+ /**
908
+ * Validation chain plugin
909
+ *
910
+ * @example
911
+ * const repo = new Repository(Model, [
912
+ * validationChainPlugin([
913
+ * requireField('email'),
914
+ * uniqueField('email', 'Email already exists'),
915
+ * blockIf('no-delete-admin', ['delete'], ctx => ctx.data?.role === 'admin', 'Cannot delete admin'),
916
+ * ])
917
+ * ]);
918
+ */
919
+ function validationChainPlugin(validators = [], options = {}) {
920
+ const { stopOnFirstError = true } = options;
921
+ validators.forEach((v, idx) => {
922
+ if (!v.name || typeof v.name !== "string") throw new Error(`Validator at index ${idx} missing 'name' (string)`);
923
+ if (typeof v.validate !== "function") throw new Error(`Validator '${v.name}' missing 'validate' function`);
924
+ });
925
+ const validatorsByOperation = {
926
+ create: [],
927
+ update: [],
928
+ findOneAndUpdate: [],
929
+ delete: [],
930
+ createMany: []
931
+ };
932
+ const allOperationsValidators = [];
933
+ validators.forEach((v) => {
934
+ if (!v.operations || v.operations.length === 0) allOperationsValidators.push(v);
935
+ else v.operations.forEach((op) => {
936
+ if (validatorsByOperation[op]) validatorsByOperation[op].push(v);
937
+ });
938
+ });
939
+ return {
940
+ name: "validation-chain",
941
+ apply(repo) {
942
+ const getValidatorsForOperation = (operation) => {
943
+ const specific = validatorsByOperation[operation] || [];
944
+ return [...allOperationsValidators, ...specific];
945
+ };
946
+ const runValidators = async (operation, context) => {
947
+ const operationValidators = getValidatorsForOperation(operation);
948
+ const errors = [];
949
+ for (const validator of operationValidators) try {
950
+ await validator.validate(context, repo);
951
+ } catch (error) {
952
+ if (stopOnFirstError) throw error;
953
+ errors.push({
954
+ validator: validator.name,
955
+ error: error.message || String(error)
956
+ });
957
+ }
958
+ if (errors.length > 0) {
959
+ const err = createError(400, `Validation failed: ${errors.map((e) => `[${e.validator}] ${e.error}`).join("; ")}`);
960
+ err.validationErrors = errors;
961
+ throw err;
962
+ }
963
+ };
964
+ repo.on("before:create", async (context) => runValidators("create", context));
965
+ repo.on("before:createMany", async (context) => runValidators("createMany", context));
966
+ repo.on("before:update", async (context) => runValidators("update", context));
967
+ repo.on("before:findOneAndUpdate", async (context) => runValidators("findOneAndUpdate", context));
968
+ repo.on("before:delete", async (context) => runValidators("delete", context));
969
+ }
970
+ };
971
+ }
972
+ /**
973
+ * Block operation if condition is true
974
+ *
975
+ * @example
976
+ * blockIf('block-library', ['delete'], ctx => ctx.data?.managed, 'Cannot delete managed records')
977
+ */
978
+ function blockIf(name, operations, condition, errorMessage) {
979
+ return {
980
+ name,
981
+ operations,
982
+ validate: (context) => {
983
+ if (condition(context)) throw createError(403, errorMessage);
984
+ }
985
+ };
986
+ }
987
+ /**
988
+ * Require a field to be present
989
+ */
990
+ function requireField(field, operations = ["create"]) {
991
+ return {
992
+ name: `require-${field}`,
993
+ operations,
994
+ validate: (context) => {
995
+ if (!context.data || context.data[field] === void 0 || context.data[field] === null) throw createError(400, `Field '${field}' is required`);
996
+ }
997
+ };
998
+ }
999
+ /**
1000
+ * Auto-inject a value if not present
1001
+ */
1002
+ function autoInject(field, getter, operations = ["create"]) {
1003
+ return {
1004
+ name: `auto-inject-${field}`,
1005
+ operations,
1006
+ validate: (context) => {
1007
+ if (context.data && !(field in context.data)) {
1008
+ const value = getter(context);
1009
+ if (value !== null && value !== void 0) context.data[field] = value;
1010
+ }
1011
+ }
1012
+ };
1013
+ }
1014
+ /**
1015
+ * Make a field immutable (cannot be updated)
1016
+ */
1017
+ function immutableField(field) {
1018
+ return {
1019
+ name: `immutable-${field}`,
1020
+ operations: ["update"],
1021
+ validate: (context) => {
1022
+ if (context.data && field in context.data) throw createError(400, `Field '${field}' cannot be modified`);
1023
+ }
1024
+ };
1025
+ }
1026
+ /**
1027
+ * Ensure field value is unique
1028
+ */
1029
+ function uniqueField(field, errorMessage) {
1030
+ return {
1031
+ name: `unique-${field}`,
1032
+ operations: ["create", "update"],
1033
+ validate: async (context, repo) => {
1034
+ if (!context.data?.[field]) return;
1035
+ if (!repo) {
1036
+ warn(`[mongokit] uniqueField('${field}'): repo not available, skipping uniqueness check`);
1037
+ return;
1038
+ }
1039
+ const query = { [field]: context.data[field] };
1040
+ const getByQuery = repo.getByQuery;
1041
+ if (typeof getByQuery !== "function") {
1042
+ warn(`[mongokit] uniqueField('${field}'): getByQuery not available on repo, skipping uniqueness check`);
1043
+ return;
1044
+ }
1045
+ const idKey = repo.idField || "_id";
1046
+ const existing = await getByQuery.call(repo, query, {
1047
+ select: idKey,
1048
+ lean: true,
1049
+ throwOnNotFound: false
1050
+ });
1051
+ if (existing && String(existing[idKey]) !== String(context.id)) throw createError(409, errorMessage || `${field} already exists`);
1052
+ }
1053
+ };
1054
+ }
1055
+ //#endregion
1056
+ export { uniqueField as a, subdocumentPlugin as c, leasePlugin as d, fieldFilterPlugin as f, aggregateHelpersPlugin as h, requireField as i, observabilityPlugin as l, cascadePlugin as m, blockIf as n, validationChainPlugin as o, elasticSearchPlugin as p, immutableField as r, createTenantContext as s, autoInject as t, mongoOperationsPlugin as u };