@classytic/mongokit 3.40.0 → 3.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +71 -0
  2. package/dist/{PaginationEngine-D-P19Y9m.d.mts → PaginationEngine-CRHyuUtw.d.mts} +17 -3
  3. package/dist/{PaginationEngine-Dvl8jcRY.mjs → PaginationEngine-DZnkbSrr.mjs} +299 -140
  4. package/dist/{Repository-BMgPSkqZ.mjs → Repository-DlhPbXlG.mjs} +571 -175
  5. package/dist/{Repository-CR8Y9g2E.d.mts → Repository-pnLw1rG5.d.mts} +57 -16
  6. package/dist/actions/index.d.mts +1 -1
  7. package/dist/actions/index.mjs +1 -1
  8. package/dist/adapter/index.mjs +1 -1
  9. package/dist/{adapter-BrVfPFSW.mjs → adapter-CkMoMF83.mjs} +1 -1
  10. package/dist/ai/index.d.mts +1 -1
  11. package/dist/better-auth/index.mjs +2 -2
  12. package/dist/{create-repository-CAle1MSU.d.mts → create-repository-BUx9vfG9.d.mts} +5 -5
  13. package/dist/{create-repository-BzBUMvd1.mjs → create-repository-Bg0H5rte.mjs} +2 -2
  14. package/dist/{index-CmjNyulu.d.mts → index-SYF8N28D.d.mts} +37 -19
  15. package/dist/index.d.mts +69 -15
  16. package/dist/index.mjs +57 -11
  17. package/dist/join-scope-DSAznE8E.mjs +168 -0
  18. package/dist/{mongooseToJsonSchema-waUVQwK4.mjs → mongooseToJsonSchema-C3k4ide0.mjs} +5 -1
  19. package/dist/{multi-tenant.plugin-CBgCo9im.d.mts → multi-tenant.plugin-a3UhQARj.d.mts} +2 -2
  20. package/dist/{operations-CrRIoc8Z.d.mts → operations-XiFgG5US.d.mts} +36 -13
  21. package/dist/outbox/index.d.mts +1 -1
  22. package/dist/outbox/index.mjs +1 -1
  23. package/dist/pagination/PaginationEngine.d.mts +2 -2
  24. package/dist/pagination/PaginationEngine.mjs +1 -1
  25. package/dist/pagination/utils/limits.d.mts +1 -1
  26. package/dist/{pagination-BpIv2bdS.d.mts → pagination-D6psses0.d.mts} +116 -13
  27. package/dist/{plugin-options-Zk46lD6F.d.mts → plugin-options-CRhIvSzx.d.mts} +2 -2
  28. package/dist/plugins/index.d.mts +3 -3
  29. package/dist/plugins/index.mjs +2 -2
  30. package/dist/query-defaults-BxUcSOoF.mjs +208 -0
  31. package/dist/read-model/index.d.mts +66 -0
  32. package/dist/read-model/index.mjs +193 -0
  33. package/dist/{repository-odl03582.d.mts → repository-DNHfjAZX.d.mts} +16 -2
  34. package/dist/sync/index.d.mts +15 -2
  35. package/dist/sync/index.mjs +38 -1
  36. package/dist/testkit/index.d.mts +40 -3
  37. package/dist/testkit/index.mjs +113 -2
  38. package/dist/{timestamp.plugin-DF0gJB6p.mjs → timestamp.plugin-DvZlnKEc.mjs} +50 -31
  39. package/dist/{to-plain-k7SjNlSS.d.mts → to-plain-CjgEInWV.d.mts} +2 -2
  40. package/dist/{transaction-B5L9glO0.mjs → transaction-DmiB4k2P.mjs} +155 -6
  41. package/dist/{update-DG0fCwRJ.mjs → update-WgeAUJ_I.mjs} +44 -22
  42. package/dist/utils/index.d.mts +1 -1
  43. package/dist/utils/index.mjs +1 -1
  44. package/dist/{validation-chain.plugin-DYp9E7K2.d.mts → validation-chain.plugin-CTcNJCmV.d.mts} +4 -4
  45. package/dist/{validation-chain.plugin-BLY2gLEk.mjs → validation-chain.plugin-D1WsGCYr.mjs} +15 -3
  46. package/package.json +10 -5
@@ -1,8 +1,8 @@
1
- import { _ as UpdateOptions, a as CreateOptions, b as LookupOptions, c as FindOneAndUpdateOptions, d as LookupPopulateResult, g as UpdateManyResult, h as SessionOptions, m as ReadOptions, o as DeleteManyResult, p as OperationOptions, r as CacheableOptions, s as DeleteResult, t as AggregateOptions, u as LookupPopulateOptions, v as WithTransactionOptions, y as LookupBuilder } from "./operations-CrRIoc8Z.mjs";
2
- import { _ as PopulateSpec, g as ObjectId, i as CountStrategy, r as CollationOptions, t as AggregatePaginationOptions, u as PaginationConfig, v as ReadPreferenceType, x as SortSpec$1, y as SelectSpec } from "./pagination-BpIv2bdS.mjs";
3
- import { _ as RepositoryOptions, d as PluginType, f as PrioritizedHook, o as Middleware, p as RepositoryContext } from "./repository-odl03582.mjs";
4
- import { t as PaginationEngine } from "./PaginationEngine-D-P19Y9m.mjs";
5
- import { AggPaginationRequest, AggRequest, AggResult, ArchiveOptions, ArchiveResult, ArchiveSink, ChangeEvent, FilterInput, KeysetAggPaginationResult, QueryOptions, RepoCapabilities, RepositoryBase, TenantPurgeOptions, TenantPurgeResult, TenantPurgeStrategy, WatchOptions } from "@classytic/repo-core/repository";
1
+ import { S as LookupOptions, _ as SessionOptions, b as WithTransactionOptions, c as DeleteResult, f as LookupPopulateOptions, g as ReadOptions, h as OperationOptions, i as CacheableOptions, l as FindOneAndUpdateOptions, n as AggregateOptions, o as CreateOptions, p as LookupPopulateResult, s as DeleteManyResult, t as AggregateCallOptions, u as GetByIdsOptions, v as UpdateManyResult, x as LookupBuilder, y as UpdateOptions } from "./operations-XiFgG5US.mjs";
2
+ import { A as ObjectId, F as SortSpec$1, M as ReadPreferenceType, N as SelectSpec, c as MongokitPageExtras, i as CountStrategy, j as PopulateSpec, r as CollationOptions, t as AggregatePaginationOptions, u as PaginationConfig } from "./pagination-D6psses0.mjs";
3
+ import { _ as RepositoryOptions, d as PluginType, f as PrioritizedHook, o as Middleware, p as RepositoryContext } from "./repository-DNHfjAZX.mjs";
4
+ import { n as PaginationEngine } from "./PaginationEngine-CRHyuUtw.mjs";
5
+ import { AggPaginationRequest, AggRequest, AggResult, ArchiveOptions, ArchiveResult, ArchiveSink, BulkUpsertOptions, BulkUpsertResult, ChangeEvent, FilterInput, KeysetAggPaginationResult, QueryOptions, RepoCapabilities, RepositoryBase, TenantPurgeOptions, TenantPurgeResult, TenantPurgeStrategy, WatchOptions } from "@classytic/repo-core/repository";
6
6
  import { ClientSession, Expression, Model, PipelineStage, PopulateOptions } from "mongoose";
7
7
  import { Filter } from "@classytic/repo-core/filter";
8
8
  import { RepositoryCacheHandle } from "@classytic/repo-core/cache";
@@ -622,6 +622,8 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
622
622
  * {@link ID_ADDRESSED_OPERATIONS}.
623
623
  */
624
624
  private readonly _guardIdAddressed;
625
+ /** This repository's own `queryDefaults` / `aggregateDefaults` (deployment ones fill the gaps). */
626
+ private readonly _queryDefaults;
625
627
  constructor(Model: Model<TDoc, any, any, any>, plugins?: PluginType[], paginationConfig?: PaginationConfig, options?: RepositoryOptions);
626
628
  /**
627
629
  * Live read-through view of the hook engine's listener registry.
@@ -772,6 +774,12 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
772
774
  * `_buildContext` inputs), so every op routed through `_runOp` — and the
773
775
  * inline-try methods that call this directly — honors them uniformly.
774
776
  */
777
+ /** One command's time bound and concerns: per call, then this repository, then the deployment. */
778
+ private _opts;
779
+ /** How an IR request runs: per-call hints, then this repository's and the deployment's defaults. */
780
+ private _aggRun;
781
+ /** Scope every join in `pipeline` under its owning collection's policy (see `join-scope.ts`). */
782
+ private _scopeJoins;
775
783
  private _withResilience;
776
784
  /**
777
785
  * Create single document
@@ -805,16 +813,15 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
805
813
  * const byId = await repo.getByIds(offerIds, ctx);
806
814
  * const doc = byId.get(offerId); // O(1); undefined if not found
807
815
  *
808
- * Sizing: there is no library-imposed cap — the bounds are MongoDB's (the
809
- * `$in` array must fit the 16 MB query document; `$in` on an indexed field
810
- * is n point-lookups). Keep batches ≤ ~10k ids per call and chunk beyond
811
- * that. Don't exclude the id field via `select` — result keys derive from
812
- * it.
816
+ * Chunking: ids are split into `$in` slices of `chunkSize` (default `DEFAULT_ID_CHUNK`), one
817
+ * command each — sequential inside a session (a transaction runs one operation at a time),
818
+ * at most `concurrency` (default 4) in flight outside one. `preserveOrder: true` returns an
819
+ * array aligned with `ids` (`undefined` for a miss). Don't exclude the id field via `select`.
813
820
  */
814
- getByIds(ids: ReadonlyArray<string | ObjectId>, options?: OperationOptions & {
815
- sort?: SortSpec$1 | string;
816
- limit?: number;
817
- }): Promise<Map<string, TDoc>>;
821
+ getByIds(ids: ReadonlyArray<string | ObjectId>, options: GetByIdsOptions & {
822
+ preserveOrder: true;
823
+ }): Promise<Array<TDoc | undefined>>;
824
+ getByIds(ids: ReadonlyArray<string | ObjectId>, options?: GetByIdsOptions): Promise<Map<string, TDoc>>;
818
825
  /**
819
826
  * Get single document by query
820
827
  */
@@ -844,6 +851,31 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
844
851
  sort?: SortSpec$1 | string;
845
852
  limit?: number;
846
853
  }): Promise<TDoc[]>;
854
+ /**
855
+ * The keyset cursor `getAll({ sort, filters, mode: 'keyset' })` would mint for `row`, under the
856
+ * same policy scope, so a page resumes AFTER it. For composing keyset walks (repo-core
857
+ * `mergeKeysetPages` via `keysetSource`), where the last CONSUMED row is not a page's last row.
858
+ */
859
+ keysetCursor(row: unknown, options: ReadOptions & {
860
+ sort: SortSpec$1 | string;
861
+ filters?: Record<string, unknown>;
862
+ collation?: CollationOptions;
863
+ }): Promise<string>;
864
+ /**
865
+ * Resumable keyset batches over `_id`: each batch is ONE bounded `find` (no long-lived server
866
+ * cursor, so no cursor timeout and no CSOT lifetime budget), memory is one batch, and every
867
+ * batch carries a `checkpoint`. Pass a checkpoint back as `after` to resume: rows written
868
+ * behind it are not revisited, rows ahead of it are reached. A checkpoint is bound to the
869
+ * collection, the post-policy filter (tenant included) and is refused elsewhere.
870
+ */
871
+ iterate(filter?: Record<string, unknown>, options?: ReadOptions & {
872
+ after?: string;
873
+ batchSize?: number;
874
+ select?: SelectSpec;
875
+ }): AsyncIterableIterator<{
876
+ docs: TDoc[];
877
+ checkpoint: string;
878
+ }>;
847
879
  /**
848
880
  * Streaming reads — async iterator over data, suitable for migrations,
849
881
  * backfills, schema audits, and any once-a-quarter "touch every row"
@@ -1562,6 +1594,13 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
1562
1594
  archiveByFilter(filter: Record<string, unknown> | Filter, sink: ArchiveSink<TDoc>, options?: ArchiveOptions & {
1563
1595
  session?: ClientSession;
1564
1596
  }): Promise<ArchiveResult>;
1597
+ /**
1598
+ * Many keyed upserts in ONE command with an exact per-row outcome (repo-core `bulkUpsert` IR).
1599
+ * Sub-ops pass through the `before:bulkUpsert` policy hooks (tenant, soft-delete) like bulkWrite
1600
+ * sub-ops. Refused unless a unique index is pinned by the key plus the policy scope. Needs
1601
+ * MongoDB 8.0 (client bulkWrite with verbose results).
1602
+ */
1603
+ bulkUpsert(rows: readonly Record<string, unknown>[], options: BulkUpsertOptions): Promise<BulkUpsertResult>;
1565
1604
  /**
1566
1605
  * Kit-native aggregation pipeline — takes a MongoDB stage array and
1567
1606
  * returns the raw pipeline output. Use this for `$lookup`, `$unwind`,
@@ -1601,7 +1640,7 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
1601
1640
  * Policy hooks (multi-tenant, soft-delete) inject context.filters
1602
1641
  * which are prepended as a `$match` stage.
1603
1642
  */
1604
- aggregatePipelinePaginate(options?: AggregatePaginationOptions): Promise<AggregatePaginationResult<TDoc>>;
1643
+ aggregatePipelinePaginate(options?: AggregatePaginationOptions): Promise<AggregatePaginationResult<TDoc, MongokitPageExtras>>;
1605
1644
  /**
1606
1645
  * Portable aggregation. Compiles the repo-core `AggRequest` IR to
1607
1646
  * `[{$match}, {$group}, {$addFields}, {$project}, {$match}, {$sort},
@@ -1624,7 +1663,9 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
1624
1663
  * `context.filter`, which is merged into the pre-aggregate `$match`
1625
1664
  * before compilation.
1626
1665
  */
