@sfxcode/mongocamp-server-core 2.2.0 → 2.4.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 (3) hide show
  1. package/dist/index.d.mts +1151 -38
  2. package/dist/index.mjs +7381 -3779
  3. package/package.json +6 -2
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
- import { MongoClient, Db, Collection } from 'mongodb';
1
+ import { MongoClient, Db, Collection, Document as Document$2, ObjectId } from 'mongodb';
2
+ import { StandardSchemaV1 } from '@standard-schema/spec';
3
+ export { StandardSchemaV1 } from '@standard-schema/spec';
2
4
  import * as hookable from 'hookable';
3
5
  import * as _prometheus_io_client from '@prometheus-io/client';
4
6
  import { Registry } from '@prometheus-io/client';
@@ -29,6 +31,7 @@ declare const ConfigKeys: {
29
31
  readonly AuthRefreshGraceDuration: "AUTH_REFRESH_GRACE_DURATION";
30
32
  readonly AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS";
31
33
  readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
34
+ readonly WatchMaxStreams: "WATCH_MAX_STREAMS";
32
35
  readonly FilterTimeZone: "FILTER_TIME_ZONE";
33
36
  readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
34
37
  readonly JobsEnabled: "JOBS_ENABLED";
@@ -145,20 +148,34 @@ declare class MongocampDatabase {
145
148
  close(): Promise<void>;
146
149
  }
147
150
 
148
- /** Body of every error response (`exception/ErrorDescription.scala`). */
151
+ /** One field of a document that is not valid: `path` in dot notation (`items.0.qty`, empty for the whole document), `[3].qty` for the fourth document of a request with several. */
152
+ interface ValidationIssue {
153
+ path: string;
154
+ message: string;
155
+ }
156
+ /** Body of every error response (`exception/ErrorDescription.scala`); `issues` only for documents that are not valid (2.3.0). */
149
157
  interface ErrorDescription {
150
158
  code: number;
151
159
  msg: string;
152
160
  additionalInfo: string;
161
+ issues?: ValidationIssue[];
162
+ /** The stored document of a version conflict (409, code 4092), as Extended JSON. */
163
+ current?: Record<string, unknown>;
153
164
  }
154
165
  /** Counterpart of `MongoCampException`: a status code plus the error code, message and additional info for the client. */
155
166
  declare class MongocampError extends Error {
156
167
  readonly status: number;
157
168
  readonly code: number;
158
169
  readonly additionalInfo: string;
159
- constructor(message: string, status: number, code?: number, additionalInfo?: string);
170
+ readonly issues?: ValidationIssue[] | undefined;
171
+ readonly current?: Record<string, unknown> | undefined;
172
+ constructor(message: string, status: number, code?: number, additionalInfo?: string, issues?: ValidationIssue[] | undefined, current?: Record<string, unknown> | undefined);
160
173
  get description(): ErrorDescription;
161
174
  static badRequest(message: string, code?: number): MongocampError;
175
+ /** 400 for documents that are not valid, with the fields in `issues` (a schema, a before-hook). */
176
+ static validation(issues: ValidationIssue[], message?: string, code?: number): MongocampError;
177
+ /** 409 for a write based on an outdated version, with the stored document (as Extended JSON) for the client to show or merge. */
178
+ static versionConflict(current: Record<string, unknown>): MongocampError;
162
179
  /** 403 and not 401: a client such as the UI clears its session on 401, but the session is fine, only this request is refused. */
163
180
  static forbidden(message: string, code?: number): MongocampError;
164
181
  static unauthorized(message?: string, code?: number): MongocampError;
@@ -166,6 +183,12 @@ declare class MongocampError extends Error {
166
183
  /** A request that cannot be decoded (`MongoCampDefaultDecodeFailureHandler`): `what` names the input, e.g. `body` or `query parameter page`. */
167
184
  static decodeFailure(what: string, additionalInfo?: string): MongocampError;
168
185
  }
186
+ type ErrorLogger = (error: unknown, status: number) => void;
187
+ /**
188
+ * Maps anything thrown in a handler to the error response of the Scala server (`MongoCampExceptionHandler`): a `MongocampError` as it is,
189
+ * a database error with the status for its code and a message without internal names, everything else as 500 with code -1.
190
+ */
191
+ declare function toErrorResponse(error: unknown, log?: ErrorLogger): Response;
169
192
 
170
193
  /** Pagination of list routes (`PagingFunctions.scala`, `MongoPaginatedFilter.scala`): 1-based pages, 100 rows per page by default. */
171
194
  declare const DefaultRowsPerPage = 100;
@@ -182,6 +205,8 @@ interface Paging {
182
205
  page?: number;
183
206
  after?: string;
184
207
  }
208
+ /** Query parameter `count`: `exact` (default) counts the matching documents, `none` skips the count and its headers. */
209
+ type CountMode = 'exact' | 'none';
185
210
  /**
186
211
  * `allCount` and `pagesCount` are missing when the count was skipped (`count=none`), `page` with cursor paging; `next` is the cursor of the
187
212
  * next page, missing when the page is the last one.
@@ -383,6 +408,8 @@ declare class AuthService {
383
408
  */
384
409
  authenticateUser(credentials: Credentials): Promise<UserInformation>;
385
410
  /** The logged in user of a request with the current roles. */
411
+ /** A user by id with its roles (2.4.0, the server collection acting for a user); 401 for a user that does not exist. */
412
+ authorizedUser(userId: string): Promise<AuthorizedUser>;
386
413
  authenticate(request: Request): Promise<AuthorizedUser>;
387
414
  /** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
388
415
  userOf(request: Request): string | undefined;
@@ -390,6 +417,8 @@ declare class AuthService {
390
417
  grantDenied(message: string): MongocampError;
391
418
  requireAdmin(request: Request): Promise<AuthorizedUser>;
392
419
  requireCollection(request: Request, collection: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
420
+ /** The grant of an authenticated user for a collection (the routes and the document service, 2.4.0). */
421
+ requireRight(user: AuthorizedUser, collection: string, right: 'read' | 'write' | 'administrate'): void;
393
422
  requireBucket(request: Request, bucket: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
394
423
  profileOf(user: UserInformation): Promise<UserProfile>;
395
424
  /** A new token for the user (`AuthHolder.generateLoginResult`), valid for `AUTH_EXPIRING_DURATION`. */
@@ -405,6 +434,403 @@ declare class AuthService {
405
434
  refresh(user: UserInformation, bearer: string | undefined): Promise<LoginResult>;
406
435
  }
407
436
 
437
+ /**
438
+ * An optional part of the server that a host switches on with `server.use(...)`, typically from a Nitro plugin on the hook
439
+ * `mongocamp:ready`. `setup` starts it and answers the function that stops it (called by `server.close()`).
440
+ */
441
+ interface MongocampFeature {
442
+ name: string;
443
+ setup: (context: MongocampContext) => Promise<() => void | Promise<void>> | (() => void | Promise<void>);
444
+ }
445
+ /** Every request as a document of `<AUTH_PREFIX>request_logging`. */
446
+ declare function requestLogging(): MongocampFeature;
447
+ /** `/system/monitoring/{runtime,system,mongodb,events,prometheus}` and the snapshots of `LOGGING_METRICS_MONGODB_*`. */
448
+ declare function metrics(): MongocampFeature;
449
+
450
+ /**
451
+ * Behaviours of declared collections (2.3.0): one flag each in `defineMongocampCollection`, with working defaults; an options object
452
+ * renames the fields (dot paths for nested fields, e.g. `metaData.created`).
453
+ *
454
+ * defineMongocampCollection({ name: 'orders', schema, timestamps: true, owner: true, softDelete: true, versioned: true, audit: true })
455
+ *
456
+ * The fields a behaviour writes ("system fields") are not part of the schema: the server writes them, clients cannot, and the document
457
+ * types and the validator of MongoDB get them added.
458
+ */
459
+ /** `true` for the default name of a field, or its (dot) path. */
460
+ type FieldOption = true | string;
461
+ interface TimestampsOptions {
462
+ /** Default `createdAt`. */
463
+ createdAt?: FieldOption;
464
+ /** Default `updatedAt`. */
465
+ updatedAt?: FieldOption;
466
+ /** The user who created the document (`true`: `createdBy`); not written unless set. */
467
+ createdBy?: FieldOption;
468
+ /** The user of the last change (`true`: `updatedBy`); not written unless set. */
469
+ updatedBy?: FieldOption;
470
+ }
471
+ /** The documents a user may read when the read rule is a function: a filter combined with every read (it can only narrow). */
472
+ type ReadScope = (context: {
473
+ user: UserInformation;
474
+ collectionName: string;
475
+ }) => Document$2 | Promise<Document$2>;
476
+ interface OwnerOptions {
477
+ /** The field with the user id of the owner; default the `createdBy` field of `timestamps`, else `owner`. */
478
+ field?: string;
479
+ /** Who reads: `own` (default) the owner only, `all` everybody with the read grant, or a function. Writes are always the owner's. */
480
+ read?: 'own' | 'all' | ReadScope;
481
+ /** Administrators read and write every document (default true). */
482
+ adminBypass?: boolean;
483
+ }
484
+ interface SoftDeleteOptions {
485
+ /** Default `deletedAt`. */
486
+ field?: string;
487
+ /** Deletes soft-deleted documents for good after this many days (a TTL index); default never. */
488
+ purgeAfterDays?: number;
489
+ }
490
+ interface VersionedOptions {
491
+ /** `counter` (default): a number `_v` that every write increases; `timestamp`: the `updatedAt` field of `timestamps` is the version. */
492
+ mode?: 'counter' | 'timestamp';
493
+ /** The counter field (mode `counter`), default `_v`. */
494
+ field?: string;
495
+ /** A replace or partial update without version is refused (428) instead of overwriting (default false). */
496
+ required?: boolean;
497
+ }
498
+ interface AuditOptions {
499
+ /** How long the audit records are kept, default 365 days. */
500
+ retentionDays?: number;
501
+ }
502
+ /** The behaviour flags of a declaration. */
503
+ interface BehaviourFlags {
504
+ timestamps?: boolean | TimestampsOptions;
505
+ owner?: boolean | OwnerOptions;
506
+ softDelete?: boolean | SoftDeleteOptions;
507
+ versioned?: boolean | VersionedOptions;
508
+ audit?: boolean | AuditOptions;
509
+ /** Fields clients cannot write (server code and before-hooks can); a replace keeps their stored values. */
510
+ protectedFields?: readonly string[];
511
+ }
512
+ interface ResolvedBehaviours {
513
+ timestamps?: {
514
+ createdAt: string;
515
+ updatedAt: string;
516
+ createdBy?: string;
517
+ updatedBy?: string;
518
+ };
519
+ owner?: {
520
+ field: string;
521
+ read: 'own' | 'all' | ReadScope;
522
+ adminBypass: boolean;
523
+ };
524
+ softDelete?: {
525
+ field: string;
526
+ purgeAfterDays?: number;
527
+ };
528
+ versioned?: {
529
+ mode: 'counter' | 'timestamp';
530
+ field: string;
531
+ required: boolean;
532
+ };
533
+ audit?: {
534
+ retentionDays: number;
535
+ };
536
+ protectedFields: string[];
537
+ }
538
+ declare const BehaviourDefaults: {
539
+ readonly createdAt: "createdAt";
540
+ readonly updatedAt: "updatedAt";
541
+ readonly createdBy: "createdBy";
542
+ readonly updatedBy: "updatedBy";
543
+ readonly owner: "owner";
544
+ readonly deletedAt: "deletedAt";
545
+ readonly version: "_v";
546
+ readonly auditRetentionDays: 365;
547
+ };
548
+ /** Resolves and checks the behaviour flags of a declaration: defaults, paths, combinations. */
549
+ declare function resolveBehaviours(flags: BehaviourFlags): ResolvedBehaviours;
550
+ /** The fields the behaviours write, with the behaviour that writes them (the version of mode `timestamp` is the updatedAt field). */
551
+ declare function systemFields(behaviours: ResolvedBehaviours): Array<{
552
+ path: string;
553
+ by: string;
554
+ }>;
555
+ type NameOf<O, K extends string, D extends string> = O extends Record<K, infer V> ? (V extends string ? V : D) : D;
556
+ type OptionalNameOf<O, K extends string, D extends string> = O extends Record<K, infer V> ? (V extends string ? V : V extends true ? D : never) : never;
557
+ type Enabled<F> = F extends true ? Record<never, never> : F extends object ? F : never;
558
+ /** `{ a: { b: V } }` for the path `a.b`. */
559
+ type AtPath<P extends string, V> = P extends `${infer Head}.${infer Rest}` ? {
560
+ [K in Head]: AtPath<Rest, V>;
561
+ } : {
562
+ [K in P]: V;
563
+ };
564
+ /** `{ a: { b?: V } }` for the path `a.b`. */
565
+ type AtOptionalPath<P extends string, V> = P extends `${infer Head}.${infer Rest}` ? {
566
+ [K in Head]: AtOptionalPath<Rest, V>;
567
+ } : {
568
+ [K in P]?: V;
569
+ };
570
+ type TimestampFields<F> = [Enabled<F>] extends [never] ? unknown : AtPath<NameOf<Enabled<F>, 'createdAt', 'createdAt'>, Date> & AtPath<NameOf<Enabled<F>, 'updatedAt', 'updatedAt'>, Date> & ([OptionalNameOf<Enabled<F>, 'createdBy', 'createdBy'>] extends [never] ? unknown : AtPath<OptionalNameOf<Enabled<F>, 'createdBy', 'createdBy'>, string>) & ([OptionalNameOf<Enabled<F>, 'updatedBy', 'updatedBy'>] extends [never] ? unknown : AtPath<OptionalNameOf<Enabled<F>, 'updatedBy', 'updatedBy'>, string>);
571
+ type OwnerField<F, T> = [Enabled<F>] extends [never] ? unknown : Enabled<F> extends {
572
+ field: infer P extends string;
573
+ } ? AtPath<P, string> : [OptionalNameOf<Enabled<T>, 'createdBy', 'createdBy'>] extends [never] ? AtPath<'owner', string> : unknown;
574
+ type SoftDeleteField<F> = [Enabled<F>] extends [never] ? unknown : AtOptionalPath<NameOf<Enabled<F>, 'field', 'deletedAt'>, Date>;
575
+ type VersionField<F> = [Enabled<F>] extends [never] ? unknown : Enabled<F> extends {
576
+ mode: 'timestamp';
577
+ } ? unknown : AtPath<NameOf<Enabled<F>, 'field', '_v'>, number>;
578
+ /** The fields the behaviours of a declaration add to its documents (`unknown` without behaviours). */
579
+ type SystemFields<D> = D extends BehaviourFlags ? TimestampFields<D['timestamps']> & OwnerField<D['owner'], D['timestamps']> & SoftDeleteField<D['softDelete']> & VersionField<D['versioned']> : unknown;
580
+ /** Objects merged and shown as one type (also nested), other values as they are. */
581
+ type Merge<T> = T extends Date | ((...args: never[]) => unknown) | readonly unknown[] ? T : T extends object ? {
582
+ [K in keyof T]: Merge<T[K]>;
583
+ } : T;
584
+ /** Every field optional, also nested. */
585
+ type DeepPartial<T> = T extends Date | readonly unknown[] ? T : T extends object ? {
586
+ [K in keyof T]?: DeepPartial<T[K]>;
587
+ } : T;
588
+
589
+ /**
590
+ * The indexes of a declared collection at the start (2.4.0). The sync only manages its **own** indexes (names `mongocamp_idx_*`):
591
+ *
592
+ * - a missing one is created (all missing ones in one `createIndexes`);
593
+ * - one whose key or options changed is dropped and created again — MongoDB cannot change most index options; only the seconds of a TTL
594
+ * index are changed in place (`collMod`);
595
+ * - an own index that is no longer declared is dropped;
596
+ * - an index of someone else (made by hand, by another tool, `_id_`) is never touched, only reported;
597
+ * - a failure (e.g. duplicate values for a unique index) is logged; the start goes on, the other indexes are synced.
598
+ *
599
+ * Every instance runs it; the second one changes nothing.
600
+ */
601
+ interface IndexSyncResult {
602
+ collection: string;
603
+ created: string[];
604
+ replaced: string[];
605
+ dropped: string[];
606
+ unchanged: string[];
607
+ /** Indexes that are not own ones (left alone). */
608
+ foreign: string[];
609
+ /** Indexes that could not be created or changed, with the reason. */
610
+ failed: Array<{
611
+ name: string;
612
+ reason: string;
613
+ }>;
614
+ }
615
+ /** Syncs the indexes of one declared collection; never throws (an unexpected failure is reported in `failed`). */
616
+ declare function syncIndexes(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<IndexSyncResult>;
617
+
618
+ /**
619
+ * Indexes of declared collections (2.4.0): the shortest form that says what is needed, the indexes the behaviours need added by
620
+ * themselves. The sync at the start (`index-sync.ts`) creates them; it only manages its own indexes (names `mongocamp_idx_*`).
621
+ *
622
+ * indexes: [
623
+ * 'status', // { status: 1 }
624
+ * '-createdAt', // { createdAt: -1 }
625
+ * ['customerId', '-createdAt'], // compound
626
+ * { fields: { number: 1 }, unique: true }, // with options
627
+ * { fields: { text: 'text' } }, // text index
628
+ * { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL
629
+ * ]
630
+ */
631
+ type IndexDirection = 1 | -1 | 'text';
632
+ interface IndexOptions {
633
+ fields: Record<string, IndexDirection>;
634
+ unique?: boolean;
635
+ sparse?: boolean;
636
+ /** TTL: documents expire this many seconds after the date in the (single) field. */
637
+ expireAfterSeconds?: number;
638
+ partialFilterExpression?: Document$2;
639
+ collation?: Document$2;
640
+ /** A name of your own (prefixed with `mongocamp_idx_`); default made of the fields. */
641
+ name?: string;
642
+ }
643
+ /** A field (`'status'`, `'-createdAt'`), fields of a compound index, or an index with options. */
644
+ type IndexDeclaration = string | readonly string[] | IndexOptions;
645
+ declare const OwnIndexPrefix = "mongocamp_idx_";
646
+ interface ResolvedIndex {
647
+ name: string;
648
+ key: Record<string, IndexDirection>;
649
+ options: Document$2;
650
+ /** Key and options, to see whether a stored index is still the declared one. */
651
+ fingerprint: string;
652
+ /** Declared, or added for a behaviour. */
653
+ origin: 'declaration' | 'owner';
654
+ }
655
+ /**
656
+ * The indexes of a declaration: the declared ones and the ones of its behaviours (an index on the owner field; with soft delete, unique
657
+ * indexes count only documents that are not deleted, so a deleted value can be used again).
658
+ */
659
+ declare function resolveIndexes(declarations: readonly IndexDeclaration[] | undefined, behaviours: ResolvedBehaviours): ResolvedIndex[];
660
+
661
+ /**
662
+ * References of declared collections (2.4.0): which fields hold the `_id` of a document of another collection. A read with
663
+ * `expand=customerId` replaces the id by the document — read with the grants and the scope of the target, never more than a direct read.
664
+ *
665
+ * refs: {
666
+ * customerId: 'customers', // one id
667
+ * tagIds: 'tags', // an array of ids (from the schema, or the value)
668
+ * 'billing.accountId': 'crm:accounts', // a nested field, a collection of another database
669
+ * }
670
+ */
671
+ /** The target collection (`name` or `database:name`), or an object with it. */
672
+ type RefDeclaration = string | {
673
+ readonly collection: string;
674
+ };
675
+ interface ResolvedRef {
676
+ /** The field path of the reference. */
677
+ field: string;
678
+ /** The target collection as the API names it (`name` or `database:name`). */
679
+ collection: string;
680
+ /** An array of ids (from the schema); `undefined` when the schema does not tell, then the value decides. */
681
+ many?: boolean;
682
+ }
683
+ /** At most this many references are expanded by one read. */
684
+ declare const MaxExpands = 5;
685
+ /**
686
+ * The references of a declaration. `jsonSchema` is the schema of the documents (MongoDB form) when the schema has one: it tells which
687
+ * references are arrays. Refused: `_id`, a field a behaviour writes, a path through an array, an empty or invalid target.
688
+ */
689
+ declare function resolveRefs(refs: Readonly<Record<string, RefDeclaration>> | undefined, behaviours: ResolvedBehaviours, jsonSchema?: Document$2): ResolvedRef[];
690
+ /** The target collection names of a refs declaration: `{ customerId: 'customers' }`. */
691
+ type RefTargets<R> = {
692
+ -readonly [K in keyof R]: R[K] extends string ? R[K] : R[K] extends {
693
+ collection: infer C extends string;
694
+ } ? C : never;
695
+ };
696
+ /** The refs of a declaration as field → target collection name (`{}` without refs). */
697
+ type InferRefs<D> = D extends {
698
+ refs: infer R;
699
+ } ? RefTargets<R> : Record<never, never>;
700
+ type Simplify<T> = {
701
+ [K in keyof T]: T[K];
702
+ } & {};
703
+ /** The value an expanded reference becomes: the target document or `null`; an array of ids becomes an array of documents. */
704
+ type ExpandedValue<V, Target> = NonNullable<V> extends readonly unknown[] ? Target[] : Target | null;
705
+ /** `T` with the value at the dot path `P` expanded to `Target` (optional fields stay optional). */
706
+ type ExpandAt<T, P extends string, Target> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? {
707
+ [K in keyof T]: K extends Head ? ExpandAt<NonNullable<T[K]>, Rest, Target> | Extract<T[K], null | undefined> : T[K];
708
+ } : T : P extends keyof T ? {
709
+ [K in keyof T]: K extends P ? ExpandedValue<T[K], Target> : T[K];
710
+ } : Simplify<T & {
711
+ [K in P]?: Target | Target[] | null;
712
+ }>;
713
+ type ExpandAll<T, Refs, Keys, Collections> = Keys extends readonly [infer First extends string, ...infer Rest] ? ExpandAll<ExpandAt<T, First, First extends keyof Refs ? (Refs[First] extends keyof Collections ? Collections[Refs[First]] : Record<string, unknown>) : Record<string, unknown>>, Refs, Rest, Collections> : T;
714
+ type UnionToTuple<U, Last = LastOf<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, Last>>, Last];
715
+ type LastOf<U> = ((U extends unknown ? (value: () => U) => void : never) extends (value: infer I) => void ? I : never) extends () => infer L ? L : never;
716
+ /**
717
+ * A document with the references `K` expanded: `ExpandedDocument<Order, { customerId: 'customers' }, 'customerId', { customers: Customer }>`
718
+ * has `customerId: Customer | null`. A target without a known type is `Record<string, unknown>`.
719
+ */
720
+ type ExpandedDocument<T, Refs, K extends keyof Refs & string, Collections = Record<never, never>> = ExpandAll<T, Refs, UnionToTuple<K>, Collections>;
721
+
722
+ /**
723
+ * The validator of MongoDB for the declared collections (2.3.0), set when the declarations are registered. The validator of a declared
724
+ * collection belongs to its declaration:
725
+ *
726
+ * - mode `off` never touches the collection;
727
+ * - a missing collection is created with the validator, an existing one gets it by `collMod` only when validator, level or action differ
728
+ * (every instance of an application runs the sync at its start, the second one changes nothing);
729
+ * - the level is `moderate`: documents that were stored before and do not match can still be changed; the action is the mode (`warn`
730
+ * logs in MongoDB, `error` refuses);
731
+ * - the validator carries a hash of its content in the `description` of its root (`[mongocamp <hash>]`): a validator whose content no
732
+ * longer matches its hash, or one without hash, was changed outside the declaration (`PATCH …/options`, the shell) and is replaced and
733
+ * reported as drift; a validator that matches its hash but not the declaration is from an older version of the declaration;
734
+ * - a failure (missing `collMod` right, a view) is logged and does not stop the start.
735
+ */
736
+ type ValidatorSyncAction = 'created' | 'unchanged' | 'replaced' | 'skipped' | 'failed';
737
+ interface ValidatorSyncResult {
738
+ collection: string;
739
+ action: ValidatorSyncAction;
740
+ /** Conversion warnings, drift and failures, also logged. */
741
+ warnings: string[];
742
+ }
743
+ declare const SyncValidationLevel = "moderate";
744
+ declare function sameValidator(a: unknown, b: unknown): boolean;
745
+ /** Sets the validator of one declared collection; never throws. */
746
+ declare function syncValidator(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<ValidatorSyncResult>;
747
+
748
+ /**
749
+ * Declared collections (2.3.0): a collection with a schema of any Standard Schema library (Zod 4, Valibot, ArkType, ...). One declaration
750
+ * gives the TypeScript type of its documents, the validation of the documents written through the API and the validator of MongoDB
751
+ * (`validation`). A host registers its declarations with `server.use(collections([...]))`; the Nuxt module does that for the files in
752
+ * `server/mongocamp/`.
753
+ *
754
+ * export default defineMongocampCollection({
755
+ * name: 'orders',
756
+ * schema: z.object({ customer: z.string(), qty: z.int().min(1) }),
757
+ * })
758
+ */
759
+ /**
760
+ * What a declaration does with documents that do not match its schema: `off` nothing, `warn` logs them but writes them (and the validator
761
+ * of MongoDB only warns), `error` refuses them (400, and MongoDB refuses them from every other client too).
762
+ */
763
+ type ValidationMode = 'off' | 'warn' | 'error';
764
+ declare const DefaultValidationMode: ValidationMode;
765
+ /**
766
+ * A declared collection. Behaviours (2.3.0) are flags of the same object: `timestamps`, `owner`, `softDelete`, `versioned`, `audit`,
767
+ * `protectedFields` (see `BehaviourFlags`).
768
+ */
769
+ interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSchemaV1> extends BehaviourFlags {
770
+ /** The name of the collection, without database. */
771
+ name: string;
772
+ /** The database of the collection, the default database of the server when omitted. */
773
+ database?: string;
774
+ /** The schema of the documents as they are stored, with the values of the driver (`ObjectId`, `Date`, ...). */
775
+ schema: S;
776
+ /** Default `warn`. */
777
+ validation?: ValidationMode;
778
+ /** A `$jsonSchema` validator for MongoDB that replaces the one converted from the schema (for schemas without JSON Schema form). */
779
+ validator?: Document$2;
780
+ /** Indexes (2.4.0): `'status'`, `'-createdAt'`, `['a', '-b']` or `{ fields, unique, ... }`; synced at the start (own indexes only). */
781
+ indexes?: readonly IndexDeclaration[];
782
+ /** References (2.4.0): field → target collection (`'customers'`, `'db:customers'`), for `expand` on reads. */
783
+ refs?: Readonly<Record<string, RefDeclaration>>;
784
+ /** Where the declaration comes from (a file), for the messages; set by the Nuxt module. */
785
+ source?: string;
786
+ }
787
+ /** The type of the documents of a declaration, with the fields of its behaviours: `InferDocument<typeof orders>`. */
788
+ type InferDocument<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferOutput<D['schema']> : Merge<StandardSchemaV1.InferOutput<D['schema']> & SystemFields<D>>;
789
+ /**
790
+ * The input type of the documents of a declaration (before defaults and transforms of the schema). The fields of behaviours are optional:
791
+ * the server writes them and ignores what a client sends, so a document that was read can be sent back as it is.
792
+ */
793
+ type InferDocumentInput<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferInput<D['schema']> : Merge<StandardSchemaV1.InferInput<D['schema']> & DeepPartial<SystemFields<D>>>;
794
+ /** Declares a collection; checks the declaration and keeps the types of its schema and its behaviours for `InferDocument`. */
795
+ declare function defineMongocampCollection<const D extends MongocampCollectionDefinition>(definition: D): D;
796
+ /** The resolved references of a declaration; errors name the collection and the source. */
797
+ declare function refsOf(definition: MongocampCollectionDefinition, behaviours?: ResolvedBehaviours): ResolvedRef[];
798
+ interface DeclaredCollection {
799
+ definition: MongocampCollectionDefinition;
800
+ databaseName: string;
801
+ validation: ValidationMode;
802
+ /** The behaviours of the declaration with their defaults (2.3.0). */
803
+ behaviours: ResolvedBehaviours;
804
+ /** The indexes of the declaration and its behaviours (2.4.0); empty when there are none. */
805
+ indexes: ResolvedIndex[];
806
+ /** The references of the declaration (2.4.0); empty when there are none. */
807
+ refs: ResolvedRef[];
808
+ /** What the start did with the indexes (2.4.0). */
809
+ indexSync?: IndexSyncResult;
810
+ /** What the start did with the validator of MongoDB (`collections()` feature). */
811
+ sync?: ValidatorSyncResult;
812
+ }
813
+ /** The declarations of a server by database and collection; `context.collections`. */
814
+ declare class CollectionRegistry {
815
+ private readonly entries;
816
+ private static key;
817
+ /** The declaration of a collection, by its database and name. */
818
+ find(databaseName: string, name: string): DeclaredCollection | undefined;
819
+ /** The declaration of a collection as the routes name it (`orders`, `otherdb:orders`). */
820
+ resolve(context: Pick<MongocampContext, 'database'>, collection: string): DeclaredCollection | undefined;
821
+ get size(): number;
822
+ all(): DeclaredCollection[];
823
+ /** Adds declarations, all or none (a collection that is declared twice is an error); the returned function removes them. */
824
+ add(declared: DeclaredCollection[]): () => void;
825
+ }
826
+ /**
827
+ * Registers declared collections in the server (`server.use(collections([orders, customers]))`), sets their validator in MongoDB
828
+ * (`syncValidator`, awaited) and validates the documents written to them through the API (see `ValidationMode`). Several calls with
829
+ * different declarations add up; a collection declared twice stops the feature. Stopped by `server.close()`, which removes the
830
+ * declarations and their validation (the validators stay in MongoDB).
831
+ */
832
+ declare function collections(definitions: MongocampCollectionDefinition[]): MongocampFeature;
833
+
408
834
  interface components {
409
835
  schemas: {
410
836
  /** BucketInformation */
@@ -583,6 +1009,18 @@ interface components {
583
1009
  code: number;
584
1010
  msg: string;
585
1011
  additionalInfo: string;
1012
+ /** @description The fields of a document that is not valid (a schema, a before-hook or the validator of the collection). Only set for these errors. */
1013
+ issues?: components["schemas"]["ValidationIssue"][];
1014
+ /** @description The stored document of a version conflict (409, code 4092, 2.3.0), as Extended JSON: show it or merge with it, then send the change again with its version. */
1015
+ current?: {
1016
+ [key: string]: unknown;
1017
+ };
1018
+ };
1019
+ /** ValidationIssue */
1020
+ ValidationIssue: {
1021
+ /** @description The field in dot notation (`items.0.qty`), empty for the whole document; `[3].qty` for the fourth document of a request with several. */
1022
+ path: string;
1023
+ message: string;
586
1024
  };
587
1025
  /** FieldInfo */
588
1026
  FieldInfo: {
@@ -815,6 +1253,8 @@ interface components {
815
1253
  filter: components["schemas"]["Map_Any"];
816
1254
  sort: components["schemas"]["Map_Any"];
817
1255
  projection: components["schemas"]["Map_Any"];
1256
+ /** @description References to expand (2.4.0), like the query parameter expand. */
1257
+ expand?: string[];
818
1258
  };
819
1259
  /** MongoIndex */
820
1260
  MongoIndex: {
@@ -882,6 +1322,101 @@ interface components {
882
1322
  isAdmin: boolean;
883
1323
  collectionGrants?: components["schemas"]["Grant"][];
884
1324
  };
1325
+ /** SuggestedValidator */
1326
+ SuggestedValidator: {
1327
+ /** @description The validator: an object with the key $jsonSchema. */
1328
+ validator: {
1329
+ [key: string]: unknown;
1330
+ };
1331
+ /**
1332
+ * Format: int64
1333
+ * @description The number of documents of the collection.
1334
+ */
1335
+ count: number;
1336
+ /**
1337
+ * Format: int64
1338
+ * @description The number of documents the suggestion is made of.
1339
+ */
1340
+ sample: number;
1341
+ warnings: string[];
1342
+ };
1343
+ /** AuditEntry */
1344
+ AuditEntry: {
1345
+ collection: string;
1346
+ database: string;
1347
+ /** @description The _id of the document; absent on a summary record. */
1348
+ documentId?: unknown;
1349
+ /** @enum {string} */
1350
+ operation: "insert" | "replace" | "update" | "delete" | "softDelete" | "restore";
1351
+ user: string;
1352
+ /** @description The time (Extended JSON date). */
1353
+ at: {
1354
+ [key: string]: unknown;
1355
+ };
1356
+ before?: {
1357
+ [key: string]: unknown;
1358
+ };
1359
+ after?: {
1360
+ [key: string]: unknown;
1361
+ };
1362
+ /** @description A write of many documents: count and recorded. */
1363
+ summary?: {
1364
+ [key: string]: unknown;
1365
+ };
1366
+ expiresAt?: {
1367
+ [key: string]: unknown;
1368
+ };
1369
+ };
1370
+ /** CollectionDeclaration */
1371
+ CollectionDeclaration: {
1372
+ name: string;
1373
+ database: string;
1374
+ /** @enum {string} */
1375
+ validation: "off" | "warn" | "error";
1376
+ /** @description The fields the server writes (timestamps, owner, version, deleted mark); clients do not send them. */
1377
+ systemFields: string[];
1378
+ protectedFields: string[];
1379
+ /** @description The indexes of the declaration and its behaviours (2.4.0), synced at the start. */
1380
+ indexes: {
1381
+ name: string;
1382
+ key: {
1383
+ [key: string]: unknown;
1384
+ };
1385
+ unique: boolean;
1386
+ }[];
1387
+ /** @description The references of the declaration (2.4.0), the fields a read can expand (query parameter expand). */
1388
+ refs: {
1389
+ field: string;
1390
+ /** @description The target collection (name or database:name). */
1391
+ collection: string;
1392
+ /** @description Whether the field holds an array of ids (from the schema); missing when the schema does not tell. */
1393
+ many?: boolean;
1394
+ }[];
1395
+ timestamps?: {
1396
+ createdAt: string;
1397
+ updatedAt: string;
1398
+ createdBy?: string;
1399
+ updatedBy?: string;
1400
+ };
1401
+ owner?: {
1402
+ field: string;
1403
+ /** @enum {string} */
1404
+ read: "own" | "all" | "custom";
1405
+ };
1406
+ softDelete?: {
1407
+ field: string;
1408
+ purgeAfterDays?: number;
1409
+ };
1410
+ versioned?: {
1411
+ /** @enum {string} */
1412
+ mode: "counter" | "timestamp";
1413
+ field: string;
1414
+ required: boolean;
1415
+ };
1416
+ audit?: {
1417
+ retentionDays: number;
1418
+ };
1419
+ };
885
1420
  /** SchemaAnalysis */
886
1421
  SchemaAnalysis: {
887
1422
  /** Format: int64 */
@@ -919,6 +1454,8 @@ interface components {
919
1454
  projection?: string[];
920
1455
  /** Format: int32 */
921
1456
  limit?: number;
1457
+ /** @description References to expand (2.4.0), like the query parameter expand. */
1458
+ expand?: string[];
922
1459
  };
923
1460
  /** CountRequest */
924
1461
  CountRequest: {
@@ -930,6 +1467,8 @@ interface components {
930
1467
  filter?: string;
931
1468
  sort?: string[];
932
1469
  projection?: string[];
1470
+ /** @description References to expand (2.4.0), like the query parameter expand. */
1471
+ expand?: string[];
933
1472
  };
934
1473
  /** SettingsResponse */
935
1474
  SettingsResponse: {
@@ -1023,7 +1562,7 @@ interface EventBase {
1023
1562
  type ByUser<T = object> = {
1024
1563
  user: UserInformation;
1025
1564
  } & T;
1026
- type Document = Record<string, unknown>;
1565
+ type Document$1 = Record<string, unknown>;
1027
1566
  /** The fields of `HttpRequestStartEvent` / `HttpRequestCompletedEvent`. */
1028
1567
  interface HttpRequestFields {
1029
1568
  requestId: string;
@@ -1102,20 +1641,32 @@ interface MongocampEvents {
1102
1641
  collectionName: string;
1103
1642
  newCollectionName: string;
1104
1643
  }>;
1644
+ /** `documents` (2.3.0): the inserted documents of an insert or insertMany (not of an import), read only by listeners that need them. */
1105
1645
  'document:create': ByUser<{
1106
1646
  collectionName: string;
1107
1647
  insertResponse: Schemas['InsertResponse'];
1648
+ documents?: Document$1[];
1108
1649
  }>;
1109
1650
  /** `oldValues` are read only when a listener is registered for the hook. */
1651
+ /** `source` (2.3.0): a replace, a partial update or an update of many documents. */
1110
1652
  'document:update': ByUser<{
1111
1653
  collectionName: string;
1112
1654
  updateResponse: Schemas['UpdateResponse'];
1113
- oldValues: Document[];
1655
+ oldValues: Document$1[];
1656
+ source?: 'replace' | 'update' | 'updateMany';
1114
1657
  }>;
1658
+ /** `softDeleted` (2.3.0): a before-hook turned the delete into an update (`instead`), the documents are still stored. */
1115
1659
  'document:delete': ByUser<{
1116
1660
  collectionName: string;
1117
1661
  deleteResponse: Schemas['DeleteResponse'];
1118
- oldValues: Document[];
1662
+ oldValues: Document$1[];
1663
+ softDeleted?: boolean;
1664
+ }>;
1665
+ /** A soft-deleted document was restored (2.3.0); `oldValues` as for updates. */
1666
+ 'document:restore': ByUser<{
1667
+ collectionName: string;
1668
+ updateResponse: Schemas['UpdateResponse'];
1669
+ oldValues: Document$1[];
1119
1670
  }>;
1120
1671
  'bucket:drop': ByUser<{
1121
1672
  bucketName: string;
@@ -1176,18 +1727,26 @@ declare class EventBus {
1176
1727
  private readonly log;
1177
1728
  readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
1178
1729
  private readonly listeners;
1730
+ /** Listeners for some collections only (2.3.0): they make expensive payloads be read for these collections only. */
1731
+ private readonly scoped;
1179
1732
  private readonly observers;
1180
1733
  private readonly targets;
1181
1734
  constructor(log?: (message: string, error: unknown) => void);
1182
- /** Registers a listener; the returned function removes it. */
1183
- on<N extends EventName>(name: N, listener: EventListener<N>): () => void;
1735
+ /**
1736
+ * Registers a listener; the returned function removes it. With `collections` (2.3.0) it only gets the events of the collections the
1737
+ * function accepts, and the expensive parts of an event (old values) are only read for them.
1738
+ */
1739
+ on<N extends EventName>(name: N, listener: EventListener<N>, options?: {
1740
+ collections?: (collectionName: string) => boolean;
1741
+ }): () => void;
1742
+ private hasListener;
1184
1743
  /** Registers an observer (metrics); the returned function removes it. */
1185
1744
  observe(observer: EventObserver): () => void;
1186
1745
  /** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
1187
1746
  forward(target: EventTarget): () => void;
1188
1747
  private targetsFor;
1189
1748
  /** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
1190
- has(name: EventName): boolean;
1749
+ has(name: EventName, collectionName?: string): boolean;
1191
1750
  /** Sends an event without waiting for the listeners; a failure of a listener is logged. */
1192
1751
  publish<N extends EventName>(name: N, payload: MongocampEvents[N]): void;
1193
1752
  }
@@ -1232,6 +1791,269 @@ declare class ConfigPersistence {
1232
1791
  close(): void;
1233
1792
  }
1234
1793
 
1794
+ /**
1795
+ * Before-hooks of the document writes. Unlike the events of the `EventBus` (notifications after a write, not awaited, failures only logged),
1796
+ * an interceptor runs before the write, is awaited, and may change the write or refuse it:
1797
+ *
1798
+ * - the listeners run one after another in the order they were registered, each one sees the changes of the ones before;
1799
+ * - a listener changes the write in place on the payload (`event.documents.push(...)`, `event.filter = {...}`); the route reads the payload
1800
+ * back after all listeners ran;
1801
+ * - a listener refuses the write by throwing: a `MongocampError` is answered with its status (e.g. `MongocampError.badRequest(...)`), any
1802
+ * other error with 500 (and logged). Nothing is written then;
1803
+ * - the stages (`InterceptorStage`) order the interceptors of different purposes: `guard` → `change` → hooks of the host → `validate` →
1804
+ * `system`; within a stage the order of registration counts.
1805
+ */
1806
+ type Document = Record<string, unknown>;
1807
+ /** The fields of every interceptor payload. */
1808
+ interface InterceptorBase {
1809
+ user: UserInformation;
1810
+ /** The collection as given in the path (`orders`, or `otherdb:orders` for another database). */
1811
+ collectionName: string;
1812
+ /** The database of the collection, resolved (the default database when the path names none). */
1813
+ databaseName: string;
1814
+ /** The user has an administrator role (2.3.0; set by the routes, absent in payloads built elsewhere). */
1815
+ isAdmin?: boolean;
1816
+ }
1817
+ interface WriteInterceptorPayloads {
1818
+ /** Documents to insert: one for `PUT …/documents`, all of the request for `insertMany`, one batch for an import. */
1819
+ 'document:beforeInsert': InterceptorBase & {
1820
+ documents: Document[];
1821
+ source: 'insert' | 'insertMany' | 'import';
1822
+ /** For an import the line numbers of the documents (1-based); not set for the other sources, where the position is the index. */
1823
+ lines?: number[];
1824
+ };
1825
+ /**
1826
+ * A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.3.0): called by the route when the
1827
+ * write matched nothing, before it answers 404 — a hook that narrowed the filter (e.g. by a version) can explain why by throwing (409).
1828
+ */
1829
+ 'document:beforeReplace': InterceptorBase & {
1830
+ filter: Document;
1831
+ document: Document;
1832
+ onNoMatch?: () => void | Promise<void>;
1833
+ };
1834
+ /** An operator update (`$set`, ...) for the documents matched by `filter`; `many` for `updateMany`. `onNoMatch` as for a replace (single). */
1835
+ 'document:beforeUpdate': InterceptorBase & {
1836
+ filter: Document;
1837
+ update: Document;
1838
+ many: boolean;
1839
+ onNoMatch?: () => void | Promise<void>;
1840
+ };
1841
+ /**
1842
+ * A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.3.0) turns the delete into this
1843
+ * update (e.g. a deleted mark); the request is answered as a delete with the number of matched documents.
1844
+ */
1845
+ 'document:beforeDelete': InterceptorBase & {
1846
+ filter: Document;
1847
+ many: boolean;
1848
+ instead?: {
1849
+ update: Document;
1850
+ };
1851
+ };
1852
+ /**
1853
+ * Every read of documents (2.3.0) and the target of every update, replace and delete: a hook narrows what the request may see by pushing
1854
+ * conditions to `scopes` (`event.scopes.push({ tenant: 'a' })`); they are combined with the filter of the client by `$and`, so no client
1855
+ * filter widens them. `filter` is the filter of the client (to look at, changing it has no effect). `withDeleted`: an administrator asked
1856
+ * for soft-deleted documents too (`withDeleted=true`).
1857
+ */
1858
+ 'document:beforeRead': InterceptorBase & {
1859
+ filter: Document;
1860
+ operation: ReadOperation;
1861
+ scopes: Document[];
1862
+ withDeleted: boolean;
1863
+ };
1864
+ }
1865
+ /**
1866
+ * The kind of request a `document:beforeRead` scopes; `write` for the target of an update, replace or delete; `expand` (2.4.0) for the
1867
+ * documents a reference of another collection is expanded to.
1868
+ */
1869
+ type ReadOperation = 'list' | 'search' | 'count' | 'get' | 'export' | 'distinct' | 'aggregate' | 'schema' | 'write' | 'restore' | 'watch' | 'expand';
1870
+ type InterceptorName = keyof WriteInterceptorPayloads;
1871
+ type WriteInterceptor<N extends InterceptorName> = (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
1872
+ /**
1873
+ * The order of the interceptors of one write: `guard` (the server's own checks of what a client may write, e.g. protected fields), `change`
1874
+ * (default: hooks that change or refuse the write), then the hooks of the host (Nitro), `validate` (the schemas of declared collections)
1875
+ * and `system` (fields that the server writes after the validation, e.g. timestamps).
1876
+ */
1877
+ type InterceptorStage = 'guard' | 'change' | 'validate' | 'system';
1878
+ /**
1879
+ * A hook system of the host that runs the interceptors too, e.g. the hooks of a Nitro app (`mongocamp:document:beforeInsert`). `listens`
1880
+ * is asked on every write, so hooks that the host adds later count right away; `call` is awaited.
1881
+ */
1882
+ interface InterceptorTarget {
1883
+ listens: (name: InterceptorName) => boolean;
1884
+ call: (name: InterceptorName, payload: WriteInterceptorPayloads[InterceptorName]) => unknown;
1885
+ }
1886
+ declare class WriteInterceptors {
1887
+ private readonly stages;
1888
+ private readonly targets;
1889
+ /** Registers an interceptor (stage `change` unless given); the returned function removes it. */
1890
+ on<N extends InterceptorName>(name: N, interceptor: WriteInterceptor<N>, options?: {
1891
+ stage?: InterceptorStage;
1892
+ }): () => void;
1893
+ /** Runs the interceptors in a hook system of the host as well (`connectHooks`), after the stages `guard` and `change`; the returned function stops it. */
1894
+ forward(target: InterceptorTarget): () => void;
1895
+ private targetsFor;
1896
+ private registered;
1897
+ /** Whether an interceptor is registered (here or in a host), so that a route builds no payload when nobody waits for it. */
1898
+ has(name: InterceptorName): boolean;
1899
+ private runStage;
1900
+ /**
1901
+ * Runs the interceptors stage by stage, one after another, and answers the payload with their changes. Rejects with the error of the first
1902
+ * interceptor that throws; the later ones do not run.
1903
+ */
1904
+ run<N extends InterceptorName>(name: N, payload: WriteInterceptorPayloads[N]): Promise<WriteInterceptorPayloads[N]>;
1905
+ }
1906
+
1907
+ interface InsertError {
1908
+ index: number;
1909
+ code: number;
1910
+ message: string;
1911
+ }
1912
+ interface ImportResponse {
1913
+ read: number;
1914
+ inserted: number;
1915
+ failed: number;
1916
+ errors: InsertError[];
1917
+ errorsTruncated: boolean;
1918
+ }
1919
+ declare class ImportState {
1920
+ read: number;
1921
+ inserted: number;
1922
+ failed: number;
1923
+ errors: InsertError[];
1924
+ errorsTruncated: boolean;
1925
+ /** The ids of the documents that were stored, as stored (for the compensation). */
1926
+ storedIds: unknown[];
1927
+ /** The ids as text, for the events of the caller. */
1928
+ get storedIdTexts(): string[];
1929
+ addErrors(errors: InsertError[]): void;
1930
+ get response(): ImportResponse;
1931
+ }
1932
+
1933
+ /**
1934
+ * How documents are written in responses (query parameter `extendedJson`).
1935
+ *
1936
+ * - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
1937
+ * decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
1938
+ * A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
1939
+ * - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
1940
+ * ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
1941
+ */
1942
+ type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
1943
+ /** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
1944
+ declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
1945
+ /** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
1946
+ declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
1947
+
1948
+ interface FindRequest {
1949
+ filter: Record<string, unknown>;
1950
+ sort: Record<string, unknown>;
1951
+ projection: Record<string, unknown>;
1952
+ }
1953
+
1954
+ /**
1955
+ * The scope of a read (2.3.0): the conditions of the `document:beforeRead` hooks (soft delete, owner, tenancy of an application) combined
1956
+ * with the filter of the client. Every route that reads documents, and every update, replace and delete for its target, goes through it;
1957
+ * without a hook nothing is done.
1958
+ */
1959
+ /** The filter with the scopes, combined by `$and`; empty parts are left out. */
1960
+ declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]): Document$2;
1961
+ /** The filter of a request with the scopes of the hooks. */
1962
+ declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
1963
+ interface ScopeOptions {
1964
+ /** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
1965
+ withDeleted?: boolean;
1966
+ }
1967
+ /** `withDeleted=true` of a read route (2.3.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
1968
+ declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
1969
+
1970
+ interface ReadOptions extends ScopeOptions {
1971
+ /** The kind of request for the hooks of `document:beforeRead` (default by operation). */
1972
+ operation?: ReadOperation;
1973
+ /** References to expand (2.4.0): declared ref fields of the collection, at most `MaxExpands`. */
1974
+ expand?: readonly string[];
1975
+ }
1976
+ interface PageResult {
1977
+ documents: Document$2[];
1978
+ info: PaginationInfo;
1979
+ }
1980
+ declare class DocumentService {
1981
+ private readonly context;
1982
+ constructor(context: MongocampContext);
1983
+ /** The collection of a name as the routes take it (`orders`, `otherdb:orders`). */
1984
+ collection(name: string): Collection;
1985
+ /** The grant of the caller; `withDeleted` only for the administrators of the collection. */
1986
+ private require;
1987
+ /** The filter with the read scope of the caller. */
1988
+ scope(user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
1989
+ /**
1990
+ * The declared references of `fields` (2.4.0); 400 for a name that is no reference of the collection and for more than `MaxExpands`.
1991
+ * Checked before anything is read.
1992
+ */
1993
+ refs(collection: string, fields: readonly string[] | undefined): ResolvedRef[];
1994
+ /**
1995
+ * Replaces the references of the documents by the documents they point to (2.4.0). Each target is read once per reference (`$in` of the
1996
+ * ids) with the grant and the read scope of the **target** for the same user, without its secret fields: a reference the user cannot
1997
+ * read directly becomes `null` (an array leaves it out), so an expansion never shows more than a direct read.
1998
+ */
1999
+ expand(user: AuthorizedUser, documents: Document$2[], refs: readonly ResolvedRef[]): Promise<Document$2[]>;
2000
+ /** A page of documents (list, find, search), with the references of `options.expand` expanded. */
2001
+ page(user: AuthorizedUser, collection: string, request: FindRequest, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
2002
+ /** The number of documents of a filter. */
2003
+ count(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<number>;
2004
+ /** One document by the id of the path (any type of id), `null` when it is missing or not in the scope of the caller. */
2005
+ get(user: AuthorizedUser, collection: string, id: string, options?: ReadOptions): Promise<Document$2 | null>;
2006
+ /** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
2007
+ exportFilter(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<{
2008
+ filter: Document$2;
2009
+ scope: Document$2;
2010
+ }>;
2011
+ /** The distinct values of a field, as aggregation results `{ _id, field }`. */
2012
+ distinct(user: AuthorizedUser, collection: string, field: string, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
2013
+ /**
2014
+ * An aggregation: `prefix` (the client's filter, the unset of secrets) and the stages of the client, after the scope of the caller as
2015
+ * first `$match`. The checks of the pipeline (denied stages) are the route's.
2016
+ */
2017
+ aggregate(user: AuthorizedUser, collection: string, prefix: Document$2[], stages: Document$2[], allowDiskUse: boolean, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
2018
+ /**
2019
+ * Runs the before-hooks of a write (after auth and decoding, before the old values are read and the write is done) and answers the
2020
+ * payload with their changes. A hook that refuses the write throws.
2021
+ */
2022
+ private intercept;
2023
+ /**
2024
+ * The insert hooks: they may change the documents, but not their number (the errors of an insert and of an import name the documents by
2025
+ * their position). A hook that does not want a document refuses the write.
2026
+ */
2027
+ private interceptInsert;
2028
+ /** The documents before a change, read only when a listener waits for them; at most `MaxOldValues`. */
2029
+ private oldValues;
2030
+ /** Deletes the documents of the filter, or applies the update of a before-hook instead (soft delete); answers the number of documents. */
2031
+ private deleteOrInstead;
2032
+ private inserted;
2033
+ private updated;
2034
+ private deleted;
2035
+ /** Inserts one document (decoded). */
2036
+ insert(user: AuthorizedUser, collection: string, document: Document$2): Promise<Schemas['InsertResponse']>;
2037
+ /** Inserts documents; `ordered: false` stores the ones that can be stored and reports the others in `errors`. */
2038
+ insertMany(user: AuthorizedUser, collection: string, input: Document$2[], ordered?: boolean): Promise<Schemas['InsertResponse']>;
2039
+ /** Imports the lines of a body stream (all or nothing); the hooks see the valid documents of each batch. */
2040
+ import(user: AuthorizedUser, collection: string, body: ReadableStream<Uint8Array> | null, maxBytes: number): Promise<ImportState>;
2041
+ /** Replaces the document of the path id (decoded body); 404 when it is missing or not in the scope, 409 of a version check. */
2042
+ replace(user: AuthorizedUser, collection: string, id: string, body: Document$2): Promise<Schemas['UpdateResponse']>;
2043
+ /** Changes the document of the path id with an operator update (`$set`, ...). */
2044
+ update(user: AuthorizedUser, collection: string, id: string, operators: Document$2): Promise<Schemas['UpdateResponse']>;
2045
+ /** Changes the documents of a filter (checked by the caller: not empty unless intended). */
2046
+ updateMany(user: AuthorizedUser, collection: string, filter: Document$2, operators: Document$2): Promise<Schemas['UpdateResponse']>;
2047
+ /** Deletes the document of the path id (or marks it, soft delete); 404 when it is missing or not in the scope. */
2048
+ remove(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['DeleteResponse']>;
2049
+ /** Deletes the documents of a filter (checked by the caller). */
2050
+ removeMany(user: AuthorizedUser, collection: string, filter: Document$2): Promise<Schemas['DeleteResponse']>;
2051
+ /** Brings a soft-deleted document back (collections declared with softDelete). */
2052
+ restore(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['UpdateResponse']>;
2053
+ /** The audit records of a filter (a document or the collection), newest first. */
2054
+ auditRecords(filter: Document$2, paging: Paging, count?: CountMode): Promise<PageResult>;
2055
+ }
2056
+
1235
2057
  /**
1236
2058
  * Jobs (`JobPlugin.scala`, `JobRoutes.scala`) on croner. A job is a document `JobConfig` in `<AUTH_PREFIX>jobs`; its `className` names a
1237
2059
  * handler of the registry (the Scala server loaded JVM classes). Cron expressions use the syntax of croner: 5, 6 or 7 fields (seconds and
@@ -1370,6 +2192,12 @@ interface MongocampContext {
1370
2192
  auth: AuthService;
1371
2193
  configurations: ConfigPersistence;
1372
2194
  events: EventBus;
2195
+ /** The before-hooks of the document writes (awaited, may change or refuse a write). */
2196
+ interceptors: WriteInterceptors;
2197
+ /** The documents of the collections for one caller, without HTTP (2.4.0): the routes and the server collection use it. */
2198
+ documents: DocumentService;
2199
+ /** The declared collections (`server.use(collections([...]))`), empty without. */
2200
+ collections: CollectionRegistry;
1373
2201
  jobs: JobScheduler;
1374
2202
  /** The metrics, with `METRICS_ENABLED` only. */
1375
2203
  metrics?: MongocampMetrics;
@@ -1380,17 +2208,76 @@ interface MongocampContext {
1380
2208
  }
1381
2209
 
1382
2210
  /**
1383
- * An optional part of the server that a host switches on with `server.use(...)`, typically from a Nitro plugin on the hook
1384
- * `mongocamp:ready`. `setup` starts it and answers the function that stops it (called by `server.close()`).
2211
+ * The documents of a collection in server code (2.4.0): `server.collection('orders', { user })` — the same operations as the API
2212
+ * (`DocumentService`), so grants, the read scope (owner, soft delete, hooks), validation, the behaviours (timestamps, version, audit) and
2213
+ * the events are the same as for a request of that user. No HTTP, no JSON: documents come and go as driver values (`ObjectId`, `Date`;
2214
+ * numbers as JavaScript numbers).
2215
+ *
2216
+ * For writes that must not go through the rules (migrations, bulk scripts) use the driver (`server.context.database`).
1385
2217
  */
1386
- interface MongocampFeature {
1387
- name: string;
1388
- setup: (context: MongocampContext) => Promise<() => void | Promise<void>> | (() => void | Promise<void>);
2218
+ /**
2219
+ * Who works with the collection: a user id, an authorized user, a `Request` (its credentials; in Nitro the request of the event), or
2220
+ * `'system'` — an administrator without grant checks and owner rules, for jobs and seeds.
2221
+ */
2222
+ type ServerCollectionUser = string | AuthorizedUser | Request | 'system';
2223
+ interface ServerCollectionOptions {
2224
+ user: ServerCollectionUser;
1389
2225
  }
1390
- /** Every request as a document of `<AUTH_PREFIX>request_logging`. */
1391
- declare function requestLogging(): MongocampFeature;
1392
- /** `/system/monitoring/{runtime,system,mongodb,events,prometheus}` and the snapshots of `LOGGING_METRICS_MONGODB_*`. */
1393
- declare function metrics(): MongocampFeature;
2226
+ interface ServerFindOptions {
2227
+ /** A MongoDB filter, or a Lucene filter as text (`status:open AND qty:[1 TO 5]`). */
2228
+ filter?: Document$2 | string;
2229
+ /** `{ field: 1 | -1 }` or fields with `-` for descending. */
2230
+ sort?: Document$2 | string[];
2231
+ projection?: Document$2 | string[];
2232
+ page?: number;
2233
+ rowsPerPage?: number;
2234
+ count?: CountMode;
2235
+ /** Soft-deleted documents too (administrators of the collection). */
2236
+ withDeleted?: boolean;
2237
+ /** References to expand (2.4.0): declared ref fields, read with the grant and scope of their collection. */
2238
+ expand?: readonly string[];
2239
+ }
2240
+ interface ServerPage<T> {
2241
+ documents: T[];
2242
+ page: number;
2243
+ rowsPerPage: number;
2244
+ countRows?: number;
2245
+ countPages?: number;
2246
+ }
2247
+ /** A document that was read (with `_id`), or its id. */
2248
+ type ServerDocumentIdentity = string | number | ObjectId | {
2249
+ _id: unknown;
2250
+ };
2251
+ interface ServerCollection<T, I = T> {
2252
+ readonly name: string;
2253
+ find: (options?: ServerFindOptions) => Promise<T[]>;
2254
+ findPage: (options?: ServerFindOptions) => Promise<ServerPage<T>>;
2255
+ /** The document, `null` when it is missing or not in the scope of the user. */
2256
+ findById: (id: ServerDocumentIdentity, options?: {
2257
+ withDeleted?: boolean;
2258
+ expand?: readonly string[];
2259
+ }) => Promise<T | null>;
2260
+ count: (filter?: Document$2 | string, options?: {
2261
+ withDeleted?: boolean;
2262
+ }) => Promise<number>;
2263
+ insert: (document: I) => Promise<Schemas['InsertResponse']>;
2264
+ insertMany: (documents: I[], options?: {
2265
+ ordered?: boolean;
2266
+ }) => Promise<Schemas['InsertResponse']>;
2267
+ /** Replaces the document; given the document that was read, its version is checked (409 when someone changed it in between). */
2268
+ replace: (target: ServerDocumentIdentity, document: I) => Promise<Schemas['UpdateResponse']>;
2269
+ /** Sets the given fields (`null` removes one); given the document that was read, its version is checked. */
2270
+ update: (target: ServerDocumentIdentity, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
2271
+ updateMany: (filter: Document$2 | string, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
2272
+ remove: (target: ServerDocumentIdentity) => Promise<Schemas['DeleteResponse']>;
2273
+ removeMany: (filter: Document$2 | string) => Promise<Schemas['DeleteResponse']>;
2274
+ restore: (target: ServerDocumentIdentity) => Promise<Schemas['UpdateResponse']>;
2275
+ /** The audit records of the document, newest first (collections declared with `audit`). */
2276
+ history: (target: ServerDocumentIdentity) => Promise<Document$2[]>;
2277
+ }
2278
+ /** The administrator of server code: every grant, no owner rule (`adminBypass`). */
2279
+ declare const SystemUser: AuthorizedUser;
2280
+ declare function createServerCollection<T = Document$2, I = T>(context: MongocampContext, name: string, options: ServerCollectionOptions): ServerCollection<T, I>;
1394
2281
 
1395
2282
  interface MongocampServerOptions extends DatabaseOptions {
1396
2283
  /** Environment variables, `process.env` when omitted. */
@@ -1417,6 +2304,10 @@ interface MongocampServerOptions extends DatabaseOptions {
1417
2304
  on?: {
1418
2305
  [N in EventName]?: EventListener<N>;
1419
2306
  };
2307
+ /** Before-hooks of the document writes, registered before the start; later ones with `server.interceptors.on(...)`. */
2308
+ intercept?: {
2309
+ [N in InterceptorName]?: WriteInterceptor<N>;
2310
+ };
1420
2311
  /**
1421
2312
  * The jobs: `false` keeps the scheduler of this instance from running the jobs on their schedule (several instances of an application
1422
2313
  * need only one that runs them; the configuration `JOBS_ENABLED=false` does the same); `handlers` adds job handlers by class name (later
@@ -1447,6 +2338,11 @@ interface MongocampServer {
1447
2338
  routes: () => string[];
1448
2339
  /** The events of the server (`hookable`): `server.events.on('document:create', event => ...)`. */
1449
2340
  events: EventBus;
2341
+ /**
2342
+ * The before-hooks of the document writes, awaited and able to change or refuse a write:
2343
+ * `server.interceptors.on('document:beforeInsert', ({ documents }) => ...)`.
2344
+ */
2345
+ interceptors: WriteInterceptors;
1450
2346
  /**
1451
2347
  * Adds a job handler after the start: the stored jobs with this `className` are scheduled right away. Returns a function that removes the
1452
2348
  * handler again. A Nuxt application registers its handlers this way in a Nitro plugin (`(await useMongocampCore()).registerJobHandler(...)`).
@@ -1457,6 +2353,11 @@ interface MongocampServer {
1457
2353
  * same name is used once; it is stopped by `close`.
1458
2354
  */
1459
2355
  use: (feature: MongocampFeature) => Promise<void>;
2356
+ /**
2357
+ * The documents of a collection for a user in server code (2.4.0): the same grants, scope, validation, behaviours and events as the API.
2358
+ * `user`: an id, an authorized user, a request (its credentials) or `'system'`.
2359
+ */
2360
+ collection: <T = Record<string, unknown>, I = T>(name: string, options: ServerCollectionOptions) => ServerCollection<T, I>;
1460
2361
  close: () => Promise<void>;
1461
2362
  }
1462
2363
  /** Creates and connects a MongoCamp server. */
@@ -1493,11 +2394,19 @@ declare const ErrorCodes: {
1493
2394
  readonly invalidCollectionName: 4007;
1494
2395
  readonly invalidImportLine: 4008;
1495
2396
  readonly invalidCollectionOptions: 4009;
2397
+ /** A document that a schema or a before-hook refuses; `ErrorDescription.issues` names the fields (the validator of MongoDB answers 121). */
2398
+ readonly validationFailed: 4010;
1496
2399
  readonly collectionExists: 4091;
2400
+ /** A write based on an outdated version of a versioned document (2.3.0); `ErrorDescription.current` is the stored document. */
2401
+ readonly versionConflict: 4092;
2402
+ /** A versioned collection with `required: true` got a write without version (2.3.0). */
2403
+ readonly versionRequired: 4281;
1497
2404
  readonly badInsertRequest: 4401;
1498
2405
  readonly idMissingForReplace: 4402;
1499
2406
  readonly authMethodNotImplemented: 5001;
1500
2407
  readonly mvnRepositoryConfigurationInvalid: 5002;
2408
+ /** Live updates need change streams: a replica set or a sharded cluster (2.3.0). */
2409
+ readonly changeStreamsUnsupported: 5011;
1501
2410
  readonly unauthorizedUser: 4011;
1502
2411
  readonly unauthorizedUserForOtherUser: 4012;
1503
2412
  readonly forbiddenStage: 4031;
@@ -1547,21 +2456,6 @@ declare function convertIdValue(id: unknown): unknown;
1547
2456
  */
1548
2457
  declare function pathIdFilter(id: string): PlainObject;
1549
2458
 
1550
- /**
1551
- * How documents are written in responses (query parameter `extendedJson`).
1552
- *
1553
- * - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
1554
- * decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
1555
- * A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
1556
- * - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
1557
- * ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
1558
- */
1559
- type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
1560
- /** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
1561
- declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
1562
- /** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
1563
- declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
1564
-
1565
2459
  /**
1566
2460
  * The queries that the Lucene parser produces (the subset of `org.apache.lucene.search.Query` that `LuceneQueryConverter` knows),
1567
2461
  * plus the kinds it does not support, which fail in the converter like in the Scala driver.
@@ -1647,19 +2541,233 @@ declare function luceneToFilter(input: string, defaultField: string, options?: C
1647
2541
  */
1648
2542
  declare function filterParameter(input: string | null | undefined, options?: ConvertOptions, parameter?: string): Record<string, unknown>;
1649
2543
 
2544
+ /**
2545
+ * The `$jsonSchema` validator of MongoDB for a declared collection (2.3.0), converted from the JSON Schema that its Standard Schema library
2546
+ * exports (Standard JSON Schema, `~standard.jsonSchema.output`): the stored shape of the documents.
2547
+ *
2548
+ * MongoDB knows draft 4 with `bsonType` and without some keywords, and the documents hold BSON values:
2549
+ * - `integer` is `int`, `long` or a whole `double` (the API stores whole numbers as `long`, the driver writes the numbers of a schema as
2550
+ * `int`, or as `double` outside the int32 range), `number` any of `double`, `int`, `long`, `decimal`;
2551
+ * - dates and ObjectIds have no JSON Schema form: the libraries are asked to mark them (`x-bsonType`, Zod `override`, ArkType `fallback`),
2552
+ * Zod is asked not to throw on other values without JSON form (`unrepresentable: 'any'`, no constraint then);
2553
+ * - `$ref`s are inlined, `const` becomes `enum`, the numeric `exclusiveMinimum` of newer drafts the boolean of draft 4, `prefixItems` the
2554
+ * `items` list; annotations (`$schema`, `default`, `format`, `examples`, ...) are dropped, other keywords MongoDB does not know are
2555
+ * dropped with a warning (the validator is then looser than the schema);
2556
+ * - `_id` is always allowed, also with `additionalProperties: false`.
2557
+ *
2558
+ * A declaration with `validator` uses that instead; a schema without JSON Schema export (e.g. Valibot without its converter) gets none.
2559
+ */
2560
+ interface ConversionResult {
2561
+ /** The `$jsonSchema` (the value, without the `$jsonSchema` key); undefined when the schema has no JSON Schema form. */
2562
+ jsonSchema: Document$2 | undefined;
2563
+ warnings: string[];
2564
+ }
2565
+ type Schema = Record<string, unknown>;
2566
+ interface ZodOverrideContext {
2567
+ zodSchema?: {
2568
+ _zod?: {
2569
+ def?: {
2570
+ type?: string;
2571
+ };
2572
+ bag?: {
2573
+ Class?: {
2574
+ name?: string;
2575
+ };
2576
+ };
2577
+ };
2578
+ };
2579
+ jsonSchema: Schema;
2580
+ }
2581
+ interface ArkTypeFallbackContext {
2582
+ code?: string;
2583
+ base?: Schema;
2584
+ proto?: {
2585
+ name?: string;
2586
+ };
2587
+ }
2588
+ /** The options of the libraries that mark the BSON values without JSON form; every library reads only its own. */
2589
+ declare const bsonMarkerOptions: {
2590
+ unrepresentable: string;
2591
+ override: (context: ZodOverrideContext) => void;
2592
+ fallback: (context: ArkTypeFallbackContext) => Schema;
2593
+ };
2594
+ /**
2595
+ * The `$jsonSchema` of a declaration: its `validator`, else converted from the JSON Schema of its schema; with the fields of its behaviours
2596
+ * added (2.3.0, see `withSystemFields`) unless `systemFields: false`.
2597
+ */
2598
+ declare function validatorOf(definition: MongocampCollectionDefinition, options?: {
2599
+ systemFields?: boolean;
2600
+ }): ConversionResult;
2601
+ /**
2602
+ * A copy of a `$jsonSchema` with the fields of the behaviours as typed properties (nested objects for dot paths), so a validator with
2603
+ * `additionalProperties: false` lets them through and refuses wrong types. They are not required: documents stored before the behaviour was
2604
+ * switched on stay valid.
2605
+ */
2606
+ declare function withSystemFields(jsonSchema: Document$2, behaviours: ResolvedBehaviours): Document$2;
2607
+ /** Converts a JSON Schema (draft 2020-12 or 07) of the documents to a `$jsonSchema` of MongoDB. */
2608
+ declare function toMongoJsonSchema(root: Record<string, unknown>): ConversionResult;
2609
+
2610
+ /**
2611
+ * What clients may not write (2.3.0): the fields of behaviours (timestamps, owner, version, deleted mark) and the `protectedFields` of a
2612
+ * declaration. The guard runs first (stage `guard`), so before-hooks and Nitro hooks of the application can still set protected fields;
2613
+ * writes with the driver (`useMongocampCore()`, scripts) are not checked at all.
2614
+ *
2615
+ * - inserts: the fields are removed from the documents;
2616
+ * - replaces: the stored values are kept (protected fields at once, so the schema sees them; fields of behaviours again after the
2617
+ * validation, which may strip fields the schema does not know);
2618
+ * - updates: operators on the fields or inside them are removed; an object set on a parent of a field of a behaviour is set field by field
2619
+ * (`metaData: {...}` → `metaData.tags`, ...), so the fields of the behaviour stay.
2620
+ */
2621
+ /** The paths of a declaration that clients cannot write: fields of behaviours first, then the protected fields. */
2622
+ declare function guardedPaths(behaviours: ResolvedBehaviours): {
2623
+ system: string[];
2624
+ protected: string[];
2625
+ };
2626
+ /** A copy of a document without the guarded paths (nested objects copied where a path goes through them). */
2627
+ declare function stripDocument(document: Document$2, paths: readonly string[]): Document$2;
2628
+ /**
2629
+ * An update without the guarded paths: keys at or below a guarded path are removed; a `$set` of an object on a parent of a field of a
2630
+ * behaviour is set field by field, without the guarded fields; other operators on such a parent are removed.
2631
+ */
2632
+ declare function stripUpdate(update: Document$2, guarded: readonly string[], system: readonly string[]): Document$2;
2633
+
2634
+ /**
2635
+ * The behaviour `softDelete` (2.3.0): a delete sets the deleted mark (`deletedAt`) instead of removing the document, every read hides
2636
+ * marked documents (`document:beforeRead`), an administrator sees them with `withDeleted=true`, `POST …/documents/{id}/restore` removes
2637
+ * the mark, and `purgeAfterDays` removes marked documents for good (a TTL index).
2638
+ */
2639
+ type SoftDelete = NonNullable<ResolvedBehaviours['softDelete']>;
2640
+ /** The condition of the documents that are not deleted. */
2641
+ declare function notDeleted(softDelete: SoftDelete): Document$2;
2642
+ /** The update that restores a document: the mark removed, the change fields of `timestamps` set. */
2643
+ declare function restoreUpdate(behaviours: ResolvedBehaviours, stamp: {
2644
+ now: Date;
2645
+ userId: string;
2646
+ }): Document$2;
2647
+ /** The name of the TTL index of `purgeAfterDays`. */
2648
+ declare function purgeIndexName(softDelete: SoftDelete): string;
2649
+ /**
2650
+ * The TTL index of `purgeAfterDays`: created, changed (`collMod`) when the days differ, dropped when the option is gone. Never throws, a
2651
+ * failure is logged.
2652
+ */
2653
+ declare function syncPurgeIndex(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<'created' | 'changed' | 'dropped' | 'unchanged' | 'failed'>;
2654
+
2655
+ /**
2656
+ * The behaviour `owner` (2.3.0): every document belongs to the user who created it. Only the owner changes, replaces, deletes and restores
2657
+ * it; reads follow `read` — `own` (default) the owner only, `all` everybody with the read grant, or a function of the application.
2658
+ * A document of someone else is answered like a missing one (404), so nobody learns which ids exist. Administrators read and write every
2659
+ * document (`adminBypass`, default true). The collection grants still apply first: owner rules narrow them, never widen them.
2660
+ *
2661
+ * The owner field is the `createdBy` field of `timestamps` when set (written there), else `owner` (written here, on insert).
2662
+ */
2663
+ type Owner = NonNullable<ResolvedBehaviours['owner']>;
2664
+ /** The condition of the documents of a user. */
2665
+ declare function ownedBy(owner: Owner, userId: string): Document$2;
2666
+
2667
+ /**
2668
+ * The behaviour `audit` (2.3.0): every write to the collection leaves a record with the operation, the user, the time and the document
2669
+ * before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
2670
+ *
2671
+ * Built on the events, so it is best effort like them: written after the request is answered, a failure is logged and does not fail the
2672
+ * write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
2673
+ * ids of the documents only.
2674
+ */
2675
+ type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
2676
+ interface AuditRecord {
2677
+ collection: string;
2678
+ database: string;
2679
+ /** The `_id` of the document; absent on a summary record. */
2680
+ documentId?: unknown;
2681
+ operation: AuditOperation;
2682
+ user: string;
2683
+ at: Date;
2684
+ before?: Document$2;
2685
+ after?: Document$2;
2686
+ /** A summary of a write of many documents: the number of documents and how many of them have a record. */
2687
+ summary?: {
2688
+ count: number;
2689
+ recorded: number;
2690
+ };
2691
+ /** When MongoDB deletes the record (TTL). */
2692
+ expiresAt: Date;
2693
+ }
2694
+ declare const AuditCollection = "audit";
2695
+ /** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
2696
+ declare function auditCollectionOf(context: Pick<MongocampContext, 'database'>): Collection<AuditRecord>;
2697
+ /** The records of one write. */
2698
+ declare function auditRecords(input: {
2699
+ declared: DeclaredCollection;
2700
+ operation: AuditOperation;
2701
+ user: string;
2702
+ at: Date;
2703
+ documents: Array<{
2704
+ before?: Document$2;
2705
+ after?: Document$2;
2706
+ }>;
2707
+ count?: number;
2708
+ }): AuditRecord[];
2709
+ /** Creates the indexes of the audit records (history per document, TTL); idempotent. */
2710
+ declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
2711
+
2712
+ /**
2713
+ * The behaviour `versioned` (2.3.0): a replace or partial update that sends the version of the document it is based on only succeeds when
2714
+ * the document still has that version; otherwise it answers 409 with the stored document (`current`) instead of overwriting the change of
2715
+ * someone else. In the same write, no read-then-write race.
2716
+ *
2717
+ * - mode `counter`: a number (`_v`), 0 on insert, increased by every write (also updateMany, soft delete and restore);
2718
+ * - mode `timestamp`: the `updatedAt` field of `timestamps` is the version (no extra field);
2719
+ * - without version in the request the write is not checked (last write wins) — unless `required`, then 428.
2720
+ *
2721
+ * The version a client sends is taken before the guard removes it (it is never stored as sent).
2722
+ */
2723
+ type Versioned = NonNullable<ResolvedBehaviours['versioned']>;
2724
+ /** The version in a replacing document. */
2725
+ declare function versionInDocument(document: Document$2, versioned: Versioned): unknown;
2726
+ /** The version in an update (`$set` of the path, or of an object above it). */
2727
+ declare function versionInUpdate(update: Document$2, versioned: Versioned): unknown;
2728
+ /** The filter with the version condition. */
2729
+ declare function withVersion(filter: Document$2, versioned: Versioned, version: unknown): Document$2;
2730
+ /** An update with the increase of the counter (mode `counter`; the timestamp mode needs nothing, timestamps writes the new version). */
2731
+ declare function withIncrement(update: Document$2, versioned: Versioned): Document$2;
2732
+
2733
+ /**
2734
+ * The behaviour `timestamps` (2.3.0): the server writes the creation and change time and, when configured, the user of the request
2735
+ * (`createdBy`, `updatedBy`) on every write path. Runs in the stage `system`, after the validation, and after the guard put the stored
2736
+ * values of a replace back — so the creation values survive every later write. Clients cannot send these fields (guard).
2737
+ */
2738
+ type Timestamps = NonNullable<ResolvedBehaviours['timestamps']>;
2739
+ /** The values of a write: one time for all documents of a request (or a batch of an import) and the user of the request. */
2740
+ interface WriteStamp {
2741
+ now: Date;
2742
+ userId: string;
2743
+ }
2744
+ /** Sets the creation and change fields of a new document. */
2745
+ declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2746
+ /**
2747
+ * Sets the change fields of a replacing document; the creation fields stay as stored (put back by the guard), a document without them
2748
+ * (stored before the behaviour was switched on) gets the values of this write.
2749
+ */
2750
+ declare function stampReplace(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2751
+ /** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
2752
+ declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
2753
+
1650
2754
  /**
1651
2755
  * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
1652
- * the server once it is started. An extension of an application is then a plain Nitro plugin:
2756
+ * the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
2757
+ * payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
1653
2758
  *
1654
2759
  * export default definePlugin((nitroApp) => {
1655
2760
  * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
1656
2761
  * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
2762
+ * nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
1657
2763
  * })
1658
2764
  */
1659
2765
  type MongocampHooks = {
1660
2766
  'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
1661
2767
  } & {
1662
2768
  [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
2769
+ } & {
2770
+ [N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
1663
2771
  };
1664
2772
  /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
1665
2773
  interface HookSystem {
@@ -1669,10 +2777,15 @@ declare const HookPrefix = "mongocamp:";
1669
2777
  /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
1670
2778
  declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
1671
2779
  /**
1672
- * Connects a started server with the hooks of its host: forwards the events and calls `mongocamp:ready` (awaited, so features that the
1673
- * plugins switch on are active before the first request is answered).
2780
+ * Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
2781
+ * hooks with a listener cost anything. The returned function stops it.
2782
+ */
2783
+ declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
2784
+ /**
2785
+ * Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
2786
+ * features that the plugins switch on are active before the first request is answered).
1674
2787
  */
1675
2788
  declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
1676
2789
 
1677
- export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, forwardEventsToHooks, luceneQueryToFilter, luceneToFilter, metrics, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, requestLogging, stringifyJson };
1678
- export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, EventTarget, ExtendedJsonMode, FetchOptions, HookSystem, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, RequestLog, VersionInfo };
2790
+ export { AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2791
+ export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, EventListener, EventName, EventTarget, ExpandedDocument, ExtendedJsonMode, FetchOptions, Grant, HookSystem, IndexDeclaration, IndexDirection, IndexOptions, IndexSyncResult, InferDocument, InferDocumentInput, InferRefs, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RefDeclaration, RefTargets, RequestLog, ResolvedBehaviours, ResolvedIndex, ResolvedRef, Role, ScopeOptions, ServerCollection, ServerCollectionOptions, ServerCollectionUser, ServerDocumentIdentity, ServerFindOptions, ServerPage, SoftDeleteOptions, SystemFields, TimestampsOptions, UserInformation, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };