mongoose-query-find 4.0.1 → 5.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/aggregate.js CHANGED
@@ -45,12 +45,17 @@
45
45
  * run the client-input sanitizer; that only applies to .filter()/.where(),
46
46
  * which parse untrusted req.query / req.body values.
47
47
  *
48
+ * Conditions (URL filter, search, where/range) that reference a joined field
49
+ * (a `.lookup()` `as` alias that is not a real schema path, e.g. "category.name")
50
+ * are automatically placed in a $match *after* the join; everything else stays
51
+ * in the first $match so indexes can be used.
52
+ *
48
53
  * ── Custom ranges ────────────────────────────────────────────────────────────
49
54
  * `.range(field, preset)` covers the fixed RangePreset values (today,
50
55
  * yesterday, last7Days, last30Days, thisWeek, thisMonth). For anything more
51
56
  * specific — a single arbitrary day, an arbitrary date span, a rolling
52
57
  * window of N days/hours, an explicit hour-of-day window, or an explicit
53
- * absolute datetime window — use the new custom range methods below:
58
+ * absolute datetime window — use the custom range methods below:
54
59
  *
55
60
  * .rangeCustomDay(field, '2026-03-14')
56
61
  * .rangeBetween(field, { from: '2026-01-01', to: '2026-01-31' })
@@ -60,7 +65,8 @@
60
65
  * .rangeCustom(field, { from: '2026-03-14T09:00:00', to: '2026-03-15T00:00:00' })
61
66
  *
62
67
  * All of these behave like .range(): they set a hard, server-side condition
63
- * that the client cannot override via query params.
68
+ * that the client cannot override via query params. Multiple server-side
69
+ * conditions on the same field are AND-ed together (never silently overwritten).
64
70
  */
65
71
  Object.defineProperty(exports, "__esModule", { value: true });
66
72
  exports.QueryAggregate = exports.QueryAggregateValidationError = exports.QueryAggregateError = void 0;
@@ -70,27 +76,38 @@ const mongoose_1 = require("mongoose");
70
76
  // ─── Constants ────────────────────────────────────────────────────────────────
71
77
  const RESERVED_KEYS = new Set(['page', 'sort', 'limit', 'fields', 'q']);
72
78
  const DEFAULT_MAX_LIMIT = 100;
79
+ const DEFAULT_LIMIT = 10;
80
+ const MAX_PAGE = 1000000000;
73
81
  const MAX_NESTING_DEPTH = 5;
74
82
  const MAX_SEARCH_LENGTH = 200;
75
83
  const MAX_SORT_FIELDS = 5;
84
+ const MAX_CURSOR_LENGTH = 1024;
76
85
  const DEFAULT_MAX_TIME_MS = 5000;
77
86
  const DEFAULT_TIMEZONE = 'Asia/Dhaka';
78
87
  // Matches only when the date-word is the LAST path segment (e.g. "createdAt",
79
- // "user.updatedAt") — used as a fallback heuristic when .dateFields() isn't
80
- // called explicitly.
88
+ // "user.updatedAt") — used as a fallback heuristic when neither .dateFields()
89
+ // nor the model schema identifies the field type.
81
90
  const DATE_FIELD_RE = /(^|\.)(createdAt|updatedAt|deletedAt|archivedAt|expiresAt|date|birthDate)$/i;
82
91
  const PLAIN_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
83
92
  // A string that already carries its own UTC offset ("Z" or "+06:00") is
84
93
  // treated as an absolute instant rather than a local wall-clock time.
85
94
  const HAS_OFFSET_RE = /([Zz]|[+-]\d{2}:?\d{2})$/;
86
95
  // Matches only when the id-word is the LAST path segment (e.g. "_id",
87
- // "categoryId", "basicInfo.brandId") — used as a fallback heuristic when
88
- // .objectIdFields() isn't called explicitly. Mirrors DATE_FIELD_RE's approach.
96
+ // "categoryId", "basicInfo.brandId") — fallback heuristic when neither
97
+ // .objectIdFields() nor the model schema identifies the field type.
89
98
  const OBJECTID_FIELD_RE = /(^|\.)(_id|[a-zA-Z0-9]*Id)$/;
90
- // A 24-char lowercase/uppercase hex string — the only shape isValidObjectId()
91
- // should be trusted to interpret as "meant to be an ObjectId" rather than a
92
- // 12-byte-length string that happens to also pass Mongoose's looser check.
99
+ // A 24-char hex string — the only shape trusted as "meant to be an ObjectId".
93
100
  const HEX24_RE = /^[a-fA-F0-9]{24}$/;
101
+ // Plain decimal numbers only (no hex, exponent, Infinity, or leading zeros
102
+ // such as phone numbers "0171...").
103
+ const NUMERIC_RE = /^-?(0|[1-9]\d*)(\.\d+)?$/;
104
+ const FIELD_PATH_RE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$/;
105
+ const METRIC_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
106
+ const DANGEROUS_KEYS = new Set([
107
+ '__proto__',
108
+ 'constructor',
109
+ 'prototype',
110
+ ]);
94
111
  const COERCIBLE_OPS = new Set([
95
112
  'eq',
96
113
  'ne',
@@ -101,9 +118,11 @@ const COERCIBLE_OPS = new Set([
101
118
  'in',
102
119
  'nin',
103
120
  ]);
104
- const IN_LIKE_OPS = new Set(['in', '$in', 'nin', '$nin']);
121
+ const IN_LIKE_OPS = new Set(['in', 'nin']);
122
+ const STAT_OPS = new Set(['sum', 'avg', 'min', 'max', 'count']);
105
123
  const DEFAULT_SORT = { createdAt: -1 };
106
- const ALLOWED_TOP_LEVEL_OPS = new Set(['$and', '$or', '$nor', '$not']);
124
+ // NOTE: `$not` is not a valid top-level query operator in MongoDB, so it is not allowed here.
125
+ const ALLOWED_TOP_LEVEL_OPS = new Set(['$and', '$or', '$nor']);
107
126
  // Rejected anywhere inside client-supplied filter/search/populate-match input.
108
127
  const BANNED_OPERATORS = new Set([
109
128
  '$where',
@@ -113,6 +132,9 @@ const BANNED_OPERATORS = new Set([
113
132
  '$map',
114
133
  '$reduce',
115
134
  '$filter',
135
+ // Not valid inside aggregation $match — would fail at runtime.
136
+ '$near',
137
+ '$nearSphere',
116
138
  ]);
117
139
  // Rejected in developer-authored pipeline stages added via addStage()/lookup()
118
140
  // pipelines — these can mutate or drop data and have no place in a query builder.
@@ -132,22 +154,39 @@ class QueryAggregateValidationError extends QueryAggregateError {
132
154
  }
133
155
  }
134
156
  exports.QueryAggregateValidationError = QueryAggregateValidationError;
157
+ const SCHEMA_KIND_MAP = {
158
+ String: 'string',
159
+ Number: 'number',
160
+ Boolean: 'boolean',
161
+ Date: 'date',
162
+ ObjectId: 'objectid',
163
+ ObjectID: 'objectid',
164
+ };
135
165
  // ─── Input parsing ────────────────────────────────────────────────────────────
166
+ function asString(v) {
167
+ return typeof v === 'string' ? v : undefined;
168
+ }
136
169
  function parsePage(raw) {
137
- const n = parseInt(raw ?? '1', 10);
138
- return isNaN(n) || n < 1 ? 1 : n;
170
+ const n = parseInt(asString(raw) ?? '1', 10);
171
+ return !Number.isSafeInteger(n) || n < 1 || n > MAX_PAGE ? 1 : n;
139
172
  }
140
173
  function parseLimit(raw, maxLimit = DEFAULT_MAX_LIMIT) {
141
- const n = parseInt(raw ?? '10', 10);
142
- if (isNaN(n) || n < 1)
143
- return 10;
174
+ const n = parseInt(asString(raw) ?? String(DEFAULT_LIMIT), 10);
175
+ if (!Number.isFinite(n) || n < 1)
176
+ return Math.min(DEFAULT_LIMIT, maxLimit);
144
177
  return Math.min(n, maxLimit);
145
178
  }
179
+ const validTimezones = new Set();
146
180
  function resolveTimezone(tz) {
147
- const candidate = tz && tz.trim() ? tz.trim() : DEFAULT_TIMEZONE;
181
+ const candidate = typeof tz === 'string' && tz.trim() && tz.length <= 64
182
+ ? tz.trim()
183
+ : DEFAULT_TIMEZONE;
184
+ if (validTimezones.has(candidate))
185
+ return candidate;
148
186
  try {
149
187
  // Throws RangeError on an invalid IANA zone — cheapest available validator.
150
- Intl.DateTimeFormat(undefined, { timeZone: candidate });
188
+ new Intl.DateTimeFormat('en-US', { timeZone: candidate });
189
+ validTimezones.add(candidate);
151
190
  return candidate;
152
191
  }
153
192
  catch {
@@ -158,12 +197,22 @@ function resolveTimezone(tz) {
158
197
  }
159
198
  }
160
199
  // ─── Timezone-aware date helpers ───────────────────────────────────────────────
161
- /** Shifts a "YYYY-MM-DD" string by N calendar days (pure date math, DST-safe via a noon-UTC anchor). */
200
+ /** True only for a real calendar date in strict "YYYY-MM-DD" form (rejects "2026-02-31"). */
201
+ function isRealPlainDate(s) {
202
+ if (!PLAIN_DATE_RE.test(s))
203
+ return false;
204
+ const [y, m, d] = s.split('-').map(Number);
205
+ const dt = new Date(Date.UTC(y, m - 1, d));
206
+ return (dt.getUTCFullYear() === y &&
207
+ dt.getUTCMonth() === m - 1 &&
208
+ dt.getUTCDate() === d);
209
+ }
210
+ /** Shifts a "YYYY-MM-DD" string by N calendar days (pure UTC date math — DST-proof). */
162
211
  function shiftLocalDateString(dateStr, days) {
163
212
  const [y, m, d] = dateStr.split('-').map(Number);
164
- const anchor = new Date(Date.UTC(y, m - 1, d, 12, 0, 0));
165
- const shifted = (0, date_fns_1.addDays)(anchor, days);
166
- return shifted.toISOString().slice(0, 10);
213
+ const dt = new Date(Date.UTC(y, m - 1, d));
214
+ dt.setUTCDate(dt.getUTCDate() + days);
215
+ return dt.toISOString().slice(0, 10);
167
216
  }
168
217
  /** [start, end) UTC instants for a single local calendar date in `timezone`. */
169
218
  function plainDateToUtcRange(dateStr, timezone) {
@@ -171,39 +220,40 @@ function plainDateToUtcRange(dateStr, timezone) {
171
220
  const end = (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(dateStr, 1)}T00:00:00.000`, timezone);
172
221
  return { start, end };
173
222
  }
174
- /** Parses a single date/datetime string to a scalar UTC Date (used for $in/$nin, where a range object isn't valid). */
223
+ /** Parses a single date/datetime string to a scalar UTC Date. */
175
224
  function coerceDateScalar(value, timezone) {
176
- const raw = PLAIN_DATE_RE.test(value) ? `${value}T00:00:00.000` : value;
177
- const parsed = HAS_OFFSET_RE.test(value)
178
- ? new Date(value)
179
- : (0, date_fns_tz_1.fromZonedTime)(raw, timezone);
225
+ let parsed;
226
+ if (PLAIN_DATE_RE.test(value)) {
227
+ if (!isRealPlainDate(value))
228
+ return undefined;
229
+ parsed = (0, date_fns_tz_1.fromZonedTime)(`${value}T00:00:00.000`, timezone);
230
+ }
231
+ else if (HAS_OFFSET_RE.test(value)) {
232
+ parsed = new Date(value);
233
+ }
234
+ else {
235
+ parsed = (0, date_fns_tz_1.fromZonedTime)(value, timezone);
236
+ }
180
237
  return isNaN(parsed.getTime()) ? undefined : parsed;
181
238
  }
182
- function isDateField(path, explicit) {
183
- if (!path)
239
+ function explicitHas(path, explicit) {
240
+ if (!explicit || explicit.size === 0 || !path)
184
241
  return false;
185
242
  const lc = path.toLowerCase();
186
- if (explicit && explicit.size > 0) {
187
- if (explicit.has(lc))
188
- return true;
189
- const lastSeg = lc.split('.').pop() ?? lc;
190
- return explicit.has(lastSeg);
191
- }
192
- return DATE_FIELD_RE.test(path);
243
+ if (explicit.has(lc))
244
+ return true;
245
+ const lastSeg = lc.split('.').pop() ?? lc;
246
+ return explicit.has(lastSeg);
193
247
  }
194
- function isObjectIdField(path, explicit) {
195
- if (!path)
248
+ // ─── Sanitization ─────────────────────────────────────────────────────────────
249
+ function isPlainObject(v) {
250
+ if (v === null || typeof v !== 'object' || Array.isArray(v))
196
251
  return false;
197
- const lc = path.toLowerCase();
198
- if (explicit && explicit.size > 0) {
199
- if (explicit.has(lc))
200
- return true;
201
- const lastSeg = lc.split('.').pop() ?? lc;
202
- return explicit.has(lastSeg);
203
- }
204
- return OBJECTID_FIELD_RE.test(path);
252
+ if (v instanceof Date)
253
+ return false;
254
+ const proto = Object.getPrototypeOf(v);
255
+ return proto === Object.prototype || proto === null;
205
256
  }
206
- // ─── Sanitization ─────────────────────────────────────────────────────────────
207
257
  /** Recursively strips non-plain values (class instances, functions) from client input. */
208
258
  function sanitize(value, depth = 0, path = '', onDrop) {
209
259
  if (depth >= MAX_NESTING_DEPTH) {
@@ -230,16 +280,16 @@ function sanitize(value, depth = 0, path = '', onDrop) {
230
280
  }
231
281
  return out;
232
282
  }
233
- if (t === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
283
+ if (isPlainObject(value)) {
234
284
  const src = value;
235
285
  const out = {};
236
- for (const k in src) {
237
- if (Object.prototype.hasOwnProperty.call(src, k)) {
238
- const childPath = path ? `${path}.${k}` : k;
239
- const s = sanitize(src[k], depth + 1, childPath, onDrop);
240
- if (s !== undefined)
241
- out[k] = s;
242
- }
286
+ for (const k of Object.keys(src)) {
287
+ if (DANGEROUS_KEYS.has(k))
288
+ continue;
289
+ const childPath = path ? `${path}.${k}` : k;
290
+ const s = sanitize(src[k], depth + 1, childPath, onDrop);
291
+ if (s !== undefined)
292
+ out[k] = s;
243
293
  }
244
294
  return out;
245
295
  }
@@ -264,27 +314,24 @@ function buildAllowedStructures(allowedFields) {
264
314
  function isFieldAllowed(field, allowedLookup) {
265
315
  return allowedLookup.has(field.toLowerCase());
266
316
  }
267
- function isPlainObject(v) {
268
- return (v !== null &&
269
- typeof v === 'object' &&
270
- !Array.isArray(v) &&
271
- !(v instanceof Date) &&
272
- Object.getPrototypeOf(v) === Object.prototype);
273
- }
274
317
  /** Strips any non-operator key not present in the allowlist; recurses into logical operators. */
275
318
  function enforceAllowlist(filter, allowedLookup, canonicalMap) {
276
319
  if (allowedLookup.size === 0)
277
320
  return filter;
278
321
  const out = {};
279
- for (const k in filter) {
280
- if (!Object.prototype.hasOwnProperty.call(filter, k))
281
- continue;
322
+ for (const k of Object.keys(filter)) {
282
323
  const v = filter[k];
283
324
  if (k.startsWith('$')) {
284
325
  if (Array.isArray(v)) {
285
- out[k] = v.map((item) => isPlainObject(item)
326
+ // Clauses that were fully stripped are dropped (an empty clause would
327
+ // otherwise match everything inside $or).
328
+ const items = v
329
+ .map((item) => isPlainObject(item)
286
330
  ? enforceAllowlist(item, allowedLookup, canonicalMap)
287
- : item);
331
+ : item)
332
+ .filter((item) => !(isPlainObject(item) && Object.keys(item).length === 0));
333
+ if (items.length > 0)
334
+ out[k] = items;
288
335
  }
289
336
  else if (isPlainObject(v)) {
290
337
  out[k] = enforceAllowlist(v, allowedLookup, canonicalMap);
@@ -300,53 +347,103 @@ function enforceAllowlist(filter, allowedLookup, canonicalMap) {
300
347
  }
301
348
  return out;
302
349
  }
303
- // ─── Fused coercion pass (timezone-aware) ──────────────────────────────────────
304
- function coerceAll(value, timezone, dateFieldsLookup, objectIdFieldsLookup, parentKey = '', parentOp) {
305
- if (value === null)
306
- return null;
307
- if (typeof value === 'string') {
308
- if (value === 'true')
309
- return true;
310
- if (value === 'false')
311
- return false;
312
- if (isDateField(parentKey, dateFieldsLookup)) {
313
- if (parentOp && IN_LIKE_OPS.has(parentOp)) {
314
- return coerceDateScalar(value, timezone) ?? value;
315
- }
316
- if (PLAIN_DATE_RE.test(value)) {
317
- const { start, end } = plainDateToUtcRange(value, timezone);
350
+ // ─── Fused coercion pass (timezone + schema aware) ─────────────────────────────
351
+ function parseNumeric(value) {
352
+ if (!NUMERIC_RE.test(value))
353
+ return undefined;
354
+ const n = Number(value);
355
+ if (!Number.isFinite(n))
356
+ return undefined;
357
+ if (Number.isInteger(n) && !Number.isSafeInteger(n))
358
+ return undefined;
359
+ return n;
360
+ }
361
+ function resolveKind(path, ctx) {
362
+ if (!path)
363
+ return { strict: false };
364
+ if (explicitHas(path, ctx.dateExplicit))
365
+ return { kind: 'date', strict: true };
366
+ if (explicitHas(path, ctx.oidExplicit))
367
+ return { kind: 'objectid', strict: true };
368
+ const st = ctx.typeOf(path);
369
+ if (st)
370
+ return { kind: st, strict: true };
371
+ if (!(ctx.dateExplicit && ctx.dateExplicit.size > 0) &&
372
+ DATE_FIELD_RE.test(path))
373
+ return { kind: 'date', strict: false };
374
+ if (!(ctx.oidExplicit && ctx.oidExplicit.size > 0) &&
375
+ OBJECTID_FIELD_RE.test(path))
376
+ return { kind: 'objectid', strict: false };
377
+ return { strict: false };
378
+ }
379
+ function coerceDateValue(value, op, timezone) {
380
+ if (op && IN_LIKE_OPS.has(op)) {
381
+ return coerceDateScalar(value, timezone) ?? value;
382
+ }
383
+ if (isRealPlainDate(value)) {
384
+ const { start, end } = plainDateToUtcRange(value, timezone);
385
+ if (isNaN(start.getTime()) || isNaN(end.getTime()))
386
+ return value;
387
+ switch (op) {
388
+ case undefined:
318
389
  return { $gte: start, $lt: end };
319
- }
320
- return coerceDateScalar(value, timezone) ?? value;
321
- }
322
- // ObjectId coercion — applies to bare equality values ("?categoryId=...")
323
- // as well as values nested under comparison/membership operators
324
- // ("?categoryId[in]=...,..."), since a plain string never matches an
325
- // ObjectId-typed field in MongoDB (different BSON types). Gated on the
326
- // field heuristic/explicit list AND a strict 24-char hex shape so we
327
- // never misinterpret a coincidentally-24-char plain string field.
328
- if (isObjectIdField(parentKey, objectIdFieldsLookup) &&
329
- HEX24_RE.test(value) &&
330
- (0, mongoose_1.isValidObjectId)(value)) {
331
- return new mongoose_1.Types.ObjectId(value);
332
- }
333
- // Numeric coercion for comparison/membership operators (eq/ne/gt/gte/lt/lte/in/nin).
334
- // Without this, a string like "50" under { $lte: "50" } never matches a
335
- // Number field in MongoDB, since comparison operators are type-sensitive.
336
- if (parentOp &&
337
- COERCIBLE_OPS.has(parentOp) &&
338
- value.trim() !== '' &&
339
- !isNaN(Number(value))) {
340
- return Number(value);
390
+ case 'gt':
391
+ return end;
392
+ case 'lte':
393
+ return new Date(end.getTime() - 1);
394
+ default: // gte / lt / eq / ne (eq/ne are normally intercepted earlier)
395
+ return start;
341
396
  }
397
+ }
398
+ return coerceDateScalar(value, timezone) ?? value;
399
+ }
400
+ function coerceString(value, path, op, ctx) {
401
+ const { kind, strict } = resolveKind(path, ctx);
402
+ if (kind === 'string')
342
403
  return value;
404
+ if (kind === 'date')
405
+ return coerceDateValue(value, op, ctx.timezone);
406
+ if (kind === 'objectid') {
407
+ if (HEX24_RE.test(value))
408
+ return new mongoose_1.Types.ObjectId(value);
409
+ if (strict)
410
+ return value;
411
+ }
412
+ else if (kind === 'number') {
413
+ return parseNumeric(value) ?? value;
414
+ }
415
+ else if (kind === 'boolean') {
416
+ return value === 'true' ? true : value === 'false' ? false : value;
417
+ }
418
+ // Unknown field type (e.g. joined/computed field) — conservative heuristics.
419
+ if (value === 'true')
420
+ return true;
421
+ if (value === 'false')
422
+ return false;
423
+ if (op && COERCIBLE_OPS.has(op)) {
424
+ const n = parseNumeric(value);
425
+ if (n !== undefined)
426
+ return n;
427
+ }
428
+ return value;
429
+ }
430
+ /**
431
+ * `inFilter` is true at the root of a filter and inside logical operators
432
+ * ($and/$or/$nor), where keys are field names; false inside a field's value,
433
+ * where keys are comparison operators or sub-paths.
434
+ */
435
+ function coerceAll(value, ctx, path = '', op, inFilter = true) {
436
+ if (value === null)
437
+ return null;
438
+ if (typeof value === 'string') {
439
+ return path ? coerceString(value, path, op, ctx) : value;
343
440
  }
344
441
  if (typeof value !== 'object' || value instanceof Date)
345
442
  return value;
346
443
  if (Array.isArray(value)) {
347
444
  const out = [];
348
- for (let i = 0; i < value.length; i++) {
349
- const coerced = coerceAll(value[i], timezone, dateFieldsLookup, objectIdFieldsLookup, parentKey, parentOp);
445
+ for (const item of value) {
446
+ const coerced = coerceAll(item, ctx, path, op, inFilter);
350
447
  if (coerced !== undefined)
351
448
  out.push(coerced);
352
449
  }
@@ -354,37 +451,79 @@ function coerceAll(value, timezone, dateFieldsLookup, objectIdFieldsLookup, pare
354
451
  }
355
452
  const src = value;
356
453
  const out = {};
357
- for (const k in src) {
358
- if (!Object.prototype.hasOwnProperty.call(src, k))
454
+ for (const k of Object.keys(src)) {
455
+ if (DANGEROUS_KEYS.has(k))
359
456
  continue;
360
- const newKey = COERCIBLE_OPS.has(k) ? `$${k}` : k;
457
+ const v = src[k];
458
+ if (inFilter) {
459
+ out[k] = k.startsWith('$')
460
+ ? coerceAll(v, ctx, '', undefined, true)
461
+ : coerceAll(v, ctx, k, undefined, false);
462
+ continue;
463
+ }
361
464
  const isOp = k.startsWith('$') || COERCIBLE_OPS.has(k);
362
- const childPath = isOp ? parentKey : parentKey ? `${parentKey}.${k}` : k;
363
- out[newKey] = coerceAll(src[k], timezone, dateFieldsLookup, objectIdFieldsLookup, childPath, isOp ? k : undefined);
465
+ if (!isOp) {
466
+ out[k] = coerceAll(v, ctx, path ? `${path}.${k}` : k, undefined, false);
467
+ continue;
468
+ }
469
+ const bare = k.startsWith('$') ? k.slice(1) : k;
470
+ const outKey = k.startsWith('$') ? k : `$${k}`;
471
+ // ?field[eq]=2026-09-01 / [ne]= on a date field -> whole-day range semantics.
472
+ if ((bare === 'eq' || bare === 'ne') &&
473
+ typeof v === 'string' &&
474
+ isRealPlainDate(v) &&
475
+ resolveKind(path, ctx).kind === 'date') {
476
+ const { start, end } = plainDateToUtcRange(v, ctx.timezone);
477
+ if (!isNaN(start.getTime()) && !isNaN(end.getTime())) {
478
+ if (bare === 'eq') {
479
+ out.$gte = start;
480
+ out.$lt = end;
481
+ }
482
+ else {
483
+ out.$not = { $gte: start, $lt: end };
484
+ }
485
+ continue;
486
+ }
487
+ }
488
+ // ?field[in]=a,b,c -> ['a','b','c']
489
+ const child = IN_LIKE_OPS.has(bare) && typeof v === 'string'
490
+ ? v
491
+ .split(',')
492
+ .map((s) => s.trim())
493
+ .filter(Boolean)
494
+ : v;
495
+ out[outKey] = coerceAll(child, ctx, path, bare, false);
364
496
  }
365
497
  return out;
366
498
  }
367
499
  // ─── Operator validation ────────────────────────────────────────────────────────
368
- /** Throws on any BANNED_OPERATORS key at any depth, and on any top-level $ key not in ALLOWED_TOP_LEVEL_OPS. */
369
- function rejectDisallowedOperators(filter, depth = 0) {
370
- for (const k in filter) {
371
- if (!Object.prototype.hasOwnProperty.call(filter, k))
372
- continue;
500
+ /**
501
+ * Throws on any BANNED_OPERATORS key at any depth. When `topLevelCheck` is true
502
+ * (client input) it also throws on any top-level $ key not in ALLOWED_TOP_LEVEL_OPS
503
+ * and requires logical operators to hold a non-empty array of plain objects.
504
+ */
505
+ function rejectDisallowedOperators(filter, depth = 0, topLevelCheck = true) {
506
+ for (const k of Object.keys(filter)) {
373
507
  if (BANNED_OPERATORS.has(k)) {
374
508
  throw new QueryAggregateValidationError(`Disallowed operator in query: "${k}"`);
375
509
  }
376
- if (depth === 0 && k.startsWith('$') && !ALLOWED_TOP_LEVEL_OPS.has(k)) {
377
- throw new QueryAggregateValidationError(`Disallowed top-level operator in query string: "${k}"`);
378
- }
379
510
  const v = filter[k];
511
+ if (topLevelCheck && depth === 0 && k.startsWith('$')) {
512
+ if (!ALLOWED_TOP_LEVEL_OPS.has(k)) {
513
+ throw new QueryAggregateValidationError(`Disallowed top-level operator in query string: "${k}"`);
514
+ }
515
+ if (!Array.isArray(v) || v.length === 0 || !v.every(isPlainObject)) {
516
+ throw new QueryAggregateValidationError(`Operator "${k}" requires a non-empty array of conditions`);
517
+ }
518
+ }
380
519
  if (Array.isArray(v)) {
381
520
  for (const item of v) {
382
521
  if (isPlainObject(item))
383
- rejectDisallowedOperators(item, depth + 1);
522
+ rejectDisallowedOperators(item, depth + 1, topLevelCheck);
384
523
  }
385
524
  }
386
525
  else if (isPlainObject(v)) {
387
- rejectDisallowedOperators(v, depth + 1);
526
+ rejectDisallowedOperators(v, depth + 1, topLevelCheck);
388
527
  }
389
528
  }
390
529
  }
@@ -396,7 +535,7 @@ function rejectBannedStages(stage) {
396
535
  }
397
536
  if (!isPlainObject(stage))
398
537
  return;
399
- for (const k in stage) {
538
+ for (const k of Object.keys(stage)) {
400
539
  if (BANNED_STAGE_OPERATORS.has(k)) {
401
540
  throw new QueryAggregateValidationError(`Disallowed pipeline stage: "${k}"`);
402
541
  }
@@ -404,15 +543,14 @@ function rejectBannedStages(stage) {
404
543
  }
405
544
  }
406
545
  // ─── Filter builder ───────────────────────────────────────────────────────────
407
- function buildFilter(raw, allowedLookup, canonicalMap, timezone, dateFieldsLookup, objectIdFieldsLookup, onDrop) {
546
+ function buildFilter(raw, allowedLookup, canonicalMap, ctx, onDrop) {
408
547
  const stripped = {};
409
- for (const k in raw) {
410
- if (Object.prototype.hasOwnProperty.call(raw, k) && !RESERVED_KEYS.has(k)) {
548
+ for (const k of Object.keys(raw)) {
549
+ if (!RESERVED_KEYS.has(k) && !DANGEROUS_KEYS.has(k))
411
550
  stripped[k] = raw[k];
412
- }
413
551
  }
414
552
  const safe = sanitize(stripped, 0, '', onDrop);
415
- const coerced = coerceAll(safe, timezone, dateFieldsLookup, objectIdFieldsLookup);
553
+ const coerced = coerceAll(safe, ctx);
416
554
  const allowed = enforceAllowlist(coerced, allowedLookup, canonicalMap);
417
555
  rejectDisallowedOperators(allowed);
418
556
  return allowed;
@@ -429,7 +567,7 @@ function parseSort(sort, allowedLookup, canonicalMap) {
429
567
  continue;
430
568
  const desc = trimmed.startsWith('-');
431
569
  const field = desc ? trimmed.slice(1).trim() : trimmed;
432
- if (!field)
570
+ if (!field || field.startsWith('$') || DANGEROUS_KEYS.has(field))
433
571
  continue;
434
572
  if (allowedLookup.size > 0) {
435
573
  if (!isFieldAllowed(field, allowedLookup))
@@ -464,16 +602,151 @@ function sanitizeProjectionString(projection, allowedLookup, canonicalMap) {
464
602
  })
465
603
  .join(' ');
466
604
  }
605
+ /**
606
+ * Converts "a b -c" to { a: 1, b: 1, c: 0 }. Tokens with `$`/empty names are
607
+ * ignored. MongoDB forbids mixing inclusion and exclusion (other than `_id`),
608
+ * so when both appear the inclusion fields win and exclusions (except `_id`)
609
+ * are dropped.
610
+ */
467
611
  function projectionStringToObject(projection) {
468
- const out = {};
612
+ const inc = {};
613
+ const exc = {};
469
614
  for (const token of projection.split(/\s+/).filter(Boolean)) {
470
- if (token.startsWith('-'))
471
- out[token.slice(1)] = 0;
615
+ const neg = token.startsWith('-');
616
+ const field = neg ? token.slice(1) : token;
617
+ if (!field || field.includes('$') || DANGEROUS_KEYS.has(field))
618
+ continue;
619
+ if (neg)
620
+ exc[field] = 0;
472
621
  else
473
- out[token] = 1;
622
+ inc[field] = 1;
474
623
  }
624
+ return normalizeProjection(inc, exc);
625
+ }
626
+ function normalizeProjection(inc, exc) {
627
+ if (Object.keys(inc).length === 0)
628
+ return exc;
629
+ const out = { ...inc };
630
+ if (exc._id === 0)
631
+ out._id = 0;
475
632
  return out;
476
633
  }
634
+ function normalizeProjectionObject(p) {
635
+ const inc = {};
636
+ const exc = {};
637
+ for (const k of Object.keys(p)) {
638
+ if (!k || k.includes('$') || DANGEROUS_KEYS.has(k))
639
+ continue;
640
+ if (p[k] === 0)
641
+ exc[k] = 0;
642
+ else
643
+ inc[k] = 1;
644
+ }
645
+ const hasIncNonId = Object.keys(inc).some((k) => k !== '_id');
646
+ if (!hasIncNonId) {
647
+ // Pure exclusion (an `_id: 1` alone is just the default).
648
+ delete inc._id;
649
+ return Object.keys(inc).length === 0 && Object.keys(exc).length === 0
650
+ ? {}
651
+ : exc;
652
+ }
653
+ return normalizeProjection(inc, exc);
654
+ }
655
+ // ─── Misc helpers ─────────────────────────────────────────────────────────────
656
+ function getByPath(obj, path) {
657
+ let cur = obj;
658
+ for (const part of path.split('.')) {
659
+ if (cur === null || typeof cur !== 'object')
660
+ return undefined;
661
+ cur = cur[part];
662
+ }
663
+ return cur;
664
+ }
665
+ /** Deletes a dotted path and removes parent objects left empty by the deletion. */
666
+ function deletePath(obj, path) {
667
+ const parts = path.split('.');
668
+ const parents = [];
669
+ let cur = obj;
670
+ for (let i = 0; i < parts.length - 1; i++) {
671
+ const next = cur[parts[i]];
672
+ if (!isPlainObject(next))
673
+ return;
674
+ parents.push(cur);
675
+ cur = next;
676
+ }
677
+ delete cur[parts[parts.length - 1]];
678
+ for (let i = parts.length - 2; i >= 0; i--) {
679
+ if (Object.keys(cur).length !== 0)
680
+ break;
681
+ const parent = parents[i];
682
+ delete parent[parts[i]];
683
+ cur = parent;
684
+ }
685
+ }
686
+ /** Converts 24-hex strings to ObjectIds (recursing through arrays / operator objects). */
687
+ function castObjectIds(value) {
688
+ if (typeof value === 'string')
689
+ return HEX24_RE.test(value) ? new mongoose_1.Types.ObjectId(value) : value;
690
+ if (Array.isArray(value))
691
+ return value.map(castObjectIds);
692
+ if (isPlainObject(value)) {
693
+ const out = {};
694
+ for (const k of Object.keys(value))
695
+ out[k] = castObjectIds(value[k]);
696
+ return out;
697
+ }
698
+ return value;
699
+ }
700
+ function assertFieldPath(field, label) {
701
+ if (typeof field !== 'string' || !FIELD_PATH_RE.test(field)) {
702
+ throw new QueryAggregateValidationError(`${label}: invalid field path "${String(field)}"`);
703
+ }
704
+ }
705
+ function encodeTyped(raw) {
706
+ if (raw === undefined || raw === null)
707
+ return { t: 'raw', v: null };
708
+ if (raw instanceof Date) {
709
+ return isNaN(raw.getTime())
710
+ ? { t: 'raw', v: null }
711
+ : { t: 'date', v: raw.toISOString() };
712
+ }
713
+ if (raw instanceof mongoose_1.Types.ObjectId)
714
+ return { t: 'oid', v: raw.toHexString() };
715
+ if (typeof raw === 'string' ||
716
+ typeof raw === 'number' ||
717
+ typeof raw === 'boolean') {
718
+ return { t: 'raw', v: raw };
719
+ }
720
+ throw new QueryAggregateValidationError('paginateCursor: the sort field must hold a scalar value (string, number, boolean, Date or ObjectId)');
721
+ }
722
+ function decodeTyped(x) {
723
+ const bad = () => new QueryAggregateValidationError('paginateCursor: invalid cursor');
724
+ if (!isPlainObject(x))
725
+ throw bad();
726
+ const { t, v } = x;
727
+ if (t === 'date') {
728
+ if (typeof v !== 'string')
729
+ throw bad();
730
+ const d = new Date(v);
731
+ if (isNaN(d.getTime()))
732
+ throw bad();
733
+ return d;
734
+ }
735
+ if (t === 'oid') {
736
+ if (typeof v !== 'string' || !HEX24_RE.test(v))
737
+ throw bad();
738
+ return new mongoose_1.Types.ObjectId(v);
739
+ }
740
+ if (t === 'raw') {
741
+ if (v === null ||
742
+ typeof v === 'string' ||
743
+ typeof v === 'number' ||
744
+ typeof v === 'boolean') {
745
+ return v;
746
+ }
747
+ }
748
+ throw bad();
749
+ }
477
750
  // ─── QueryAggregate ─────────────────────────────────────────────────────────────
478
751
  /**
479
752
  * Fluent aggregation-pipeline builder / paginator for Mongoose 8/9, with
@@ -486,26 +759,49 @@ class QueryAggregate {
486
759
  this._dateFieldsLookup = null;
487
760
  this._objectIdFieldsLookup = null;
488
761
  /** URL-derived filter and server conditions are kept separate so server
489
- * conditions (merged last) can never be overridden by URL params. */
762
+ * conditions can never be overridden by URL params. Server conditions are a
763
+ * list (AND-ed together) so repeated conditions on one field never overwrite
764
+ * each other. */
490
765
  this._urlFilter = {};
491
- this._serverConditions = {};
766
+ this._serverConditions = [];
492
767
  this._searchOr = [];
493
768
  this._sort = { ...DEFAULT_SORT };
494
769
  this._projection = null;
495
770
  this._defaultProjection = null;
496
771
  /** $lookup/$unwind/addStage() stages, in call order, spliced in after the base $match. */
497
772
  this._stages = [];
773
+ /** Root names of `as` aliases created by lookups; conditions on them run post-join. */
774
+ this._joinAliases = new Set();
775
+ /** Index in `_stages` right after the last $lookup — where the post-join $match goes. */
776
+ this._postJoinIndex = 0;
777
+ this._kindCache = new Map();
778
+ this._pathExistsCache = new Map();
498
779
  this.model = model;
499
780
  this.qs = Object.freeze({ ...queryString });
781
+ const maxLimit = typeof options.maxLimit === 'number' &&
782
+ Number.isFinite(options.maxLimit) &&
783
+ options.maxLimit >= 1
784
+ ? Math.floor(options.maxLimit)
785
+ : DEFAULT_MAX_LIMIT;
786
+ const maxTimeMS = typeof options.maxTimeMS === 'number' &&
787
+ Number.isFinite(options.maxTimeMS) &&
788
+ options.maxTimeMS >= 0
789
+ ? options.maxTimeMS
790
+ : DEFAULT_MAX_TIME_MS;
791
+ const weekStartsOn = typeof options.weekStartsOn === 'number' &&
792
+ Number.isInteger(options.weekStartsOn) &&
793
+ options.weekStartsOn >= 0 &&
794
+ options.weekStartsOn <= 6
795
+ ? options.weekStartsOn
796
+ : 6;
500
797
  this.options = {
501
798
  timezone: resolveTimezone(options.timezone),
502
- maxTimeMS: options.maxTimeMS ?? DEFAULT_MAX_TIME_MS,
799
+ maxTimeMS,
503
800
  slowQueryThresholdMS: options.slowQueryThresholdMS ??
504
- options.maxTimeMS ??
505
- DEFAULT_MAX_TIME_MS,
506
- maxLimit: options.maxLimit ?? DEFAULT_MAX_LIMIT,
801
+ (maxTimeMS > 0 ? maxTimeMS : DEFAULT_MAX_TIME_MS),
802
+ maxLimit,
507
803
  allowDiskUse: options.allowDiskUse ?? false,
508
- weekStartsOn: options.weekStartsOn ?? 6,
804
+ weekStartsOn,
509
805
  onSlowQuery: options.onSlowQuery,
510
806
  onSanitizeDrop: options.onSanitizeDrop,
511
807
  };
@@ -516,6 +812,45 @@ class QueryAggregate {
516
812
  get timezone() {
517
813
  return this.options.timezone;
518
814
  }
815
+ // ── Schema helpers ────────────────────────────────────────────────────────
816
+ schemaType(path) {
817
+ try {
818
+ const schema = this.model.schema;
819
+ return schema?.path(path) ?? undefined;
820
+ }
821
+ catch {
822
+ return undefined;
823
+ }
824
+ }
825
+ /** Field type from the model schema, when known (undefined for joined/computed/unknown paths). */
826
+ schemaKind(path) {
827
+ if (this._kindCache.has(path))
828
+ return this._kindCache.get(path);
829
+ const st = this.schemaType(path);
830
+ let instance = st?.instance;
831
+ if (instance === 'Array') {
832
+ instance = st?.embeddedSchemaType?.instance ?? st?.caster?.instance;
833
+ }
834
+ const kind = instance ? SCHEMA_KIND_MAP[instance] : undefined;
835
+ this._kindCache.set(path, kind);
836
+ return kind;
837
+ }
838
+ schemaHasPath(path) {
839
+ const cached = this._pathExistsCache.get(path);
840
+ if (cached !== undefined)
841
+ return cached;
842
+ const exists = this.schemaType(path) !== undefined;
843
+ this._pathExistsCache.set(path, exists);
844
+ return exists;
845
+ }
846
+ coerceCtx() {
847
+ return {
848
+ timezone: this.options.timezone,
849
+ dateExplicit: this._dateFieldsLookup,
850
+ oidExplicit: this._objectIdFieldsLookup,
851
+ typeOf: (p) => this.schemaKind(p),
852
+ };
853
+ }
519
854
  // ── Configuration ─────────────────────────────────────────────────────────
520
855
  /** Fields the client may filter, sort, and project. Case-insensitive. Call before filter()/sort()/project(). */
521
856
  allowFields(fields) {
@@ -524,12 +859,12 @@ class QueryAggregate {
524
859
  this._canonicalMap = canonical;
525
860
  return this;
526
861
  }
527
- /** Explicit list of fields treated as dates for timezone-aware coercion. Falls back to a name heuristic (createdAt/updatedAt/...) when omitted. */
862
+ /** Explicit list of fields treated as dates for timezone-aware coercion. Falls back to the model schema / a name heuristic (createdAt/updatedAt/...) when omitted. */
528
863
  dateFields(fields) {
529
864
  this._dateFieldsLookup = new Set(fields.map((f) => f.toLowerCase()));
530
865
  return this;
531
866
  }
532
- /** Explicit list of fields treated as ObjectId refs for coercion (client-supplied hex strings -> Types.ObjectId). Falls back to a name heuristic (_id/*Id) when omitted. */
867
+ /** Explicit list of fields treated as ObjectId refs for coercion (client-supplied hex strings -> Types.ObjectId). Falls back to the model schema / a name heuristic (_id/*Id) when omitted. */
533
868
  objectIdFields(fields) {
534
869
  this._objectIdFieldsLookup = new Set(fields.map((f) => f.toLowerCase()));
535
870
  return this;
@@ -537,44 +872,56 @@ class QueryAggregate {
537
872
  // ── Builder methods ───────────────────────────────────────────────────────
538
873
  /** Parses URL query params (req.query) into a Mongoose filter. Only allowlisted fields pass through. */
539
874
  filter() {
540
- const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.timezone, this._dateFieldsLookup, this._objectIdFieldsLookup, this.options.onSanitizeDrop);
875
+ const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.coerceCtx(), this.options.onSanitizeDrop);
541
876
  Object.assign(this._urlFilter, parsed);
542
877
  return this;
543
878
  }
544
- /** Mandatory server-side conditions the client cannot override — merged into the final $match last. */
879
+ /**
880
+ * Mandatory server-side conditions the client cannot override. Repeated
881
+ * calls (and range*() calls) are AND-ed together, never overwritten.
882
+ * Strings that are 24-hex ObjectIds on ObjectId schema paths are cast
883
+ * automatically (aggregate() does not auto-cast like find() does).
884
+ */
545
885
  where(conditions) {
546
886
  const asRecord = conditions;
547
- rejectDisallowedOperators(asRecord);
548
- Object.assign(this._serverConditions, asRecord);
887
+ for (const k of Object.keys(asRecord)) {
888
+ if (asRecord[k] === undefined) {
889
+ throw new QueryAggregateValidationError(`where: condition for "${k}" is undefined`);
890
+ }
891
+ }
892
+ rejectDisallowedOperators(asRecord, 0, false);
893
+ if (Object.keys(asRecord).length === 0)
894
+ return this;
895
+ this._serverConditions.push(this.castServerConditions(asRecord));
549
896
  return this;
550
897
  }
551
898
  /** Adds a hard, server-defined UTC date range (in this instance's timezone) on `field`. Not client-overridable. */
552
899
  range(field, preset) {
553
900
  const { start, end } = this.resolveRangePreset(preset);
554
- this._serverConditions[field] = { $gte: start, $lt: end };
901
+ this.pushRange(field, start, end);
555
902
  return this;
556
903
  }
557
- // ── Custom range methods (additive — RangePreset/.range() above is
558
- // untouched; these cover custom day / custom range / custom N-days /
559
- // custom N-hours / custom hour-of-day window / custom absolute datetime
560
- // window use cases) ─────────────────────────────────────────────────────
904
+ // ── Custom range methods ──────────────────────────────────────────────────
561
905
  /** Hard server-side condition for a single arbitrary local calendar date (e.g. "2026-03-14"), in this instance's timezone. Not client-overridable. */
562
906
  rangeCustomDay(field, date) {
563
- if (!PLAIN_DATE_RE.test(date)) {
564
- throw new QueryAggregateValidationError(`rangeCustomDay: "date" must be in YYYY-MM-DD format, got "${date}"`);
907
+ if (!isRealPlainDate(date)) {
908
+ throw new QueryAggregateValidationError(`rangeCustomDay: "date" must be a valid date in YYYY-MM-DD format, got "${date}"`);
565
909
  }
566
910
  const { start, end } = this.utcRangeForLocalDates(date, date);
567
- this._serverConditions[field] = { $gte: start, $lt: end };
911
+ this.pushRange(field, start, end);
568
912
  return this;
569
913
  }
570
914
  /** Hard server-side condition for an arbitrary inclusive local-date span (e.g. { from: "2026-01-01", to: "2026-01-31" }), in this instance's timezone. Not client-overridable. */
571
915
  rangeBetween(field, custom) {
572
916
  const { from, to } = custom;
573
- if (!PLAIN_DATE_RE.test(from) || !PLAIN_DATE_RE.test(to)) {
574
- throw new QueryAggregateValidationError(`rangeBetween: "from"/"to" must be in YYYY-MM-DD format, got "${from}" / "${to}"`);
917
+ if (!isRealPlainDate(from) || !isRealPlainDate(to)) {
918
+ throw new QueryAggregateValidationError(`rangeBetween: "from"/"to" must be valid dates in YYYY-MM-DD format, got "${from}" / "${to}"`);
919
+ }
920
+ if (from > to) {
921
+ throw new QueryAggregateValidationError(`rangeBetween: "from" (${from}) must not be after "to" (${to})`);
575
922
  }
576
923
  const { start, end } = this.utcRangeForLocalDates(from, to);
577
- this._serverConditions[field] = { $gte: start, $lt: end };
924
+ this.pushRange(field, start, end);
578
925
  return this;
579
926
  }
580
927
  /** Hard server-side condition for a rolling window of the last N whole calendar days (inclusive of today), in this instance's timezone. Not client-overridable. */
@@ -582,12 +929,10 @@ class QueryAggregate {
582
929
  if (!Number.isInteger(days) || days < 1) {
583
930
  throw new QueryAggregateValidationError(`rangeLastNDays: "days" must be a positive integer, got ${days}`);
584
931
  }
585
- const tz = this.options.timezone;
586
- const zonedNow = (0, date_fns_tz_1.toZonedTime)(new Date(), tz);
587
- const todayStr = (0, date_fns_1.format)(zonedNow, 'yyyy-MM-dd');
932
+ const todayStr = this.todayLocal();
588
933
  const fromStr = shiftLocalDateString(todayStr, -(days - 1));
589
934
  const { start, end } = this.utcRangeForLocalDates(fromStr, todayStr);
590
- this._serverConditions[field] = { $gte: start, $lt: end };
935
+ this.pushRange(field, start, end);
591
936
  return this;
592
937
  }
593
938
  /** Hard server-side condition for a rolling window of the last N hours, ending at the moment this is called (exact UTC instants — no calendar-date snapping). Not client-overridable. */
@@ -597,14 +942,17 @@ class QueryAggregate {
597
942
  }
598
943
  const end = new Date();
599
944
  const start = new Date(end.getTime() - hours * 60 * 60 * 1000);
600
- this._serverConditions[field] = { $gte: start, $lt: end };
945
+ if (isNaN(start.getTime())) {
946
+ throw new QueryAggregateValidationError(`rangeLastNHours: "hours" is too large, got ${hours}`);
947
+ }
948
+ this.pushRange(field, start, end);
601
949
  return this;
602
950
  }
603
951
  /** Hard server-side condition for an explicit hour-of-day window on a given local date (e.g. 09:00–17:00 on "2026-03-14"), in this instance's timezone. `toHour` is exclusive; pass 24 for "through end of day". Not client-overridable. */
604
952
  rangeHours(field, custom) {
605
953
  const { date, fromHour, toHour } = custom;
606
- if (!PLAIN_DATE_RE.test(date)) {
607
- throw new QueryAggregateValidationError(`rangeHours: "date" must be in YYYY-MM-DD format, got "${date}"`);
954
+ if (!isRealPlainDate(date)) {
955
+ throw new QueryAggregateValidationError(`rangeHours: "date" must be a valid date in YYYY-MM-DD format, got "${date}"`);
608
956
  }
609
957
  if (!Number.isInteger(fromHour) ||
610
958
  !Number.isInteger(toHour) ||
@@ -617,11 +965,13 @@ class QueryAggregate {
617
965
  }
618
966
  const tz = this.options.timezone;
619
967
  const pad = (n) => String(n).padStart(2, '0');
620
- const start = (0, date_fns_tz_1.fromZonedTime)(`${date}T${pad(fromHour)}:00:00.000`, tz);
968
+ const start = fromHour === 24
969
+ ? (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(date, 1)}T00:00:00.000`, tz)
970
+ : (0, date_fns_tz_1.fromZonedTime)(`${date}T${pad(fromHour)}:00:00.000`, tz);
621
971
  const end = toHour === 24
622
972
  ? (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(date, 1)}T00:00:00.000`, tz)
623
973
  : (0, date_fns_tz_1.fromZonedTime)(`${date}T${pad(toHour)}:00:00.000`, tz);
624
- this._serverConditions[field] = { $gte: start, $lt: end };
974
+ this.pushRange(field, start, end);
625
975
  return this;
626
976
  }
627
977
  /**
@@ -640,12 +990,12 @@ class QueryAggregate {
640
990
  if (end <= start) {
641
991
  throw new QueryAggregateValidationError(`rangeCustom: "to" (${custom.to}) must be after "from" (${custom.from})`);
642
992
  }
643
- this._serverConditions[field] = { $gte: start, $lt: end };
993
+ this.pushRange(field, start, end);
644
994
  return this;
645
995
  }
646
996
  /** Case-insensitive full-text search across the given fields when ?q= is present. */
647
997
  globalSearch(fields) {
648
- const raw = this.qs.q?.trim();
998
+ const raw = asString(this.qs.q)?.trim();
649
999
  if (!raw || raw.length > MAX_SEARCH_LENGTH || fields.length === 0)
650
1000
  return this;
651
1001
  const safeFields = this._allowedLookup.size > 0
@@ -661,8 +1011,9 @@ class QueryAggregate {
661
1011
  }
662
1012
  /** Parses ?sort= (e.g. "-createdAt,name"). Fields not in allowFields() are dropped; falls back to DEFAULT_SORT. */
663
1013
  sort() {
664
- if (this.qs.sort) {
665
- this._sort = parseSort(this.qs.sort, this._allowedLookup, this._canonicalMap);
1014
+ const raw = asString(this.qs.sort);
1015
+ if (raw) {
1016
+ this._sort = parseSort(raw, this._allowedLookup, this._canonicalMap);
666
1017
  }
667
1018
  return this;
668
1019
  }
@@ -674,21 +1025,22 @@ class QueryAggregate {
674
1025
  */
675
1026
  project(defaultProjection) {
676
1027
  if (defaultProjection) {
677
- this._defaultProjection =
678
- typeof defaultProjection === 'string'
679
- ? projectionStringToObject(defaultProjection)
680
- : defaultProjection;
1028
+ const obj = typeof defaultProjection === 'string'
1029
+ ? projectionStringToObject(defaultProjection)
1030
+ : normalizeProjectionObject(defaultProjection);
1031
+ this._defaultProjection = Object.keys(obj).length > 0 ? obj : null;
681
1032
  }
682
- if (this.qs.fields) {
683
- const raw = this.qs.fields
1033
+ const fieldsRaw = asString(this.qs.fields);
1034
+ if (fieldsRaw) {
1035
+ const raw = fieldsRaw
684
1036
  .split(',')
685
1037
  .map((f) => f.trim())
686
1038
  .filter(Boolean)
687
1039
  .join(' ');
688
1040
  const sanitized = sanitizeProjectionString(raw, this._allowedLookup, this._canonicalMap);
689
- this._projection = sanitized
690
- ? projectionStringToObject(sanitized)
691
- : this._defaultProjection;
1041
+ const obj = sanitized ? projectionStringToObject(sanitized) : {};
1042
+ this._projection =
1043
+ Object.keys(obj).length > 0 ? obj : this._defaultProjection;
692
1044
  }
693
1045
  else {
694
1046
  this._projection = this._defaultProjection;
@@ -697,6 +1049,12 @@ class QueryAggregate {
697
1049
  }
698
1050
  /** Adds a $lookup (join) stage, optionally followed by $unwind when `single` is true. */
699
1051
  lookup(opts) {
1052
+ const hasLocalForeign = Boolean(opts.localField && opts.foreignField);
1053
+ if (!hasLocalForeign && !opts.pipeline) {
1054
+ throw new QueryAggregateValidationError('lookup: provide either localField + foreignField or a pipeline');
1055
+ }
1056
+ if (opts.pipeline)
1057
+ rejectBannedStages(opts.pipeline);
700
1058
  const lookupStage = {
701
1059
  $lookup: {
702
1060
  from: opts.from,
@@ -712,15 +1070,48 @@ class QueryAggregate {
712
1070
  $unwind: { path: `$${opts.as}`, preserveNullAndEmptyArrays: true },
713
1071
  });
714
1072
  }
1073
+ this.registerJoin(opts.as);
715
1074
  return this;
716
1075
  }
717
1076
  /** Escape hatch for any other developer-authored stage ($addFields, $group, post-join $match, ...). Blocks $out/$merge only — this path is for trusted, server-defined stages, not client input. */
718
1077
  addStage(stage) {
719
1078
  rejectBannedStages(stage);
720
1079
  this._stages.push(stage);
1080
+ if ('$lookup' in stage) {
1081
+ const as = stage.$lookup.as;
1082
+ if (typeof as === 'string')
1083
+ this.registerJoin(as);
1084
+ }
721
1085
  return this;
722
1086
  }
723
1087
  // ── Private helpers ───────────────────────────────────────────────────────
1088
+ registerJoin(as) {
1089
+ this._joinAliases.add(as.split('.')[0]);
1090
+ this._postJoinIndex = this._stages.length;
1091
+ }
1092
+ pushRange(field, start, end) {
1093
+ if (isNaN(start.getTime()) || isNaN(end.getTime())) {
1094
+ throw new QueryAggregateValidationError(`Invalid date range for "${field}"`);
1095
+ }
1096
+ this._serverConditions.push({ [field]: { $gte: start, $lt: end } });
1097
+ }
1098
+ todayLocal() {
1099
+ return (0, date_fns_1.format)((0, date_fns_tz_1.toZonedTime)(new Date(), this.options.timezone), 'yyyy-MM-dd');
1100
+ }
1101
+ castServerConditions(cond) {
1102
+ const out = {};
1103
+ for (const k of Object.keys(cond)) {
1104
+ const v = cond[k];
1105
+ if (k.startsWith('$')) {
1106
+ out[k] = Array.isArray(v)
1107
+ ? v.map((i) => (isPlainObject(i) ? this.castServerConditions(i) : i))
1108
+ : v;
1109
+ continue;
1110
+ }
1111
+ out[k] = this.schemaKind(k) === 'objectid' ? castObjectIds(v) : v;
1112
+ }
1113
+ return out;
1114
+ }
724
1115
  resolveRangePreset(preset) {
725
1116
  const tz = this.options.timezone;
726
1117
  const zonedNow = (0, date_fns_tz_1.toZonedTime)(new Date(), tz);
@@ -745,7 +1136,7 @@ class QueryAggregate {
745
1136
  return this.utcRangeForLocalDates(monthStartStr, todayStr);
746
1137
  }
747
1138
  default:
748
- throw new QueryAggregateValidationError(`Unknown range preset: "${preset}"`);
1139
+ throw new QueryAggregateValidationError(`Unknown range preset: "${String(preset)}"`);
749
1140
  }
750
1141
  }
751
1142
  /** [start of fromStr, start of (toStr + 1 day)) in this instance's timezone — an inclusive local-date range. */
@@ -755,79 +1146,91 @@ class QueryAggregate {
755
1146
  const end = (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(toStr, 1)}T00:00:00.000`, tz);
756
1147
  return { start, end };
757
1148
  }
758
- buildMatchStage() {
759
- let base;
760
- const hasUrlFilter = Object.keys(this._urlFilter).length > 0;
761
- if (this._searchOr.length > 0) {
762
- base = hasUrlFilter
763
- ? { $and: [this._urlFilter, { $or: this._searchOr }] }
764
- : { $or: this._searchOr };
765
- }
766
- else {
767
- base = hasUrlFilter ? this._urlFilter : {};
1149
+ /** Effective sort: the requested sort plus `_id` as a stable tiebreaker (prevents duplicate/missing rows across pages). */
1150
+ effectiveSort() {
1151
+ if ('_id' in this._sort)
1152
+ return { ...this._sort };
1153
+ const dir = Object.values(this._sort)[0] ?? -1;
1154
+ return { ...this._sort, _id: dir };
1155
+ }
1156
+ // A key is "joined" when it lives under a lookup alias and is not a real schema path.
1157
+ isJoinedKey(key) {
1158
+ if (this._joinAliases.size === 0)
1159
+ return false;
1160
+ if (this.schemaHasPath(key))
1161
+ return false;
1162
+ return this._joinAliases.has(key.split('.')[0]);
1163
+ }
1164
+ referencesJoined(key, value) {
1165
+ if (!key.startsWith('$'))
1166
+ return this.isJoinedKey(key);
1167
+ const items = Array.isArray(value) ? value : [value];
1168
+ return items.some((it) => isPlainObject(it) &&
1169
+ Object.keys(it).some((k) => this.referencesJoined(k, it[k])));
1170
+ }
1171
+ splitConditions(cond) {
1172
+ const pre = {};
1173
+ const post = {};
1174
+ for (const k of Object.keys(cond)) {
1175
+ (this.referencesJoined(k, cond[k]) ? post : pre)[k] = cond[k];
768
1176
  }
769
- const hasServer = Object.keys(this._serverConditions).length > 0;
770
- const finalFilter = Object.keys(base).length > 0 && hasServer
771
- ? { $and: [base, this._serverConditions] }
772
- : hasServer
773
- ? this._serverConditions
774
- : base;
775
- return Object.keys(finalFilter).length > 0 ? { $match: finalFilter } : null;
776
- }
777
- /** Match + lookups/custom stages only, no $project/$sort — shared by count()/distinct()/stats(), which don't need either. */
778
- buildMatchAndStagesPipeline() {
779
- const pipeline = [];
780
- const matchStage = this.buildMatchStage();
781
- if (matchStage)
782
- pipeline.push(matchStage);
783
- pipeline.push(...this._stages);
784
- return pipeline;
1177
+ return { pre, post };
785
1178
  }
786
- /** Encodes a keyset cursor from a result row: the current sort field's value plus `_id` as a stable tiebreaker. */
787
- encodeCursor(doc, sortField) {
788
- const raw = doc[sortField];
789
- let v = raw;
790
- let t = 'other';
791
- if (raw instanceof Date) {
792
- v = raw.toISOString();
793
- t = 'date';
1179
+ /** Builds the pre-join $match (index-friendly) and the post-join $match (conditions on joined fields). */
1180
+ buildMatchStages() {
1181
+ const preClauses = [];
1182
+ const postClauses = [];
1183
+ const add = (arr, c) => {
1184
+ if (Object.keys(c).length > 0)
1185
+ arr.push(c);
1186
+ };
1187
+ const url = this.splitConditions(this._urlFilter);
1188
+ add(preClauses, url.pre);
1189
+ add(postClauses, url.post);
1190
+ if (this._searchOr.length > 0) {
1191
+ const clause = { $or: this._searchOr };
1192
+ const joined = this._searchOr.some((o) => Object.keys(o).some((k) => this.isJoinedKey(k)));
1193
+ (joined ? postClauses : preClauses).push(clause);
794
1194
  }
795
- else if (raw instanceof mongoose_1.Types.ObjectId) {
796
- v = raw.toString();
797
- t = 'objectid';
1195
+ for (const cond of this._serverConditions) {
1196
+ const s = this.splitConditions(cond);
1197
+ add(preClauses, s.pre);
1198
+ add(postClauses, s.post);
798
1199
  }
799
- const id = doc._id;
800
- return Buffer.from(JSON.stringify({ v, t, id: String(id) })).toString('base64url');
1200
+ const mk = (c) => c.length === 0 ? null : { $match: c.length === 1 ? c[0] : { $and: c } };
1201
+ return { pre: mk(preClauses), post: mk(postClauses) };
801
1202
  }
802
- /** Decodes a cursor produced by encodeCursor(), restoring Date/ObjectId typing so comparisons stay type-correct. */
803
- decodeCursor(cursor) {
804
- let parsed;
805
- try {
806
- parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
807
- }
808
- catch {
809
- throw new QueryAggregateValidationError('paginateCursor: invalid cursor');
1203
+ /** Match + lookups/custom stages only, no $project/$sort — shared by count()/distinct()/stats()/paginateCursor(). */
1204
+ buildHeadPipeline() {
1205
+ const { pre, post } = this.buildMatchStages();
1206
+ const pipeline = [];
1207
+ if (pre)
1208
+ pipeline.push(pre);
1209
+ if (post) {
1210
+ const idx = Math.min(this._postJoinIndex, this._stages.length);
1211
+ pipeline.push(...this._stages.slice(0, idx), post, ...this._stages.slice(idx));
810
1212
  }
811
- let v = parsed.v;
812
- if (parsed.t === 'date' && typeof v === 'string')
813
- v = new Date(v);
814
- if (parsed.t === 'objectid' &&
815
- typeof v === 'string' &&
816
- (0, mongoose_1.isValidObjectId)(v)) {
817
- v = new mongoose_1.Types.ObjectId(v);
1213
+ else {
1214
+ pipeline.push(...this._stages);
818
1215
  }
819
- return { v, id: parsed.id };
1216
+ return pipeline;
820
1217
  }
821
- /** Base pipeline shared by every execution path: match -> lookups/custom stages -> project -> sort. */
822
- buildBasePipeline() {
823
- const pipeline = [];
824
- const matchStage = this.buildMatchStage();
825
- if (matchStage)
826
- pipeline.push(matchStage);
827
- pipeline.push(...this._stages);
1218
+ /**
1219
+ * Base pipeline shared by every execution path:
1220
+ * match -> lookups/custom stages -> sort -> [skip/limit] -> project.
1221
+ * $project runs last so it can never drop a field that sorting needs,
1222
+ * and only touches the documents that survive skip/limit.
1223
+ */
1224
+ buildBasePipeline(range) {
1225
+ const pipeline = this.buildHeadPipeline();
1226
+ pipeline.push({ $sort: this.effectiveSort() });
1227
+ if (range) {
1228
+ if (range.skip > 0)
1229
+ pipeline.push({ $skip: range.skip });
1230
+ pipeline.push({ $limit: range.limit });
1231
+ }
828
1232
  if (this._projection)
829
1233
  pipeline.push({ $project: this._projection });
830
- pipeline.push({ $sort: this._sort });
831
1234
  return pipeline;
832
1235
  }
833
1236
  execAggregate(pipeline) {
@@ -839,40 +1242,63 @@ class QueryAggregate {
839
1242
  return agg.exec();
840
1243
  }
841
1244
  async wrapTimed(fn, page, limit, pipeline) {
842
- const { onSlowQuery, slowQueryThresholdMS, maxTimeMS } = this.options;
1245
+ const { onSlowQuery, slowQueryThresholdMS } = this.options;
843
1246
  if (!onSlowQuery)
844
1247
  return fn();
845
1248
  const start = Date.now();
846
- const result = await fn();
847
- const elapsedMs = Date.now() - start;
848
- if (elapsedMs >= (slowQueryThresholdMS ?? maxTimeMS)) {
849
- onSlowQuery({ elapsedMs, pipeline, sort: this._sort, page, limit });
1249
+ try {
1250
+ return await fn();
850
1251
  }
851
- return result;
1252
+ finally {
1253
+ const elapsedMs = Date.now() - start;
1254
+ if (elapsedMs >= slowQueryThresholdMS) {
1255
+ try {
1256
+ onSlowQuery({
1257
+ elapsedMs,
1258
+ pipeline,
1259
+ sort: this.effectiveSort(),
1260
+ page,
1261
+ limit,
1262
+ });
1263
+ }
1264
+ catch {
1265
+ // A faulty logging callback must never break the query.
1266
+ }
1267
+ }
1268
+ }
1269
+ }
1270
+ fetchPage(page, limit) {
1271
+ const pipeline = this.buildBasePipeline({
1272
+ skip: (page - 1) * limit,
1273
+ limit,
1274
+ });
1275
+ return this.wrapTimed(() => this.execAggregate(pipeline), page, limit, pipeline);
1276
+ }
1277
+ async runCount(page, limit) {
1278
+ const pipeline = [
1279
+ ...this.buildHeadPipeline(),
1280
+ { $count: 'count' },
1281
+ ];
1282
+ const [row] = await this.wrapTimed(() => this.execAggregate(pipeline), page, limit, pipeline);
1283
+ return row?.count ?? 0;
852
1284
  }
853
1285
  // ── Terminal ───────────────────────────────────────────────────────────────
854
1286
  /**
855
- * Executes the pipeline and returns a paginated result via $facet (single
856
- * round trip: data page + total count together). Pass a prior page-1
857
- * `total` as `cachedTotal` on later pages to skip the count entirely.
858
- *
859
- * Note: $facet buffers both branches in memory per query — for very large
860
- * collections with expensive pre-facet stages, consider passing
861
- * `cachedTotal` on subsequent pages, or run count/data as two calls.
1287
+ * Executes the pipeline and returns a paginated result. The data page
1288
+ * (sort + skip + limit, so MongoDB can use top-k / index sorting) and the
1289
+ * total count run in parallel. Pass a prior page-1 `total` as `cachedTotal`
1290
+ * on later pages to skip the count entirely.
862
1291
  */
863
1292
  async paginate(cachedTotal) {
864
1293
  const page = this._page;
865
1294
  const limit = this._limit;
866
- const basePipeline = this.buildBasePipeline();
867
1295
  if (cachedTotal !== undefined) {
1296
+ if (!Number.isInteger(cachedTotal) || cachedTotal < 0) {
1297
+ throw new QueryAggregateValidationError(`paginate: "cachedTotal" must be a non-negative integer, got ${cachedTotal}`);
1298
+ }
868
1299
  const totalPages = Math.max(Math.ceil(cachedTotal / limit), 1);
869
1300
  const safePage = page > totalPages ? 1 : page;
870
- const dataPipeline = [
871
- ...basePipeline,
872
- { $skip: (safePage - 1) * limit },
873
- { $limit: limit },
874
- ];
875
- const data = await this.wrapTimed(() => this.execAggregate(dataPipeline), safePage, limit, dataPipeline);
1301
+ const data = await this.fetchPage(safePage, limit);
876
1302
  return {
877
1303
  data,
878
1304
  total: cachedTotal,
@@ -883,27 +1309,15 @@ class QueryAggregate {
883
1309
  hasPrevPage: safePage > 1,
884
1310
  };
885
1311
  }
886
- const facetPipeline = [
887
- ...basePipeline,
888
- {
889
- $facet: {
890
- data: [{ $skip: (page - 1) * limit }, { $limit: limit }],
891
- totalCount: [{ $count: 'count' }],
892
- },
893
- },
894
- ];
895
- const [facetResult] = await this.wrapTimed(() => this.execAggregate(facetPipeline), page, limit, facetPipeline);
896
- const total = facetResult?.totalCount?.[0]?.count ?? 0;
1312
+ const [pageData, total] = await Promise.all([
1313
+ this.fetchPage(page, limit),
1314
+ this.runCount(page, limit),
1315
+ ]);
897
1316
  const totalPages = Math.max(Math.ceil(total / limit), 1);
898
- if (page > totalPages && page !== 1) {
899
- // Requested page doesn't exist for this filter — refetch page 1 rather
900
- // than returning an empty page silently.
901
- const fallbackPipeline = [
902
- ...basePipeline,
903
- { $skip: 0 },
904
- { $limit: limit },
905
- ];
906
- const data = await this.execAggregate(fallbackPipeline);
1317
+ if (page > totalPages) {
1318
+ // Requested page doesn't exist for this filter — return page 1 rather
1319
+ // than an empty page silently.
1320
+ const data = await this.fetchPage(1, limit);
907
1321
  return {
908
1322
  data,
909
1323
  total,
@@ -915,7 +1329,7 @@ class QueryAggregate {
915
1329
  };
916
1330
  }
917
1331
  return {
918
- data: facetResult?.data ?? [],
1332
+ data: pageData,
919
1333
  total,
920
1334
  page,
921
1335
  totalPages,
@@ -924,12 +1338,11 @@ class QueryAggregate {
924
1338
  hasPrevPage: page > 1,
925
1339
  };
926
1340
  }
927
- // ── Advanced terminal & utility methods (additive — paginate() above is
928
- // untouched) ─────────────────────────────────────────────────────────────
1341
+ // ── Advanced terminal & utility methods ───────────────────────────────────
929
1342
  /** Returns just the matching document count — cheaper than paginate() when you don't need the data page. Ignores $project/$sort. */
930
1343
  async count() {
931
1344
  const pipeline = [
932
- ...this.buildMatchAndStagesPipeline(),
1345
+ ...this.buildHeadPipeline(),
933
1346
  { $count: 'count' },
934
1347
  ];
935
1348
  const [row] = await this.execAggregate(pipeline);
@@ -937,8 +1350,9 @@ class QueryAggregate {
937
1350
  }
938
1351
  /** Returns the distinct values of `field` for the current filter/where/range conditions. */
939
1352
  async distinct(field) {
1353
+ assertFieldPath(field, 'distinct');
940
1354
  const pipeline = [
941
- ...this.buildMatchAndStagesPipeline(),
1355
+ ...this.buildHeadPipeline(),
942
1356
  { $group: { _id: `$${field}` } },
943
1357
  ];
944
1358
  const rows = await this.execAggregate(pipeline);
@@ -953,6 +1367,14 @@ class QueryAggregate {
953
1367
  async stats(specs) {
954
1368
  const group = { _id: null };
955
1369
  for (const spec of specs) {
1370
+ if (!METRIC_NAME_RE.test(spec.name) ||
1371
+ spec.name === '_id' ||
1372
+ DANGEROUS_KEYS.has(spec.name)) {
1373
+ throw new QueryAggregateValidationError(`stats: invalid metric name "${spec.name}"`);
1374
+ }
1375
+ if (!STAT_OPS.has(spec.op)) {
1376
+ throw new QueryAggregateValidationError(`stats: unsupported op "${String(spec.op)}" for metric "${spec.name}"`);
1377
+ }
956
1378
  if (spec.op === 'count') {
957
1379
  group[spec.name] = { $sum: 1 };
958
1380
  }
@@ -960,11 +1382,12 @@ class QueryAggregate {
960
1382
  if (!spec.field) {
961
1383
  throw new QueryAggregateValidationError(`stats: metric "${spec.name}" needs a "field" for op "${spec.op}"`);
962
1384
  }
1385
+ assertFieldPath(spec.field, `stats(${spec.name})`);
963
1386
  group[spec.name] = { [`$${spec.op}`]: `$${spec.field}` };
964
1387
  }
965
1388
  }
966
1389
  const pipeline = [
967
- ...this.buildMatchAndStagesPipeline(),
1390
+ ...this.buildHeadPipeline(),
968
1391
  { $group: group },
969
1392
  ];
970
1393
  const [row] = await this.execAggregate(pipeline);
@@ -991,44 +1414,54 @@ class QueryAggregate {
991
1414
  /**
992
1415
  * Keyset ("seek") pagination — scales far better than .paginate()'s
993
1416
  * $skip on deep pages of large collections, at the cost of not supporting
994
- * "jump to page N". Requires .sort() to have been called with exactly the
995
- * field you want to seek on (falls back to DEFAULT_SORT's `createdAt`
996
- * otherwise). Pass the previous page's `nextCursor` back in as `cursor`
997
- * to continue; a `hasNextPage: false` / `nextCursor: null` page is the end.
1417
+ * "jump to page N". Seeks on the FIRST field of .sort() (falls back to
1418
+ * DEFAULT_SORT's `createdAt`) with `_id` as a stable tiebreaker. Pass the
1419
+ * previous page's `nextCursor` back in as `cursor` to continue; a
1420
+ * `hasNextPage: false` / `nextCursor: null` page is the end. A cursor is
1421
+ * bound to the sort field/direction it was created with.
998
1422
  */
999
1423
  async paginateCursor(opts = {}) {
1000
- const limit = opts.limit && opts.limit > 0
1001
- ? Math.min(opts.limit, this.options.maxLimit)
1424
+ const limit = typeof opts.limit === 'number' &&
1425
+ Number.isFinite(opts.limit) &&
1426
+ opts.limit >= 1
1427
+ ? Math.min(Math.floor(opts.limit), this.options.maxLimit)
1002
1428
  : this._limit;
1003
- const [sortField, sortDir] = Object.entries(this._sort)[0] ?? [
1004
- 'createdAt',
1005
- -1,
1006
- ];
1007
- const pipeline = this.buildMatchAndStagesPipeline();
1429
+ const first = Object.entries(this._sort)[0] ?? ['createdAt', -1];
1430
+ const sortField = first[0];
1431
+ const sortDir = first[1] === 1 ? 1 : -1;
1432
+ const pipeline = this.buildHeadPipeline();
1008
1433
  if (opts.cursor) {
1009
- const { v, id } = this.decodeCursor(opts.cursor);
1010
- const cmp = sortDir === -1 ? '$lt' : '$gt';
1011
- const idValue = (0, mongoose_1.isValidObjectId)(id) ? new mongoose_1.Types.ObjectId(id) : id;
1434
+ const { v, id } = this.decodeCursor(opts.cursor, sortField, sortDir);
1012
1435
  pipeline.push({
1013
- $match: {
1014
- $or: [
1015
- { [sortField]: { [cmp]: v } },
1016
- { [sortField]: v, _id: { [cmp]: idValue } },
1017
- ],
1018
- },
1436
+ $match: this.buildCursorMatch(sortField, sortDir, v, id),
1019
1437
  });
1020
1438
  }
1021
- if (this._projection)
1022
- pipeline.push({ $project: this._projection });
1023
- pipeline.push({ $sort: { [sortField]: sortDir, _id: sortDir } });
1439
+ pipeline.push({
1440
+ $sort: sortField === '_id'
1441
+ ? { _id: sortDir }
1442
+ : { [sortField]: sortDir, _id: sortDir },
1443
+ });
1024
1444
  pipeline.push({ $limit: limit + 1 });
1025
- const rows = await this.execAggregate(pipeline);
1445
+ // Projection goes last; the sort field and `_id` are force-included for
1446
+ // cursor creation and stripped again from the returned rows.
1447
+ const { projection, injectId, injectSort } = this.buildCursorProjection(sortField);
1448
+ if (projection)
1449
+ pipeline.push({ $project: projection });
1450
+ const rows = await this.wrapTimed(() => this.execAggregate(pipeline), 1, limit, pipeline);
1026
1451
  const hasNextPage = rows.length > limit;
1027
- const data = (hasNextPage ? rows.slice(0, limit) : rows);
1028
- const nextCursor = hasNextPage
1029
- ? this.encodeCursor(data[data.length - 1], sortField)
1452
+ const pageRows = hasNextPage ? rows.slice(0, limit) : rows;
1453
+ const nextCursor = hasNextPage && pageRows.length > 0
1454
+ ? this.encodeCursor(pageRows[pageRows.length - 1], sortField, sortDir)
1030
1455
  : null;
1031
- return { data, limit, nextCursor, hasNextPage };
1456
+ if (injectId || injectSort) {
1457
+ for (const row of pageRows) {
1458
+ if (injectId)
1459
+ delete row._id;
1460
+ if (injectSort)
1461
+ deletePath(row, sortField);
1462
+ }
1463
+ }
1464
+ return { data: pageRows, limit, nextCursor, hasNextPage };
1032
1465
  }
1033
1466
  /**
1034
1467
  * Runs the built pipeline through Mongoose's .explain() for debugging
@@ -1041,13 +1474,14 @@ class QueryAggregate {
1041
1474
  }
1042
1475
  /** Convenience wrapper over addStage() for a computed $addFields entry, e.g. .computeField('margin', { $subtract: ['$price', '$cost'] }). */
1043
1476
  computeField(name, expression) {
1477
+ assertFieldPath(name, 'computeField');
1044
1478
  return this.addStage({
1045
1479
  $addFields: { [name]: expression },
1046
1480
  });
1047
1481
  }
1048
1482
  /** Convenience server-side condition excluding soft-deleted docs (matches both `null` and a missing field, per MongoDB equality semantics). Not client-overridable. */
1049
1483
  excludeSoftDeleted(field = 'deletedAt') {
1050
- this._serverConditions[field] = null;
1484
+ this._serverConditions.push({ [field]: null });
1051
1485
  return this;
1052
1486
  }
1053
1487
  /** Applies .where(conditions) only when `condition` is truthy — avoids scattering if-statements around chained builder calls. */
@@ -1068,7 +1502,7 @@ class QueryAggregate {
1068
1502
  ? new Set(this._objectIdFieldsLookup)
1069
1503
  : null;
1070
1504
  copy._urlFilter = { ...this._urlFilter };
1071
- copy._serverConditions = { ...this._serverConditions };
1505
+ copy._serverConditions = [...this._serverConditions];
1072
1506
  copy._searchOr = [...this._searchOr];
1073
1507
  copy._sort = { ...this._sort };
1074
1508
  copy._projection = this._projection ? { ...this._projection } : null;
@@ -1076,12 +1510,110 @@ class QueryAggregate {
1076
1510
  ? { ...this._defaultProjection }
1077
1511
  : null;
1078
1512
  copy._stages = [...this._stages];
1513
+ copy._joinAliases = new Set(this._joinAliases);
1514
+ copy._postJoinIndex = this._postJoinIndex;
1079
1515
  return copy;
1080
1516
  }
1081
1517
  /** Returns the fully-built pipeline without executing it — for logging, snapshot tests, or sanity-checking what will actually run. */
1082
1518
  debugPipeline() {
1083
1519
  return this.buildBasePipeline();
1084
1520
  }
1521
+ // ── Cursor internals ──────────────────────────────────────────────────────
1522
+ buildCursorProjection(sortField) {
1523
+ const proj = this._projection;
1524
+ if (!proj)
1525
+ return { projection: null, injectId: false, injectSort: false };
1526
+ const p = { ...proj };
1527
+ let injectId = false;
1528
+ let injectSort = false;
1529
+ const needSort = sortField !== '_id';
1530
+ const isInclusion = Object.keys(p).some((k) => k !== '_id' && p[k] === 1);
1531
+ const conflict = () => new QueryAggregateValidationError(`paginateCursor: projection conflicts with sort field "${sortField}" (a parent/child path of it is projected)`);
1532
+ if (p._id === 0) {
1533
+ delete p._id;
1534
+ injectId = true;
1535
+ }
1536
+ if (needSort) {
1537
+ if (isInclusion) {
1538
+ const covered = Object.keys(p).some((k) => p[k] === 1 && (k === sortField || sortField.startsWith(`${k}.`)));
1539
+ if (!covered) {
1540
+ if (Object.keys(p).some((k) => k.startsWith(`${sortField}.`)))
1541
+ throw conflict();
1542
+ p[sortField] = 1;
1543
+ injectSort = true;
1544
+ }
1545
+ }
1546
+ else {
1547
+ if (p[sortField] === 0) {
1548
+ delete p[sortField];
1549
+ injectSort = true;
1550
+ }
1551
+ else if (Object.keys(p).some((k) => sortField.startsWith(`${k}.`))) {
1552
+ throw conflict();
1553
+ }
1554
+ }
1555
+ }
1556
+ return {
1557
+ projection: Object.keys(p).length > 0 ? p : null,
1558
+ injectId,
1559
+ injectSort,
1560
+ };
1561
+ }
1562
+ /** Encodes a keyset cursor from a result row: the sort field's value plus `_id` as a stable tiebreaker. */
1563
+ encodeCursor(doc, sortField, sortDir) {
1564
+ const payload = {
1565
+ f: sortField,
1566
+ d: sortDir,
1567
+ v: encodeTyped(getByPath(doc, sortField)),
1568
+ id: encodeTyped(doc._id),
1569
+ };
1570
+ return Buffer.from(JSON.stringify(payload)).toString('base64url');
1571
+ }
1572
+ /** Decodes and strictly validates a cursor, restoring Date/ObjectId typing so comparisons stay type-correct. */
1573
+ decodeCursor(cursor, sortField, sortDir) {
1574
+ const bad = () => new QueryAggregateValidationError('paginateCursor: invalid cursor');
1575
+ if (typeof cursor !== 'string' || cursor.length > MAX_CURSOR_LENGTH)
1576
+ throw bad();
1577
+ let parsed;
1578
+ try {
1579
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
1580
+ }
1581
+ catch {
1582
+ throw bad();
1583
+ }
1584
+ if (!isPlainObject(parsed))
1585
+ throw bad();
1586
+ const c = parsed;
1587
+ if (c.f !== sortField || c.d !== sortDir) {
1588
+ throw new QueryAggregateValidationError('paginateCursor: cursor does not match the current sort');
1589
+ }
1590
+ return { v: decodeTyped(c.v), id: decodeTyped(c.id) };
1591
+ }
1592
+ /** $match selecting every row strictly after the cursor row in (sortField, _id) order — null/missing-safe. */
1593
+ buildCursorMatch(sortField, sortDir, v, id) {
1594
+ const cmp = sortDir === -1 ? '$lt' : '$gt';
1595
+ const tie = { _id: { [cmp]: id } };
1596
+ if (sortField === '_id')
1597
+ return { _id: { [cmp]: id } };
1598
+ // MongoDB sorts null/missing first ascending, last descending.
1599
+ if (v === null) {
1600
+ return sortDir === 1
1601
+ ? {
1602
+ $or: [
1603
+ { [sortField]: { $ne: null } },
1604
+ { [sortField]: null, ...tie },
1605
+ ],
1606
+ }
1607
+ : { [sortField]: null, ...tie };
1608
+ }
1609
+ const or = [
1610
+ { [sortField]: { [cmp]: v } },
1611
+ { [sortField]: v, ...tie },
1612
+ ];
1613
+ if (sortDir === -1)
1614
+ or.push({ [sortField]: null });
1615
+ return { $or: or };
1616
+ }
1085
1617
  }
1086
1618
  exports.QueryAggregate = QueryAggregate;
1087
1619
  exports.default = QueryAggregate;