1627
- aggregate<TRow extends Record<string, unknown> = Record<string, unknown>>(req: AggRequest, options?: QueryOptions): Promise<AggResult<TRow>>;
1666
+ aggregate<TRow extends Record<string, unknown> = Record<string, unknown>>(req: AggRequest, options?: QueryOptions & AggregateCallOptions): Promise<AggResult<TRow> & {
1667
+ plan?: unknown;
1668
+ }>;
1628
1669
  /**
1629
1670
  * Invalidate every aggregate-cache entry tagged with ANY of the
1630
1671
  * given tags. Delegates to the unified cache plugin's handle
@@ -1,2 +1,2 @@
1
- import { c as create_d_exports, i as delete_d_exports, n as update_d_exports, r as read_d_exports, u as aggregate_d_exports } from "../index-CmjNyulu.mjs";
1
+ import { c as create_d_exports, i as delete_d_exports, n as update_d_exports, r as read_d_exports, u as aggregate_d_exports } from "../index-SYF8N28D.mjs";
2
2
  export { aggregate_d_exports as aggregate, create_d_exports as create, delete_d_exports as deleteActions, read_d_exports as read, update_d_exports as update };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
- import { S as create_exports, i as update_exports, m as aggregate_exports, p as delete_exports, u as read_exports } from "../update-DG0fCwRJ.mjs";
2
+ import { S as create_exports, i as update_exports, m as aggregate_exports, p as delete_exports, u as read_exports } from "../update-WgeAUJ_I.mjs";
3
3
  //#region src/actions/index.ts
4
4
  var actions_exports = /* @__PURE__ */ __exportAll({
5
5
  aggregate: () => aggregate_exports,
@@ -1,2 +1,2 @@
1
- import { n as createMongooseAdapter, r as isMongooseModel, t as MongooseAdapter } from "../adapter-BrVfPFSW.mjs";
1
+ import { n as createMongooseAdapter, r as isMongooseModel, t as MongooseAdapter } from "../adapter-CkMoMF83.mjs";
2
2
  export { MongooseAdapter, createMongooseAdapter, isMongooseModel };
@@ -1,5 +1,5 @@
1
1
  import { n as warn } from "./logger-K7dPmu2U.mjs";
2
- import { t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-waUVQwK4.mjs";
2
+ import { t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-C3k4ide0.mjs";
3
3
  import { matchesRecordFilter } from "@classytic/repo-core/filter";
4
4
  import { mergeFieldRuleConstraints } from "@classytic/repo-core/schema";
5
5
  import { asRepositoryLike, isRepository } from "@classytic/repo-core/adapter";
@@ -1,4 +1,4 @@
1
- import { l as Plugin } from "../repository-odl03582.mjs";
1
+ import { l as Plugin } from "../repository-DNHfjAZX.mjs";
2
2
  import { PipelineStage } from "mongoose";
3
3
  //#region src/ai/types.d.ts
4
4
  /** Supported similarity metrics for vector search */
@@ -1,5 +1,5 @@
1
- import { n as Repository } from "../Repository-BMgPSkqZ.mjs";
2
- import { n as createMongooseAdapter } from "../adapter-BrVfPFSW.mjs";
1
+ import { n as Repository } from "../Repository-DlhPbXlG.mjs";
2
+ import { n as createMongooseAdapter } from "../adapter-CkMoMF83.mjs";
3
3
  import { asReadOnlyRepo } from "@classytic/repo-core/repository";
4
4
  import { pluralizeBetterAuthCollection, resolveBetterAuthCollections } from "@classytic/repo-core/better-auth";
5
5
  //#region src/better-auth/index.ts
@@ -1,8 +1,8 @@
1
- import { u as PaginationConfig } from "./pagination-BpIv2bdS.mjs";
2
- import { _ as RepositoryOptions, d as PluginType } from "./repository-odl03582.mjs";
3
- import { D as AuditTrailOptions, i as CustomIdOptions, t as MultiTenantOptions, y as RepositoryCachePluginOptions } from "./multi-tenant.plugin-CBgCo9im.mjs";
4
- import { r as Repository } from "./Repository-CR8Y9g2E.mjs";
5
- import { i as Logger, o as SoftDeleteOptions } from "./plugin-options-Zk46lD6F.mjs";
1
+ import { u as PaginationConfig } from "./pagination-D6psses0.mjs";
2
+ import { _ as RepositoryOptions, d as PluginType } from "./repository-DNHfjAZX.mjs";
3
+ import { D as AuditTrailOptions, i as CustomIdOptions, t as MultiTenantOptions, y as RepositoryCachePluginOptions } from "./multi-tenant.plugin-a3UhQARj.mjs";
4
+ import { r as Repository } from "./Repository-pnLw1rG5.mjs";
5
+ import { i as Logger, o as SoftDeleteOptions } from "./plugin-options-CRhIvSzx.mjs";
6
6
  import { Model } from "mongoose";
7
7
  //#region src/create-repository.d.ts
8
8
  /**
@@ -1,5 +1,5 @@
1
- import { n as Repository } from "./Repository-BMgPSkqZ.mjs";
2
- import { b as auditLogPlugin, g as cachePlugin, i as multiTenantPlugin, l as customIdPlugin, n as softDeletePlugin, t as timestampPlugin, v as auditTrailPlugin } from "./timestamp.plugin-DF0gJB6p.mjs";
1
+ import { n as Repository } from "./Repository-DlhPbXlG.mjs";
2
+ import { b as auditLogPlugin, g as cachePlugin, i as multiTenantPlugin, l as customIdPlugin, n as softDeletePlugin, t as timestampPlugin, v as auditTrailPlugin } from "./timestamp.plugin-DvZlnKEc.mjs";
3
3
  import { n as batchOperationsPlugin, t as methodRegistryPlugin } from "./method-registry.plugin-C63pGn1d.mjs";
4
4
  //#region src/create-repository.ts
5
5
  function isLoggerAudit(value) {
@@ -1,5 +1,5 @@
1
- import { _ as UpdateOptions, a as CreateOptions, b as LookupOptions, c as FindOneAndUpdateOptions, f as MinMaxResult, g as UpdateManyResult, l as GroupResult, p as OperationOptions, s as DeleteResult } from "./operations-CrRIoc8Z.mjs";
2
- import { _ as PopulateSpec, g as ObjectId, p as AnyDocument, v as ReadPreferenceType, x as SortSpec, y as SelectSpec } from "./pagination-BpIv2bdS.mjs";
1
+ import { S as LookupOptions, c as DeleteResult, d as GroupResult, h as OperationOptions, l as FindOneAndUpdateOptions, m as MinMaxResult, o as CreateOptions, v as UpdateManyResult, y as UpdateOptions } from "./operations-XiFgG5US.mjs";
2
+ import { A as ObjectId, D as AnyDocument, F as SortSpec, N as SelectSpec, j as PopulateSpec, y as ResolvedQueryOptions } from "./pagination-D6psses0.mjs";
3
3
  import { p as UpdateWithValidationResult } from "./type-utils-CLzRFtIA.mjs";
4
4
  import { Model, PipelineStage } from "mongoose";
5
5
  declare namespace aggregate_d_exports {
@@ -79,7 +79,7 @@ declare function facet<TResult = Record<string, unknown[]>>(Model: Model<any>, f
79
79
  */
80
80
  declare function distinct<T = unknown>(Model: Model<any>, field: string, query?: Record<string, unknown>, options?: {
81
81
  session?: unknown;
82
- readPreference?: string;
82
+ queryOptions?: ResolvedQueryOptions;
83
83
  }): Promise<T[]>;
84
84
  /**
85
85
  * Calculate sum
@@ -102,10 +102,14 @@ declare function minMax(Model: Model<any>, field: string, query?: Record<string,
102
102
  declare namespace create_d_exports {
103
103
  export { CreateManyFailure, CreateManyPartial, CreateManyPartialError, create, createDefault, createMany, isCreateManyPartialError, upsert };
104
104
  }
105
+ /** Action options: the repository resolves the write concern once and passes it here. */
106
+ type ActionCreateOptions = CreateOptions & {
107
+ queryOptions?: ResolvedQueryOptions;
108
+ };
105
109
  /**
106
110
  * Create single document
107
111
  */
108
- declare function create<TDoc = AnyDocument>(Model: Model<TDoc>, data: Record<string, unknown>, options?: CreateOptions): Promise<TDoc>;
112
+ declare function create<TDoc = AnyDocument>(Model: Model<TDoc>, data: Record<string, unknown>, options?: ActionCreateOptions): Promise<TDoc>;
109
113
  /**
110
114
  * One rejected input, keyed by its position in the array that was passed in.
111
115
  *
@@ -159,7 +163,7 @@ declare function isCreateManyPartialError<TDoc = AnyDocument>(err: unknown): err
159
163
  * `failed`, or to reconcile — and prefer a unique index or an idempotency key
160
164
  * for anything that will be retried automatically.
161
165
  */
162
- declare function createMany<TDoc = AnyDocument>(Model: Model<TDoc>, dataArray: Record<string, unknown>[], options?: CreateOptions): Promise<TDoc[]>;
166
+ declare function createMany<TDoc = AnyDocument>(Model: Model<TDoc>, dataArray: Record<string, unknown>[], options?: ActionCreateOptions): Promise<TDoc[]>;
163
167
  /**
164
168
  * Create with defaults (useful for initialization)
165
169
  */
@@ -181,6 +185,7 @@ declare namespace delete_d_exports {
181
185
  declare function deleteById<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, options?: {
182
186
  session?: unknown;
183
187
  query?: Record<string, unknown>;
188
+ queryOptions?: ResolvedQueryOptions;
184
189
  }): Promise<DeleteResult | null>;
185
190
  /**
186
191
  * Delete many documents. Always returns a {@link DeleteResult} (never
@@ -196,6 +201,7 @@ declare function deleteMany<TDoc = AnyDocument>(Model: Model<TDoc>, query: Recor
196
201
  declare function deleteByQuery(Model: Model<any>, query: Record<string, unknown>, options?: {
197
202
  session?: unknown;
198
203
  throwOnNotFound?: boolean;
204
+ queryOptions?: ResolvedQueryOptions;
199
205
  }): Promise<DeleteResult | null>;
200
206
  /**
201
207
  * Soft delete (set deleted flag). Returns `null` on miss for parity with
@@ -215,6 +221,10 @@ declare function restore<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | Ob
215
221
  declare namespace read_d_exports {
216
222
  export { count, exists, getAll, getById, getByQuery, getOrCreate, tryGetByQuery };
217
223
  }
224
+ /** Action options: the repository resolves time bound / concerns once and passes them here. */
225
+ type ActionReadOptions = OperationOptions & {
226
+ queryOptions?: ResolvedQueryOptions;
227
+ };
218
228
  /**
219
229
  * Get document by ID
220
230
  *
@@ -224,7 +234,7 @@ declare namespace read_d_exports {
224
234
  * @returns Document or null
225
235
  * @throws Error if document not found and throwOnNotFound is true
226
236
  */
227
- declare function getById<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, options?: OperationOptions): Promise<TDoc | null>;
237
+ declare function getById<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, options?: ActionReadOptions): Promise<TDoc | null>;
228
238
  /**
229
239
  * Get document by query
230
240
  *
@@ -234,13 +244,13 @@ declare function getById<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | Ob
234
244
  * @returns Document or null
235
245
  * @throws Error if document not found and throwOnNotFound is true
236
246
  */
237
- declare function getByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, options?: OperationOptions & {
247
+ declare function getByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, options?: ActionReadOptions & {
238
248
  sort?: SortSpec;
239
249
  }): Promise<TDoc | null>;
240
250
  /**
241
251
  * Get document by query without throwing (returns null if not found)
242
252
  */
243
- declare function tryGetByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, options?: Omit<OperationOptions, 'throwOnNotFound'>): Promise<TDoc | null>;
253
+ declare function tryGetByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, options?: Omit<ActionReadOptions, 'throwOnNotFound'>): Promise<TDoc | null>;
244
254
  /**
245
255
  * Get all documents (basic query without pagination)
246
256
  * For pagination, use Repository.paginate() or Repository.stream()
@@ -253,7 +263,7 @@ declare function getAll<TDoc = AnyDocument>(Model: Model<TDoc>, query?: Record<s
253
263
  skip?: number;
254
264
  lean?: boolean;
255
265
  session?: unknown;
256
- readPreference?: ReadPreferenceType;
266
+ queryOptions?: ResolvedQueryOptions;
257
267
  }): Promise<TDoc[]>;
258
268
  /**
259
269
  * Get or create document (atomic upsert).
@@ -282,29 +292,36 @@ declare function getOrCreate<TDoc = AnyDocument>(Model: Model<TDoc>, query: Reco
282
292
  */
