@classytic/mongokit 3.6.4 → 3.8.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.
- package/dist/{PaginationEngine-CunXkR9p.mjs → PaginationEngine-C2_tAvAD.mjs} +8 -5
- package/dist/actions/index.d.mts +1 -1
- package/dist/actions/index.mjs +1 -1
- package/dist/ai/index.d.mts +23 -1
- package/dist/ai/index.mjs +194 -12
- package/dist/{cursor-CHToazHy.mjs → cursor-J84rR6wG.mjs} +11 -7
- package/dist/error-Lw9GEAro.mjs +46 -0
- package/dist/{index-jzO5hMtF.d.mts → index-DlSAFIc9.d.mts} +10 -2
- package/dist/index.d.mts +97 -9
- package/dist/index.mjs +53 -12
- package/dist/logger-DJ7egMnd.mjs +30 -0
- package/dist/{mongooseToJsonSchema-BvD1NDl9.d.mts → mongooseToJsonSchema-BZaKOXXI.d.mts} +18 -2
- package/dist/{mongooseToJsonSchema-BlfkI9LC.mjs → mongooseToJsonSchema-DUwXPStK.mjs} +1 -1
- package/dist/pagination/PaginationEngine.d.mts +3 -1
- package/dist/pagination/PaginationEngine.mjs +1 -1
- package/dist/plugins/index.d.mts +2 -2
- package/dist/plugins/index.mjs +2 -2
- package/dist/query/primitives/coercion.d.mts +1 -1
- package/dist/query/primitives/coercion.mjs +1 -1
- package/dist/query/primitives/indexes.d.mts +1 -1
- package/dist/{sort-C-BJEWUZ.mjs → sort-CrZjTK25.mjs} +19 -4
- package/dist/{types-BoH1qdHo.d.mts → types-D57SZJeE.d.mts} +83 -3
- package/dist/{update-AVfKWNGt.mjs → update-yjSoNnWy.mjs} +26 -2
- package/dist/utils/index.d.mts +2 -2
- package/dist/utils/index.mjs +5 -4
- package/dist/{validation-chain.plugin-7A5qGEQq.mjs → validation-chain.plugin-DwoOOWse.mjs} +460 -144
- package/dist/{validation-chain.plugin-BXx6Ogpp.d.mts → validation-chain.plugin-wGF34Ym-.d.mts} +27 -4
- package/package.json +8 -3
- package/dist/error-Bpbi_NKo.mjs +0 -63
- /package/dist/{coercion-B19MD38s.d.mts → coercion-oM8G4b6m.d.mts} +0 -0
- /package/dist/{field-selection-C5o7jyyA.mjs → field-selection-dI0m4RBs.mjs} +0 -0
- /package/dist/{id-resolution-LZ-cCwR5.mjs → id-resolution-e4BT9zAV.mjs} +0 -0
- /package/dist/{indexes-qIBCZ3mY.d.mts → indexes-C26GNZRU.d.mts} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { r as warn, t as configureLogger } from "./logger-DJ7egMnd.mjs";
|
|
2
|
+
import { b as LookupBuilder } from "./update-yjSoNnWy.mjs";
|
|
3
|
+
import { n as parseDuplicateKeyError, t as createError } from "./error-Lw9GEAro.mjs";
|
|
3
4
|
import { t as actions_exports } from "./actions/index.mjs";
|
|
4
|
-
import { t as
|
|
5
|
-
import {
|
|
5
|
+
import { A as AuditTrailQuery, C as cachePlugin, D as withTransaction, E as isTransactionUnsupported, F as MUTATING_OPERATIONS, I as OP_REGISTRY, L as READ_OPERATIONS, M as auditLogPlugin, N as aggregateHelpersPlugin, O as AggregationBuilder, P as ALL_OPERATIONS, R as operationsByPolicyKey, S as cascadePlugin, T as Repository, _ as customIdPlugin, a as uniqueField, b as prefixedId, c as createTenantContext, d as observabilityPlugin, f as multiTenantPlugin, g as elasticSearchPlugin, h as fieldFilterPlugin, i as requireField, j as auditTrailPlugin, k as batchOperationsPlugin, l as subdocumentPlugin, m as methodRegistryPlugin, n as blockIf, o as validationChainPlugin, p as mongoOperationsPlugin, r as immutableField, s as timestampPlugin, t as autoInject, u as softDeletePlugin, v as dateSequentialId, w as HOOK_PRIORITY, x as sequentialId, y as getNextSequence } from "./validation-chain.plugin-DwoOOWse.mjs";
|
|
6
|
+
import { t as PaginationEngine } from "./PaginationEngine-C2_tAvAD.mjs";
|
|
6
7
|
import { isGeoOperator, parseGeoFilter } from "./query/primitives/geo.mjs";
|
|
7
|
-
import { i as getMongooseProjection, n as filterResponseData, r as getFieldsForUser, t as createFieldPreset } from "./field-selection-
|
|
8
|
+
import { i as getMongooseProjection, n as filterResponseData, r as getFieldsForUser, t as createFieldPreset } from "./field-selection-dI0m4RBs.mjs";
|
|
8
9
|
import { buildFieldTypeMap, coerceFieldValue, coerceHeuristic } from "./query/primitives/coercion.mjs";
|
|
9
10
|
import { extractSchemaIndexes } from "./query/primitives/indexes.mjs";
|
|
10
|
-
import { a as isFieldUpdateAllowed, i as getSystemManagedFields, n as buildCrudSchemasFromMongooseSchema, o as validateUpdateBody, r as getImmutableFields, s as createMemoryCache, t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-
|
|
11
|
+
import { a as isFieldUpdateAllowed, i as getSystemManagedFields, n as buildCrudSchemasFromMongooseSchema, o as validateUpdateBody, r as getImmutableFields, s as createMemoryCache, t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-DUwXPStK.mjs";
|
|
11
12
|
//#region src/query/QueryParser.ts
|
|
12
13
|
/**
|
|
13
14
|
* Modern Query Parser
|
|
@@ -48,15 +49,47 @@ var QueryParser = class {
|
|
|
48
49
|
*/
|
|
49
50
|
_schemaIndexes;
|
|
50
51
|
/**
|
|
51
|
-
* Regex patterns that can cause catastrophic backtracking (ReDoS attacks)
|
|
52
|
-
* Detects:
|
|
52
|
+
* Regex patterns that can cause catastrophic backtracking (ReDoS attacks).
|
|
53
|
+
* Detects common footguns:
|
|
53
54
|
* - Quantifiers: {n,m}
|
|
54
55
|
* - Possessive quantifiers: *+, ++, ?+
|
|
55
56
|
* - Nested quantifiers: (a+)+, (a*)*
|
|
56
57
|
* - Backreferences: \1, \2, etc.
|
|
57
58
|
* - Complex character classes: [...]...[...]
|
|
59
|
+
*
|
|
60
|
+
* This pattern detector is FAIL-SAFE (on match, the input is escaped), but
|
|
61
|
+
* it is not exhaustive. {@link _regexComplexityExceedsBudget} complements
|
|
62
|
+
* it with a deterministic static complexity budget so patterns that happen
|
|
63
|
+
* to evade the detector still fail over when their unbounded-quantifier
|
|
64
|
+
* density is pathological.
|
|
58
65
|
*/
|
|
59
66
|
dangerousRegexPatterns = /(\{[0-9,]+\}|\*\+|\+\+|\?\+|(\(.+\))\+|\(\?:|\\[0-9]|(\[.+\]).+(\[.+\]))/;
|
|
67
|
+
/**
|
|
68
|
+
* Static complexity budget for user-supplied regex patterns.
|
|
69
|
+
* Returns `true` if the pattern crosses a budget that empirically correlates
|
|
70
|
+
* with ReDoS risk — independent of the heuristic regex detector.
|
|
71
|
+
*
|
|
72
|
+
* Budget components (any single threshold crossed → over budget):
|
|
73
|
+
* - unbounded quantifiers (`*`, `+`, `?`) — hard cap 20
|
|
74
|
+
* - nested groups `(` — hard cap 8
|
|
75
|
+
* - alternations `|` — hard cap 10
|
|
76
|
+
* - combined: (quantifiers * groups) — hard cap 40
|
|
77
|
+
*
|
|
78
|
+
* These thresholds are intentionally permissive for legitimate queries and
|
|
79
|
+
* tight enough to refuse known-pathological patterns like `(a+)+b` with
|
|
80
|
+
* heavy repetition.
|
|
81
|
+
*/
|
|
82
|
+
_regexComplexityExceedsBudget(patternStr) {
|
|
83
|
+
const stripped = patternStr.replace(/\\[^\\]/g, "");
|
|
84
|
+
const unboundedQuantifiers = (stripped.match(/[*+?]/g) ?? []).length;
|
|
85
|
+
const groups = (stripped.match(/\(/g) ?? []).length;
|
|
86
|
+
const alternations = (stripped.match(/\|/g) ?? []).length;
|
|
87
|
+
if (unboundedQuantifiers > 20) return true;
|
|
88
|
+
if (groups > 8) return true;
|
|
89
|
+
if (alternations > 10) return true;
|
|
90
|
+
if (unboundedQuantifiers * groups > 40) return true;
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
60
93
|
constructor(options = {}) {
|
|
61
94
|
this.options = {
|
|
62
95
|
maxRegexLength: options.maxRegexLength ?? 500,
|
|
@@ -770,6 +803,10 @@ var QueryParser = class {
|
|
|
770
803
|
warn("[mongokit] Potentially dangerous regex pattern, escaping");
|
|
771
804
|
return new RegExp(this._escapeRegex(patternStr), flags);
|
|
772
805
|
}
|
|
806
|
+
if (this._regexComplexityExceedsBudget(patternStr)) {
|
|
807
|
+
warn("[mongokit] Regex complexity budget exceeded, escaping");
|
|
808
|
+
return new RegExp(this._escapeRegex(patternStr), flags);
|
|
809
|
+
}
|
|
773
810
|
try {
|
|
774
811
|
return new RegExp(patternStr, flags);
|
|
775
812
|
} catch {
|
|
@@ -783,7 +820,11 @@ var QueryParser = class {
|
|
|
783
820
|
* Sanitize $match configuration to prevent dangerous operators
|
|
784
821
|
* Recursively filters out operators like $where, $function, $accumulator
|
|
785
822
|
*/
|
|
786
|
-
_sanitizeMatchConfig(config) {
|
|
823
|
+
_sanitizeMatchConfig(config, depth = 0) {
|
|
824
|
+
if (depth > this.options.maxFilterDepth) {
|
|
825
|
+
warn(`[mongokit] $match sanitize depth ${depth} exceeds maximum ${this.options.maxFilterDepth}, truncating branch`);
|
|
826
|
+
return {};
|
|
827
|
+
}
|
|
787
828
|
const sanitized = {};
|
|
788
829
|
const logicalArrayOps = new Set([
|
|
789
830
|
"$or",
|
|
@@ -795,10 +836,10 @@ var QueryParser = class {
|
|
|
795
836
|
warn(`[mongokit] Blocked dangerous operator in aggregation: ${key}`);
|
|
796
837
|
continue;
|
|
797
838
|
}
|
|
798
|
-
if (value && typeof value === "object" && !Array.isArray(value)) sanitized[key] = this._sanitizeMatchConfig(value);
|
|
839
|
+
if (value && typeof value === "object" && !Array.isArray(value)) sanitized[key] = this._sanitizeMatchConfig(value, depth + 1);
|
|
799
840
|
else if (Array.isArray(value)) {
|
|
800
841
|
const sanitizedArray = value.map((item) => {
|
|
801
|
-
if (item && typeof item === "object" && !Array.isArray(item)) return this._sanitizeMatchConfig(item);
|
|
842
|
+
if (item && typeof item === "object" && !Array.isArray(item)) return this._sanitizeMatchConfig(item, depth + 1);
|
|
802
843
|
return item;
|
|
803
844
|
});
|
|
804
845
|
if (logicalArrayOps.has(key)) {
|
|
@@ -945,4 +986,4 @@ function createRepository(Model, plugins = [], paginationConfig = {}, options =
|
|
|
945
986
|
}
|
|
946
987
|
var src_default = Repository;
|
|
947
988
|
//#endregion
|
|
948
|
-
export { AggregationBuilder, AuditTrailQuery, HOOK_PRIORITY, LookupBuilder, PaginationEngine, QueryParser, Repository, actions_exports as actions, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, configureLogger, createError, createFieldPreset, createMemoryCache, createRepository, customIdPlugin, dateSequentialId, src_default as default, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getImmutableFields, getMongooseProjection, getNextSequence, getSystemManagedFields, immutableField, isFieldUpdateAllowed, isTransactionUnsupported, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, parseDuplicateKeyError, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validateUpdateBody, validationChainPlugin, withTransaction };
|
|
989
|
+
export { ALL_OPERATIONS, AggregationBuilder, AuditTrailQuery, HOOK_PRIORITY, LookupBuilder, MUTATING_OPERATIONS, OP_REGISTRY, PaginationEngine, QueryParser, READ_OPERATIONS, Repository, actions_exports as actions, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, configureLogger, createError, createFieldPreset, createMemoryCache, createRepository, createTenantContext, customIdPlugin, dateSequentialId, src_default as default, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getImmutableFields, getMongooseProjection, getNextSequence, getSystemManagedFields, immutableField, isFieldUpdateAllowed, isTransactionUnsupported, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validateUpdateBody, validationChainPlugin, withTransaction };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/utils/logger.ts
|
|
2
|
+
const noop = () => {};
|
|
3
|
+
let current = {
|
|
4
|
+
warn: console.warn.bind(console),
|
|
5
|
+
debug: noop
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Configure the internal logger.
|
|
9
|
+
* Pass `false` to silence all output.
|
|
10
|
+
*/
|
|
11
|
+
function configureLogger(config) {
|
|
12
|
+
if (config === false) current = {
|
|
13
|
+
warn: noop,
|
|
14
|
+
debug: noop
|
|
15
|
+
};
|
|
16
|
+
else current = {
|
|
17
|
+
...current,
|
|
18
|
+
...config
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** Emit a warning — security blocks, config issues, performance hints */
|
|
22
|
+
function warn(message, ...args) {
|
|
23
|
+
current.warn(message, ...args);
|
|
24
|
+
}
|
|
25
|
+
/** Emit debug info — only visible when debug is enabled */
|
|
26
|
+
function debug(message, ...args) {
|
|
27
|
+
current.debug(message, ...args);
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { debug as n, warn as r, configureLogger as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as HttpError, St as ValidationResult, T as FieldPreset, _ as CrudSchemas, bt as UserContext, s as CacheAdapter, st as SchemaBuilderOptions } from "./types-D57SZJeE.mjs";
|
|
2
2
|
import mongoose, { Schema } from "mongoose";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/error.d.ts
|
|
@@ -15,13 +15,29 @@ import mongoose, { Schema } from "mongoose";
|
|
|
15
15
|
* throw createError(403, 'Access denied');
|
|
16
16
|
*/
|
|
17
17
|
declare function createError(status: number, message: string): HttpError;
|
|
18
|
+
/** Options for parseDuplicateKeyError */
|
|
19
|
+
interface ParseDuplicateKeyOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Include the offending values inline in the error message and under
|
|
22
|
+
* `error.duplicate.values`. Default is `false` because those values can be
|
|
23
|
+
* PII (emails, tokens, phone numbers) and end up in logs/crash reports.
|
|
24
|
+
* Enable in dev or for trusted internal tools only.
|
|
25
|
+
*/
|
|
26
|
+
exposeValues?: boolean;
|
|
27
|
+
}
|
|
18
28
|
/**
|
|
19
29
|
* Detect and convert a MongoDB E11000 duplicate-key error into
|
|
20
30
|
* a 409 HttpError with an actionable message.
|
|
21
31
|
*
|
|
32
|
+
* PII-safe by default: the error message lists only the conflicting field
|
|
33
|
+
* names, never the values. Structured field names are attached under
|
|
34
|
+
* `error.duplicate.fields` for downstream handlers. Pass
|
|
35
|
+
* `{ exposeValues: true }` to opt into including the values (dev or trusted
|
|
36
|
+
* server-to-server contexts only).
|
|
37
|
+
*
|
|
22
38
|
* Returns `null` when the error is not a duplicate-key error.
|
|
23
39
|
*/
|
|
24
|
-
declare function parseDuplicateKeyError(error: unknown): HttpError | null;
|
|
40
|
+
declare function parseDuplicateKeyError(error: unknown, options?: ParseDuplicateKeyOptions): HttpError | null;
|
|
25
41
|
//#endregion
|
|
26
42
|
//#region src/utils/field-selection.d.ts
|
|
27
43
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as
|
|
1
|
+
import { F as KeysetPaginationOptions, I as KeysetPaginationResult, K as PaginationConfig, U as OffsetPaginationOptions, W as OffsetPaginationResult, a as AnyDocument, n as AggregatePaginationOptions, r as AggregatePaginationResult } from "../types-D57SZJeE.mjs";
|
|
2
2
|
import { Model } from "mongoose";
|
|
3
3
|
|
|
4
4
|
//#region src/pagination/PaginationEngine.d.ts
|
|
@@ -11,6 +11,8 @@ interface ResolvedPaginationConfig {
|
|
|
11
11
|
maxPage: number;
|
|
12
12
|
deepPageThreshold: number;
|
|
13
13
|
cursorVersion: number;
|
|
14
|
+
minCursorVersion: number;
|
|
15
|
+
strictKeysetSortFields: string[] | undefined;
|
|
14
16
|
useEstimatedCount: boolean;
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as PaginationEngine } from "../PaginationEngine-
|
|
1
|
+
import { t as PaginationEngine } from "../PaginationEngine-C2_tAvAD.mjs";
|
|
2
2
|
export { PaginationEngine };
|
package/dist/plugins/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { type AggregateHelpersMethods, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailOptions, AuditTrailQuery, type BatchOperationsMethods, type CacheMethods, type CustomIdOptions, type DateSequentialIdOptions, type ElasticSearchOptions, type IdGenerator, type MethodRegistryRepository, type MongoOperationsMethods, type MultiTenantOptions, type ObservabilityOptions, type OperationMetric, type PrefixedIdOptions, type SequentialIdOptions, type SoftDeleteMethods, type SubdocumentMethods, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, cachePlugin, cascadePlugin, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, getNextSequence, immutableField, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validationChainPlugin };
|
|
1
|
+
import { $ as aggregateHelpersPlugin, A as PrefixedIdOptions, B as BatchOperationsMethods, C as methodRegistryPlugin, D as CustomIdOptions, E as elasticSearchPlugin, F as prefixedId, G as AuditQueryOptions, H as batchOperationsPlugin, I as sequentialId, J as AuditTrailOptions, K as AuditQueryResult, L as cascadePlugin, M as customIdPlugin, N as dateSequentialId, O as DateSequentialIdOptions, P as getNextSequence, Q as AggregateHelpersMethods, R as CacheMethods, S as MethodRegistryRepository, T as ElasticSearchOptions, U as AuditEntry, W as AuditOperation, X as auditTrailPlugin, Y as AuditTrailQuery, Z as auditLogPlugin, _ as observabilityPlugin, a as uniqueField, b as MongoOperationsMethods, c as TenantContext, d as SubdocumentMethods, f as subdocumentPlugin, g as OperationMetric, h as ObservabilityOptions, i as requireField, j as SequentialIdOptions, k as IdGenerator, l as TenantStore, m as softDeletePlugin, n as blockIf, o as validationChainPlugin, p as SoftDeleteMethods, q as AuditTrailMethods, r as immutableField, s as timestampPlugin, t as autoInject, u as createTenantContext, v as MultiTenantOptions, w as fieldFilterPlugin, x as mongoOperationsPlugin, y as multiTenantPlugin, z as cachePlugin } from "../validation-chain.plugin-wGF34Ym-.mjs";
|
|
2
|
+
export { type AggregateHelpersMethods, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailOptions, AuditTrailQuery, type BatchOperationsMethods, type CacheMethods, type CustomIdOptions, type DateSequentialIdOptions, type ElasticSearchOptions, type IdGenerator, type MethodRegistryRepository, type MongoOperationsMethods, type MultiTenantOptions, type ObservabilityOptions, type OperationMetric, type PrefixedIdOptions, type SequentialIdOptions, type SoftDeleteMethods, type SubdocumentMethods, type TenantContext, type TenantStore, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, cachePlugin, cascadePlugin, createTenantContext, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, getNextSequence, immutableField, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validationChainPlugin };
|
package/dist/plugins/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { AuditTrailQuery, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, cachePlugin, cascadePlugin, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, getNextSequence, immutableField, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validationChainPlugin };
|
|
1
|
+
import { A as AuditTrailQuery, C as cachePlugin, M as auditLogPlugin, N as aggregateHelpersPlugin, S as cascadePlugin, _ as customIdPlugin, a as uniqueField, b as prefixedId, c as createTenantContext, d as observabilityPlugin, f as multiTenantPlugin, g as elasticSearchPlugin, h as fieldFilterPlugin, i as requireField, j as auditTrailPlugin, k as batchOperationsPlugin, l as subdocumentPlugin, m as methodRegistryPlugin, n as blockIf, o as validationChainPlugin, p as mongoOperationsPlugin, r as immutableField, s as timestampPlugin, t as autoInject, u as softDeletePlugin, v as dateSequentialId, x as sequentialId, y as getNextSequence } from "../validation-chain.plugin-DwoOOWse.mjs";
|
|
2
|
+
export { AuditTrailQuery, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, blockIf, cachePlugin, cascadePlugin, createTenantContext, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, getNextSequence, immutableField, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, prefixedId, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, timestampPlugin, uniqueField, validationChainPlugin };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as coerceHeuristic, i as coerceFieldValue, n as SchemaPathsLike, o as coerceToType, r as buildFieldTypeMap, s as normalizeMongooseType, t as FieldType } from "../../coercion-
|
|
1
|
+
import { a as coerceHeuristic, i as coerceFieldValue, n as SchemaPathsLike, o as coerceToType, r as buildFieldTypeMap, s as normalizeMongooseType, t as FieldType } from "../../coercion-oM8G4b6m.mjs";
|
|
2
2
|
export { FieldType, SchemaPathsLike, buildFieldTypeMap, coerceFieldValue, coerceHeuristic, coerceToType, normalizeMongooseType };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as SchemaIndexes, r as extractSchemaIndexes, t as IndexableSchema } from "../../indexes-
|
|
1
|
+
import { n as SchemaIndexes, r as extractSchemaIndexes, t as IndexableSchema } from "../../indexes-C26GNZRU.mjs";
|
|
2
2
|
export { IndexableSchema, SchemaIndexes, extractSchemaIndexes };
|
|
@@ -21,21 +21,36 @@ function normalizeSort(sort) {
|
|
|
21
21
|
return normalized;
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
* Validates and normalizes sort for keyset pagination
|
|
25
|
-
* Auto-adds _id tie-breaker if needed
|
|
26
|
-
*
|
|
24
|
+
* Validates and normalizes sort for keyset pagination.
|
|
25
|
+
* Auto-adds `_id` tie-breaker if needed; ensures `_id` direction matches the
|
|
26
|
+
* primary field.
|
|
27
|
+
*
|
|
28
|
+
* **Known limitation (MongoDB mixed-type sort):** keyset pagination across a
|
|
29
|
+
* field that can hold both typed values (Date, Number) and `null`/`undefined`
|
|
30
|
+
* is lossy — `$lt/$gt` don't cross the type boundary in BSON comparison, so
|
|
31
|
+
* some docs at the null/non-null boundary are unreachable. If your sort field
|
|
32
|
+
* is nullable, either:
|
|
33
|
+
* - sort by `_id` alone (always safe), or
|
|
34
|
+
* - use `allowedPrimaryFields` to lock keyset sort to fields your schema
|
|
35
|
+
* guarantees non-null (see `PaginationConfig.strictKeysetSortFields`).
|
|
27
36
|
*
|
|
28
37
|
* @param sort - Sort specification
|
|
38
|
+
* @param allowedPrimaryFields - Optional allowlist of primary (non-_id) sort
|
|
39
|
+
* field names. When set, rejects sorts whose primary field isn't listed.
|
|
40
|
+
* `_id` is always allowed.
|
|
29
41
|
* @returns Validated and normalized sort
|
|
30
42
|
* @throws Error if sort is invalid for keyset pagination
|
|
31
43
|
*/
|
|
32
|
-
function validateKeysetSort(sort) {
|
|
44
|
+
function validateKeysetSort(sort, allowedPrimaryFields) {
|
|
33
45
|
const keys = Object.keys(sort);
|
|
34
46
|
if (keys.length === 0) throw new Error("Keyset pagination requires at least one sort field");
|
|
35
47
|
if (keys.length === 1 && keys[0] === "_id") return normalizeSort(sort);
|
|
36
48
|
for (const key of keys) if (sort[key] !== 1 && sort[key] !== -1) throw new Error(`Invalid sort direction for "${key}": must be 1 or -1, got ${sort[key]}`);
|
|
37
49
|
const nonIdKeys = keys.filter((k) => k !== "_id");
|
|
38
50
|
const primaryDirection = sort[nonIdKeys[0]];
|
|
51
|
+
if (allowedPrimaryFields && allowedPrimaryFields.length > 0) {
|
|
52
|
+
for (const key of nonIdKeys) if (!allowedPrimaryFields.includes(key)) throw new Error(`Keyset sort field "${key}" is not in the strictKeysetSortFields allowlist. Allowed: ${allowedPrimaryFields.join(", ")}. (See PaginationConfig.strictKeysetSortFields — protects against lossy null/non-null keyset boundaries.)`);
|
|
53
|
+
}
|
|
39
54
|
for (const key of nonIdKeys) if (sort[key] !== primaryDirection) throw new Error("All sort fields must share the same direction for keyset pagination");
|
|
40
55
|
if (keys.includes("_id") && sort._id !== primaryDirection) throw new Error("_id direction must match primary field direction");
|
|
41
56
|
if (!keys.includes("_id")) return normalizeSort({
|
|
@@ -570,6 +570,19 @@ interface RepositoryOptions {
|
|
|
570
570
|
* Required for regex mode to take effect.
|
|
571
571
|
*/
|
|
572
572
|
searchFields?: string[];
|
|
573
|
+
/**
|
|
574
|
+
* How to react to a plugin composition that is known to be unsafe.
|
|
575
|
+
* - 'warn' (default): log a warning via the configured logger.
|
|
576
|
+
* - 'throw': fail fast at construction time — recommended for production.
|
|
577
|
+
* - 'off': disable the check entirely.
|
|
578
|
+
*
|
|
579
|
+
* Checks currently enforced:
|
|
580
|
+
* - soft-delete must precede batch-operations (otherwise deleteMany /
|
|
581
|
+
* updateMany skip the soft-delete filter injection).
|
|
582
|
+
* - multi-tenant must precede cache (otherwise cache keys are computed
|
|
583
|
+
* before tenant scoping → cross-tenant cache poisoning risk).
|
|
584
|
+
*/
|
|
585
|
+
pluginOrderChecks?: 'warn' | 'throw' | 'off';
|
|
573
586
|
}
|
|
574
587
|
/** Pagination configuration */
|
|
575
588
|
interface PaginationConfig {
|
|
@@ -583,6 +596,27 @@ interface PaginationConfig {
|
|
|
583
596
|
deepPageThreshold?: number;
|
|
584
597
|
/** Cursor version for forward compatibility (default: 1) */
|
|
585
598
|
cursorVersion?: number;
|
|
599
|
+
/**
|
|
600
|
+
* Minimum cursor version accepted. Bump alongside `cursorVersion` when a
|
|
601
|
+
* breaking format change ships so stale client cursors are rejected with a
|
|
602
|
+
* clear error instead of silently paginating from the wrong position.
|
|
603
|
+
* Default: 1 (accept any cursor <= cursorVersion).
|
|
604
|
+
*/
|
|
605
|
+
minCursorVersion?: number;
|
|
606
|
+
/**
|
|
607
|
+
* Allowlist of primary sort fields for keyset pagination. When set, any
|
|
608
|
+
* `getAll({ sort })` whose primary (non-_id) field is not in this list
|
|
609
|
+
* throws at validation time.
|
|
610
|
+
*
|
|
611
|
+
* Use this to lock down keyset pagination to fields that are structurally
|
|
612
|
+
* guaranteed non-null in your schema — keyset sort across null/non-null
|
|
613
|
+
* boundaries is lossy (MongoDB's `$lt/$gt` semantics leave a gap at the
|
|
614
|
+
* type boundary, so not every doc is reachable).
|
|
615
|
+
*
|
|
616
|
+
* `_id` is always allowed regardless of this list.
|
|
617
|
+
* Undefined (default) = no allowlist, any sort field accepted.
|
|
618
|
+
*/
|
|
619
|
+
strictKeysetSortFields?: string[];
|
|
586
620
|
/** Use estimatedDocumentCount for faster counts on large collections */
|
|
587
621
|
useEstimatedCount?: boolean;
|
|
588
622
|
}
|
|
@@ -788,6 +822,31 @@ interface UpdateOptions extends OperationOptions {
|
|
|
788
822
|
/** Array filters for positional operator $[<identifier>] updates */
|
|
789
823
|
arrayFilters?: Record<string, unknown>[];
|
|
790
824
|
}
|
|
825
|
+
/**
|
|
826
|
+
* Options for atomic findOneAndUpdate (compare-and-set primitive).
|
|
827
|
+
*
|
|
828
|
+
* Designed for outbox/lock/semaphore patterns that need a single round-trip
|
|
829
|
+
* match-and-mutate. Goes through the full hook pipeline (multi-tenant scope,
|
|
830
|
+
* soft-delete, audit) the same way `update()` does.
|
|
831
|
+
*/
|
|
832
|
+
interface FindOneAndUpdateOptions extends OperationOptions {
|
|
833
|
+
/** Sort to disambiguate when filter matches multiple docs (e.g. FIFO claim). */
|
|
834
|
+
sort?: SortSpec;
|
|
835
|
+
/** Return doc state before or after the update. Default: 'after'. */
|
|
836
|
+
returnDocument?: 'before' | 'after';
|
|
837
|
+
/** Insert if no doc matches. Default: false. */
|
|
838
|
+
upsert?: boolean;
|
|
839
|
+
/** Array filters for positional `$[<identifier>]` updates. */
|
|
840
|
+
arrayFilters?: Record<string, unknown>[];
|
|
841
|
+
/** Allow aggregation-pipeline updates (array form). Default: false. */
|
|
842
|
+
updatePipeline?: boolean;
|
|
843
|
+
/** Run mongoose schema validators on the update. Default: true. */
|
|
844
|
+
runValidators?: boolean;
|
|
845
|
+
/** Collation for locale-aware string comparison. */
|
|
846
|
+
collation?: CollationOptions;
|
|
847
|
+
/** Maximum execution time in milliseconds. */
|
|
848
|
+
maxTimeMS?: number;
|
|
849
|
+
}
|
|
791
850
|
/** Aggregate operation options */
|
|
792
851
|
interface AggregateOptions extends ReadOptions {
|
|
793
852
|
/** Allow aggregation to use disk for large sorts/groups */
|
|
@@ -993,7 +1052,7 @@ interface RepositoryInstance {
|
|
|
993
1052
|
[key: string]: unknown;
|
|
994
1053
|
}
|
|
995
1054
|
/** Repository operation names */
|
|
996
|
-
type RepositoryOperation = 'create' | 'createMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany' | 'restore' | 'getById' | 'getByQuery' | 'getOne' | 'getAll' | 'findAll' | 'getOrCreate' | 'count' | 'exists' | 'distinct' | 'aggregate' | 'aggregatePaginate' | 'lookupPopulate' | 'bulkWrite';
|
|
1055
|
+
type RepositoryOperation = 'create' | 'createMany' | 'update' | 'updateMany' | 'findOneAndUpdate' | 'delete' | 'deleteMany' | 'restore' | 'getById' | 'getByQuery' | 'getOne' | 'getAll' | 'findAll' | 'getOrCreate' | 'count' | 'exists' | 'distinct' | 'aggregate' | 'aggregatePaginate' | 'lookupPopulate' | 'bulkWrite';
|
|
997
1056
|
/** Event lifecycle phases */
|
|
998
1057
|
type EventPhase = 'before' | 'after' | 'error';
|
|
999
1058
|
/** Repository event names (generated from template literals) */
|
|
@@ -1139,7 +1198,7 @@ interface ValidatorDefinition {
|
|
|
1139
1198
|
/** Validator name */
|
|
1140
1199
|
name: string;
|
|
1141
1200
|
/** Operations to apply validator to */
|
|
1142
|
-
operations?: Array<'create' | 'createMany' | 'update' | 'delete'>;
|
|
1201
|
+
operations?: Array<'create' | 'createMany' | 'update' | 'findOneAndUpdate' | 'delete'>;
|
|
1143
1202
|
/** Validation function */
|
|
1144
1203
|
validate: (context: RepositoryContext, repo?: RepositoryInstance) => void | Promise<void>;
|
|
1145
1204
|
}
|
|
@@ -1269,6 +1328,17 @@ interface CacheOptions {
|
|
|
1269
1328
|
skipIf?: {
|
|
1270
1329
|
largeLimit?: number;
|
|
1271
1330
|
};
|
|
1331
|
+
/**
|
|
1332
|
+
* TTL jitter to mitigate cache stampedes. When many entries share the same
|
|
1333
|
+
* TTL and expire simultaneously, every concurrent reader misses and hammers
|
|
1334
|
+
* the DB at once. Jitter spreads expirations over a window.
|
|
1335
|
+
*
|
|
1336
|
+
* - `number` in [0, 1]: fractional symmetric jitter. `0.1` multiplies the
|
|
1337
|
+
* TTL by a random factor in [0.9, 1.1]. Default: 0 (no jitter).
|
|
1338
|
+
* - `function(ttl)`: full control — receive the configured TTL (seconds),
|
|
1339
|
+
* return the effective TTL (seconds) to store with.
|
|
1340
|
+
*/
|
|
1341
|
+
jitter?: number | ((ttlSeconds: number) => number);
|
|
1272
1342
|
}
|
|
1273
1343
|
/** Options for cache-aware operations */
|
|
1274
1344
|
interface CacheOperationOptions {
|
|
@@ -1325,6 +1395,16 @@ interface HttpError extends Error {
|
|
|
1325
1395
|
validator: string;
|
|
1326
1396
|
error: string;
|
|
1327
1397
|
}>;
|
|
1398
|
+
/**
|
|
1399
|
+
* Structured metadata for duplicate-key (E11000) errors. Safe to surface in
|
|
1400
|
+
* logs/audit. Includes the offending field names and a boolean-only mirror
|
|
1401
|
+
* of whether each field had a duplicate value — never the value itself
|
|
1402
|
+
* unless `parseDuplicateKeyError` was called with `{ exposeValues: true }`.
|
|
1403
|
+
*/
|
|
1404
|
+
duplicate?: {
|
|
1405
|
+
fields: string[]; /** Only populated when parseDuplicateKeyError was called with exposeValues:true. */
|
|
1406
|
+
values?: Record<string, unknown>;
|
|
1407
|
+
};
|
|
1328
1408
|
}
|
|
1329
1409
|
/**
|
|
1330
1410
|
* Combines all plugin method types into a single type
|
|
@@ -1470,4 +1550,4 @@ type AllPluginMethods<TDoc> = {
|
|
|
1470
1550
|
*/
|
|
1471
1551
|
type WithPlugins<TDoc, TRepo extends RepositoryInstance = RepositoryInstance> = TRepo & AllPluginMethods<TDoc>;
|
|
1472
1552
|
//#endregion
|
|
1473
|
-
export {
|
|
1553
|
+
export { ReadOptions as $, HttpError as A, LookupBuilder as At, MinMaxResult as B, EventPayload as C, ValidatorDefinition as Ct, FindOneAndUpdateOptions as D, IControllerResponse as Dt, FieldRules as E, IController as Et, KeysetPaginationOptions as F, OperationOptions as G, ObjectId as H, KeysetPaginationResult as I, PartialBy as J, PaginationConfig as K, Logger as L, InferRawDoc as M, JsonSchema as N, GroupResult as O, IRequestContext as Ot, KeysOfType as P, PopulateSpec as Q, LookupPopulateOptions as R, EventHandlers as S, ValidationResult as St, FieldPreset as T, WithTransactionOptions as Tt, OffsetPaginationOptions as U, NonNullableFields as V, OffsetPaginationResult as W, PluginFunction as X, Plugin as Y, PluginType as Z, CrudSchemas as _, UpdateManyResult as _t, AnyDocument as a, RepositoryOptions as at, DeleteResult as b, UserContext as bt, CacheOperationOptions as c, SelectSpec as ct, CacheableOptions as d, SoftDeleteOptions as dt, ReadPreferenceType as et, CascadeOptions as f, SoftDeleteRepository as ft, CreateOptions as g, UpdateInput as gt, CreateInput as h, Strict as ht, AllPluginMethods as i, RepositoryOperation as it, InferDocument as j, LookupOptions as jt, HookMode as k, IResponseFormatter as kt, CacheOptions as l, SessionOptions as lt, CollationOptions as m, SortSpec as mt, AggregatePaginationOptions as n, RepositoryEvent as nt, AnyModel as o, RequiredBy as ot, CascadeRelation as p, SortDirection as pt, PaginationResult as q, AggregatePaginationResult as r, RepositoryInstance as rt, CacheAdapter as s, SchemaBuilderOptions as st, AggregateOptions as t, RepositoryContext as tt, CacheStats as u, SoftDeleteFilterMode as ut, DecodedCursor as v, UpdateOptions as vt, EventPhase as w, WithPlugins as wt, DocField as x, ValidationChainOptions as xt, DeepPartial as y, UpdateWithValidationResult as yt, LookupPopulateResult as z };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { r as warn } from "./logger-DJ7egMnd.mjs";
|
|
3
|
+
import { t as createError } from "./error-Lw9GEAro.mjs";
|
|
3
4
|
//#region src/query/LookupBuilder.ts
|
|
4
5
|
/** Stages that are never valid inside a $lookup pipeline */
|
|
5
6
|
const BLOCKED_PIPELINE_STAGES = [
|
|
@@ -728,6 +729,7 @@ async function exists(Model, query, options = {}) {
|
|
|
728
729
|
//#endregion
|
|
729
730
|
//#region src/actions/update.ts
|
|
730
731
|
var update_exports = /* @__PURE__ */ __exportAll({
|
|
732
|
+
findOneAndUpdate: () => findOneAndUpdate,
|
|
731
733
|
increment: () => increment,
|
|
732
734
|
pullFromArray: () => pullFromArray,
|
|
733
735
|
pushToArray: () => pushToArray,
|
|
@@ -860,6 +862,28 @@ async function updateByQuery(Model, query, data, options = {}) {
|
|
|
860
862
|
return document;
|
|
861
863
|
}
|
|
862
864
|
/**
|
|
865
|
+
* Atomic findOneAndUpdate primitive.
|
|
866
|
+
*
|
|
867
|
+
* Returns the matched document (post-update by default) or null when no doc
|
|
868
|
+
* matches and `upsert` is false. Used by outbox relays, distributed locks,
|
|
869
|
+
* and workflow semaphores that need compare-and-set in a single round-trip.
|
|
870
|
+
*/
|
|
871
|
+
async function findOneAndUpdate(Model, filter, update, options = {}) {
|
|
872
|
+
assertUpdatePipelineAllowed(update, options.updatePipeline);
|
|
873
|
+
const returnDocument = options.returnDocument ?? "after";
|
|
874
|
+
return await Model.findOneAndUpdate(filter, update, {
|
|
875
|
+
returnDocument,
|
|
876
|
+
upsert: options.upsert ?? false,
|
|
877
|
+
runValidators: options.runValidators ?? true,
|
|
878
|
+
session: options.session,
|
|
879
|
+
...options.sort ? { sort: options.sort } : {},
|
|
880
|
+
...options.arrayFilters ? { arrayFilters: options.arrayFilters } : {},
|
|
881
|
+
...options.collation ? { collation: options.collation } : {},
|
|
882
|
+
...options.maxTimeMS ? { maxTimeMS: options.maxTimeMS } : {},
|
|
883
|
+
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
884
|
+
}).select(options.select || "").populate(parsePopulate(options.populate)).lean(options.lean ?? true);
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
863
887
|
* Increment field
|
|
864
888
|
*/
|
|
865
889
|
async function increment(Model, id, field, value = 1, options = {}) {
|
|
@@ -878,4 +902,4 @@ async function pullFromArray(Model, id, field, value, options = {}) {
|
|
|
878
902
|
return update(Model, id, { $pull: { [field]: value } }, options);
|
|
879
903
|
}
|
|
880
904
|
//#endregion
|
|
881
|
-
export {
|
|
905
|
+
export { upsert as _, count as a, LookupBuilder as b, getByQuery as c, deleteById as d, deleteByQuery as f, create_exports as g, createMany as h, update_exports as i, getOrCreate as l, create as m, update as n, exists as o, delete_exports as p, updateByQuery as r, getById as s, findOneAndUpdate as t, read_exports as u, aggregate_exports as v, distinct as y };
|
package/dist/utils/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as isFieldUpdateAllowed, c as configureLogger, d as getFieldsForUser, f as getMongooseProjection, i as getSystemManagedFields, l as createFieldPreset, n as buildCrudSchemasFromMongooseSchema, o as validateUpdateBody, p as createError, r as getImmutableFields, s as createMemoryCache, t as buildCrudSchemasFromModel, u as filterResponseData } from "../mongooseToJsonSchema-
|
|
1
|
+
import { Q as PopulateSpec, ct as SelectSpec, mt as SortSpec } from "../types-D57SZJeE.mjs";
|
|
2
|
+
import { a as isFieldUpdateAllowed, c as configureLogger, d as getFieldsForUser, f as getMongooseProjection, i as getSystemManagedFields, l as createFieldPreset, n as buildCrudSchemasFromMongooseSchema, o as validateUpdateBody, p as createError, r as getImmutableFields, s as createMemoryCache, t as buildCrudSchemasFromModel, u as filterResponseData } from "../mongooseToJsonSchema-BZaKOXXI.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/cache-keys.d.ts
|
|
5
5
|
/**
|
package/dist/utils/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { a as
|
|
1
|
+
import { t as configureLogger } from "../logger-DJ7egMnd.mjs";
|
|
2
|
+
import { t as createError } from "../error-Lw9GEAro.mjs";
|
|
3
|
+
import { n as isObjectIdInstance, r as isValidIdForType, t as getSchemaIdType } from "../id-resolution-e4BT9zAV.mjs";
|
|
4
|
+
import { a as byIdKey, c as listQueryKey, i as getMongooseProjection, l as modelPattern, n as filterResponseData, o as byQueryKey, r as getFieldsForUser, s as listPattern, t as createFieldPreset, u as versionKey } from "../field-selection-dI0m4RBs.mjs";
|
|
5
|
+
import { a as isFieldUpdateAllowed, i as getSystemManagedFields, n as buildCrudSchemasFromMongooseSchema, o as validateUpdateBody, r as getImmutableFields, s as createMemoryCache, t as buildCrudSchemasFromModel } from "../mongooseToJsonSchema-DUwXPStK.mjs";
|
|
5
6
|
export { buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, byIdKey, byQueryKey, configureLogger, createError, createFieldPreset, createMemoryCache, filterResponseData, getFieldsForUser, getImmutableFields, getMongooseProjection, getSchemaIdType, getSystemManagedFields, isFieldUpdateAllowed, isObjectIdInstance, isValidIdForType, listPattern, listQueryKey, modelPattern, validateUpdateBody, versionKey };
|