@classytic/mongokit 2.1.0 → 3.0.1
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/README.md +35 -4
- package/dist/actions/index.d.ts +2 -2
- package/dist/actions/index.js +0 -2
- package/dist/{index-CgOJ2pqz.d.ts → index-CKy3H2SY.d.ts} +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.js +183 -6
- package/dist/{memory-cache-DG2oSSbx.d.ts → memory-cache-tn3v1xgG.d.ts} +1 -1
- package/dist/pagination/PaginationEngine.d.ts +1 -1
- package/dist/pagination/PaginationEngine.js +0 -2
- package/dist/plugins/index.d.ts +37 -2
- package/dist/plugins/index.js +173 -3
- package/dist/{types-Nxhmi1aI.d.cts → types-vDtcOhyx.d.ts} +19 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +0 -2
- package/package.json +6 -12
- package/dist/actions/index.cjs +0 -479
- package/dist/actions/index.cjs.map +0 -1
- package/dist/actions/index.d.cts +0 -3
- package/dist/actions/index.js.map +0 -1
- package/dist/index-BfVJZF-3.d.cts +0 -337
- package/dist/index.cjs +0 -2142
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -239
- package/dist/index.js.map +0 -1
- package/dist/memory-cache-DqfFfKes.d.cts +0 -142
- package/dist/pagination/PaginationEngine.cjs +0 -375
- package/dist/pagination/PaginationEngine.cjs.map +0 -1
- package/dist/pagination/PaginationEngine.d.cts +0 -117
- package/dist/pagination/PaginationEngine.js.map +0 -1
- package/dist/plugins/index.cjs +0 -874
- package/dist/plugins/index.cjs.map +0 -1
- package/dist/plugins/index.d.cts +0 -275
- package/dist/plugins/index.js.map +0 -1
- package/dist/types-Nxhmi1aI.d.ts +0 -510
- package/dist/utils/index.cjs +0 -667
- package/dist/utils/index.cjs.map +0 -1
- package/dist/utils/index.d.cts +0 -189
- package/dist/utils/index.js.map +0 -1
package/dist/utils/index.cjs
DELETED
|
@@ -1,667 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var mongoose2 = require('mongoose');
|
|
4
|
-
|
|
5
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
6
|
-
|
|
7
|
-
var mongoose2__default = /*#__PURE__*/_interopDefault(mongoose2);
|
|
8
|
-
|
|
9
|
-
// src/utils/field-selection.ts
|
|
10
|
-
function getFieldsForUser(user, preset) {
|
|
11
|
-
if (!preset) {
|
|
12
|
-
throw new Error("Field preset is required");
|
|
13
|
-
}
|
|
14
|
-
const fields = [...preset.public || []];
|
|
15
|
-
if (user) {
|
|
16
|
-
fields.push(...preset.authenticated || []);
|
|
17
|
-
const roles = Array.isArray(user.roles) ? user.roles : user.roles ? [user.roles] : [];
|
|
18
|
-
if (roles.includes("admin") || roles.includes("superadmin")) {
|
|
19
|
-
fields.push(...preset.admin || []);
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
return [...new Set(fields)];
|
|
23
|
-
}
|
|
24
|
-
function getMongooseProjection(user, preset) {
|
|
25
|
-
const fields = getFieldsForUser(user, preset);
|
|
26
|
-
return fields.join(" ");
|
|
27
|
-
}
|
|
28
|
-
function filterObject(obj, allowedFields) {
|
|
29
|
-
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
30
|
-
return obj;
|
|
31
|
-
}
|
|
32
|
-
const filtered = {};
|
|
33
|
-
for (const field of allowedFields) {
|
|
34
|
-
if (field in obj) {
|
|
35
|
-
filtered[field] = obj[field];
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return filtered;
|
|
39
|
-
}
|
|
40
|
-
function filterResponseData(data, preset, user = null) {
|
|
41
|
-
const allowedFields = getFieldsForUser(user, preset);
|
|
42
|
-
if (Array.isArray(data)) {
|
|
43
|
-
return data.map((item) => filterObject(item, allowedFields));
|
|
44
|
-
}
|
|
45
|
-
return filterObject(data, allowedFields);
|
|
46
|
-
}
|
|
47
|
-
function createFieldPreset(config) {
|
|
48
|
-
return {
|
|
49
|
-
public: config.public || [],
|
|
50
|
-
authenticated: config.authenticated || [],
|
|
51
|
-
admin: config.admin || []
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
var QueryParser = class {
|
|
55
|
-
operators = {
|
|
56
|
-
eq: "$eq",
|
|
57
|
-
ne: "$ne",
|
|
58
|
-
gt: "$gt",
|
|
59
|
-
gte: "$gte",
|
|
60
|
-
lt: "$lt",
|
|
61
|
-
lte: "$lte",
|
|
62
|
-
in: "$in",
|
|
63
|
-
nin: "$nin",
|
|
64
|
-
like: "$regex",
|
|
65
|
-
contains: "$regex",
|
|
66
|
-
regex: "$regex",
|
|
67
|
-
exists: "$exists",
|
|
68
|
-
size: "$size",
|
|
69
|
-
type: "$type"
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* Dangerous MongoDB operators that should never be accepted from user input
|
|
73
|
-
* Security: Prevent NoSQL injection attacks
|
|
74
|
-
*/
|
|
75
|
-
dangerousOperators = ["$where", "$function", "$accumulator", "$expr"];
|
|
76
|
-
/**
|
|
77
|
-
* Parse query parameters into MongoDB query format
|
|
78
|
-
*/
|
|
79
|
-
parseQuery(query) {
|
|
80
|
-
const {
|
|
81
|
-
page,
|
|
82
|
-
limit = 20,
|
|
83
|
-
sort = "-createdAt",
|
|
84
|
-
populate,
|
|
85
|
-
search,
|
|
86
|
-
after,
|
|
87
|
-
cursor,
|
|
88
|
-
...filters
|
|
89
|
-
} = query || {};
|
|
90
|
-
const parsed = {
|
|
91
|
-
filters: this._parseFilters(filters),
|
|
92
|
-
limit: parseInt(String(limit), 10),
|
|
93
|
-
sort: this._parseSort(sort),
|
|
94
|
-
populate,
|
|
95
|
-
search
|
|
96
|
-
};
|
|
97
|
-
if (after || cursor) {
|
|
98
|
-
parsed.after = after || cursor;
|
|
99
|
-
} else if (page !== void 0) {
|
|
100
|
-
parsed.page = parseInt(String(page), 10);
|
|
101
|
-
} else {
|
|
102
|
-
parsed.page = 1;
|
|
103
|
-
}
|
|
104
|
-
const orGroup = this._parseOr(query);
|
|
105
|
-
if (orGroup) {
|
|
106
|
-
parsed.filters = { ...parsed.filters, $or: orGroup };
|
|
107
|
-
}
|
|
108
|
-
parsed.filters = this._enhanceWithBetween(parsed.filters);
|
|
109
|
-
return parsed;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Parse sort parameter
|
|
113
|
-
* Converts string like '-createdAt' to { createdAt: -1 }
|
|
114
|
-
* Handles multiple sorts: '-createdAt,name' → { createdAt: -1, name: 1 }
|
|
115
|
-
*/
|
|
116
|
-
_parseSort(sort) {
|
|
117
|
-
if (!sort) return void 0;
|
|
118
|
-
if (typeof sort === "object") return sort;
|
|
119
|
-
const sortObj = {};
|
|
120
|
-
const fields = sort.split(",").map((s) => s.trim());
|
|
121
|
-
for (const field of fields) {
|
|
122
|
-
if (field.startsWith("-")) {
|
|
123
|
-
sortObj[field.substring(1)] = -1;
|
|
124
|
-
} else {
|
|
125
|
-
sortObj[field] = 1;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
return sortObj;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Parse standard filter parameter (filter[field]=value)
|
|
132
|
-
*/
|
|
133
|
-
_parseFilters(filters) {
|
|
134
|
-
const parsedFilters = {};
|
|
135
|
-
for (const [key, value] of Object.entries(filters)) {
|
|
136
|
-
if (this.dangerousOperators.includes(key) || key.startsWith("$") && !["$or", "$and"].includes(key)) {
|
|
137
|
-
console.warn(`[mongokit] Blocked dangerous operator: ${key}`);
|
|
138
|
-
continue;
|
|
139
|
-
}
|
|
140
|
-
if (["page", "limit", "sort", "populate", "search", "select", "lean", "includeDeleted"].includes(key)) {
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
const operatorMatch = key.match(/^(.+)\[(.+)\]$/);
|
|
144
|
-
if (operatorMatch) {
|
|
145
|
-
const [, , operator] = operatorMatch;
|
|
146
|
-
if (this.dangerousOperators.includes("$" + operator)) {
|
|
147
|
-
console.warn(`[mongokit] Blocked dangerous operator: ${operator}`);
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
this._handleOperatorSyntax(parsedFilters, {}, operatorMatch, value);
|
|
151
|
-
continue;
|
|
152
|
-
}
|
|
153
|
-
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
154
|
-
this._handleBracketSyntax(key, value, parsedFilters);
|
|
155
|
-
} else {
|
|
156
|
-
parsedFilters[key] = this._convertValue(value);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
return parsedFilters;
|
|
160
|
-
}
|
|
161
|
-
/**
|
|
162
|
-
* Handle operator syntax: field[operator]=value
|
|
163
|
-
*/
|
|
164
|
-
_handleOperatorSyntax(filters, regexFields, operatorMatch, value) {
|
|
165
|
-
const [, field, operator] = operatorMatch;
|
|
166
|
-
if (operator.toLowerCase() === "options" && regexFields[field]) {
|
|
167
|
-
const fieldValue = filters[field];
|
|
168
|
-
if (typeof fieldValue === "object" && fieldValue !== null && "$regex" in fieldValue) {
|
|
169
|
-
fieldValue.$options = value;
|
|
170
|
-
}
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
if (operator.toLowerCase() === "contains" || operator.toLowerCase() === "like") {
|
|
174
|
-
filters[field] = { $regex: new RegExp(String(value), "i") };
|
|
175
|
-
regexFields[field] = true;
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const mongoOperator = this._toMongoOperator(operator);
|
|
179
|
-
if (this.dangerousOperators.includes(mongoOperator)) {
|
|
180
|
-
console.warn(`[mongokit] Blocked dangerous operator in field[${operator}]: ${mongoOperator}`);
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
if (mongoOperator === "$eq") {
|
|
184
|
-
filters[field] = value;
|
|
185
|
-
} else if (mongoOperator === "$regex") {
|
|
186
|
-
filters[field] = { $regex: value };
|
|
187
|
-
regexFields[field] = true;
|
|
188
|
-
} else {
|
|
189
|
-
if (typeof filters[field] !== "object" || filters[field] === null || Array.isArray(filters[field])) {
|
|
190
|
-
filters[field] = {};
|
|
191
|
-
}
|
|
192
|
-
let processedValue;
|
|
193
|
-
const op = operator.toLowerCase();
|
|
194
|
-
if (["gt", "gte", "lt", "lte", "size"].includes(op)) {
|
|
195
|
-
processedValue = parseFloat(String(value));
|
|
196
|
-
if (isNaN(processedValue)) return;
|
|
197
|
-
} else if (op === "in" || op === "nin") {
|
|
198
|
-
processedValue = Array.isArray(value) ? value : String(value).split(",").map((v) => v.trim());
|
|
199
|
-
} else {
|
|
200
|
-
processedValue = this._convertValue(value);
|
|
201
|
-
}
|
|
202
|
-
filters[field][mongoOperator] = processedValue;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Handle bracket syntax with object value
|
|
207
|
-
*/
|
|
208
|
-
_handleBracketSyntax(field, operators, parsedFilters) {
|
|
209
|
-
if (!parsedFilters[field]) {
|
|
210
|
-
parsedFilters[field] = {};
|
|
211
|
-
}
|
|
212
|
-
for (const [operator, value] of Object.entries(operators)) {
|
|
213
|
-
if (operator === "between") {
|
|
214
|
-
parsedFilters[field].between = value;
|
|
215
|
-
continue;
|
|
216
|
-
}
|
|
217
|
-
if (this.operators[operator]) {
|
|
218
|
-
const mongoOperator = this.operators[operator];
|
|
219
|
-
let processedValue;
|
|
220
|
-
if (["gt", "gte", "lt", "lte", "size"].includes(operator)) {
|
|
221
|
-
processedValue = parseFloat(String(value));
|
|
222
|
-
if (isNaN(processedValue)) continue;
|
|
223
|
-
} else if (operator === "in" || operator === "nin") {
|
|
224
|
-
processedValue = Array.isArray(value) ? value : String(value).split(",").map((v) => v.trim());
|
|
225
|
-
} else if (operator === "like" || operator === "contains") {
|
|
226
|
-
processedValue = value !== void 0 && value !== null ? new RegExp(String(value), "i") : /.*/;
|
|
227
|
-
} else {
|
|
228
|
-
processedValue = this._convertValue(value);
|
|
229
|
-
}
|
|
230
|
-
parsedFilters[field][mongoOperator] = processedValue;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
/**
|
|
235
|
-
* Convert operator to MongoDB format
|
|
236
|
-
*/
|
|
237
|
-
_toMongoOperator(operator) {
|
|
238
|
-
const op = operator.toLowerCase();
|
|
239
|
-
return op.startsWith("$") ? op : "$" + op;
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Convert values based on operator type
|
|
243
|
-
*/
|
|
244
|
-
_convertValue(value) {
|
|
245
|
-
if (value === null || value === void 0) return value;
|
|
246
|
-
if (Array.isArray(value)) return value.map((v) => this._convertValue(v));
|
|
247
|
-
if (typeof value === "object") return value;
|
|
248
|
-
const stringValue = String(value);
|
|
249
|
-
if (stringValue === "true") return true;
|
|
250
|
-
if (stringValue === "false") return false;
|
|
251
|
-
if (mongoose2__default.default.Types.ObjectId.isValid(stringValue) && stringValue.length === 24) {
|
|
252
|
-
return stringValue;
|
|
253
|
-
}
|
|
254
|
-
return stringValue;
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Parse $or conditions
|
|
258
|
-
*/
|
|
259
|
-
_parseOr(query) {
|
|
260
|
-
const orArray = [];
|
|
261
|
-
const raw = query?.or || query?.OR || query?.$or;
|
|
262
|
-
if (!raw) return void 0;
|
|
263
|
-
const items = Array.isArray(raw) ? raw : typeof raw === "object" ? Object.values(raw) : [];
|
|
264
|
-
for (const item of items) {
|
|
265
|
-
if (typeof item === "object" && item) {
|
|
266
|
-
orArray.push(this._parseFilters(item));
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
return orArray.length ? orArray : void 0;
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Enhance filters with between operator
|
|
273
|
-
*/
|
|
274
|
-
_enhanceWithBetween(filters) {
|
|
275
|
-
const output = { ...filters };
|
|
276
|
-
for (const [key, value] of Object.entries(filters || {})) {
|
|
277
|
-
if (value && typeof value === "object" && "between" in value) {
|
|
278
|
-
const between = value.between;
|
|
279
|
-
const [from, to] = String(between).split(",").map((s) => s.trim());
|
|
280
|
-
const fromDate = from ? new Date(from) : void 0;
|
|
281
|
-
const toDate = to ? new Date(to) : void 0;
|
|
282
|
-
const range = {};
|
|
283
|
-
if (fromDate && !isNaN(fromDate.getTime())) range.$gte = fromDate;
|
|
284
|
-
if (toDate && !isNaN(toDate.getTime())) range.$lte = toDate;
|
|
285
|
-
output[key] = range;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return output;
|
|
289
|
-
}
|
|
290
|
-
};
|
|
291
|
-
var queryParser_default = new QueryParser();
|
|
292
|
-
function isMongooseSchema(value) {
|
|
293
|
-
return value instanceof mongoose2__default.default.Schema;
|
|
294
|
-
}
|
|
295
|
-
function isPlainObject(value) {
|
|
296
|
-
return Object.prototype.toString.call(value) === "[object Object]";
|
|
297
|
-
}
|
|
298
|
-
function isObjectIdType(t) {
|
|
299
|
-
return t === mongoose2__default.default.Schema.Types.ObjectId || t === mongoose2__default.default.Types.ObjectId;
|
|
300
|
-
}
|
|
301
|
-
function buildCrudSchemasFromMongooseSchema(mongooseSchema, options = {}) {
|
|
302
|
-
const tree = mongooseSchema?.obj || {};
|
|
303
|
-
const jsonCreate = buildJsonSchemaForCreate(tree, options);
|
|
304
|
-
const jsonUpdate = buildJsonSchemaForUpdate(jsonCreate, options);
|
|
305
|
-
const jsonParams = {
|
|
306
|
-
type: "object",
|
|
307
|
-
properties: { id: { type: "string", pattern: "^[0-9a-fA-F]{24}$" } },
|
|
308
|
-
required: ["id"]
|
|
309
|
-
};
|
|
310
|
-
const jsonQuery = buildJsonSchemaForQuery(tree, options);
|
|
311
|
-
const crudSchemas = {
|
|
312
|
-
create: { body: jsonCreate },
|
|
313
|
-
update: { body: jsonUpdate, params: jsonParams },
|
|
314
|
-
get: { params: jsonParams },
|
|
315
|
-
list: { query: jsonQuery },
|
|
316
|
-
remove: { params: jsonParams }
|
|
317
|
-
};
|
|
318
|
-
return { createBody: jsonCreate, updateBody: jsonUpdate, params: jsonParams, listQuery: jsonQuery, crudSchemas };
|
|
319
|
-
}
|
|
320
|
-
function buildCrudSchemasFromModel(mongooseModel, options = {}) {
|
|
321
|
-
if (!mongooseModel || !mongooseModel.schema) {
|
|
322
|
-
throw new Error("Invalid mongoose model");
|
|
323
|
-
}
|
|
324
|
-
return buildCrudSchemasFromMongooseSchema(mongooseModel.schema, options);
|
|
325
|
-
}
|
|
326
|
-
function getImmutableFields(options = {}) {
|
|
327
|
-
const immutable = [];
|
|
328
|
-
const fieldRules = options?.fieldRules || {};
|
|
329
|
-
Object.entries(fieldRules).forEach(([field, rules]) => {
|
|
330
|
-
if (rules.immutable || rules.immutableAfterCreate) {
|
|
331
|
-
immutable.push(field);
|
|
332
|
-
}
|
|
333
|
-
});
|
|
334
|
-
(options?.update?.omitFields || []).forEach((f) => {
|
|
335
|
-
if (!immutable.includes(f)) immutable.push(f);
|
|
336
|
-
});
|
|
337
|
-
return immutable;
|
|
338
|
-
}
|
|
339
|
-
function getSystemManagedFields(options = {}) {
|
|
340
|
-
const systemManaged = [];
|
|
341
|
-
const fieldRules = options?.fieldRules || {};
|
|
342
|
-
Object.entries(fieldRules).forEach(([field, rules]) => {
|
|
343
|
-
if (rules.systemManaged) {
|
|
344
|
-
systemManaged.push(field);
|
|
345
|
-
}
|
|
346
|
-
});
|
|
347
|
-
return systemManaged;
|
|
348
|
-
}
|
|
349
|
-
function isFieldUpdateAllowed(fieldName, options = {}) {
|
|
350
|
-
const immutableFields = getImmutableFields(options);
|
|
351
|
-
const systemManagedFields = getSystemManagedFields(options);
|
|
352
|
-
return !immutableFields.includes(fieldName) && !systemManagedFields.includes(fieldName);
|
|
353
|
-
}
|
|
354
|
-
function validateUpdateBody(body = {}, options = {}) {
|
|
355
|
-
const violations = [];
|
|
356
|
-
const immutableFields = getImmutableFields(options);
|
|
357
|
-
const systemManagedFields = getSystemManagedFields(options);
|
|
358
|
-
Object.keys(body).forEach((field) => {
|
|
359
|
-
if (immutableFields.includes(field)) {
|
|
360
|
-
violations.push({ field, reason: "Field is immutable" });
|
|
361
|
-
} else if (systemManagedFields.includes(field)) {
|
|
362
|
-
violations.push({ field, reason: "Field is system-managed" });
|
|
363
|
-
}
|
|
364
|
-
});
|
|
365
|
-
return {
|
|
366
|
-
valid: violations.length === 0,
|
|
367
|
-
violations
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
function jsonTypeFor(def, options, seen) {
|
|
371
|
-
if (Array.isArray(def)) {
|
|
372
|
-
if (def[0] === mongoose2__default.default.Schema.Types.Mixed) {
|
|
373
|
-
return { type: "array", items: { type: "object", additionalProperties: true } };
|
|
374
|
-
}
|
|
375
|
-
return { type: "array", items: jsonTypeFor(def[0] ?? String, options, seen) };
|
|
376
|
-
}
|
|
377
|
-
if (isPlainObject(def) && "type" in def) {
|
|
378
|
-
const typedDef = def;
|
|
379
|
-
if (typedDef.enum && Array.isArray(typedDef.enum) && typedDef.enum.length) {
|
|
380
|
-
return { type: "string", enum: typedDef.enum.map(String) };
|
|
381
|
-
}
|
|
382
|
-
if (Array.isArray(typedDef.type)) {
|
|
383
|
-
const inner = typedDef.type[0] !== void 0 ? typedDef.type[0] : String;
|
|
384
|
-
if (inner === mongoose2__default.default.Schema.Types.Mixed) {
|
|
385
|
-
return { type: "array", items: { type: "object", additionalProperties: true } };
|
|
386
|
-
}
|
|
387
|
-
return { type: "array", items: jsonTypeFor(inner, options, seen) };
|
|
388
|
-
}
|
|
389
|
-
if (typedDef.type === String) return { type: "string" };
|
|
390
|
-
if (typedDef.type === Number) return { type: "number" };
|
|
391
|
-
if (typedDef.type === Boolean) return { type: "boolean" };
|
|
392
|
-
if (typedDef.type === Date) {
|
|
393
|
-
const mode = options?.dateAs || "datetime";
|
|
394
|
-
return mode === "date" ? { type: "string", format: "date" } : { type: "string", format: "date-time" };
|
|
395
|
-
}
|
|
396
|
-
if (typedDef.type === Map || typedDef.type === mongoose2__default.default.Schema.Types.Map) {
|
|
397
|
-
const ofSchema = jsonTypeFor(typedDef.of || String, options, seen);
|
|
398
|
-
return { type: "object", additionalProperties: ofSchema };
|
|
399
|
-
}
|
|
400
|
-
if (typedDef.type === mongoose2__default.default.Schema.Types.Mixed) {
|
|
401
|
-
return { type: "object", additionalProperties: true };
|
|
402
|
-
}
|
|
403
|
-
if (isObjectIdType(typedDef.type)) {
|
|
404
|
-
return { type: "string", pattern: "^[0-9a-fA-F]{24}$" };
|
|
405
|
-
}
|
|
406
|
-
if (isMongooseSchema(typedDef.type)) {
|
|
407
|
-
const obj = typedDef.type.obj;
|
|
408
|
-
if (obj && typeof obj === "object") {
|
|
409
|
-
if (seen.has(obj)) return { type: "object", additionalProperties: true };
|
|
410
|
-
seen.add(obj);
|
|
411
|
-
return convertTreeToJsonSchema(obj, options, seen);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
if (def === String) return { type: "string" };
|
|
416
|
-
if (def === Number) return { type: "number" };
|
|
417
|
-
if (def === Boolean) return { type: "boolean" };
|
|
418
|
-
if (def === Date) {
|
|
419
|
-
const mode = options?.dateAs || "datetime";
|
|
420
|
-
return mode === "date" ? { type: "string", format: "date" } : { type: "string", format: "date-time" };
|
|
421
|
-
}
|
|
422
|
-
if (isObjectIdType(def)) return { type: "string", pattern: "^[0-9a-fA-F]{24}$" };
|
|
423
|
-
if (isPlainObject(def)) {
|
|
424
|
-
if (seen.has(def)) return { type: "object", additionalProperties: true };
|
|
425
|
-
seen.add(def);
|
|
426
|
-
return convertTreeToJsonSchema(def, options, seen);
|
|
427
|
-
}
|
|
428
|
-
return {};
|
|
429
|
-
}
|
|
430
|
-
function convertTreeToJsonSchema(tree, options, seen = /* @__PURE__ */ new WeakSet()) {
|
|
431
|
-
if (!tree || typeof tree !== "object") {
|
|
432
|
-
return { type: "object", properties: {} };
|
|
433
|
-
}
|
|
434
|
-
if (seen.has(tree)) {
|
|
435
|
-
return { type: "object", additionalProperties: true };
|
|
436
|
-
}
|
|
437
|
-
seen.add(tree);
|
|
438
|
-
const properties = {};
|
|
439
|
-
const required = [];
|
|
440
|
-
for (const [key, val] of Object.entries(tree || {})) {
|
|
441
|
-
if (key === "__v" || key === "_id" || key === "id") continue;
|
|
442
|
-
const cfg = isPlainObject(val) && "type" in val ? val : { };
|
|
443
|
-
properties[key] = jsonTypeFor(val, options, seen);
|
|
444
|
-
if (cfg.required === true) required.push(key);
|
|
445
|
-
}
|
|
446
|
-
const schema = { type: "object", properties };
|
|
447
|
-
if (required.length) schema.required = required;
|
|
448
|
-
return schema;
|
|
449
|
-
}
|
|
450
|
-
function buildJsonSchemaForCreate(tree, options) {
|
|
451
|
-
const base = convertTreeToJsonSchema(tree, options, /* @__PURE__ */ new WeakSet());
|
|
452
|
-
const fieldsToOmit = /* @__PURE__ */ new Set(["createdAt", "updatedAt", "__v"]);
|
|
453
|
-
(options?.create?.omitFields || []).forEach((f) => fieldsToOmit.add(f));
|
|
454
|
-
const fieldRules = options?.fieldRules || {};
|
|
455
|
-
Object.entries(fieldRules).forEach(([field, rules]) => {
|
|
456
|
-
if (rules.systemManaged) {
|
|
457
|
-
fieldsToOmit.add(field);
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
fieldsToOmit.forEach((field) => {
|
|
461
|
-
if (base.properties?.[field]) {
|
|
462
|
-
delete base.properties[field];
|
|
463
|
-
}
|
|
464
|
-
if (base.required) {
|
|
465
|
-
base.required = base.required.filter((k) => k !== field);
|
|
466
|
-
}
|
|
467
|
-
});
|
|
468
|
-
const reqOv = options?.create?.requiredOverrides || {};
|
|
469
|
-
const optOv = options?.create?.optionalOverrides || {};
|
|
470
|
-
base.required = base.required || [];
|
|
471
|
-
for (const [k, v] of Object.entries(reqOv)) {
|
|
472
|
-
if (v && !base.required.includes(k)) base.required.push(k);
|
|
473
|
-
}
|
|
474
|
-
for (const [k, v] of Object.entries(optOv)) {
|
|
475
|
-
if (v && base.required) base.required = base.required.filter((x) => x !== k);
|
|
476
|
-
}
|
|
477
|
-
Object.entries(fieldRules).forEach(([field, rules]) => {
|
|
478
|
-
if (rules.optional && base.required) {
|
|
479
|
-
base.required = base.required.filter((x) => x !== field);
|
|
480
|
-
}
|
|
481
|
-
});
|
|
482
|
-
const schemaOverrides = options?.create?.schemaOverrides || {};
|
|
483
|
-
for (const [k, override] of Object.entries(schemaOverrides)) {
|
|
484
|
-
if (base.properties?.[k]) {
|
|
485
|
-
base.properties[k] = override;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
if (options?.strictAdditionalProperties === true) {
|
|
489
|
-
base.additionalProperties = false;
|
|
490
|
-
}
|
|
491
|
-
return base;
|
|
492
|
-
}
|
|
493
|
-
function buildJsonSchemaForUpdate(createJson, options) {
|
|
494
|
-
const clone = JSON.parse(JSON.stringify(createJson));
|
|
495
|
-
delete clone.required;
|
|
496
|
-
const fieldsToOmit = /* @__PURE__ */ new Set();
|
|
497
|
-
(options?.update?.omitFields || []).forEach((f) => fieldsToOmit.add(f));
|
|
498
|
-
const fieldRules = options?.fieldRules || {};
|
|
499
|
-
Object.entries(fieldRules).forEach(([field, rules]) => {
|
|
500
|
-
if (rules.immutable || rules.immutableAfterCreate) {
|
|
501
|
-
fieldsToOmit.add(field);
|
|
502
|
-
}
|
|
503
|
-
});
|
|
504
|
-
fieldsToOmit.forEach((field) => {
|
|
505
|
-
if (clone.properties?.[field]) {
|
|
506
|
-
delete clone.properties[field];
|
|
507
|
-
}
|
|
508
|
-
});
|
|
509
|
-
if (options?.strictAdditionalProperties === true) {
|
|
510
|
-
clone.additionalProperties = false;
|
|
511
|
-
}
|
|
512
|
-
return clone;
|
|
513
|
-
}
|
|
514
|
-
function buildJsonSchemaForQuery(_tree, options) {
|
|
515
|
-
const basePagination = {
|
|
516
|
-
type: "object",
|
|
517
|
-
properties: {
|
|
518
|
-
page: { type: "string" },
|
|
519
|
-
limit: { type: "string" },
|
|
520
|
-
sort: { type: "string" },
|
|
521
|
-
populate: { type: "string" },
|
|
522
|
-
search: { type: "string" },
|
|
523
|
-
select: { type: "string" },
|
|
524
|
-
lean: { type: "string" },
|
|
525
|
-
includeDeleted: { type: "string" }
|
|
526
|
-
},
|
|
527
|
-
additionalProperties: true
|
|
528
|
-
};
|
|
529
|
-
const filterable = options?.query?.filterableFields || {};
|
|
530
|
-
for (const [k, v] of Object.entries(filterable)) {
|
|
531
|
-
if (basePagination.properties) {
|
|
532
|
-
basePagination.properties[k] = v && typeof v === "object" && "type" in v ? v : { type: "string" };
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
return basePagination;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
// src/utils/error.ts
|
|
539
|
-
function createError(status, message) {
|
|
540
|
-
const error = new Error(message);
|
|
541
|
-
error.status = status;
|
|
542
|
-
return error;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// src/utils/memory-cache.ts
|
|
546
|
-
function createMemoryCache(maxEntries = 1e3) {
|
|
547
|
-
const cache = /* @__PURE__ */ new Map();
|
|
548
|
-
function cleanup() {
|
|
549
|
-
const now = Date.now();
|
|
550
|
-
for (const [key, entry] of cache) {
|
|
551
|
-
if (entry.expiresAt < now) {
|
|
552
|
-
cache.delete(key);
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
function evictOldest() {
|
|
557
|
-
if (cache.size >= maxEntries) {
|
|
558
|
-
const firstKey = cache.keys().next().value;
|
|
559
|
-
if (firstKey) cache.delete(firstKey);
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
return {
|
|
563
|
-
async get(key) {
|
|
564
|
-
cleanup();
|
|
565
|
-
const entry = cache.get(key);
|
|
566
|
-
if (!entry) return null;
|
|
567
|
-
if (entry.expiresAt < Date.now()) {
|
|
568
|
-
cache.delete(key);
|
|
569
|
-
return null;
|
|
570
|
-
}
|
|
571
|
-
return entry.value;
|
|
572
|
-
},
|
|
573
|
-
async set(key, value, ttl) {
|
|
574
|
-
cleanup();
|
|
575
|
-
evictOldest();
|
|
576
|
-
cache.set(key, {
|
|
577
|
-
value,
|
|
578
|
-
expiresAt: Date.now() + ttl * 1e3
|
|
579
|
-
});
|
|
580
|
-
},
|
|
581
|
-
async del(key) {
|
|
582
|
-
cache.delete(key);
|
|
583
|
-
},
|
|
584
|
-
async clear(pattern) {
|
|
585
|
-
if (!pattern) {
|
|
586
|
-
cache.clear();
|
|
587
|
-
return;
|
|
588
|
-
}
|
|
589
|
-
const regex = new RegExp(
|
|
590
|
-
"^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$"
|
|
591
|
-
);
|
|
592
|
-
for (const key of cache.keys()) {
|
|
593
|
-
if (regex.test(key)) {
|
|
594
|
-
cache.delete(key);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
};
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// src/utils/cache-keys.ts
|
|
602
|
-
function hashString(str) {
|
|
603
|
-
let hash = 5381;
|
|
604
|
-
for (let i = 0; i < str.length; i++) {
|
|
605
|
-
hash = (hash << 5) + hash ^ str.charCodeAt(i);
|
|
606
|
-
}
|
|
607
|
-
return (hash >>> 0).toString(16);
|
|
608
|
-
}
|
|
609
|
-
function stableStringify(obj) {
|
|
610
|
-
if (obj === null || obj === void 0) return "";
|
|
611
|
-
if (typeof obj !== "object") return String(obj);
|
|
612
|
-
if (Array.isArray(obj)) {
|
|
613
|
-
return "[" + obj.map(stableStringify).join(",") + "]";
|
|
614
|
-
}
|
|
615
|
-
const sorted = Object.keys(obj).sort().map((key) => `${key}:${stableStringify(obj[key])}`);
|
|
616
|
-
return "{" + sorted.join(",") + "}";
|
|
617
|
-
}
|
|
618
|
-
function byIdKey(prefix, model, id) {
|
|
619
|
-
return `${prefix}:id:${model}:${id}`;
|
|
620
|
-
}
|
|
621
|
-
function byQueryKey(prefix, model, query, options) {
|
|
622
|
-
const hashInput = stableStringify({ q: query, s: options?.select, p: options?.populate });
|
|
623
|
-
return `${prefix}:one:${model}:${hashString(hashInput)}`;
|
|
624
|
-
}
|
|
625
|
-
function listQueryKey(prefix, model, version, params) {
|
|
626
|
-
const hashInput = stableStringify({
|
|
627
|
-
f: params.filters,
|
|
628
|
-
s: params.sort,
|
|
629
|
-
pg: params.page,
|
|
630
|
-
lm: params.limit,
|
|
631
|
-
af: params.after,
|
|
632
|
-
sl: params.select,
|
|
633
|
-
pp: params.populate
|
|
634
|
-
});
|
|
635
|
-
return `${prefix}:list:${model}:${version}:${hashString(hashInput)}`;
|
|
636
|
-
}
|
|
637
|
-
function versionKey(prefix, model) {
|
|
638
|
-
return `${prefix}:ver:${model}`;
|
|
639
|
-
}
|
|
640
|
-
function modelPattern(prefix, model) {
|
|
641
|
-
return `${prefix}:*:${model}:*`;
|
|
642
|
-
}
|
|
643
|
-
function listPattern(prefix, model) {
|
|
644
|
-
return `${prefix}:list:${model}:*`;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
exports.buildCrudSchemasFromModel = buildCrudSchemasFromModel;
|
|
648
|
-
exports.buildCrudSchemasFromMongooseSchema = buildCrudSchemasFromMongooseSchema;
|
|
649
|
-
exports.byIdKey = byIdKey;
|
|
650
|
-
exports.byQueryKey = byQueryKey;
|
|
651
|
-
exports.createError = createError;
|
|
652
|
-
exports.createFieldPreset = createFieldPreset;
|
|
653
|
-
exports.createMemoryCache = createMemoryCache;
|
|
654
|
-
exports.filterResponseData = filterResponseData;
|
|
655
|
-
exports.getFieldsForUser = getFieldsForUser;
|
|
656
|
-
exports.getImmutableFields = getImmutableFields;
|
|
657
|
-
exports.getMongooseProjection = getMongooseProjection;
|
|
658
|
-
exports.getSystemManagedFields = getSystemManagedFields;
|
|
659
|
-
exports.isFieldUpdateAllowed = isFieldUpdateAllowed;
|
|
660
|
-
exports.listPattern = listPattern;
|
|
661
|
-
exports.listQueryKey = listQueryKey;
|
|
662
|
-
exports.modelPattern = modelPattern;
|
|
663
|
-
exports.queryParser = queryParser_default;
|
|
664
|
-
exports.validateUpdateBody = validateUpdateBody;
|
|
665
|
-
exports.versionKey = versionKey;
|
|
666
|
-
//# sourceMappingURL=index.cjs.map
|
|
667
|
-
//# sourceMappingURL=index.cjs.map
|