283
293
  declare function count<TDoc = AnyDocument>(Model: Model<TDoc>, query?: Record<string, unknown>, options?: {
284
294
  session?: unknown;
285
- readPreference?: ReadPreferenceType;
295
+ queryOptions?: ResolvedQueryOptions;
286
296
  }): Promise<number>;
287
297
  /**
288
298
  * Check if document exists
289
299
  */
290
300
  declare function exists<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, options?: {
291
301
  session?: unknown;
292
- readPreference?: ReadPreferenceType;
302
+ queryOptions?: ResolvedQueryOptions;
293
303
  }): Promise<{
294
304
  _id: unknown;
295
305
  } | null>;
296
306
  declare namespace update_d_exports {
297
307
  export { findOneAndUpdate, increment, pullFromArray, pushToArray, update, updateByQuery, updateMany, updateWithConstraints, updateWithValidation };
298
308
  }
309
+ /** Action options: the repository resolves time bound / write concern once and passes them here. */
310
+ type ActionUpdateOptions = UpdateOptions & {
311
+ queryOptions?: ResolvedQueryOptions;
312
+ };
313
+ type ActionFindOneAndUpdateOptions = FindOneAndUpdateOptions & {
314
+ queryOptions?: ResolvedQueryOptions;
315
+ };
299
316
  /**
300
317
  * Update by ID
301
318
  */
302
- declare function update<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, options?: UpdateOptions): Promise<TDoc | null>;
319
+ declare function update<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, options?: ActionUpdateOptions): Promise<TDoc | null>;
303
320
  /**
304
321
  * Update with query constraints (optimized)
305
322
  * Returns null if constraints not met (not an error)
306
323
  */
307
- declare function updateWithConstraints<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, constraints?: Record<string, unknown>, options?: UpdateOptions): Promise<TDoc | null>;
324
+ declare function updateWithConstraints<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, constraints?: Record<string, unknown>, options?: ActionUpdateOptions): Promise<TDoc | null>;
308
325
  /**
309
326
  * Validation options for smart update
310
327
  */
@@ -323,7 +340,7 @@ interface ValidationOptions {
323
340
  * Update with validation (smart optimization)
324
341
  * 1-query on success, 2-queries for detailed errors
325
342
  */
326
- declare function updateWithValidation<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, validationOptions?: ValidationOptions, options?: UpdateOptions): Promise<UpdateWithValidationResult<TDoc>>;
343
+ declare function updateWithValidation<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, data: Record<string, unknown>, validationOptions?: ValidationOptions, options?: ActionUpdateOptions): Promise<UpdateWithValidationResult<TDoc>>;
327
344
  /**
328
345
  * Update many documents
329
346
  */
@@ -331,11 +348,12 @@ declare function updateMany(Model: Model<unknown>, query: Record<string, unknown
331
348
  session?: unknown;
332
349
  updatePipeline?: boolean;
333
350
  arrayFilters?: Record<string, unknown>[];
351
+ queryOptions?: ResolvedQueryOptions;
334
352
  }): Promise<UpdateManyResult>;
335
353
  /**
336
354
  * Update by query
337
355
  */
338
- declare function updateByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, data: Record<string, unknown>, options?: UpdateOptions): Promise<TDoc | null>;
356
+ declare function updateByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Record<string, unknown>, data: Record<string, unknown>, options?: ActionUpdateOptions): Promise<TDoc | null>;
339
357
  /**
340
358
  * Atomic findOneAndUpdate primitive.
341
359
  *
@@ -343,19 +361,19 @@ declare function updateByQuery<TDoc = AnyDocument>(Model: Model<TDoc>, query: Re
343
361
  * matches and `upsert` is false. Used by outbox relays, distributed locks,
344
362
  * and workflow semaphores that need compare-and-set in a single round-trip.
345
363
  */
346
- declare function findOneAndUpdate<TDoc = AnyDocument>(Model: Model<TDoc>, filter: Record<string, unknown>, update: Record<string, unknown> | Record<string, unknown>[], options?: FindOneAndUpdateOptions): Promise<TDoc | null>;
364
+ declare function findOneAndUpdate<TDoc = AnyDocument>(Model: Model<TDoc>, filter: Record<string, unknown>, update: Record<string, unknown> | Record<string, unknown>[], options?: ActionFindOneAndUpdateOptions): Promise<TDoc | null>;
347
365
  /**
348
366
  * Increment field
349
367
  */
350
- declare function increment<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value?: number, options?: UpdateOptions): Promise<TDoc | null>;
368
+ declare function increment<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value?: number, options?: ActionUpdateOptions): Promise<TDoc | null>;
351
369
  /**
352
370
  * Push to array
353
371
  */
354
- declare function pushToArray<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value: unknown, options?: UpdateOptions): Promise<TDoc | null>;
372
+ declare function pushToArray<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value: unknown, options?: ActionUpdateOptions): Promise<TDoc | null>;
355
373
  /**
356
374
  * Pull from array
357
375
  */
358
- declare function pullFromArray<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value: unknown, options?: UpdateOptions): Promise<TDoc | null>;
376
+ declare function pullFromArray<TDoc = AnyDocument>(Model: Model<TDoc>, id: string | ObjectId, field: string, value: unknown, options?: ActionUpdateOptions): Promise<TDoc | null>;
359
377
  declare namespace index_d_exports {
360
378
  export { aggregate_d_exports as aggregate, create_d_exports as create, delete_d_exports as deleteActions, read_d_exports as read, update_d_exports as update };
361
379
  }
package/dist/index.d.mts CHANGED
@@ -1,19 +1,21 @@
1
- import { _ as UpdateOptions, a as CreateOptions, b as LookupOptions, c as FindOneAndUpdateOptions, d as LookupPopulateResult, f as MinMaxResult, g as UpdateManyResult, h as SessionOptions, i as ConvenientTransactionOptions, l as GroupResult, m as ReadOptions, n as CacheOperationOptions, p as OperationOptions, r as CacheableOptions, s as DeleteResult, t as AggregateOptions, u as LookupPopulateOptions, v as WithTransactionOptions, y as LookupBuilder } from "./operations-CrRIoc8Z.mjs";
2
- import { _ as PopulateSpec, a as CursorPayload, b as SortDirection, c as MongokitPageExtras, d as ValueType, f as CursorSecret, g as ObjectId, i as CountStrategy, l as OffsetPaginationOptions, m as AnyModel, n as BasePaginationOptions, o as DecodedCursor, p as AnyDocument, r as CollationOptions, s as KeysetPaginationOptions, t as AggregatePaginationOptions, u as PaginationConfig, v as ReadPreferenceType, x as SortSpec$1, y as SelectSpec } from "./pagination-BpIv2bdS.mjs";
3
- import { a as CreateManyFailure, l as isCreateManyPartialError, o as CreateManyPartial, s as CreateManyPartialError, t as index_d_exports } from "./index-CmjNyulu.mjs";
1
+ import { S as LookupOptions, _ as SessionOptions, a as ConvenientTransactionOptions, b as WithTransactionOptions, c as DeleteResult, d as GroupResult, f as LookupPopulateOptions, g as ReadOptions, h as OperationOptions, i as CacheableOptions, l as FindOneAndUpdateOptions, m as MinMaxResult, n as AggregateOptions, o as CreateOptions, p as LookupPopulateResult, r as CacheOperationOptions, t as AggregateCallOptions, u as GetByIdsOptions, v as UpdateManyResult, x as LookupBuilder, y as UpdateOptions } from "./operations-XiFgG5US.mjs";
2
+ import { A as ObjectId, C as configureQueryDefaults, D as AnyDocument, E as resolveQueryOptions, F as SortSpec$1, M as ReadPreferenceType, N as SelectSpec, O as AnyModel, P as SortDirection, S as configureAggregateDefaults, T as resetQueryDefaults, _ as QueryDefaults, a as CursorPayload, b as WriteConcernSpec, c as MongokitPageExtras, d as ValueType, f as CursorSecret, g as QUERY_DEFAULTS_ERROR_CODES, h as PerCallQueryOptions, i as CountStrategy, j as PopulateSpec, l as OffsetPaginationOptions, m as CommandKind, n as BasePaginationOptions, o as DecodedCursor, p as AggregateDefaults, r as CollationOptions, s as KeysetPaginationOptions, t as AggregatePaginationOptions, u as PaginationConfig, v as ReadConcernLevel, w as getQueryDefaults, x as assertQueryDefaultsConfigured, y as ResolvedQueryOptions } from "./pagination-D6psses0.mjs";
3
+ import { a as CreateManyFailure, l as isCreateManyPartialError, o as CreateManyPartial, s as CreateManyPartialError, t as index_d_exports } from "./index-SYF8N28D.mjs";
4
4
  import { a as InferRawDoc, c as NonNullableFields, d as Strict, f as UpdatePatch, i as InferDocument, l as PartialBy, n as DeepPartial, o as KeysOfType, p as UpdateWithValidationResult, r as DocField, s as MongoOperatorUpdate, t as CreateInput, u as RequiredBy } from "./type-utils-CLzRFtIA.mjs";
