@querykitjs/mongoose 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,514 +1,2 @@
1
- 'use strict';
2
-
3
- var core = require('@querykitjs/core');
4
- var async_hooks = require('async_hooks');
5
-
6
- // src/registry.ts
7
-
8
- // src/internal/fields.ts
9
- function resolveField(model, key) {
10
- const name = key === "id" ? "_id" : key;
11
- if (name === "_id") return "_id";
12
- return model.schema.path(name) ? name : void 0;
13
- }
14
- function hasPath(model, path) {
15
- return Boolean(model.schema.path(path));
16
- }
17
- function castValue(model, field, value) {
18
- const path = model.schema.path(field);
19
- if (!path) return value;
20
- try {
21
- return path.cast(value);
22
- } catch {
23
- return value;
24
- }
25
- }
26
-
27
- // src/internal/operators.ts
28
- var esc = (s) => String(s ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
- var sqlLikeToRegex = (pattern) => {
30
- let out = "";
31
- for (const ch of String(pattern ?? "")) {
32
- if (ch === "%") out += ".*";
33
- else if (ch === "_") out += ".";
34
- else out += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35
- }
36
- return `^${out}$`;
37
- };
38
- var asTuple = (v) => Array.isArray(v) && v.length === 2 ? [v[0], v[1]] : void 0;
39
- var operators = {
40
- "=": (v) => ({ $eq: v }),
41
- eq: (v) => ({ $eq: v }),
42
- // SQL three-valued logic: inequality/negation excludes NULL (and missing) rows,
43
- // matching drizzle-pg. `$nin: [v, null]` = "not v AND not null".
44
- "!=": (v) => ({ $nin: [v, null] }),
45
- ne: (v) => ({ $nin: [v, null] }),
46
- ">": (v) => ({ $gt: v }),
47
- gt: (v) => ({ $gt: v }),
48
- ">=": (v) => ({ $gte: v }),
49
- gte: (v) => ({ $gte: v }),
50
- "<": (v) => ({ $lt: v }),
51
- lt: (v) => ({ $lt: v }),
52
- "<=": (v) => ({ $lte: v }),
53
- lte: (v) => ({ $lte: v }),
54
- contains: (v) => ({ $regex: esc(v), $options: "i" }),
55
- "%_%": (v) => ({ $regex: esc(v), $options: "i" }),
56
- startsWith: (v) => ({ $regex: `^${esc(v)}`, $options: "i" }),
57
- "%_": (v) => ({ $regex: `^${esc(v)}`, $options: "i" }),
58
- endsWith: (v) => ({ $regex: `${esc(v)}$`, $options: "i" }),
59
- "_%": (v) => ({ $regex: `${esc(v)}$`, $options: "i" }),
60
- like: (v) => ({ $regex: sqlLikeToRegex(v) }),
61
- ilike: (v) => ({ $regex: sqlLikeToRegex(v), $options: "i" }),
62
- // negation also excludes NULL/missing (SQL `NOT LIKE` semantics).
63
- notLike: (v) => ({ $not: { $regex: sqlLikeToRegex(v) }, $ne: null }),
64
- in: (v) => Array.isArray(v) ? { $in: v } : void 0,
65
- notIn: (v) => Array.isArray(v) ? { $nin: [...v, null] } : void 0,
66
- between: (v) => {
67
- const t = asTuple(v);
68
- return t ? { $gte: t[0], $lte: t[1] } : void 0;
69
- },
70
- notBetween: (v) => {
71
- const t = asTuple(v);
72
- return t ? { $not: { $gte: t[0], $lte: t[1] }, $ne: null } : void 0;
73
- },
74
- isNull: () => ({ $eq: null }),
75
- isNotNull: () => ({ $ne: null })
76
- };
77
-
78
- // src/internal/where.ts
79
- var isObject = (n) => typeof n === "object" && n !== null;
80
- var isFieldCondition = (n) => isObject(n) && "key" in n && !("and" in n) && !("or" in n) && !("not" in n);
81
- function combine(kind, parts) {
82
- const valid = parts.filter((p) => p !== void 0);
83
- if (valid.length === 0) return void 0;
84
- if (valid.length === 1) return valid[0];
85
- return { [kind]: valid };
86
- }
87
- function buildCondition(model, cond) {
88
- const operator = cond.operation ?? "=";
89
- const build = operators[operator];
90
- if (!build) throw new Error(`Unsupported filter operator: "${operator}"`);
91
- const field = resolveField(model, cond.key);
92
- if (!field) return void 0;
93
- const fragment = build(cond.value);
94
- if (fragment === void 0) return void 0;
95
- return { [field]: fragment };
96
- }
97
- function buildNode(model, node) {
98
- if (isFieldCondition(node)) return buildCondition(model, node);
99
- if (isObject(node)) {
100
- if ("and" in node)
101
- return combine(
102
- "$and",
103
- node.and.map((n) => buildNode(model, n))
104
- );
105
- if ("or" in node)
106
- return combine(
107
- "$or",
108
- node.or.map((n) => buildNode(model, n))
109
- );
110
- if ("not" in node) {
111
- const notNode = node.not;
112
- const inner = buildNode(model, notNode);
113
- if (!inner) return void 0;
114
- if (isFieldCondition(notNode)) {
115
- const op = notNode.operation ?? "=";
116
- if (op !== "isNull" && op !== "isNotNull") {
117
- const field = resolveField(model, notNode.key);
118
- if (field) return { $and: [{ [field]: { $ne: null } }, { $nor: [inner] }] };
119
- }
120
- }
121
- return { $nor: [inner] };
122
- }
123
- return node;
124
- }
125
- return void 0;
126
- }
127
- function buildWhere(model, filter) {
128
- if (filter === void 0) return void 0;
129
- if (Array.isArray(filter))
130
- return combine(
131
- "$and",
132
- filter.map((c) => buildNode(model, c))
133
- );
134
- return buildNode(model, filter);
135
- }
136
-
137
- // src/internal/order-by.ts
138
- function normalize(sort) {
139
- if (!sort) return [];
140
- return sort.filter((item) => item && item.key).map((item) => ({ key: item.key, direction: item.direction ?? "asc" }));
141
- }
142
- function buildSort(model, sort) {
143
- const spec = {};
144
- for (const item of normalize(sort)) {
145
- const field = resolveField(model, item.key);
146
- if (field) spec[field] = item.direction === "desc" ? -1 : 1;
147
- }
148
- if (Object.keys(spec).length === 0) {
149
- if (hasPath(model, "createdAt")) spec.createdAt = -1;
150
- else spec._id = -1;
151
- }
152
- return spec;
153
- }
154
-
155
- // src/internal/cursor.ts
156
- function encodeCursor(value) {
157
- const normalized = value instanceof Date ? value.toISOString() : value;
158
- const json = JSON.stringify({ v: normalized });
159
- return Buffer.from(json, "utf8").toString("base64url");
160
- }
161
- function decodeCursor(cursor) {
162
- if (!cursor) return void 0;
163
- try {
164
- const json = Buffer.from(cursor, "base64url").toString("utf8");
165
- const payload = JSON.parse(json);
166
- return payload.v;
167
- } catch {
168
- return void 0;
169
- }
170
- }
171
-
172
- // src/repository.ts
173
- function buildRepository(runtime, model, config = {}) {
174
- const m = model;
175
- const hasDeletedAt = hasPath(m, "deletedAt");
176
- const timestampsOn = Boolean(m.schema.options?.timestamps);
177
- const stampUpdatedAt = hasPath(m, "updatedAt") && !timestampsOn;
178
- const forUpdate = (patch) => stampUpdatedAt ? { ...patch, updatedAt: /* @__PURE__ */ new Date() } : patch;
179
- const scopeConditions = config.scope ? Object.entries(config.scope).map(([key, value]) => ({ key, operation: "=", value })) : [];
180
- const scopeWhere = scopeConditions.length ? buildWhere(m, scopeConditions) : void 0;
181
- const sortSpec = (sort) => buildSort(m, sort);
182
- const composeWhere = (userFilter, withDeleted) => {
183
- const parts = [buildWhere(m, userFilter), scopeWhere, hasDeletedAt && !withDeleted ? { deletedAt: { $eq: null } } : void 0].filter(
184
- (p) => p !== void 0
185
- );
186
- if (parts.length === 0) return {};
187
- if (parts.length === 1) return parts[0];
188
- return { $and: parts };
189
- };
190
- const withId = (filter, idKey, id) => {
191
- const idCondition = { key: idKey, operation: "=", value: id };
192
- if (!filter) return [idCondition];
193
- if (Array.isArray(filter)) return [...filter, idCondition];
194
- return { and: [filter, idCondition] };
195
- };
196
- const projection = (columns) => {
197
- if (!columns) return void 0;
198
- const keys = Object.keys(columns).filter((k) => columns[k]);
199
- if (keys.length === 0) return void 0;
200
- const proj = {};
201
- let includesId = false;
202
- for (const k of keys) {
203
- const field = resolveField(m, k);
204
- if (!field) continue;
205
- proj[field] = 1;
206
- if (field === "_id") includesId = true;
207
- }
208
- if (Object.keys(proj).length === 0) return void 0;
209
- if (!includesId) proj._id = 0;
210
- return proj;
211
- };
212
- const applyPopulate = (q, withRel) => {
213
- if (withRel) {
214
- for (const key of Object.keys(withRel)) {
215
- const value = withRel[key];
216
- if (!value) continue;
217
- q.populate(typeof value === "object" ? { path: key, ...value } : key);
218
- }
219
- }
220
- return q;
221
- };
222
- const attachSession = (q) => {
223
- const s = runtime.getSession();
224
- if (s) q.session(s);
225
- return q;
226
- };
227
- const toArr = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
228
- const forInsert = (values) => ({
229
- ...config.scope,
230
- ...values,
231
- ...config.scope
232
- });
233
- const buildUpsert = (values, options) => {
234
- const targetKeys = toArr(options.target);
235
- const inserted = forInsert(values);
236
- const filter = {};
237
- for (const key of targetKeys) {
238
- const field = resolveField(m, key);
239
- if (!field) throw new Error(`upsert: unknown target field "${key}".`);
240
- filter[field] = inserted[key];
241
- }
242
- const set = options.set ? { ...options.set } : Object.fromEntries(Object.entries(inserted).filter(([k]) => !targetKeys.includes(k)));
243
- const setOnInsert = Object.fromEntries(Object.entries(inserted).filter(([k]) => !targetKeys.includes(k) && !(k in set)));
244
- const update = {};
245
- if (Object.keys(set).length) update.$set = set;
246
- if (Object.keys(setOnInsert).length) update.$setOnInsert = setOnInsert;
247
- return { filter, update };
248
- };
249
- const runFind = (where, opts) => {
250
- let q = m.find(where, projection(opts.columns));
251
- if (opts.sort) q = q.sort(opts.sort);
252
- if (typeof opts.skip === "number") q = q.skip(opts.skip);
253
- if (typeof opts.limit === "number") q = q.limit(opts.limit);
254
- q = applyPopulate(q, opts.with);
255
- return attachSession(q).lean().exec();
256
- };
257
- const countWhere = (where) => attachSession(m.countDocuments(where)).exec();
258
- const repository = {
259
- model,
260
- async findAll(params = {}) {
261
- const rows = await runFind(composeWhere(params.filter, params.withDeleted), {
262
- sort: sortSpec(params.sort),
263
- columns: params.columns,
264
- with: params.with
265
- });
266
- return rows;
267
- },
268
- async findOne(params = {}) {
269
- let q = m.findOne(composeWhere(params.filter, params.withDeleted), projection(params.columns));
270
- q = q.sort(sortSpec(params.sort));
271
- q = applyPopulate(q, params.with);
272
- const row = await attachSession(q).lean().exec();
273
- return row ?? void 0;
274
- },
275
- async findById(id, params = {}) {
276
- const { idKey = "id", filter, columns, with: withRel } = params;
277
- let q = m.findOne(composeWhere(withId(filter, idKey, id), params.withDeleted), projection(columns));
278
- q = applyPopulate(q, withRel);
279
- const row = await attachSession(q).lean().exec();
280
- return row ?? void 0;
281
- },
282
- async findList(params = {}) {
283
- const page = Math.max(1, Math.trunc(params.page ?? 1));
284
- const perPage = Math.max(1, Math.trunc(params.perPage ?? runtime.defaultPerPage));
285
- const where = composeWhere(params.filter, params.withDeleted);
286
- const [data, total_items] = await Promise.all([
287
- runFind(where, { sort: sortSpec(params.sort), columns: params.columns, with: params.with, limit: perPage, skip: (page - 1) * perPage }),
288
- countWhere(where)
289
- ]);
290
- const total_pages = Math.ceil(total_items / perPage);
291
- return {
292
- data,
293
- meta: {
294
- total_items,
295
- total_pages,
296
- current_page: page,
297
- per_page: perPage,
298
- has_next: page < total_pages,
299
- has_prev: page > 1
300
- }
301
- };
302
- },
303
- async findInfinite(params = {}) {
304
- const limit = Math.max(1, Math.trunc(params.limit ?? runtime.defaultLimit));
305
- const offset = Math.max(0, Math.trunc(params.offset ?? 0));
306
- const rows = await runFind(composeWhere(params.filter, params.withDeleted), {
307
- sort: sortSpec(params.sort),
308
- columns: params.columns,
309
- with: params.with,
310
- limit: limit + 1,
311
- skip: offset
312
- });
313
- const has_more = rows.length > limit;
314
- const data = has_more ? rows.slice(0, limit) : rows;
315
- return {
316
- data,
317
- meta: { limit, offset, count: data.length, has_more, next_offset: has_more ? offset + limit : null }
318
- };
319
- },
320
- async findCursor(params = {}) {
321
- const limit = Math.max(1, Math.trunc(params.limit ?? runtime.defaultLimit));
322
- const cursorKey = params.cursorKey ?? "id";
323
- const order = params.order ?? "asc";
324
- const direction = params.direction ?? "forward";
325
- const field = resolveField(m, cursorKey);
326
- if (!field) throw new Error(`findCursor: unknown cursorKey "${cursorKey}".`);
327
- const decoded = decodeCursor(params.cursor);
328
- const cursorValue = decoded !== void 0 ? castValue(m, field, decoded) : void 0;
329
- const baseWhere = composeWhere(params.filter, params.withDeleted);
330
- const ascInQuery = direction === "forward" ? order === "asc" : order === "desc";
331
- const seek = cursorValue !== void 0 ? { [field]: ascInQuery ? { $gt: cursorValue } : { $lt: cursorValue } } : void 0;
332
- const where = seek ? Object.keys(baseWhere).length ? { $and: [baseWhere, seek] } : seek : baseWhere;
333
- const selected = projection(params.columns);
334
- const proj = selected ? { ...selected, [field]: 1 } : void 0;
335
- let q = m.find(where, proj).sort({ [field]: ascInQuery ? 1 : -1 }).limit(limit + 1);
336
- q = applyPopulate(q, params.with);
337
- const rows = await attachSession(q).lean().exec();
338
- const hasExtra = rows.length > limit;
339
- let pageRows = hasExtra ? rows.slice(0, limit) : rows;
340
- if (direction === "backward") pageRows = [...pageRows].reverse();
341
- const first = pageRows[0];
342
- const last = pageRows[pageRows.length - 1];
343
- const has_next = direction === "forward" ? hasExtra : cursorValue !== void 0;
344
- const has_prev = direction === "forward" ? cursorValue !== void 0 : hasExtra;
345
- return {
346
- data: pageRows,
347
- meta: {
348
- limit,
349
- has_next,
350
- has_prev,
351
- next_cursor: has_next && last ? encodeCursor(last[field]) : null,
352
- prev_cursor: has_prev && first ? encodeCursor(first[field]) : null
353
- }
354
- };
355
- },
356
- count(filter) {
357
- return countWhere(composeWhere(filter));
358
- },
359
- async exists(filter) {
360
- return await countWhere(composeWhere(filter)) > 0;
361
- },
362
- /* ------------------------------- writes ------------------------------- */
363
- async create(values) {
364
- const [doc] = await m.create([forInsert(values)], { session: runtime.getSession() });
365
- return doc.toObject();
366
- },
367
- async createMany(values) {
368
- if (values.length === 0) return [];
369
- const docs = await m.insertMany(values.map(forInsert), { session: runtime.getSession() });
370
- return docs.map((d) => d.toObject());
371
- },
372
- async upsert(values, options) {
373
- const { filter, update } = buildUpsert(values, options);
374
- const q = m.findOneAndUpdate(filter, update, { returnDocument: "after", upsert: true });
375
- return await attachSession(q).lean().exec();
376
- },
377
- async upsertMany(values, options) {
378
- if (values.length === 0) return [];
379
- const CHUNK = 1e3;
380
- const entries = values.map((v) => buildUpsert(v, options));
381
- for (let i = 0; i < entries.length; i += CHUNK) {
382
- const ops = entries.slice(i, i + CHUNK).map((e) => ({ updateOne: { filter: e.filter, update: e.update, upsert: true } }));
383
- await m.bulkWrite(ops, { session: runtime.getSession() });
384
- }
385
- const rows = await attachSession(m.find({ $or: entries.map((e) => e.filter) })).lean().exec();
386
- const targetFields = toArr(options.target).map((k) => resolveField(m, k)).filter((f2) => Boolean(f2));
387
- const keyOf = (o) => targetFields.map((f2) => String(o[f2])).join("\0");
388
- const byKey = new Map(rows.map((r) => [keyOf(r), r]));
389
- return entries.map((e) => byKey.get(keyOf(e.filter))).filter((r) => Boolean(r));
390
- },
391
- async updateById(id, patch, idKey = "id") {
392
- const where = composeWhere(withId(void 0, idKey, id));
393
- const q = m.findOneAndUpdate(where, forUpdate(patch), { returnDocument: "after" });
394
- const row = await attachSession(q).lean().exec();
395
- return row ?? void 0;
396
- },
397
- async updateWhere(filter, patch) {
398
- const where = composeWhere(filter);
399
- const found = await attachSession(m.find(where).select({ _id: 1 })).lean().exec();
400
- if (found.length === 0) return [];
401
- const ids = found.map((d) => d._id);
402
- await attachSession(m.updateMany({ _id: { $in: ids } }, forUpdate(patch))).exec();
403
- return await attachSession(m.find({ _id: { $in: ids } })).lean().exec();
404
- },
405
- async deleteById(id, idKey = "id") {
406
- const where = composeWhere(withId(void 0, idKey, id));
407
- const row = await attachSession(m.findOneAndDelete(where)).lean().exec();
408
- return row ?? void 0;
409
- },
410
- async deleteWhere(filter) {
411
- const where = composeWhere(filter);
412
- const rows = await attachSession(m.find(where)).lean().exec();
413
- if (rows.length === 0) return [];
414
- await attachSession(m.deleteMany({ _id: { $in: rows.map((d) => d._id) } })).exec();
415
- return rows;
416
- },
417
- async softDelete(id, idKey = "id") {
418
- if (!hasDeletedAt) throw new Error("softDelete: schema has no deletedAt path.");
419
- const where = composeWhere(withId(void 0, idKey, id), false);
420
- const q = m.findOneAndUpdate(where, forUpdate({ deletedAt: /* @__PURE__ */ new Date() }), { returnDocument: "after" });
421
- const row = await attachSession(q).lean().exec();
422
- return row ?? void 0;
423
- },
424
- async restore(id, idKey = "id") {
425
- if (!hasDeletedAt) throw new Error("restore: schema has no deletedAt path.");
426
- const where = composeWhere(withId(void 0, idKey, id), true);
427
- const q = m.findOneAndUpdate(where, forUpdate({ deletedAt: null }), { returnDocument: "after" });
428
- const row = await attachSession(q).lean().exec();
429
- return row ?? void 0;
430
- },
431
- async aggregate(spec) {
432
- const groupKeys = toArr(spec.groupBy);
433
- const rawMatch = composeWhere(spec.filter, spec.withDeleted);
434
- let match = rawMatch;
435
- try {
436
- const q = m.find(rawMatch);
437
- q.cast(m);
438
- match = q.getFilter();
439
- } catch {
440
- }
441
- const groupId = groupKeys.length ? Object.fromEntries(groupKeys.map((k) => [k, `$${resolveField(m, k) ?? k}`])) : null;
442
- const group = { _id: groupId };
443
- if (spec.count) group.count = { $sum: 1 };
444
- const addAgg = (op, keys, prefix) => {
445
- for (const k of keys) {
446
- const field = resolveField(m, k);
447
- if (field) group[`${prefix}_${k}`] = { [op]: `$${field}` };
448
- }
449
- };
450
- addAgg("$sum", toArr(spec.sum), "sum");
451
- addAgg("$avg", toArr(spec.avg), "avg");
452
- addAgg("$min", toArr(spec.min), "min");
453
- addAgg("$max", toArr(spec.max), "max");
454
- let agg = m.aggregate([{ $match: match }, { $group: group }]);
455
- const session = runtime.getSession();
456
- if (session) agg = agg.session(session);
457
- const rows = await agg.exec();
458
- return rows.map(({ _id, ...rest }) => ({ ...typeof _id === "object" && _id ? _id : {}, ...rest }));
459
- },
460
- scoped(scope) {
461
- return buildRepository(runtime, model, { ...config, scope: { ...config.scope, ...scope } });
462
- }
463
- };
464
- return repository;
465
- }
466
- function createContextStore() {
467
- const als = new async_hooks.AsyncLocalStorage();
468
- return {
469
- get: () => als.getStore(),
470
- run: (patch, fn) => als.run({ ...als.getStore(), ...patch }, fn)
471
- };
472
- }
473
-
474
- // src/registry.ts
475
- function createRegistry(connection, options = {}) {
476
- const ctx = createContextStore();
477
- const runtime = {
478
- getSession: () => ctx.get()?.session,
479
- defaultPerPage: options.defaultPerPage ?? core.DEFAULT_PER_PAGE,
480
- defaultLimit: options.defaultLimit ?? core.DEFAULT_LIMIT
481
- };
482
- function repository(model, arg2, arg3) {
483
- const extend = typeof arg2 === "function" ? arg2 : arg3;
484
- const base = buildRepository(runtime, model);
485
- return extend ? { ...base, ...extend(base) } : base;
486
- }
487
- const transaction = async (fn) => {
488
- if (ctx.get()?.session) return fn();
489
- const session = await connection.startSession();
490
- try {
491
- let result;
492
- await session.withTransaction(async () => {
493
- result = await ctx.run({ session }, fn);
494
- });
495
- return result;
496
- } finally {
497
- await session.endSession();
498
- }
499
- };
500
- return { repository, transaction };
501
- }
502
- function createFilters() {
503
- return core.createFilters();
504
- }
505
-
506
- Object.defineProperty(exports, "f", {
507
- enumerable: true,
508
- get: function () { return core.f; }
509
- });
510
- exports.buildRepository = buildRepository;
511
- exports.createFilters = createFilters;
512
- exports.createRegistry = createRegistry;
513
- //# sourceMappingURL=index.cjs.map
1
+ 'use strict';var core=require('@querykitjs/core'),internal=require('@querykitjs/core/internal');function F(e,t){let o=t==="id"?"_id":t;return o==="_id"?"_id":e.schema.path(o)?o:void 0}function E(e,t){return !!e.schema.path(t)}function G(e,t,o,n=E(e,"createdAt")?"createdAt":void 0){let u={};for(let l of internal.normalizeSort(t,o)){let y=F(e,l.key);y?u[y]=l.direction==="desc"?-1:1:internal.reportSkip(o,{site:"sort",key:l.key,reason:"unknown-key"});}return Object.keys(u).length===0&&(n?u[n]=-1:u._id=-1),u}var H=new Set(core.TEXT_FILTER_OPERATORS),P=Symbol("querykit.invalid-value"),Y=e=>H.has(e);function J(e,t){return e.schema.path(t)?.instance==="Date"}function j(e,t,o){let n=e.schema.path(t);if(!n||o===null||o===void 0||!ke.has(n.instance))return o;if(o instanceof Date)return Number.isNaN(o.getTime())?P:o;try{let u=n.cast(o);if(u instanceof Date)return Number.isNaN(u.getTime())?P:u;if(u==null)return P;let l=n.enumValues;return n.instance==="String"&&l&&l.length>0&&!l.includes(u)?P:u}catch{return P}}var ke=new Set(["Date","Number","Boolean","ObjectId","String","Decimal128"]);function Z(e,t,o,n){if(n===void 0||H.has(o))return n;if(Array.isArray(n)){let l=[];for(let y of n){let d=j(e,t,y);if(d===P)return P;l.push(d);}return l}let u=j(e,t,n);return u===P?P:u}var Q=e=>String(e??"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=e=>{let t="";for(let o of String(e??""))o==="%"?t.endsWith(".*")||(t+=".*"):o==="_"?t+=".":t+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return `^${t}$`},ee=e=>Array.isArray(e)&&e.length===2?[e[0],e[1]]:void 0,te={"=":e=>({$eq:e}),eq:e=>({$eq:e}),"!=":e=>({$nin:[e,null]}),ne:e=>({$nin:[e,null]}),">":e=>({$gt:e}),gt:e=>({$gt:e}),">=":e=>({$gte:e}),gte:e=>({$gte:e}),"<":e=>({$lt:e}),lt:e=>({$lt:e}),"<=":e=>({$lte:e}),lte:e=>({$lte:e}),contains:e=>({$regex:Q(e),$options:"i"}),"%_%":e=>({$regex:Q(e),$options:"i"}),startsWith:e=>({$regex:`^${Q(e)}`,$options:"i"}),"%_":e=>({$regex:`^${Q(e)}`,$options:"i"}),endsWith:e=>({$regex:`${Q(e)}$`,$options:"i"}),"_%":e=>({$regex:`${Q(e)}$`,$options:"i"}),like:e=>({$regex:v(e)}),ilike:e=>({$regex:v(e),$options:"i"}),notLike:e=>({$not:{$regex:v(e)},$ne:null}),in:e=>Array.isArray(e)?{$in:e}:void 0,notIn:e=>Array.isArray(e)?{$nin:[...e,null]}:void 0,between:e=>{let t=ee(e);return t?{$gte:t[0],$lte:t[1]}:void 0},notBetween:e=>{let t=ee(e);return t?{$not:{$gte:t[0],$lte:t[1]},$ne:null}:void 0},isNull:()=>({$eq:null}),isNotNull:()=>({$ne:null})};var B=e=>typeof e=="object"&&e!==null,ne=e=>B(e)&&"key"in e&&!("and"in e)&&!("or"in e)&&!("not"in e);function _(e,t){let o=t.filter(n=>n!==void 0);if(o.length!==0)return o.length===1?o[0]:{[e]:o}}function oe(e,t,o){let n=t.operation??"=",u=te[n];if(!u)throw new Error(`Unsupported filter operator: "${n}"`);let l=F(e,t.key);if(!l){internal.reportSkip(o,{site:"filter",key:t.key,operation:n,reason:"unknown-key"});return}if(Y(n)&&J(e,l)){internal.reportSkip(o,{site:"filter",key:t.key,operation:n,reason:"invalid-value"});return}let y=Z(e,l,n,t.value);if(y===P){internal.reportSkip(o,{site:"filter",key:t.key,operation:n,reason:"invalid-value"});return}let d=u(y);if(d===void 0){internal.reportSkip(o,{site:"filter",key:t.key,operation:n,reason:"invalid-value"});return}return {[l]:d}}function I(e,t,o){if(ne(t))return oe(e,t,o);if(B(t)){if("and"in t)return _("$and",t.and.map(n=>I(e,n,o)));if("or"in t)return _("$or",t.or.map(n=>I(e,n,o)));if("not"in t)return U(e,t.not,o);if(internal.isRaw(t))return t;throw new core.QueryKitError({source:e.modelName,site:"filter",key:Object.keys(t)[0]??"",reason:"forbidden-key"})}}function U(e,t,o){if(ne(t)){let u=oe(e,t,o);if(!u)return;let l=t.operation??"=",y=l==="isNull"||l==="isNotNull"?void 0:F(e,t.key);return y?{$and:[{[y]:{$ne:null}},{$nor:[u]}]}:{$nor:[u]}}if(B(t)){if("and"in t)return _("$or",t.and.map(u=>U(e,u,o)));if("or"in t)return _("$and",t.or.map(u=>U(e,u,o)));if("not"in t)return I(e,t.not,o)}let n=I(e,t,o);return n?{$nor:[n]}:void 0}function N(e,t,o){if(t!==void 0)return Array.isArray(t)?_("$and",t.map(n=>I(e,n,o))):I(e,t,o)}var re=e=>Object.entries(e).filter(([,t])=>t).map(([t])=>t);function ie(e,t){let o=t.forcedColumns?re(t.forcedColumns):void 0;if(t.forcedColumns&&o.length===0)throw new Error("buildRepository: forcedColumns must select at least one field (an empty selection would return the full document).");let n=t.allowedColumns?new Set(t.allowedColumns):void 0;if(t.allowedColumns&&n.size===0)throw new Error("buildRepository: allowedColumns must list at least one field (an empty allowlist would return the full document).");let u=d=>o?o.includes(d):n?n.has(d):true,l=d=>{let R=d.filter(A=>n.has(A));return R.length>0?R:[...n]};return {guarded:!!(o??n),permits:u,projection:d=>{let R=d?re(d):[],A=o??(n?l(R):R);if(A.length===0)return;let a={},T=false;for(let w of A){let b=F(e,w);b&&(a[b]=1,b==="_id"&&(T=true));}if(Object.keys(a).length!==0)return T||(a._id=0),a}}}function ue(e,t,o){let n=t,u=F(n,e.timestamps?.deletedAt??"deletedAt")??"deletedAt",l=E(n,u),y=e.timestamps?.createdAt!==void 0,d=F(n,e.timestamps?.createdAt??"createdAt"),R=!!n.schema.options?.timestamps,A=E(n,"updatedAt")&&!R,a=m=>A?{...m,updatedAt:new Date}:m,T=Qe(n,o),w={source:n.modelName,strict:e.strict,onSkipped:e.onSkippedCondition},b=m=>G(n,m,w,d),r=m=>internal.checkWith(m,o.relations,Ce,w.source),i=(m,x)=>{let D=[m,T,l&&!x?{[u]:{$eq:null}}:void 0].filter(C=>C!==void 0);return D.length===0?{}:D.length===1?D[0]:{$and:D}},s=(m,x)=>i(N(n,m,w),x),c=(m,x,D)=>{let C={key:x,operation:"=",value:D};return m?Array.isArray(m)?[...m,C]:{and:[m,C]}:[C]},g=ie(n,o),p=o.maxTimeMS??e.maxTimeMS,h=m=>{let x=e.getSession();return x&&m.session(x),Ie.has(m.op??"")&&Ee(m,n.modelName,p),m},S=(m,x)=>{let D=n.find(m,g.projection(x.columns));return x.sort&&(D=D.sort(x.sort)),typeof x.skip=="number"&&(D=D.skip(x.skip)),typeof x.limit=="number"&&(D=D.limit(x.limit)),D=ce(D,x.with),h(D).lean().exec()},f=m=>h(n.countDocuments(m)).exec(),k=internal.resolvePolicy({source:n.modelName,fieldOf:m=>F(n,m),primaryKey:"_id",createdAt:y?d:d??F(n,"created_at"),filterable:o.filterable,sortable:o.sortable,allowedColumns:o.allowedColumns,forcedColumns:o.forcedColumns,limits:{...e.limits,...o.limits}});return {...g,policy:k,maxTimeMS:p,runtime:e,m:n,diag:w,hasDeletedAt:l,deletedAtPath:u,forUpdate:a,sortSpec:b,withOf:r,composeWhere:s,mutationWhere:(m,x)=>{if(internal.isAllRows(m))return i(void 0);internal.isEmptyFilter(m)&&internal.refuseEmptyFilter(w.source,x),k.checkFilter(m);let D=N(n,m,w);return D===void 0?internal.refuseEmptyFilter(w.source,x):i(D)},withId:c,applyPopulate:ce,attachSession:h,runFind:S,countWhere:f}}var Ce={columns:"select",nested:"populate",filters:["match"],logical:["$and","$or","$nor"],paging:["limit","skip"],options:"options"};function ce(e,t){if(t)for(let o of Object.keys(t)){let n=t[o];n&&e.populate(typeof n=="object"?{path:o,...n}:o);}return e}var M=e=>e===void 0?[]:Array.isArray(e)?e:[e];function Qe(e,t){let o=internal.scopeConditions(t.scope);for(let n of o)if(!F(e,n.key))throw new core.QueryKitError({source:e.modelName,site:"filter",key:n.key,reason:"unknown-key"});return o.length?N(e,o):void 0}var Ie=new Set(["find","findOne","countDocuments","distinct"]),q=e=>typeof e=="object"&&e!==null&&(e.codeName==="MaxTimeMSExpired"||e.code===50);function Ee(e,t,o){e.maxTimeMS(o);let n=e.exec.bind(e);e.exec=(async(...u)=>{try{return await n(...u)}catch(l){throw q(l)?new core.QueryKitTimeoutError(t,o,{cause:l}):l}});}function ae(e){let{runtime:t,m:o,diag:n,permits:u,policy:l,maxTimeMS:y,composeWhere:d}=e,R=a=>{let T=u(a)?F(o,a):void 0;return T||internal.reportSkip(n,{site:"aggregate",key:a,reason:"unknown-key"}),T},A=a=>{try{let T=o.find(a);return T.cast(o),T.getFilter()}catch{return a}};return {async aggregate(a){l.checkFilter(a.filter);for(let p of [a.groupBy,a.sum,a.avg,a.min,a.max].flatMap(h=>h===void 0?[]:Array.isArray(h)?h:[h]))l.checkAggregateKey(p);let T=M(a.groupBy).filter(p=>!!R(p)),w=A(d(a.filter,a.withDeleted)),r={_id:T.length?Object.fromEntries(T.map(p=>[p,`$${R(p)??p}`])):null};a.count&&(r.count={$sum:1});let i=(p,h,S)=>{for(let f of h){let k=R(f);k&&(r[`${S}_${f}`]={[p]:`$${k}`});}};i("$sum",M(a.sum),"sum"),i("$avg",M(a.avg),"avg"),i("$min",M(a.min),"min"),i("$max",M(a.max),"max");let s=o.aggregate([{$match:w},{$group:r}]),c=t.getSession();c&&(s=s.session(c)),s=s.option({maxTimeMS:y});let g;try{g=await s.exec();}catch(p){throw q(p)?new core.QueryKitTimeoutError(o.modelName,y,{cause:p}):p}return g.map(({_id:p,...h})=>({...typeof p=="object"&&p?p:{},...h}))}}}function le(e){let{runtime:t,m:o,diag:n,guarded:u,permits:l,projection:y,policy:d,withOf:R,composeWhere:A,applyPopulate:a,attachSession:T}=e;return {async findCursor(w={}){let b=internal.clampPageSize(w.limit,t.defaultLimit,t.maxLimit),r=w.cursorKey??"id";d.checkFilter(w.filter),w.cursorKey!==void 0&&d.checkCursorKey(r);let i=w.order??"asc",s=w.direction??"forward",c=F(o,r);if(!c)throw new core.QueryKitError({source:n.source,site:"cursorKey",key:r,reason:"unknown-key"});let g=await internal.decodeCursorToken(w.cursor,{source:n.source,secret:t.cursorSecret,key:r}),p=g===void 0?void 0:j(o,c,g.k),h=g===void 0?void 0:j(o,"_id",g.id);if(p===P||h===P)throw new core.QueryKitError({source:n.source,site:"cursorKey",key:r,reason:"invalid-value"});let S=A(w.filter,w.withDeleted),f=s==="forward"?i==="asc":i==="desc",k=f?"$gt":"$lt",$=c!=="_id",m=g===void 0?void 0:$?{$or:[{[c]:{[k]:p}},{[c]:p,_id:{[k]:h}}]}:{[c]:{[k]:p}},x=m?Object.keys(S).length?{$and:[S,m]}:m:S,D=y(w.columns),C=D?{...D,[c]:1,_id:1}:void 0,z=O=>D!==void 0&&!!D[O],X=D===void 0?[]:[c,"_id"].filter(O=>u&&(!l(O)||!z(O))||O==="_id"&&O!==c&&!z(O)),K=o.find(x,C).sort($?{[c]:f?1:-1,_id:f?1:-1}:{[c]:f?1:-1}).limit(b+1);K=a(K,R(w.with));let we=await T(K).lean().exec(),V=await internal.cursorPage(we,{limit:b,direction:s,hasCursor:g!==void 0,cursorField:c,idField:"_id",secret:t.cursorSecret});return X.length>0&&(V.data=V.data.map(O=>Object.fromEntries(Object.entries(O).filter(([he])=>!X.includes(he))))),V}}}var fe=1e3,Ve="\0";function me(e,t){let{runtime:o,m:n,hasDeletedAt:u,deletedAtPath:l,forUpdate:y,composeWhere:d,mutationWhere:R,withId:A,attachSession:a}=e,T=i=>internal.clampPageSize(i.limit,o.defaultLimit,o.maxLimit),w=i=>({...internal.scopeDefaults(t.scope),...i,...internal.scopeDefaults(t.scope)}),b=(i,s)=>{let c=M(s.target),g=w(i),p={};for(let k of c){let $=F(n,k);if(!$)throw new Error(`upsert: unknown target field "${k}".`);p[$]=g[k];}let h=s.set?{...s.set}:Object.fromEntries(Object.entries(g).filter(([k])=>!c.includes(k))),S=Object.fromEntries(Object.entries(g).filter(([k])=>!c.includes(k)&&!(k in h))),f={};return Object.keys(h).length&&(f.$set=h),Object.keys(S).length&&(f.$setOnInsert=S),{filter:p,update:f}},r=async(i,s)=>{let c=n.findOneAndUpdate(i,s,{returnDocument:"after"});return await a(c).lean().exec()??void 0};return {async create(i){let[s]=await n.create([w(i)],{session:o.getSession()});return s.toObject()},async createMany(i){return i.length===0?[]:(await n.insertMany(i.map(w),{session:o.getSession()})).map(c=>c.toObject())},async upsert(i,s){let{filter:c,update:g}=b(i,s),p=n.findOneAndUpdate(c,g,{returnDocument:"after",upsert:true});return await a(p).lean().exec()},async upsertMany(i,s){if(i.length===0)return [];let c=i.map(f=>b(f,s));for(let f=0;f<c.length;f+=fe){let k=c.slice(f,f+fe).map($=>({updateOne:{filter:$.filter,update:$.update,upsert:true}}));await n.bulkWrite(k,{session:o.getSession()});}let g=await a(n.find({$or:c.map(f=>f.filter)})).lean().exec(),p=M(s.target).map(f=>F(n,f)).filter(f=>!!f),h=f=>p.map(k=>String(f[k])).join(Ve),S=new Map(g.map(f=>[h(f),f]));return c.map(f=>S.get(h(f.filter))).filter(f=>!!f)},updateById(i,s,c="id"){return r(d(A(void 0,c,i)),y(s))},async updateWhere(i,s,c={}){let g=R(i,"updateWhere"),{matchedCount:p}=await a(n.updateMany(g,y(s))).exec();if(!c.returning)return {count:p};let h=await a(n.find(g).limit(T(c.returning))).lean().exec();return {count:p,rows:h}},async deleteById(i,s="id"){let c=d(A(void 0,s,i));return await a(n.findOneAndDelete(c)).lean().exec()??void 0},async deleteWhere(i,s={}){let c=R(i,"deleteWhere"),g=s.returning?await a(n.find(c).limit(T(s.returning))).lean().exec():void 0,{deletedCount:p}=await a(n.deleteMany(c)).exec();return g?{count:p,rows:g}:{count:p}},async softDelete(i,s="id"){if(!u)throw new Error("softDelete: schema has no deletedAt path.");return r(d(A(void 0,s,i),false),y({[l]:new Date}))},async restore(i,s="id"){if(!u)throw new Error("restore: schema has no deletedAt path.");return r(d(A(void 0,s,i),true),y({[l]:null}))}}}function ge(e){let{runtime:t,m:o,policy:n,projection:u,sortSpec:l,withOf:y,composeWhere:d,withId:R,applyPopulate:A,attachSession:a,runFind:T,countWhere:w}=e,b=r=>{n.checkFilter(r.filter),n.checkSort(r.sort);};return {async findAll(r={}){return b(r),await T(d(r.filter,r.withDeleted),{sort:l(r.sort),columns:r.columns,with:y(r.with)})},async findOne(r={}){b(r);let i=o.findOne(d(r.filter,r.withDeleted),u(r.columns));return i=i.sort(l(r.sort)),i=A(i,y(r.with)),await a(i).lean().exec()??void 0},async findById(r,i={}){let{idKey:s="id",filter:c,columns:g,with:p}=i;n.checkFilter(c);let h=o.findOne(d(R(c,s,r),i.withDeleted),u(g));return h=A(h,p),await a(h).lean().exec()??void 0},async findList(r={}){b(r);let i=internal.clampPage(r.page),s=internal.clampPageSize(r.perPage,t.defaultPerPage,t.maxPerPage);n.checkPage({page:i,perPage:s});let c=d(r.filter,r.withDeleted),g=S=>T(c,{sort:l(r.sort),columns:r.columns,with:y(r.with),limit:S,skip:(i-1)*s});if(r.withTotal===false)return internal.offsetPageWithoutTotal(await g(s+1),i,s);let[p,h]=await Promise.all([g(s),w(c)]);return {data:p,meta:internal.offsetMeta(i,s,h)}},async findInfinite(r={}){let i=internal.clampPageSize(r.limit,t.defaultLimit,t.maxLimit),s=internal.clampOffset(r.offset);b(r),n.checkPage({offset:s});let c=await T(d(r.filter,r.withDeleted),{sort:l(r.sort),columns:r.columns,with:y(r.with),limit:i+1,skip:s});return internal.infinitePage(c,i,s)},async count(r){return n.checkFilter(r),w(d(r))},async exists(r){return n.checkFilter(r),await w(d(r))>0}}}function W(e,t,o={}){let n=ue(e,t,o);return {model:t,...ge(n),...le(n),...me(n,o),...ae(n),scoped(l){return W(e,t,{...o,scope:{...o.scope,...l}})}}}var Ze=2e3;function et(e,t={}){let o=internal.createContextStore(),n={getSession:()=>o.get()?.session,defaultPerPage:t.defaultPerPage??core.DEFAULT_PER_PAGE,defaultLimit:t.defaultLimit??core.DEFAULT_LIMIT,maxPerPage:t.maxPerPage??core.DEFAULT_MAX_PER_PAGE,maxLimit:t.maxLimit??core.DEFAULT_MAX_LIMIT,strict:t.strict??false,onSkippedCondition:t.onSkippedCondition,limits:t.limits,cursorSecret:t.cursorSecret,timestamps:t.timestamps,maxTimeMS:t.maxTimeMS??Ze};function u(y,d,R){let A=typeof d=="function"?void 0:d,a=typeof d=="function"?d:R,T=W(n,y,A);return a?{...T,...a(T)}:T}return {repository:u,transaction:async y=>{if(o.get()?.session)return y();let d=await e.startSession();try{let R;return await d.withTransaction(async()=>{R=await o.run({session:d},y);}),R}finally{await d.endSession();}}}}function ot(){return core.createFilters()}Object.defineProperty(exports,"f",{enumerable:true,get:function(){return core.f}});exports.buildRepository=W;exports.createFilters=ot;exports.createRegistry=et;//# sourceMappingURL=index.cjs.map
514
2
  //# sourceMappingURL=index.cjs.map