5
- import { S as RepositoryPluginName, _ as RepositoryOptions, a as HookMode, b as MONGOKIT_PLUGIN_NAMES, c as MinimalRepoView, d as PluginType, f as PrioritizedHook, g as RepositoryOperation, h as RepositoryInstance, i as EventPhase, l as Plugin, m as RepositoryEvent, n as EventHandlers, o as Middleware, p as RepositoryContext, r as EventPayload, s as MiddlewareContext, t as AllPluginMethods, u as PluginFunction, v as UserContext, x as MongoKitPluginName, y as WithPlugins } from "./repository-odl03582.mjs";
6
- import { A as EnsureAuditTrailReadyOptions, C as AuditQueryOptions, D as AuditTrailOptions, E as AuditTrailMode, M as ensureAuditTrailReady, O as AuditTrailQuery, S as AuditOperation, T as AuditTrailMethods, _ as CacheOptions, a as DateSequentialIdOptions, b as cachePlugin, c as SequentialIdOptions, d as ensureSequenceAtLeast, f as getNextSequence, g as CacheAdapter, h as sequentialId, i as CustomIdOptions, j as auditTrailPlugin, k as AuditTrailQueryOptions, l as customIdPlugin, m as readSequence, n as adminBypass, o as IdGenerator, p as prefixedId, r as multiTenantPlugin, s as PrefixedIdOptions, t as MultiTenantOptions, u as dateSequentialId, v as RepositoryCacheHandle, w as AuditQueryResult, x as AuditEntry, y as RepositoryCachePluginOptions } from "./multi-tenant.plugin-CBgCo9im.mjs";
7
- import { t as PaginationEngine } from "./PaginationEngine-D-P19Y9m.mjs";
8
- import { a as AggregationBuilder, c as ProjectionSpec, d as VectorSearchOptions, i as TransitionMachine, l as SortOrder, n as HOOK_PRIORITY, o as AggregationPlan, r as Repository, s as GroupSpec, t as GetAllParams, u as SortSpec } from "./Repository-CR8Y9g2E.mjs";
9
- import { a as SoftDeleteFilterMode, c as ValidationChainOptions, i as Logger, l as ValidatorDefinition, n as CascadeRelation, o as SoftDeleteOptions, r as FieldPreset, s as SoftDeleteRepository, t as CascadeOptions } from "./plugin-options-Zk46lD6F.mjs";
10
- import { n as CreateRepositoryConfig, r as createRepository, t as AuditConfig } from "./create-repository-CAle1MSU.mjs";
11
- import { A as IdempotencyStoreMethods, B as batchOperationsPlugin, C as LeaseMethods, D as ImmutableStatesPluginOptions, E as ImmutableClaimView, F as elasticSearchPlugin, G as aggregateHelpersPlugin, H as AppendOnlyPluginOptions, I as cascadePlugin, L as BatchOperationsMethods, M as idempotencyStorePlugin, N as fieldFilterPlugin, O as immutableStatesPlugin, P as ElasticSearchOptions, R as BulkWriteOptions, S as methodRegistryPlugin, T as leasePlugin, U as appendOnlyPlugin, V as auditLogPlugin, W as AggregateHelpersMethods, _ as OperationMetric, a as requireField, b as mongoOperationsPlugin, c as timestampPlugin, d as createTenantContext, f as SubdocumentMethods, g as ObservabilityOptions, h as softDeletePlugin, i as immutableField, j as IdempotencyStorePluginOptions, k as IdempotencyClaim, l as TenantContext, m as SoftDeleteMethods, n as autoInject, o as uniqueField, p as subdocumentPlugin, r as blockIf, s as validationChainPlugin, t as OperationType, u as TenantStore, v as observabilityPlugin, w as LeasePluginOptions, y as MongoOperationsMethods, z as BulkWriteResult } from "./validation-chain.plugin-DYp9E7K2.mjs";
5
+ import { S as RepositoryPluginName, _ as RepositoryOptions, a as HookMode, b as MONGOKIT_PLUGIN_NAMES, c as MinimalRepoView, d as PluginType, f as PrioritizedHook, g as RepositoryOperation, h as RepositoryInstance, i as EventPhase, l as Plugin, m as RepositoryEvent, n as EventHandlers, o as Middleware, p as RepositoryContext, r as EventPayload, s as MiddlewareContext, t as AllPluginMethods, u as PluginFunction, v as UserContext, x as MongoKitPluginName, y as WithPlugins } from "./repository-DNHfjAZX.mjs";
6
+ import { A as EnsureAuditTrailReadyOptions, C as AuditQueryOptions, D as AuditTrailOptions, E as AuditTrailMode, M as ensureAuditTrailReady, O as AuditTrailQuery, S as AuditOperation, T as AuditTrailMethods, _ as CacheOptions, a as DateSequentialIdOptions, b as cachePlugin, c as SequentialIdOptions, d as ensureSequenceAtLeast, f as getNextSequence, g as CacheAdapter, h as sequentialId, i as CustomIdOptions, j as auditTrailPlugin, k as AuditTrailQueryOptions, l as customIdPlugin, m as readSequence, n as adminBypass, o as IdGenerator, p as prefixedId, r as multiTenantPlugin, s as PrefixedIdOptions, t as MultiTenantOptions, u as dateSequentialId, v as RepositoryCacheHandle, w as AuditQueryResult, x as AuditEntry, y as RepositoryCachePluginOptions } from "./multi-tenant.plugin-a3UhQARj.mjs";
7
+ import { n as PaginationEngine, t as CountMemoKey } from "./PaginationEngine-CRHyuUtw.mjs";
8
+ import { a as AggregationBuilder, c as ProjectionSpec, d as VectorSearchOptions, i as TransitionMachine, l as SortOrder, n as HOOK_PRIORITY, o as AggregationPlan, r as Repository, s as GroupSpec, t as GetAllParams, u as SortSpec } from "./Repository-pnLw1rG5.mjs";
9
+ import { a as SoftDeleteFilterMode, c as ValidationChainOptions, i as Logger, l as ValidatorDefinition, n as CascadeRelation, o as SoftDeleteOptions, r as FieldPreset, s as SoftDeleteRepository, t as CascadeOptions } from "./plugin-options-CRhIvSzx.mjs";
10
+ import { n as CreateRepositoryConfig, r as createRepository, t as AuditConfig } from "./create-repository-BUx9vfG9.mjs";
11
+ import { A as IdempotencyStoreMethods, B as batchOperationsPlugin, C as LeaseMethods, D as ImmutableStatesPluginOptions, E as ImmutableClaimView, F as elasticSearchPlugin, G as aggregateHelpersPlugin, H as AppendOnlyPluginOptions, I as cascadePlugin, L as BatchOperationsMethods, M as idempotencyStorePlugin, N as fieldFilterPlugin, O as immutableStatesPlugin, P as ElasticSearchOptions, R as BulkWriteOptions, S as methodRegistryPlugin, T as leasePlugin, U as appendOnlyPlugin, V as auditLogPlugin, W as AggregateHelpersMethods, _ as OperationMetric, a as requireField, b as mongoOperationsPlugin, c as timestampPlugin, d as createTenantContext, f as SubdocumentMethods, g as ObservabilityOptions, h as softDeletePlugin, i as immutableField, j as IdempotencyStorePluginOptions, k as IdempotencyClaim, l as TenantContext, m as SoftDeleteMethods, n as autoInject, o as uniqueField, p as subdocumentPlugin, r as blockIf, s as validationChainPlugin, t as OperationType, u as TenantStore, v as observabilityPlugin, w as LeasePluginOptions, y as MongoOperationsMethods, z as BulkWriteResult } from "./validation-chain.plugin-CTcNJCmV.mjs";
12
12
  import { n as SchemaPathsLike, t as FieldType$1 } from "./coercion-BjdPX3YF.mjs";
13
13
  import { n as SchemaIndexes } from "./indexes-DIjMpYES.mjs";
14
- import { S as parseDuplicateKeyError, _ as getMongooseProjection, a as createMemoryCache, b as createError, g as getFieldsForUser, h as filterResponseData, i as buildCrudSchemasFromMongooseSchema, m as createFieldPreset, n as CrudSchemasFramework, o as LoggerConfig, r as buildCrudSchemasFromModel, s as configureLogger, t as toPlain, u as idVariants, v as CreateErrorOptions, x as isDuplicateKeyError, y as ParseDuplicateKeyOptions } from "./to-plain-k7SjNlSS.mjs";
14
+ import { S as parseDuplicateKeyError, _ as getMongooseProjection, a as createMemoryCache, b as createError, g as getFieldsForUser, h as filterResponseData, i as buildCrudSchemasFromMongooseSchema, m as createFieldPreset, n as CrudSchemasFramework, o as LoggerConfig, r as buildCrudSchemasFromModel, s as configureLogger, t as toPlain, u as idVariants, v as CreateErrorOptions, x as isDuplicateKeyError, y as ParseDuplicateKeyOptions } from "./to-plain-CjgEInWV.mjs";
15
15
  import { RepoCapabilities } from "@classytic/repo-core/repository";
16
16
  import { ClientSession, Connection, Model, PipelineStage, Schema } from "mongoose";
17
+ import { HttpError } from "@classytic/repo-core/errors";
18
+ import { KeysetSource } from "@classytic/repo-core/pagination";
17
19
  import "@classytic/repo-core/query-parser";
18
20
  //#region src/actions/cascade-references.d.ts
19
21
  type PurgeMode = 'hard' | 'soft' | 'anonymize';
@@ -431,6 +433,10 @@ interface PaginationDefaults {
431
433
  cursorSecret?: CursorSecret;
432
434
  /** See {@link PaginationConfig.defaultMode}. */
433
435
  defaultMode?: 'offset' | 'keyset';
436
+ /** See {@link PaginationConfig.maxOffset}: the deployment's deep-offset guard. */
437
+ maxOffset?: number;
438
+ /** See {@link PaginationConfig.countCacheTtlMs}. */
439
+ countCacheTtlMs?: number;
434
440
  /**
435
441
  * See {@link PaginationConfig.maxPage}.
436
442
  *
@@ -461,6 +467,22 @@ declare function getPaginationDefaults(): Readonly<PaginationDefaults>;
461
467
  /** Back to library defaults. For tests — a global that cannot be reset is a leak between them. */
462
468
  declare function resetPaginationDefaults(): void;
463
469
  //#endregion
470
+ //#region src/pagination/keyset-source.d.ts
471
+ interface KeysetSourceOptions extends ReadOptions {
472
+ name: string;
473
+ sort: SortSpec$1;
474
+ filters?: Record<string, unknown>;
475
+ }
476
+ declare function keysetSource<TDoc>(repo: Repository<TDoc>, options: KeysetSourceOptions): KeysetSource<TDoc>;
477
+ //#endregion
478
+ //#region src/pagination/utils/guards.d.ts
479
+ declare const PAGINATION_ERROR_CODES: {
480
+ readonly OFFSET_TOO_DEEP: "mongokit.pagination.offset_too_deep";
481
+ /** repo-core's shared cursor vocabulary (one code set across kits and merged cursors). */
482
+ readonly CURSOR_INVALID: "repo.cursor.invalid";
483
+ readonly CURSOR_SCOPE_MISMATCH: "repo.cursor.scope_mismatch";
484
+ };
485
+ //#endregion
464
486
  //#region src/query/parser/types.d.ts
465
487
  type SortSpec$2 = Record<string, 1 | -1>;
466
488
  type FilterQuery = Record<string, unknown>;
@@ -508,6 +530,10 @@ interface ParsedQuery {
508
530
  page?: number;
509
531
  /** Cursor for keyset pagination */
510
532
  after?: string;
533
+ /** Keyset cursor for the previous page (never with `after`). */
534
+ before?: string;
535
+ /** Explicit paging mode, when the caller named one. */
536
+ mode?: 'offset' | 'keyset';
511
537
  /** Limit */
512
538
  limit: number;
513
539
  /** Full-text search query */
@@ -713,6 +739,20 @@ declare class QueryParser {
713
739
  };
714
740
  }
715
741
  //#endregion
742
+ //#region src/repository/join-scope.d.ts
743
+ /** Returns the predicate a read of the owning collection carries for this call, or none. */
744
+ type CollectionScopeRule = (context: RepositoryContext, operation: string) => Record<string, unknown> | undefined;
745
+ declare const JOIN_ERROR_CODES: {
746
+ readonly UNKNOWN_COLLECTION: "mongokit.join.unknown_collection";
747
+ readonly UNGOVERNED_COLLECTION: "mongokit.join.ungoverned_collection";
748
+ readonly UNSCOPE_REFUSED: "mongokit.join.unscope_refused";
749
+ readonly UNRESOLVABLE_FROM: "mongokit.join.unresolvable_from";
750
+ };
751
+ /** Called by a policy plugin at bind: reads of this model's collection carry `rule`. */
752
+ declare function declareCollectionScope(model: object, rule: CollectionScopeRule, meta?: {
753
+ tenantField?: string;
754
+ }): void;
755
+ //#endregion
716
756
  //#region src/transaction.d.ts
717
757
  /** Minimal shape we need from a Mongoose connection. */
718
758
  interface SessionStarter {
@@ -721,9 +761,9 @@ interface SessionStarter {
721
761
  /**
722
762
  * Run a callback inside a MongoDB transaction on the given connection.
723
763
  *
724
- * - Starts a session, runs `session.withTransaction(callback)` (which auto-retries
725
- * on `TransientTransactionError` and `UnknownTransactionCommitResult`), and
726
- * always ends the session in `finally`.
764
+ * - Starts a session and runs the callback in a transaction with the driver's retry rules
765
+ * (`TransientTransactionError` → retry the attempt, `UnknownTransactionCommitResult` → retry
766
+ * the commit), ending the session in `finally`. See {@link runTransaction}.
727
767
  * - When `allowFallback` is true and the deployment doesn't support transactions
728
768
  * (e.g. standalone MongoDB in dev), the callback runs once without a
729
769
  * transaction on the same session. `onFallback` is invoked with the original
@@ -742,6 +782,20 @@ interface SessionStarter {
742
782
  * ```
743
783
  */
744
784
  declare function withTransaction<T>(connection: SessionStarter, callback: (session: ClientSession) => Promise<T>, options?: WithTransactionOptions): Promise<T>;
785
+ declare const TRANSACTION_ERROR_CODES: {
786
+ /** The session lacks a method the transaction loop drives (a partial or wrapped fake). */
787
+ readonly SESSION_INCOMPLETE: "mongokit.transaction.session_incomplete";
788
+ };
789
+ /**
790
+ * The driver's convenient-transaction algorithm (start → callback → commit, label-based retry,
791
+ * jittered backoff, a deadline), run here so the driver never attaches a session `timeoutContext`:
792
+ * with one, every legacy bulk write (`insertMany`, `bulkWrite`) in the transaction is refused once
793
+ * the client carries `timeoutMS` (driver <= 7.7: the bulk path re-resolves the inherited client
794
+ * `timeoutMS` as a per-op one). Each operation keeps its own per-op CSOT budget instead.
795
+ * Deadline: `transactionOptions.timeoutMS`, else the client's `timeoutMS`, else 120 s (as the driver).
796
+ * Pinned by `tests/integration/csot-transaction-matrix.test.ts`.
797
+ */
798
+ declare function runTransaction<T>(session: ClientSession, callback: (session: ClientSession) => Promise<T>, transactionOptions?: ConvenientTransactionOptions): Promise<T>;
745
799
  /**
746
800
  * Multi-repo transactional batch — every repo in `repos` becomes a
747
801
  * session-bound proxy inside the callback. Eliminates the per-call
@@ -1062,4 +1116,4 @@ declare function createOptionsExtractor<TCtx extends Record<string, unknown>>(fi
1062
1116
  */
1063
1117
  declare function systemContext(extra?: SessionOptions): SessionOptions;
1064
1118
  //#endregion
1065
- export { ALL_OPERATIONS, type AggregateHelpersMethods, type AggregateOptions, type AggregatePaginationOptions, AggregationBuilder, type AggregationPlan, type SortOrder as AggregationSortOrder, type SortSpec as AggregationSortSpec, type AllPluginMethods, type AnyDocument, type AnyModel, type AppendOnlyPluginOptions, type AuditConfig, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailMode, type AuditTrailOptions, AuditTrailQuery, type AuditTrailQueryOptions, type BasePaginationOptions, type BatchOperationsMethods, type BulkWriteOptions, type BulkWriteResult, type CacheAdapter, type CacheOperationOptions, type CacheOptions, type CacheableOptions, type CapabilityConnectionLike, type CapabilityProbeOptions, type CapabilityResolution, type CascadeOptions, type CascadePurgeReferencesOptions, type CascadeRelation, type CollationOptions, type CollectionRWLike, type ConvenientTransactionOptions, type CountStrategy, type CreateErrorOptions, type CreateInput, type CreateManyFailure, type CreateManyPartial, type CreateManyPartialError, type CreateOptions, type CreateRepositoryConfig, type CrudSchemasFramework, type CursorPayload, type CursorSecret, type CustomIdOptions, type DateSequentialIdOptions, type DecodedCursor, type DeepPartial, type DefineModelOptions, type DeleteResult, type DocField, type ElasticSearchOptions, type EnsureAuditTrailReadyOptions, type EventHandlers, type EventPayload, type EventPhase, type ExistingModelPolicy, type FieldPreset, type FieldType, type FilterQuery, type FindOneAndUpdateOptions, type GetAllParams, type GroupResult, type GroupSpec, HOOK_PRIORITY, type HookMode, type IdGenerator, type IdempotencyClaim, type IdempotencyStoreMethods, type IdempotencyStorePluginOptions, type ImmutableClaimView, type ImmutableStatesPluginOptions, type InferDocument, type InferRawDoc, type KeysOfType, type KeysetPaginationOptions, type LeaseMethods, type LeasePluginOptions, type Logger, type LoggerConfig, LookupBuilder, type LookupOptions, type LookupPopulateOptions, type LookupPopulateResult, MONGOKIT_CAPABILITIES, MONGOKIT_PLUGIN_NAMES, MUTATING_OPERATIONS, type Middleware, type MiddlewareContext, type MinMaxResult, type MinimalRepoView, type ModelBlueprint, ModelCollisionError, type ModelSpec, type MongoKitPluginName, type MongoOperationsMethods, type MongoOperatorUpdate, type MongoRepoCapabilities, type MongokitPageExtras, type MultiTenantOptions, type NonNullableFields, OP_REGISTRY, type ObjectId, type ObservabilityOptions, type OffsetPaginationOptions, type OperationDescriptor, type OperationMetric, type OperationOptions, type OperationType, type PaginationConfig, type PaginationDefaults, PaginationEngine, type ParseDuplicateKeyOptions, type ParsedQuery, type PartialBy, type Plugin, type PluginFunction, type PluginType, type PolicyKey, type PopulateOption, type PopulateSpec, type PrefixedIdOptions, type PrioritizedHook, type ProjectionSpec, type PurgeMode, type PurgeableRepoLike, QueryParser, type QueryParserOptions, type QuerySchema, READ_OPERATIONS, type ReadOptions, type ReadPreferenceType, type ReferencePurgeResult, type ReferenceRelation, type RepoScope, Repository, Repository as default, type RepositoryCacheHandle, type RepositoryCachePluginOptions, type RepositoryContext, type RepositoryEvent, type RepositoryInstance, type RepositoryOperation, type RepositoryOptions, type RepositoryPluginName, type RequiredBy, type SchemaLike, type SearchMode, type SelectSpec, type SequentialIdOptions, type SessionOptions, type SessionStarter, type SoftDeleteFilterMode, type SoftDeleteMethods, type SoftDeleteOptions, type SoftDeleteRepository, type SortDirection, type SortSpec$1 as SortSpec, type Strict, type SubdocumentMethods, type TenantContext, type TenantStore, type TransactionSupport, type TransitionMachine, type UpdateManyResult, type UpdateOptions, type UpdatePatch, type UpdateWithValidationResult, type UserContext, type ValidationChainOptions, type ValidatorDefinition, type ValueType, type VectorSearchOptions, type WithPlugins, type WithTransactionOptions, index_d_exports as actions, adminBypass, aggregateHelpersPlugin, appendOnlyPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, capabilitiesForSupport, cascadePlugin, cascadePurgeReferences, classifyHelloReply, compileFilterToMongo, configureLogger, configurePaginationDefaults, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, declareTenantContextKey, defineModel, defineModels, elasticSearchPlugin, ensureAuditTrailReady, ensureSequenceAtLeast, fieldFilterPlugin, filterResponseData, forwardScope, getFieldsForUser, getMongooseProjection, getNextSequence, getPaginationDefaults, idVariants, idempotencyStorePlugin, immutableField, immutableStatesPlugin, isCreateManyPartialError, isDuplicateKeyError, isModelRegistered, isTransactionUnsupported, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, probeMongoCapabilities, readSequence, repoOptionsFromCtx, requireField, resetCapabilityProbeCache, resetPaginationDefaults, resolveMongoCapabilities, resolveTransactionSupport, sequentialId, softDeletePlugin, subdocumentPlugin, supportsTransactions, systemContext, tenantContextKeysOf, timestampPlugin, toPlain, transactionResolutionOf, uniqueField, validationChainPlugin, withTransaction };
1119
+ export { ALL_OPERATIONS, type AggregateCallOptions, type AggregateDefaults, type AggregateHelpersMethods, type AggregateOptions, type AggregatePaginationOptions, AggregationBuilder, type AggregationPlan, type SortOrder as AggregationSortOrder, type SortSpec as AggregationSortSpec, type AllPluginMethods, type AnyDocument, type AnyModel, type AppendOnlyPluginOptions, type AuditConfig, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailMode, type AuditTrailOptions, AuditTrailQuery, type AuditTrailQueryOptions, type BasePaginationOptions, type BatchOperationsMethods, type BulkWriteOptions, type BulkWriteResult, type CacheAdapter, type CacheOperationOptions, type CacheOptions, type CacheableOptions, type CapabilityConnectionLike, type CapabilityProbeOptions, type CapabilityResolution, type CascadeOptions, type CascadePurgeReferencesOptions, type CascadeRelation, type CollationOptions, type CollectionRWLike, type CollectionScopeRule, type CommandKind, type ConvenientTransactionOptions, type CountMemoKey, type CountStrategy, type CreateErrorOptions, type CreateInput, type CreateManyFailure, type CreateManyPartial, type CreateManyPartialError, type CreateOptions, type CreateRepositoryConfig, type CrudSchemasFramework, type CursorPayload, type CursorSecret, type CustomIdOptions, type DateSequentialIdOptions, type DecodedCursor, type DeepPartial, type DefineModelOptions, type DeleteResult, type DocField, type ElasticSearchOptions, type EnsureAuditTrailReadyOptions, type EventHandlers, type EventPayload, type EventPhase, type ExistingModelPolicy, type FieldPreset, type FieldType, type FilterQuery, type FindOneAndUpdateOptions, type GetAllParams, type GetByIdsOptions, type GroupResult, type GroupSpec, HOOK_PRIORITY, type HookMode, type IdGenerator, type IdempotencyClaim, type IdempotencyStoreMethods, type IdempotencyStorePluginOptions, type ImmutableClaimView, type ImmutableStatesPluginOptions, type InferDocument, type InferRawDoc, JOIN_ERROR_CODES, type KeysOfType, type KeysetPaginationOptions, type KeysetSourceOptions, type LeaseMethods, type LeasePluginOptions, type Logger, type LoggerConfig, LookupBuilder, type LookupOptions, type LookupPopulateOptions, type LookupPopulateResult, MONGOKIT_CAPABILITIES, MONGOKIT_PLUGIN_NAMES, MUTATING_OPERATIONS, type Middleware, type MiddlewareContext, type MinMaxResult, type MinimalRepoView, type ModelBlueprint, ModelCollisionError, type ModelSpec, type MongoKitPluginName, type MongoOperationsMethods, type MongoOperatorUpdate, type MongoRepoCapabilities, type MongokitPageExtras, type MultiTenantOptions, type NonNullableFields, OP_REGISTRY, type ObjectId, type ObservabilityOptions, type OffsetPaginationOptions, type OperationDescriptor, type OperationMetric, type OperationOptions, type OperationType, PAGINATION_ERROR_CODES, type PaginationConfig, type PaginationDefaults, PaginationEngine, type ParseDuplicateKeyOptions, type ParsedQuery, type PartialBy, type PerCallQueryOptions, type Plugin, type PluginFunction, type PluginType, type PolicyKey, type PopulateOption, type PopulateSpec, type PrefixedIdOptions, type PrioritizedHook, type ProjectionSpec, type PurgeMode, type PurgeableRepoLike, QUERY_DEFAULTS_ERROR_CODES, type QueryDefaults, QueryParser, type QueryParserOptions, type QuerySchema, READ_OPERATIONS, type ReadConcernLevel, type ReadOptions, type ReadPreferenceType, type ReferencePurgeResult, type ReferenceRelation, type RepoScope, Repository, Repository as default, type RepositoryCacheHandle, type RepositoryCachePluginOptions, type RepositoryContext, type RepositoryEvent, type RepositoryInstance, type RepositoryOperation, type RepositoryOptions, type RepositoryPluginName, type RequiredBy, type ResolvedQueryOptions, type SchemaLike, type SearchMode, type SelectSpec, type SequentialIdOptions, type SessionOptions, type SessionStarter, type SoftDeleteFilterMode, type SoftDeleteMethods, type SoftDeleteOptions, type SoftDeleteRepository, type SortDirection, type SortSpec$1 as SortSpec, type Strict, type SubdocumentMethods, TRANSACTION_ERROR_CODES, type TenantContext, type TenantStore, type TransactionSupport, type TransitionMachine, type UpdateManyResult, type UpdateOptions, type UpdatePatch, type UpdateWithValidationResult, type UserContext, type ValidationChainOptions, type ValidatorDefinition, type ValueType, type VectorSearchOptions, type WithPlugins, type WithTransactionOptions, type WriteConcernSpec, index_d_exports as actions, adminBypass, aggregateHelpersPlugin, appendOnlyPlugin, assertQueryDefaultsConfigured, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, capabilitiesForSupport, cascadePlugin, cascadePurgeReferences, classifyHelloReply, compileFilterToMongo, configureAggregateDefaults, configureLogger, configurePaginationDefaults, configureQueryDefaults, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, declareCollectionScope, declareTenantContextKey, defineModel, defineModels, elasticSearchPlugin, ensureAuditTrailReady, ensureSequenceAtLeast, fieldFilterPlugin, filterResponseData, forwardScope, getFieldsForUser, getMongooseProjection, getNextSequence, getPaginationDefaults, getQueryDefaults, idVariants, idempotencyStorePlugin, immutableField, immutableStatesPlugin, isCreateManyPartialError, isDuplicateKeyError, isModelRegistered, isTransactionUnsupported, keysetSource, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, probeMongoCapabilities, readSequence, repoOptionsFromCtx, requireField, resetCapabilityProbeCache, resetPaginationDefaults, resetQueryDefaults, resolveMongoCapabilities, resolveQueryOptions, resolveTransactionSupport, runTransaction, sequentialId, softDeletePlugin, subdocumentPlugin, supportsTransactions, systemContext, tenantContextKeysOf, timestampPlugin, toPlain, transactionResolutionOf, uniqueField, validationChainPlugin, withTransaction };