@sfxcode/mongocamp-server-core 2.3.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 +440 -61
  2. package/dist/index.mjs +1808 -1074
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { HTTPError, getRouterParam, createEventStream, H3 } from 'h3';
2
- import { MongoError, MongoServerError, MongoBulkWriteError, MongoNetworkError, MongoServerSelectionError, MongoTopologyClosedError, MongoParseError, Long, Int32, Double, MongoClient, Decimal128, ObjectId, MaxKey, MinKey, UUID, BSONRegExp, Timestamp, Binary, BSONSymbol, Code, BSON, GridFSBucket } from 'mongodb';
2
+ import { MongoError, MongoServerError, MongoBulkWriteError, MongoNetworkError, MongoServerSelectionError, MongoTopologyClosedError, MongoParseError, Long, Int32, Double, MongoClient, Decimal128, ObjectId, MaxKey, MinKey, UUID, BSONRegExp, Timestamp, Binary, BSON, BSONSymbol, Code, GridFSBucket } from 'mongodb';
3
3
  import { Cron } from 'croner';
4
4
  import { randomBytes, timingSafeEqual, createHash, scrypt, randomUUID, createHmac } from 'node:crypto';
5
5
  import { createHooks } from 'hookable';
@@ -136,15 +136,15 @@ const ErrorCodes = {
136
136
  /** A document that a schema or a before-hook refuses; `ErrorDescription.issues` names the fields (the validator of MongoDB answers 121). */
137
137
  validationFailed: 4010,
138
138
  collectionExists: 4091,
139
- /** A write based on an outdated version of a versioned document (2.4.0); `ErrorDescription.current` is the stored document. */
139
+ /** A write based on an outdated version of a versioned document (2.3.0); `ErrorDescription.current` is the stored document. */
140
140
  versionConflict: 4092,
141
- /** A versioned collection with `required: true` got a write without version (2.4.0). */
141
+ /** A versioned collection with `required: true` got a write without version (2.3.0). */
142
142
  versionRequired: 4281,
143
143
  badInsertRequest: 4401,
144
144
  idMissingForReplace: 4402,
145
145
  authMethodNotImplemented: 5001,
146
146
  mvnRepositoryConfigurationInvalid: 5002,
147
- /** Live updates need change streams: a replica set or a sharded cluster (2.4.0). */
147
+ /** Live updates need change streams: a replica set or a sharded cluster (2.3.0). */
148
148
  changeStreamsUnsupported: 5011,
149
149
  unauthorizedUser: 4011,
150
150
  unauthorizedUserForOtherUser: 4012,
@@ -575,7 +575,7 @@ const DefaultJobGroup = "Default";
575
575
  const DefaultJobPriority = 1;
576
576
  const CleanUpTokenJobClass = "dev.mongocamp.server.jobs.CleanUpTokenJob";
577
577
  const CleanUpTokenJob = { name: "CleanUpTokenJob", className: CleanUpTokenJobClass, description: "", cronExpression: "0 */5 * * * *", group: "CleanUp", priority: 10 };
578
- const keyOf = (group, name) => `${group}\0${name}`;
578
+ const keyOf$1 = (group, name) => `${group}\0${name}`;
579
579
  function checkCronExpression(expression) {
580
580
  try {
581
581
  new Cron(expression, { paused: true });
@@ -617,7 +617,7 @@ class JobScheduler {
617
617
  /** Reads the stored jobs and brings the schedules in line: new ones are added, changed ones rescheduled, removed ones stopped. */
618
618
  async refresh() {
619
619
  const stored = (await this.collection.find({ className: { $type: "string" } }).toArray()).map(toConfig);
620
- const keys = new Set(stored.map((config) => keyOf(config.group, config.name)));
620
+ const keys = new Set(stored.map((config) => keyOf$1(config.group, config.name)));
621
621
  for (const [key, entry] of this.entries) {
622
622
  if (!keys.has(key)) {
623
623
  entry.cron?.stop();
@@ -625,14 +625,14 @@ class JobScheduler {
625
625
  }
626
626
  }
627
627
  for (const config of stored) {
628
- const existing = this.entries.get(keyOf(config.group, config.name));
628
+ const existing = this.entries.get(keyOf$1(config.group, config.name));
629
629
  if (!existing || !sameConfig(existing.config, config)) {
630
630
  this.schedule(config, existing?.lastRun);
631
631
  }
632
632
  }
633
633
  }
634
634
  schedule(config, lastRun) {
635
- const key = keyOf(config.group, config.name);
635
+ const key = keyOf$1(config.group, config.name);
636
636
  this.entries.get(key)?.cron?.stop();
637
637
  const entry = { config, lastRun };
638
638
  this.entries.set(key, entry);
@@ -757,8 +757,8 @@ class JobScheduler {
757
757
  } else {
758
758
  await this.insert(job);
759
759
  await this.collection.deleteOne({ group, name });
760
- this.entries.get(keyOf(group, name))?.cron?.stop();
761
- this.entries.delete(keyOf(group, name));
760
+ this.entries.get(keyOf$1(group, name))?.cron?.stop();
761
+ this.entries.delete(keyOf$1(group, name));
762
762
  }
763
763
  const entry = this.schedule(job);
764
764
  this.events.publish("job:update", { user, jobName: name, jobGroup: group, jobConfig: job });
@@ -766,7 +766,7 @@ class JobScheduler {
766
766
  }
767
767
  async delete(group, name, user) {
768
768
  const result = await this.collection.deleteOne({ group, name });
769
- const key = keyOf(group, name);
769
+ const key = keyOf$1(group, name);
770
770
  this.entries.get(key)?.cron?.stop();
771
771
  this.entries.delete(key);
772
772
  if (result.deletedCount === 0) {
@@ -777,7 +777,7 @@ class JobScheduler {
777
777
  }
778
778
  /** Starts a run now and answers without waiting for its end (`triggerJob`). */
779
779
  execute(group, name) {
780
- const entry = this.entries.get(keyOf(group, name));
780
+ const entry = this.entries.get(keyOf$1(group, name));
781
781
  if (!entry || !this.handlers.has(entry.config.className)) {
782
782
  throw new MongocampError(`${name} with group ${group} not found`, 404, ErrorCodes.jobCouldNotFound);
783
783
  }
@@ -958,7 +958,7 @@ const configDefinitions = [
958
958
  // 2.1.0: 403 by default, a user who only lacks a grant keeps the session (401 clears it in the clients); 401 stays configurable
959
959
  define(K.AuthGrantDeniedStatus, "Long", 403),
960
960
  define(K.ImportMaxBytes, "Long", 1073741824),
961
- // 2.4.0: live updates, change streams open at the same time in one instance (each holds a cursor of the database)
961
+ // 2.3.0: live updates, change streams open at the same time in one instance (each holds a cursor of the database)
962
962
  define(K.WatchMaxStreams, "Long", 100),
963
963
  define(K.FilterTimeZone, "String", "UTC"),
964
964
  define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
@@ -1601,6 +1601,14 @@ class AuthService {
1601
1601
  throw MongocampError.unauthorized();
1602
1602
  }
1603
1603
  /** The logged in user of a request with the current roles. */
1604
+ /** 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. */
1605
+ async authorizedUser(userId) {
1606
+ const user = await this.holder.findUserOption(userId);
1607
+ if (user === void 0) {
1608
+ throw MongocampError.unauthorized(`the user ${userId} does not exist`);
1609
+ }
1610
+ return new AuthorizedUser(user, await this.holder.findRoles(user.roles));
1611
+ }
1604
1612
  async authenticate(request) {
1605
1613
  const user = await this.authenticateUser(readCredentials(request));
1606
1614
  this.requestUsers.set(request, user.userId);
@@ -1624,11 +1632,15 @@ class AuthService {
1624
1632
  }
1625
1633
  async requireCollection(request, collection, right) {
1626
1634
  const user = await this.authenticate(request);
1635
+ this.requireRight(user, collection, right);
1636
+ return user;
1637
+ }
1638
+ /** The grant of an authenticated user for a collection (the routes and the document service, 2.4.0). */
1639
+ requireRight(user, collection, right) {
1627
1640
  const allowed = right === "read" ? user.canRead(collection) : right === "write" ? user.canWrite(collection) : user.canAdministrate(collection);
1628
1641
  if (!allowed) {
1629
1642
  throw this.grantDenied("user not authorized for collection");
1630
1643
  }
1631
- return user;
1632
1644
  }
1633
1645
  async requireBucket(request, bucket, right) {
1634
1646
  const user = await this.authenticate(request);
@@ -2090,12 +2102,12 @@ class EventBus {
2090
2102
  }
2091
2103
  hooks = createHooks();
2092
2104
  listeners = /* @__PURE__ */ new Map();
2093
- /** Listeners for some collections only (2.4.0): they make expensive payloads be read for these collections only. */
2105
+ /** Listeners for some collections only (2.3.0): they make expensive payloads be read for these collections only. */
2094
2106
  scoped = /* @__PURE__ */ new Map();
2095
2107
  observers = /* @__PURE__ */ new Set();
2096
2108
  targets = /* @__PURE__ */ new Set();
2097
2109
  /**
2098
- * Registers a listener; the returned function removes it. With `collections` (2.4.0) it only gets the events of the collections the
2110
+ * Registers a listener; the returned function removes it. With `collections` (2.3.0) it only gets the events of the collections the
2099
2111
  * function accepts, and the expensive parts of an event (old values) are only read for them.
2100
2112
  */
2101
2113
  on(name, listener, options = {}) {
@@ -2916,6 +2928,251 @@ function schemaNodeAt(jsonSchema, path) {
2916
2928
  return current;
2917
2929
  }
2918
2930
 
2931
+ const OwnIndexPrefix = "mongocamp_idx_";
2932
+ function directedField(field, what) {
2933
+ const descending = field.startsWith("-");
2934
+ return [checkFieldPath(descending ? field.slice(1) : field, what), descending ? -1 : 1];
2935
+ }
2936
+ function keyOf(declaration, what) {
2937
+ if (typeof declaration === "string") {
2938
+ return { key: Object.fromEntries([directedField(declaration, what)]), options: {} };
2939
+ }
2940
+ if (Array.isArray(declaration)) {
2941
+ if (declaration.length === 0) {
2942
+ throw new Error(`${what} has no fields`);
2943
+ }
2944
+ return { key: Object.fromEntries(declaration.map((field) => directedField(field, what))), options: {} };
2945
+ }
2946
+ const { fields, ...options } = declaration;
2947
+ if (fields === null || typeof fields !== "object" || Object.keys(fields).length === 0) {
2948
+ throw new Error(`${what} has no fields`);
2949
+ }
2950
+ for (const [field, direction] of Object.entries(fields)) {
2951
+ checkFieldPath(field, what);
2952
+ if (direction !== 1 && direction !== -1 && direction !== "text") {
2953
+ throw new Error(`${what}: the direction of ${field} must be 1, -1 or 'text'`);
2954
+ }
2955
+ }
2956
+ const known = ["unique", "sparse", "expireAfterSeconds", "partialFilterExpression", "collation", "name"];
2957
+ const unknown = Object.keys(options).filter((key) => !known.includes(key));
2958
+ if (unknown.length > 0) {
2959
+ throw new Error(`${what} has unknown options ${unknown.join(", ")} (known: fields, ${known.join(", ")})`);
2960
+ }
2961
+ return { key: { ...fields }, options };
2962
+ }
2963
+ function nameOf(key, name) {
2964
+ const base = name ?? Object.entries(key).map(([field, direction]) => `${field.replaceAll(".", "_")}_${direction}`).join("_");
2965
+ const full = base.startsWith(OwnIndexPrefix) ? base : `${OwnIndexPrefix}${base}`;
2966
+ return full.length <= 100 ? full : `${full.slice(0, 80)}_${createHash("sha256").update(full).digest("hex").slice(0, 12)}`;
2967
+ }
2968
+ function fingerprintOf(key, options) {
2969
+ return createHash("sha256").update(BSON.EJSON.stringify({ key, options }, { relaxed: false })).digest("hex").slice(0, 16);
2970
+ }
2971
+ function resolved(key, options, name, origin) {
2972
+ return { name: nameOf(key, name), key, options, fingerprint: fingerprintOf(key, options), origin };
2973
+ }
2974
+ function resolveIndexes(declarations, behaviours) {
2975
+ if (declarations !== void 0 && !Array.isArray(declarations)) {
2976
+ throw new Error("indexes must be a list");
2977
+ }
2978
+ const indexes = (declarations ?? []).map((declaration, position) => {
2979
+ const what = `indexes[${position}]`;
2980
+ const { key, options } = keyOf(declaration, what);
2981
+ const textFields = Object.values(key).filter((direction) => direction === "text").length;
2982
+ if (options.expireAfterSeconds !== void 0) {
2983
+ if (Object.keys(key).length !== 1 || textFields > 0) {
2984
+ throw new Error(`${what}: an index with expireAfterSeconds has exactly one field (not text)`);
2985
+ }
2986
+ if (typeof options.expireAfterSeconds !== "number" || options.expireAfterSeconds < 0) {
2987
+ throw new Error(`${what}: expireAfterSeconds must be 0 or more`);
2988
+ }
2989
+ }
2990
+ const indexOptions = {};
2991
+ for (const option of ["unique", "sparse", "expireAfterSeconds", "partialFilterExpression", "collation"]) {
2992
+ if (options[option] !== void 0) {
2993
+ indexOptions[option] = options[option];
2994
+ }
2995
+ }
2996
+ if (indexOptions.unique === true && behaviours.softDelete !== void 0 && indexOptions.partialFilterExpression === void 0) {
2997
+ indexOptions.partialFilterExpression = { [behaviours.softDelete.field]: null };
2998
+ }
2999
+ return resolved(key, indexOptions, options.name, "declaration");
3000
+ });
3001
+ if (indexes.filter((index) => Object.values(index.key).includes("text")).length > 1) {
3002
+ throw new Error("a collection has at most one text index");
3003
+ }
3004
+ if (behaviours.owner !== void 0 && !indexes.some((index) => Object.keys(index.key)[0] === behaviours.owner.field)) {
3005
+ indexes.push(resolved({ [behaviours.owner.field]: 1 }, {}, void 0, "owner"));
3006
+ }
3007
+ const names = /* @__PURE__ */ new Set();
3008
+ for (const index of indexes) {
3009
+ if (names.has(index.name)) {
3010
+ throw new Error(`two indexes are named ${index.name}`);
3011
+ }
3012
+ names.add(index.name);
3013
+ }
3014
+ return indexes;
3015
+ }
3016
+
3017
+ function storedOptions(index) {
3018
+ const options = {};
3019
+ for (const option of ["unique", "sparse", "expireAfterSeconds", "partialFilterExpression", "collation"]) {
3020
+ if (index[option] !== void 0) {
3021
+ options[option] = index[option];
3022
+ }
3023
+ }
3024
+ if (options.collation !== void 0 && typeof options.collation === "object") {
3025
+ options.collation = { locale: options.collation.locale };
3026
+ }
3027
+ return options;
3028
+ }
3029
+ function storedKey(index) {
3030
+ if ("_fts" in index.key) {
3031
+ return Object.fromEntries(Object.keys(index.weights ?? {}).map((field) => [field, "text"]));
3032
+ }
3033
+ return index.key;
3034
+ }
3035
+ function canonical$1(value) {
3036
+ return BSON.EJSON.stringify({ v: value }, { relaxed: true });
3037
+ }
3038
+ function sameIndex(stored, declared) {
3039
+ const declaredOptions = { ...declared.options };
3040
+ if (declaredOptions.collation !== void 0) {
3041
+ declaredOptions.collation = { locale: declaredOptions.collation.locale };
3042
+ }
3043
+ return canonical$1(storedKey(stored)) === canonical$1(declared.key) && canonical$1(storedOptions(stored)) === canonical$1(declaredOptions);
3044
+ }
3045
+ function onlyTtlDiffers(stored, declared) {
3046
+ if (stored.expireAfterSeconds === void 0 || declared.options.expireAfterSeconds === void 0) {
3047
+ return false;
3048
+ }
3049
+ return sameIndex({ ...stored, expireAfterSeconds: declared.options.expireAfterSeconds }, declared);
3050
+ }
3051
+ const reason = (error) => error instanceof Error ? error.message : String(error);
3052
+ async function syncIndexes(db, declared, logger) {
3053
+ const target = `${db.databaseName}:${declared.definition.name}`;
3054
+ const result = { collection: target, created: [], replaced: [], dropped: [], unchanged: [], foreign: [], failed: [] };
3055
+ try {
3056
+ await sync(db, declared, logger, result);
3057
+ } catch (error) {
3058
+ result.failed.push({ name: "*", reason: reason(error) });
3059
+ logger.warn(`[mongocamp] indexes of ${target} could not be synced: ${reason(error)}`);
3060
+ }
3061
+ return result;
3062
+ }
3063
+ async function sync(db, declared, logger, result) {
3064
+ const name = declared.definition.name;
3065
+ const target = result.collection;
3066
+ const collection = db.collection(name);
3067
+ const stored = await collection.indexes().catch((error) => {
3068
+ if (error.code === 26) {
3069
+ return [];
3070
+ }
3071
+ throw error;
3072
+ });
3073
+ const declaredByName = new Map(declared.indexes.map((index) => [index.name, index]));
3074
+ const toCreate = [];
3075
+ for (const index of stored) {
3076
+ const own = index.name?.startsWith(OwnIndexPrefix) === true;
3077
+ const wanted = index.name !== void 0 ? declaredByName.get(index.name) : void 0;
3078
+ if (!own) {
3079
+ if (index.name !== "_id_") {
3080
+ result.foreign.push(index.name ?? "?");
3081
+ }
3082
+ continue;
3083
+ }
3084
+ try {
3085
+ if (wanted === void 0) {
3086
+ await collection.dropIndex(index.name);
3087
+ result.dropped.push(index.name);
3088
+ } else if (sameIndex(index, wanted)) {
3089
+ result.unchanged.push(wanted.name);
3090
+ } else if (onlyTtlDiffers(index, wanted)) {
3091
+ await db.command({ collMod: name, index: { name: wanted.name, expireAfterSeconds: wanted.options.expireAfterSeconds } });
3092
+ result.replaced.push(wanted.name);
3093
+ } else {
3094
+ await collection.dropIndex(wanted.name);
3095
+ toCreate.push(wanted);
3096
+ result.replaced.push(wanted.name);
3097
+ }
3098
+ } catch (error) {
3099
+ result.failed.push({ name: index.name, reason: reason(error) });
3100
+ }
3101
+ }
3102
+ const storedNames = new Set(stored.map((index) => index.name));
3103
+ toCreate.push(...declared.indexes.filter((index) => !storedNames.has(index.name)));
3104
+ for (const index of toCreate) {
3105
+ try {
3106
+ await collection.createIndex(index.key, { ...index.options, name: index.name });
3107
+ if (!result.replaced.includes(index.name)) {
3108
+ result.created.push(index.name);
3109
+ }
3110
+ } catch (error) {
3111
+ result.replaced = result.replaced.filter((entry) => entry !== index.name);
3112
+ result.failed.push({ name: index.name, reason: reason(error) });
3113
+ }
3114
+ }
3115
+ for (const [kind, names] of [["created", result.created], ["replaced", result.replaced], ["dropped", result.dropped]]) {
3116
+ if (names.length > 0) {
3117
+ logger.info(`[mongocamp] indexes of ${target} ${kind}: ${names.join(", ")}`);
3118
+ }
3119
+ }
3120
+ if (result.foreign.length > 0 && declared.indexes.length > 0) {
3121
+ logger.info(`[mongocamp] indexes of ${target} not declared, left alone: ${result.foreign.join(", ")}`);
3122
+ }
3123
+ for (const failure of result.failed) {
3124
+ logger.warn(`[mongocamp] index ${failure.name} of ${target} could not be set, the server starts without it: ${failure.reason}`);
3125
+ }
3126
+ }
3127
+
3128
+ const MaxExpands = 5;
3129
+ function schemaAt(jsonSchema, path) {
3130
+ let node = jsonSchema;
3131
+ let throughArray = false;
3132
+ const parts = path.split(".");
3133
+ for (const [position, part] of parts.entries()) {
3134
+ const properties = node?.properties;
3135
+ node = properties?.[part];
3136
+ if (node === void 0) {
3137
+ return { throughArray };
3138
+ }
3139
+ if (position < parts.length - 1 && isArrayNode(node)) {
3140
+ throughArray = true;
3141
+ }
3142
+ }
3143
+ return { node, throughArray };
3144
+ }
3145
+ function isArrayNode(node) {
3146
+ const types = [node.bsonType, node.type].flat().filter((type) => type !== void 0);
3147
+ return types.includes("array");
3148
+ }
3149
+ function resolveRefs(refs, behaviours, jsonSchema) {
3150
+ if (refs === void 0) {
3151
+ return [];
3152
+ }
3153
+ if (typeof refs !== "object" || refs === null || Array.isArray(refs)) {
3154
+ throw new Error("refs must be an object of field: collection");
3155
+ }
3156
+ const written = new Map(systemFields(behaviours).map((field) => [field.path, field.by]));
3157
+ return Object.entries(refs).map(([field, declaration]) => {
3158
+ checkFieldPath(field, "a field of refs");
3159
+ const by = written.get(field);
3160
+ if (by !== void 0) {
3161
+ throw new Error(`refs: ${field} is written by ${by}, it cannot be a reference`);
3162
+ }
3163
+ const collection = typeof declaration === "string" ? declaration : declaration?.collection;
3164
+ const target = typeof collection === "string" ? parseCollectionName(collection) : void 0;
3165
+ if (target === void 0 || target.name.trim() === "" || target.database !== void 0 && target.database.trim() === "" || target.name.includes(CollectionSeparator)) {
3166
+ throw new Error(`refs: the target of ${field} must be a collection name (name or database:name): ${JSON.stringify(declaration)}`);
3167
+ }
3168
+ const { node, throughArray } = schemaAt(jsonSchema, field);
3169
+ if (throughArray) {
3170
+ throw new Error(`refs: ${field} goes through an array, only the last part of a reference may be an array`);
3171
+ }
3172
+ return { field, collection, ...node !== void 0 ? { many: isArrayNode(node) } : {} };
3173
+ });
3174
+ }
3175
+
2919
3176
  const bsonTypeOfClass = {
2920
3177
  ObjectId: "objectId",
2921
3178
  Date: "date",
@@ -4046,7 +4303,9 @@ function defineMongocampCollection(definition) {
4046
4303
  if (definition.validation !== void 0 && !validationModes.includes(definition.validation)) {
4047
4304
  throw new Error(`the validation of the declared collection ${definition.name} must be one of ${validationModes.join(", ")}${where}: ${String(definition.validation)}`);
4048
4305
  }
4049
- behavioursOf(definition);
4306
+ const behaviours = behavioursOf(definition);
4307
+ indexesOf(definition, behaviours);
4308
+ refsOf(definition, behaviours);
4050
4309
  return definition;
4051
4310
  }
4052
4311
  function behavioursOf(definition) {
@@ -4064,6 +4323,25 @@ function behavioursOf(definition) {
4064
4323
  throw new Error(`the declared collection ${definition.name}: ${error instanceof Error ? error.message : String(error)}${where}`, { cause: error });
4065
4324
  }
4066
4325
  }
4326
+ function indexesOf(definition, behaviours = behavioursOf(definition)) {
4327
+ try {
4328
+ return resolveIndexes(definition.indexes, behaviours);
4329
+ } catch (error) {
4330
+ const where = definition.source !== void 0 ? ` (${definition.source})` : "";
4331
+ throw new Error(`the declared collection ${definition.name}: ${error instanceof Error ? error.message : String(error)}${where}`, { cause: error });
4332
+ }
4333
+ }
4334
+ function refsOf(definition, behaviours = behavioursOf(definition)) {
4335
+ if (definition.refs === void 0) {
4336
+ return [];
4337
+ }
4338
+ try {
4339
+ return resolveRefs(definition.refs, behaviours, validatorOf$1({ ...definition, validator: void 0 }, { systemFields: false }).jsonSchema);
4340
+ } catch (error) {
4341
+ const where = definition.source !== void 0 ? ` (${definition.source})` : "";
4342
+ throw new Error(`the declared collection ${definition.name}: ${error instanceof Error ? error.message : String(error)}${where}`, { cause: error });
4343
+ }
4344
+ }
4067
4345
  class CollectionRegistry {
4068
4346
  entries = /* @__PURE__ */ new Map();
4069
4347
  static key(databaseName, name) {
@@ -4118,11 +4396,14 @@ function declare(context, definitions) {
4118
4396
  } catch (error) {
4119
4397
  throw new Error(`${error instanceof Error ? error.message : String(error)}${definition.source !== void 0 ? ` (${definition.source})` : ""}`, { cause: error });
4120
4398
  }
4399
+ const behaviours = behavioursOf(definition);
4121
4400
  return {
4122
4401
  definition,
4123
4402
  databaseName: databaseOf(context.database, { database: definition.database, name: definition.name }).databaseName,
4124
4403
  validation: definition.validation ?? DefaultValidationMode,
4125
- behaviours: behavioursOf(definition)
4404
+ behaviours,
4405
+ indexes: indexesOf(definition, behaviours),
4406
+ refs: refsOf(definition, behaviours)
4126
4407
  };
4127
4408
  });
4128
4409
  }
@@ -4229,6 +4510,7 @@ function collections(definitions) {
4229
4510
  if (entry.behaviours.softDelete !== void 0) {
4230
4511
  await syncPurgeIndex(context.database.db(entry.databaseName), entry, context.logger);
4231
4512
  }
4513
+ entry.indexSync = await syncIndexes(context.database.db(entry.databaseName), entry, context.logger);
4232
4514
  }
4233
4515
  const own = new Set(definitions);
4234
4516
  const stopValidation = declared.some((entry) => entry.validation !== "off") ? validationInterceptors(context, own) : () => {
@@ -4271,412 +4553,741 @@ function collections(definitions) {
4271
4553
  };
4272
4554
  }
4273
4555
 
4274
- const allowedMethods = "OPTIONS, POST, PUT, PATCH, GET, DELETE";
4275
- function requestOrigin(request) {
4276
- const origin = request.headers.get("origin");
4277
- if (origin) {
4278
- return origin;
4556
+ const BatchSize = 1e3;
4557
+ const MaxReportedErrors = 1e3;
4558
+ const MaxLineBytes = 17 * 1024 * 1024;
4559
+ class ImportState {
4560
+ read = 0;
4561
+ inserted = 0;
4562
+ failed = 0;
4563
+ errors = [];
4564
+ errorsTruncated = false;
4565
+ /** The ids of the documents that were stored, as stored (for the compensation). */
4566
+ storedIds = [];
4567
+ /** The ids as text, for the events of the caller. */
4568
+ get storedIdTexts() {
4569
+ return this.storedIds.map(idToString);
4279
4570
  }
4280
- const referer = request.headers.get("referer");
4281
- return referer ? referer.replace(/\/$/, "") : void 0;
4282
- }
4283
- function corsHeaders(config, origin) {
4284
- const allowedOrigins = config.list(ConfigKeys.CorsOriginsAllowed).filter((entry) => entry !== "");
4285
- let allowOrigin;
4286
- if (origin !== void 0 && allowedOrigins.includes(origin)) {
4287
- allowOrigin = origin;
4288
- } else if (allowedOrigins.length === 0) {
4289
- allowOrigin = "*";
4290
- } else {
4291
- allowOrigin = allowedOrigins[0];
4571
+ addErrors(errors) {
4572
+ const room = MaxReportedErrors - this.errors.length;
4573
+ this.errors.push(...errors.slice(0, Math.max(room, 0)));
4574
+ this.errorsTruncated ||= errors.length > room;
4292
4575
  }
4293
- return {
4294
- "access-control-allow-origin": allowOrigin,
4295
- "access-control-allow-credentials": "true",
4296
- "access-control-allow-headers": config.list(ConfigKeys.CorsHeadersAllowed).join(","),
4297
- "access-control-expose-headers": config.list(ConfigKeys.CorsHeadersExposed).join(",")
4298
- };
4299
- }
4300
- function preflightResponse(request, config) {
4301
- return new Response(null, {
4302
- status: 200,
4303
- headers: {
4304
- ...corsHeaders(config, requestOrigin(request)),
4305
- "access-control-allow-methods": allowedMethods
4306
- }
4307
- });
4308
- }
4309
- const requestIdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
4310
- function newRequestId() {
4311
- return Array.from(randomBytes(10), (byte) => requestIdAlphabet[byte % requestIdAlphabet.length]).join("");
4312
- }
4313
- function withCommonHeaders(response, request, config, version, requestId) {
4314
- const headers = {
4315
- ...corsHeaders(config, requestOrigin(request)),
4316
- "server": `${version.name}/${version.version}`,
4317
- "x-request-id": requestId
4318
- };
4319
- try {
4320
- for (const [name, value] of Object.entries(headers)) {
4321
- response.headers.set(name, value);
4322
- }
4323
- return response;
4324
- } catch {
4325
- const copy = new Response(response.body, response);
4326
- for (const [name, value] of Object.entries(headers)) {
4327
- copy.headers.set(name, value);
4328
- }
4329
- return copy;
4576
+ get response() {
4577
+ return { read: this.read, inserted: this.inserted, failed: this.failed, errors: this.errors, errorsTruncated: this.errorsTruncated };
4330
4578
  }
4331
4579
  }
4332
-
4333
- const resourcePattern = /^\/mongodb\/(collections|buckets|databases)\/([^/]+)/;
4334
- function decoded(segment) {
4580
+ function lineError(number, message) {
4581
+ return { index: number, code: ErrorCodes.invalidImportLine, message };
4582
+ }
4583
+ function parseLine(number, text) {
4584
+ let json;
4335
4585
  try {
4336
- return decodeURIComponent(segment);
4337
- } catch {
4338
- return segment;
4586
+ json = parseJson(text);
4587
+ } catch (error) {
4588
+ const reason = (error instanceof Error ? error.message : String(error)).split("\n")[0].slice(0, 160);
4589
+ return { error: lineError(number, `the line is not valid JSON: ${reason}`) };
4339
4590
  }
4340
- }
4341
- function requestFields(request, response, fields, user) {
4342
- const result = { requestId: fields.requestId, operation: fields.methodName, controller: fields.controller };
4343
- if (user) {
4344
- result.user = user;
4591
+ if (!isPlainObject(json)) {
4592
+ return { error: lineError(number, "the line has to be a JSON object") };
4345
4593
  }
4346
- const match = resourcePattern.exec(new URL(request.url).pathname);
4347
- if (match && match[2] !== "info") {
4348
- const name = decoded(match[2]);
4349
- if (match[1] === "collections") {
4350
- result.collection = name;
4351
- } else if (match[1] === "buckets") {
4352
- result.bucket = name;
4353
- } else if (match[2] !== "infos") {
4354
- result.database = name;
4594
+ try {
4595
+ const document = convertFields(decodeAny(json));
4596
+ return { document: "_id" in document ? document : { _id: new ObjectId(), ...document } };
4597
+ } catch (error) {
4598
+ if (error instanceof MongocampError) {
4599
+ return { error: lineError(number, error.message) };
4355
4600
  }
4601
+ throw error;
4356
4602
  }
4357
- const rows = Number.parseInt(response.headers.get(PaginationHeaders.countRows) ?? "", 10);
4358
- if (Number.isFinite(rows)) {
4359
- result.rows = rows;
4603
+ }
4604
+ async function importBatch(collection, batch, state, beforeBatch) {
4605
+ const parseErrors = batch.flatMap(([, entry]) => "error" in entry ? [entry.error] : []);
4606
+ let valid = batch.flatMap(([number, entry]) => "document" in entry ? [[number, entry.document]] : []);
4607
+ if (beforeBatch !== void 0 && valid.length > 0) {
4608
+ const changed = await beforeBatch(valid.map(([, document]) => document), valid.map(([number]) => number));
4609
+ valid = valid.map(([number], index) => [number, changed[index]]);
4360
4610
  }
4361
- if (response.status >= 400) {
4362
- const code = response.headers.get(ErrorHeaders.code);
4363
- const message = response.headers.get(ErrorHeaders.message);
4364
- if (code) {
4365
- result.errorCode = code;
4366
- }
4367
- if (message) {
4368
- result.errorMessage = message;
4611
+ const databaseErrors = [];
4612
+ if (valid.length > 0) {
4613
+ try {
4614
+ await collection.insertMany(valid.map(([, document]) => document), { ordered: false });
4615
+ } catch (error) {
4616
+ const writeErrors = error instanceof MongoBulkWriteError ? Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors] : [];
4617
+ if (writeErrors.length === 0) {
4618
+ throw error;
4619
+ }
4620
+ for (const writeError of writeErrors) {
4621
+ const index = Number(writeError.index);
4622
+ databaseErrors.push({ index: valid[index][0], code: Number(writeError.code), message: removeInternalNames(writeError.errmsg ?? "") });
4623
+ }
4369
4624
  }
4370
4625
  }
4371
- return result;
4626
+ const failedLines = new Set(databaseErrors.map((error) => error.index));
4627
+ const stored = valid.filter(([number]) => !failedLines.has(number)).map(([, document]) => document._id);
4628
+ const errors = [...parseErrors, ...databaseErrors].sort((a, b) => a.index - b.index);
4629
+ state.read += batch.length;
4630
+ state.inserted += stored.length;
4631
+ state.failed += errors.length;
4632
+ state.storedIds.push(...stored);
4633
+ state.addErrors(errors);
4372
4634
  }
4373
- function addRequestFields(log, request, response, fields, user) {
4374
- try {
4375
- log.set({ mongocamp: requestFields(request, response, fields, user) });
4376
- } catch {
4635
+ async function compensate(collection, ids) {
4636
+ let deleted = 0;
4637
+ for (let start = 0; start < ids.length; start += BatchSize) {
4638
+ deleted += (await collection.deleteMany({ _id: { $in: ids.slice(start, start + BatchSize) } })).deletedCount;
4377
4639
  }
4640
+ return deleted;
4378
4641
  }
4379
-
4380
- const operations = [
4381
- ["POST", "/auth/login", "login", "Auth", "Login User"],
4382
- ["POST", "/auth/logout", "logout", "Auth", "Logout User"],
4383
- ["DELETE", "/auth/logout", "logoutByDelete", "Auth", "Logout User"],
4384
- ["GET", "/auth/token/refresh", "refreshToken", "Auth", "Refresh User"],
4385
- ["PATCH", "/auth/profile/password", "updatePassword", "Auth", "Update Password"],
4386
- ["PATCH", "/auth/profile/apikey", "generateNewApiKey", "Auth", "Update ApiKey"],
4387
- ["GET", "/auth/profile", "userProfile", "Auth", "User Profile"],
4388
- ["GET", "/auth/permissions", "userPermissions", "Auth", "Collection permissions"],
4389
- ["GET", "/auth/authenticated", "isAuthenticated", "Auth", "Check Authentication"],
4390
- ["GET", "/admin/users", "listUsers", "Admin", "List Users"],
4391
- ["PUT", "/admin/users", "addUser", "Admin", "Add User"],
4392
- ["PATCH", "/admin/users/:userId/apikey", "gnerateNewApiKeyForUser", "Admin", "Update ApiKey"],
4393
- ["PATCH", "/admin/users/:userId/password", "updatePasswordForUser", "Admin", "Update Password"],
4394
- ["PATCH", "/admin/users/:userId/roles", "updateRolesForUser", "Admin", "Update User Roles"],
4395
- ["GET", "/admin/users/:userId", "getUser", "Admin", "UserProfile for userId"],
4396
- ["DELETE", "/admin/users/:userId", "deleteUser", "Admin", "Delete User"],
4397
- ["GET", "/admin/roles", "listRoles", "Admin", "List Roles"],
4398
- ["PUT", "/admin/roles", "addRole", "Admin", "Add Role"],
4399
- ["GET", "/admin/roles/:roleName", "getRole", "Admin", "Get Role"],
4400
- ["DELETE", "/admin/roles/:roleName", "deleteRole", "Admin", "Delete Role"],
4401
- ["PATCH", "/admin/roles/:roleName", "updateRole", "Admin", "Update Role"],
4402
- ["GET", "/mongodb/buckets/:bucketName/files", "listFiles", "File", "Files in Bucket"],
4403
- ["PUT", "/mongodb/buckets/:bucketName/files", "insertFile", "File", "Insert File"],
4404
- ["POST", "/mongodb/buckets/:bucketName/files", "findFiles", "File", "Files in Bucket"],
4405
- ["GET", "/mongodb/buckets/:bucketName/files/:fileId", "getFileInformation", "File", "FileInformation from Bucket"],
4406
- ["DELETE", "/mongodb/buckets/:bucketName/files/:fileId", "deleteFile", "File", "Delete File from Bucket"],
4407
- ["PATCH", "/mongodb/buckets/:bucketName/files/:fileId", "updateFileInformation", "File", "Update FileInformation in Bucket"],
4408
- ["GET", "/mongodb/buckets/:bucketName/files/:fileId/file", "getFile", "File", "File from Bucket"],
4409
- ["GET", "/mongodb/buckets", "listBuckets", "Bucket", "List of Buckets"],
4410
- ["GET", "/mongodb/buckets/:bucketName", "getBucket", "Bucket", "Bucket Information"],
4411
- ["DELETE", "/mongodb/buckets/:bucketName", "deleteBucket", "Bucket", "Delete Bucket"],
4412
- ["DELETE", "/mongodb/buckets/:bucketName/clear", "clearBucket", "Bucket", "Clear Bucket"],
4413
- ["GET", "/mongodb/collections", "listCollections", "Collection", "List of Collections"],
4414
- ["GET", "/mongodb/collections/info", "listCollectionInformation", "Collection", "Information of all Collections"],
4415
- ["GET", "/mongodb/collections/:collectionName", "getCollectionInformation", "Collection", "Collection Information"],
4416
- ["PUT", "/mongodb/collections/:collectionName", "createCollection", "Collection", "Create Collection"],
4417
- ["DELETE", "/mongodb/collections/:collectionName", "deleteCollection", "Collection", "Delete Collection"],
4418
- ["GET", "/mongodb/collections/:collectionName/fields", "getCollectionFields", "Collection", "Collection Fields"],
4419
- ["GET", "/mongodb/collections/:collectionName/fields/detail", "getFieldDetails", "Collection", "Fields of a Collection with types"],
4420
- ["GET", "/mongodb/collections/:collectionName/schema", "getJsonSchema", "Collection", "Collection Fields"],
4421
- ["GET", "/mongodb/collections/:collectionName/schema/analysis", "getSchemaAnalysis", "Collection", "Collection Fields"],
4422
- ["GET", "/mongodb/collections/:collectionName/schema/validator", "getSuggestedValidator", "Collection", "Suggested Validator"],
4423
- ["POST", "/mongodb/collections/:collectionName/rename", "renameCollection", "Collection", "Rename Collection"],
4424
- ["GET", "/mongodb/collections/:collectionName/options", "getCollectionOptions", "Collection", "Collection Options"],
4425
- ["PATCH", "/mongodb/collections/:collectionName/options", "modifyCollectionOptions", "Collection", "Change the Validation of a Collection"],
4426
- ["POST", "/mongodb/collections/:collectionName/copy", "copyCollection", "Collection", "Copy Collection"],
4427
- ["DELETE", "/mongodb/collections/:collectionName/clear", "clearCollection", "Collection", "Clear Collection"],
4428
- ["POST", "/mongodb/collections/:collectionName/aggregate", "aggregate", "Collection", "Aggregate in Collection"],
4429
- ["POST", "/mongodb/collections/:collectionName/distinct/:field", "distinct", "Collection", "Distinct in Collection"],
4430
- ["GET", "/system/settings", "settings", "Application", "System Settings"],
4431
- ["GET", "/system/configurations", "listConfigurations", "Application", "List Configurations"],
4432
- ["GET", "/system/configurations/:configurationKey", "getConfig", "Application", "Configuration for configurationKey"],
4433
- ["PATCH", "/system/configurations/:configurationKey", "updateConfiguration", "Application", "Update Configuration"],
4434
- ["DELETE", "/system", "shutdown", "Application", "Shutdown MongoCamp"],
4435
- ["GET", "/mongodb/databases", "ListDatabases", "Database", "List of Databases"],
4436
- ["GET", "/mongodb/databases/infos", "databaseInfos", "Database", "List of Database Infos"],
4437
- ["GET", "/mongodb/databases/:databaseName", "getDatabaseInfo", "Database", "Database Infos of selected Database"],
4438
- ["DELETE", "/mongodb/databases/:databaseName", "deleteDatabase", "Database", "Delete Database"],
4439
- ["GET", "/mongodb/databases/:databaseName/collections", "listCollectionsByDatabase", "Database", "List of Collections"],
4440
- ["GET", "/mongodb/collections/:collectionName/documents", "listDocuments", "Document", "Documents in Collection"],
4441
- ["PUT", "/mongodb/collections/:collectionName/documents", "insert", "Document", "Insert Document"],
4442
- ["POST", "/mongodb/collections/:collectionName/documents", "find", "Document", "Documents in Collection"],
4443
- ["GET", "/mongodb/collections/:collectionName/documents/count", "countDocuments", "Document", "Count Documents in Collection"],
4444
- ["POST", "/mongodb/collections/:collectionName/documents/count", "countDocumentsByBody", "Document", "Count Documents in Collection (filter in the body)"],
4445
- ["POST", "/mongodb/collections/:collectionName/documents/search", "searchDocuments", "Document", "Search Documents in Collection"],
4446
- ["GET", "/mongodb/collections/:collectionName/documents/export", "exportDocuments", "Document", "Export Documents of a Collection"],
4447
- ["POST", "/mongodb/collections/:collectionName/documents/export", "exportDocumentsByBody", "Document", "Export Documents of a Collection (filter in the body)"],
4448
- ["POST", "/mongodb/collections/:collectionName/documents/import", "importDocuments", "Document", "Import Documents into a Collection"],
4449
- ["PUT", "/mongodb/collections/:collectionName/documents/many/insert", "insertMany", "Document", "Insert many Documents"],
4450
- ["PATCH", "/mongodb/collections/:collectionName/documents/many/update", "updateMany", "Document", "Update many in Collection"],
4451
- ["DELETE", "/mongodb/collections/:collectionName/documents/many/delete", "deleteMany", "Document", "Delete Many in Collection"],
4452
- ["GET", "/mongodb/collections/:collectionName/documents/:documentId", "getDocument", "Document", "Document from Collection"],
4453
- ["DELETE", "/mongodb/collections/:collectionName/documents/:documentId", "delete", "Document", "Delete Document from Collection"],
4454
- ["PATCH", "/mongodb/collections/:collectionName/documents/:documentId", "update", "Document", "Update Document in Collection"],
4455
- ["PATCH", "/mongodb/collections/:collectionName/documents/:documentId/partial", "updateDocumentPartial", "Document", "Update Document Parts in Collection"],
4456
- ["POST", "/mongodb/collections/:collectionName/documents/:documentId/restore", "restoreDocument", "Document", "Restore a soft-deleted Document"],
4457
- ["GET", "/mongodb/collections/:collectionName/documents/watch", "watchDocuments", "Document", "Live Updates of a Collection"],
4458
- ["GET", "/mongodb/collections/:collectionName/documents/:documentId/history", "getDocumentHistory", "Document", "History of a Document"],
4459
- ["GET", "/mongodb/collections/:collectionName/history", "getCollectionHistory", "Collection", "History of a Collection"],
4460
- ["GET", "/mongodb/collections/:collectionName/declaration", "getCollectionDeclaration", "Collection", "Declaration of a Collection"],
4461
- ["GET", "/mongodb/collections/:collectionName/index", "listIndices", "Index", "List Indices for Collection"],
4462
- ["PUT", "/mongodb/collections/:collectionName/index", "createIndex", "Index", "Create Index for Collection"],
4463
- ["GET", "/mongodb/collections/:collectionName/index/stats", "indexStats", "Index", "Index usage for Collection"],
4464
- ["GET", "/mongodb/collections/:collectionName/index/details", "indexDetails", "Index", "Indices with details for Collection"],
4465
- ["GET", "/mongodb/collections/:collectionName/index/:indexName", "index", "Index", "Index for Collection"],
4466
- ["DELETE", "/mongodb/collections/:collectionName/index/:indexName", "deleteIndex", "Index", "Delete Index"],
4467
- ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName", "createIndexForField", "Index", "Create Index by Field for Collection"],
4468
- ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/unique", "createUniqueIndex", "Index", "Create Unique Index"],
4469
- ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/:duration/expiring", "createExpiringIndex", "Index", "Create expiring Index by Field for Collection"],
4470
- ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/text", "createTextIndex", "Index", "Create text index by field for collection"],
4471
- ["GET", "/version", "version", "System", "Version Information"],
4472
- ["GET", "/system/jobs", "jobsList", "Jobs", "Registered Jobs"],
4473
- ["PUT", "/system/jobs", "registerJob", "Jobs", "Register Job"],
4474
- ["POST", "/system/jobs/:jobGroup/:jobName", "executeJob", "Jobs", "Execute Job"],
4475
- ["DELETE", "/system/jobs/:jobGroup/:jobName", "deleteJob", "Jobs", "Delete Job"],
4476
- ["PATCH", "/system/jobs/:jobGroup/:jobName", "updateJob", "Jobs", "Update Job"],
4477
- ["GET", "/system/jobs/classes", "possibleJobsList", "Jobs", "Possible Jobs"],
4478
- ["GET", "/system/cluster", "viewCluster", "System", "Registered Jobs"],
4479
- ["GET", "/system/info", "systemInfo", "System", "System Information"],
4480
- ["GET", "/system/stats", "systemStats", "System", "System Statistics"],
4481
- ["GET", "/system/capabilities", "systemCapabilities", "System", "System Capabilities"]
4482
- ];
4483
-
4484
- const router = createRouter();
4485
- for (const [method, path, operationId, tag, summary] of operations) {
4486
- addRoute(router, method, path, { operationId, tag, summary });
4487
- }
4488
- function findOperation(method, path) {
4489
- return findRoute(router, method.toUpperCase(), path)?.data;
4490
- }
4491
- function controllerName(tag) {
4492
- return tag.replaceAll("/", "").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
4493
- }
4494
-
4495
- function remoteAddressOf(request) {
4496
- const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
4497
- return forwarded || request.headers.get("x-real-ip") || request.ip || "NOT_SET";
4498
- }
4499
- async function userIdOf(request, auth) {
4500
- const credentials = readCredentials(request);
4501
- const authorization = request.headers.get("authorization");
4502
- if (authorization === null && credentials.apiKey === void 0) {
4503
- return "";
4642
+ function abortError(error, info) {
4643
+ if (error instanceof MongocampError) {
4644
+ return new MongocampError(error.message, error.status, error.code, [error.additionalInfo, info].filter((part) => part !== "").join("; "));
4504
4645
  }
4646
+ return error;
4647
+ }
4648
+ async function importStream(collection, body, maxBytes, beforeBatch) {
4649
+ const state = new ImportState();
4505
4650
  try {
4506
- return (await auth.authenticateUser(credentials)).userId;
4507
- } catch {
4508
- if (credentials.bearer !== void 0) {
4509
- return "INVALID_TOKEN";
4651
+ await readLines(collection, body, maxBytes, state, beforeBatch);
4652
+ return state;
4653
+ } catch (error) {
4654
+ if (state.storedIds.length === 0) {
4655
+ throw error;
4510
4656
  }
4511
- return authorization !== null ? "INVALID_AUTH" : "INVALID_APIKEY";
4657
+ const stored = state.storedIds.length;
4658
+ const deleted = await compensate(collection, state.storedIds).catch(() => -1);
4659
+ throw abortError(error, deleted === stored ? `the import was rolled back, the ${stored} documents stored before were deleted` : `the import was aborted, deleting the ${stored} documents stored before failed (${Math.max(deleted, 0)} deleted)`);
4512
4660
  }
4513
4661
  }
4514
- class RequestEvents {
4515
- constructor(events, auth) {
4516
- this.events = events;
4517
- this.auth = auth;
4518
- }
4519
- get needsUser() {
4520
- return this.events.has("http:requestStart") || this.events.has("http:requestCompleted");
4521
- }
4522
- /** Publishes the start; the answer is the input of `completed`. */
4523
- async started(request, requestId) {
4524
- const startedAt = performance.now();
4525
- const url = new URL(request.url);
4526
- const operation = findOperation(request.method, url.pathname);
4527
- const methodName = operation ? operation.operationId || operation.tag : "NOT_SET";
4528
- const fields = {
4529
- requestId,
4530
- httpMethod: request.method,
4531
- methodName,
4532
- uri: request.url,
4533
- remoteAddress: remoteAddressOf(request),
4534
- userId: this.needsUser ? await userIdOf(request, this.auth) : "",
4535
- controller: operation ? controllerName(operation.tag) : "NOT_SET",
4536
- controllerMethod: methodName,
4537
- comment: operation?.summary ?? "NOT_SET"
4538
- };
4539
- this.events.publish("http:requestStart", fields);
4540
- return { fields, startedAt };
4662
+ async function readLines(collection, body, maxBytes, state, beforeBatch) {
4663
+ if (!body) {
4664
+ return;
4541
4665
  }
4542
- completed(start, response) {
4543
- this.events.publish("http:requestCompleted", { ...start.fields, durationMillis: Math.round((performance.now() - start.startedAt) * 1e3) / 1e3, responseCode: response.status });
4666
+ const reader = body.getReader();
4667
+ const decoder = new TextDecoder();
4668
+ let pending = "";
4669
+ let bytes = 0;
4670
+ let lineNumber = 0;
4671
+ let batch = [];
4672
+ const takeLine = async (rawLine) => {
4673
+ lineNumber += 1;
4674
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
4675
+ if (line.trim() === "") {
4676
+ return;
4677
+ }
4678
+ batch.push([lineNumber, parseLine(lineNumber, line)]);
4679
+ if (batch.length >= BatchSize) {
4680
+ const full = batch;
4681
+ batch = [];
4682
+ await importBatch(collection, full, state, beforeBatch);
4683
+ }
4684
+ };
4685
+ let finished = false;
4686
+ try {
4687
+ for (; ; ) {
4688
+ const { value, done } = await reader.read();
4689
+ if (done) {
4690
+ finished = true;
4691
+ break;
4692
+ }
4693
+ bytes += value.byteLength;
4694
+ if (bytes > maxBytes) {
4695
+ throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
4696
+ }
4697
+ pending += decoder.decode(value, { stream: true });
4698
+ let newline = pending.indexOf("\n");
4699
+ while (newline >= 0) {
4700
+ const line = pending.slice(0, newline);
4701
+ pending = pending.slice(newline + 1);
4702
+ await takeLine(line);
4703
+ newline = pending.indexOf("\n");
4704
+ }
4705
+ if (Buffer.byteLength(pending) > MaxLineBytes) {
4706
+ throw MongocampError.badRequest(`a line is longer than ${MaxLineBytes} bytes`);
4707
+ }
4708
+ }
4709
+ pending += decoder.decode();
4710
+ if (pending !== "") {
4711
+ await takeLine(pending);
4712
+ }
4713
+ if (batch.length > 0) {
4714
+ await importBatch(collection, batch, state, beforeBatch);
4715
+ }
4716
+ } finally {
4717
+ if (!finished) {
4718
+ await reader.cancel().catch(() => {
4719
+ });
4720
+ }
4721
+ reader.releaseLock();
4544
4722
  }
4545
4723
  }
4546
4724
 
4547
- function fail(field) {
4548
- throw MongocampError.decodeFailure("body", `field ${field}`);
4725
+ function cursorSort(sort) {
4726
+ const keys = Object.entries(sort).map(([field, direction]) => [field, Number(direction) < 0 ? -1 : 1]);
4727
+ return keys.some(([field]) => field === "_id") ? keys : [...keys, ["_id", 1]];
4549
4728
  }
4550
- function asObject(value, field = "body") {
4551
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
4552
- fail(field);
4729
+ function valueAt$1(document, path) {
4730
+ let current = document;
4731
+ for (const segment of path.split(".")) {
4732
+ if (current === null || typeof current !== "object") {
4733
+ return null;
4734
+ }
4735
+ current = current[segment];
4553
4736
  }
4554
- return value;
4737
+ return current === void 0 ? null : current;
4555
4738
  }
4556
- function requiredString(body, field) {
4557
- const value = body[field];
4558
- if (typeof value !== "string") {
4559
- fail(field);
4560
- }
4561
- return value;
4739
+ function encodeCursor(sort, document) {
4740
+ const token = { s: sort, v: sort.map(([field]) => valueAt$1(document, field)) };
4741
+ return Buffer.from(BSON.EJSON.stringify(token, { relaxed: false }), "utf8").toString("base64url");
4562
4742
  }
4563
- function optionalString(body, field) {
4564
- const value = body[field];
4565
- if (value === void 0 || value === null) {
4566
- return void 0;
4743
+ function invalidCursor() {
4744
+ return MongocampError.decodeFailure("query parameter after");
4745
+ }
4746
+ function decodeCursor(token, sort) {
4747
+ let decoded;
4748
+ try {
4749
+ decoded = BSON.EJSON.parse(Buffer.from(token, "base64url").toString("utf8"), { relaxed: false });
4750
+ } catch {
4751
+ throw invalidCursor();
4567
4752
  }
4568
- if (typeof value !== "string") {
4569
- fail(field);
4753
+ const { s, v } = decoded ?? {};
4754
+ if (!Array.isArray(s) || !Array.isArray(v) || v.length !== sort.length || JSON.stringify(s) !== JSON.stringify(sort)) {
4755
+ throw invalidCursor();
4570
4756
  }
4571
- return value;
4757
+ return v;
4572
4758
  }
4573
- function requiredBoolean(body, field) {
4574
- const value = body[field];
4575
- if (typeof value !== "boolean") {
4576
- fail(field);
4759
+ function afterValue(field, direction, value) {
4760
+ if (value === null) {
4761
+ return direction === 1 ? { [field]: { $ne: null } } : void 0;
4577
4762
  }
4578
- return value;
4763
+ return direction === 1 ? { [field]: { $gt: value } } : { $or: [{ [field]: { $lt: value } }, { [field]: null }] };
4579
4764
  }
4580
- function optionalBoolean(body, field) {
4581
- const value = body[field];
4582
- if (value === void 0 || value === null) {
4583
- return void 0;
4584
- }
4585
- if (typeof value !== "boolean") {
4586
- fail(field);
4765
+ function afterFilter(sort, values) {
4766
+ const branches = [];
4767
+ for (let index = 0; index < sort.length; index++) {
4768
+ const [field, direction] = sort[index];
4769
+ const after = afterValue(field, direction, values[index]);
4770
+ if (after) {
4771
+ const equal = sort.slice(0, index).map(([previous], position) => ({ [previous]: values[position] }));
4772
+ branches.push(equal.length === 0 ? after : { $and: [...equal, after] });
4773
+ }
4587
4774
  }
4588
- return value;
4775
+ return branches.length === 0 ? { _id: { $exists: false } } : branches.length === 1 ? branches[0] : { $or: branches };
4589
4776
  }
4590
- function optionalInteger$1(body, field) {
4591
- const value = body[field];
4592
- if (value === void 0 || value === null) {
4593
- return void 0;
4777
+ function isExclusion(projection) {
4778
+ const values = Object.entries(projection).filter(([field]) => field !== "_id").map(([, value]) => value);
4779
+ return values.length > 0 && values.every((value) => value === 0 || value === false);
4780
+ }
4781
+ function related(a, b) {
4782
+ return a === b || a.startsWith(`${b}.`) || b.startsWith(`${a}.`);
4783
+ }
4784
+ function cursorProjection(projection, sort) {
4785
+ if (Object.keys(projection).length === 0) {
4786
+ return { projection, added: [] };
4594
4787
  }
4595
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
4596
- fail(field);
4788
+ const result = { ...projection };
4789
+ const added = [];
4790
+ const exclusion = isExclusion(projection);
4791
+ for (const [field] of sort) {
4792
+ const value = projection[field];
4793
+ if (field === "_id") {
4794
+ if (value === 0 || value === false) {
4795
+ delete result._id;
4796
+ added.push("_id");
4797
+ }
4798
+ continue;
4799
+ }
4800
+ if (exclusion) {
4801
+ for (const excluded of Object.keys(projection).filter((key) => related(key, field))) {
4802
+ Reflect.deleteProperty(result, excluded);
4803
+ added.push(excluded);
4804
+ }
4805
+ } else if (!Object.keys(projection).some((key) => key !== "_id" && (key === field || field.startsWith(`${key}.`)))) {
4806
+ result[field] = 1;
4807
+ added.push(field);
4808
+ }
4597
4809
  }
4598
- return value;
4810
+ return { projection: result, added };
4599
4811
  }
4600
- function stringList(value, field) {
4601
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
4602
- fail(field);
4812
+ function stripAdded(document, added, projection) {
4813
+ if (added.length === 0) {
4814
+ return document;
4603
4815
  }
4604
- return value;
4816
+ const exclusion = isExclusion(projection);
4817
+ const requested = Object.keys(projection).filter((key) => key !== "_id" && projection[key] !== 0 && projection[key] !== false);
4818
+ for (const path of added) {
4819
+ const segments = path.split(".");
4820
+ const top = segments[0];
4821
+ if (segments.length === 1 || !exclusion && !requested.some((key) => related(key, top))) {
4822
+ Reflect.deleteProperty(document, top);
4823
+ continue;
4824
+ }
4825
+ let parent = document;
4826
+ for (const segment of segments.slice(0, -1)) {
4827
+ parent = parent && typeof parent === "object" ? parent[segment] : void 0;
4828
+ }
4829
+ if (parent && typeof parent === "object") {
4830
+ Reflect.deleteProperty(parent, segments.at(-1));
4831
+ }
4832
+ }
4833
+ return document;
4605
4834
  }
4606
- function optionalList(body, field, map) {
4607
- const value = body[field];
4608
- if (value === void 0 || value === null) {
4609
- return [];
4835
+
4836
+ const readOptions$1 = { promoteValues: false, bsonRegExp: true };
4837
+ function plainNumbers(value) {
4838
+ if (value instanceof Long || value instanceof Int32 || value instanceof Double) {
4839
+ return Number(value.valueOf());
4610
4840
  }
4611
- if (!Array.isArray(value)) {
4612
- fail(field);
4841
+ if (Array.isArray(value)) {
4842
+ return value.map(plainNumbers);
4613
4843
  }
4614
- return value.map(map);
4844
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
4845
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, plainNumbers(entry)]));
4846
+ }
4847
+ return value;
4615
4848
  }
4616
-
4617
- function readLogin(body) {
4618
- const object = asObject(body);
4619
- return { userId: requiredString(object, "userId"), password: requiredString(object, "password") };
4849
+ function sortFromList(fields) {
4850
+ return Object.fromEntries(fields.map((field) => field.startsWith("-") ? [field.slice(1), -1] : [field, 1]));
4620
4851
  }
4621
- function readPasswordUpdate(body) {
4622
- return requiredString(asObject(body), "password");
4852
+ function projectionFromList(fields) {
4853
+ return Object.fromEntries(fields.map((field) => [field, 1]));
4623
4854
  }
4624
- function readUserInformation(body) {
4625
- const object = asObject(body);
4626
- return {
4627
- userId: requiredString(object, "userId"),
4628
- password: requiredString(object, "password"),
4629
- apiKey: optionalString(object, "apiKey") ?? null,
4630
- roles: object.roles === void 0 || object.roles === null ? [] : stringList(object.roles, "roles")
4631
- };
4855
+ async function countMatching(collection, filter, count = "exact") {
4856
+ if (count === "none") {
4857
+ return void 0;
4858
+ }
4859
+ return Object.keys(filter).length === 0 ? collection.estimatedDocumentCount() : collection.countDocuments(filter);
4632
4860
  }
4633
- function readGrant(value, index) {
4634
- const object = asObject(value, `collectionGrants[${index}]`);
4635
- return {
4636
- name: requiredString(object, "name"),
4637
- read: requiredBoolean(object, "read"),
4638
- write: requiredBoolean(object, "write"),
4639
- administrate: requiredBoolean(object, "administrate"),
4640
- grantType: requiredString(object, "grantType")
4641
- };
4861
+ async function readPage(collection, request, paging, count = "exact") {
4862
+ const { rows, page, skip } = resolvePaging(paging);
4863
+ const sort = plainNumbers(request.sort);
4864
+ const projection = plainNumbers(request.projection);
4865
+ const total = countMatching(collection, request.filter, count);
4866
+ if (paging.after === void 0) {
4867
+ let cursor2 = collection.find(request.filter, readOptions$1);
4868
+ if (Object.keys(sort).length > 0) {
4869
+ cursor2 = cursor2.sort(sort);
4870
+ }
4871
+ if (Object.keys(projection).length > 0) {
4872
+ cursor2 = cursor2.project(projection);
4873
+ }
4874
+ const [allCount2, documents2] = await Promise.all([total, cursor2.skip(skip).limit(rows).toArray()]);
4875
+ return { documents: documents2, info: paginationInfo(allCount2, rows, page) };
4876
+ }
4877
+ const sortKeys = cursorSort(sort);
4878
+ const after = paging.after === "" ? void 0 : afterFilter(sortKeys, decodeCursor(paging.after, sortKeys));
4879
+ const filter = after === void 0 ? request.filter : Object.keys(request.filter).length === 0 ? after : { $and: [request.filter, after] };
4880
+ const read = cursorProjection(projection, sortKeys);
4881
+ let cursor = collection.find(filter, readOptions$1).sort(sortKeys);
4882
+ if (Object.keys(read.projection).length > 0) {
4883
+ cursor = cursor.project(read.projection);
4884
+ }
4885
+ const [allCount, documents] = await Promise.all([total, cursor.limit(rows).toArray()]);
4886
+ const next = documents.length === rows ? encodeCursor(sortKeys, documents.at(-1)) : void 0;
4887
+ return { documents: documents.map((document) => stripAdded(document, read.added, projection)), info: paginationInfo(allCount, rows, void 0, next) };
4642
4888
  }
4643
- function readRole(body) {
4644
- const object = asObject(body);
4645
- return {
4646
- name: requiredString(object, "name"),
4647
- isAdmin: requiredBoolean(object, "isAdmin"),
4648
- collectionGrants: optionalList(object, "collectionGrants", readGrant)
4649
- };
4889
+ function numberOf$6(value) {
4890
+ if (typeof value === "number") {
4891
+ return value;
4892
+ }
4893
+ if (value && typeof value === "object" && "valueOf" in value) {
4894
+ return Number(value.valueOf());
4895
+ }
4896
+ return 0;
4650
4897
  }
4651
- function readUpdateRole(body) {
4652
- const object = asObject(body);
4653
- return {
4654
- isAdmin: requiredBoolean(object, "isAdmin"),
4655
- collectionGrants: optionalList(object, "collectionGrants", readGrant)
4656
- };
4898
+ async function paginatedAggregation(collection, pipeline, allowDiskUse, paging, count = "exact") {
4899
+ const { rows, page, skip } = resolvePaging(paging);
4900
+ if (count === "none") {
4901
+ const documents = await collection.aggregate(pagedPipeline(pipeline, skip, rows), { allowDiskUse, ...readOptions$1 }).toArray();
4902
+ return { documents, info: paginationInfo(void 0, rows, page) };
4903
+ }
4904
+ const facet = { $facet: { metadata: [{ $count: "total" }], data: [{ $skip: skip }, { $limit: rows }] } };
4905
+ const [result] = await collection.aggregate([...pipeline, facet], { allowDiskUse, ...readOptions$1 }).toArray();
4906
+ const metadata = Array.isArray(result?.metadata) ? result.metadata : [];
4907
+ const total = metadata.length === 0 ? 0 : numberOf$6(metadata[0].total);
4908
+ return { documents: Array.isArray(result?.data) ? result.data : [], info: paginationInfo(total, rows, page) };
4657
4909
  }
4658
- function readRoleNames(body) {
4659
- return stringList(body, "body");
4910
+ function pagedPipeline(pipeline, skip, rows) {
4911
+ return [...pipeline, ...skip > 0 ? [{ $skip: skip }] : [], { $limit: rows }];
4660
4912
  }
4661
4913
 
4662
- async function readJson(event) {
4663
- const text = await event.req.text();
4664
- if (text.trim() === "") {
4665
- throw MongocampError.decodeFailure("body");
4666
- }
4667
- return parseJsonBody(text);
4914
+ function combineScopes(filter, scopes) {
4915
+ const parts = [filter, ...scopes].filter((part) => Object.keys(part).length > 0);
4916
+ return parts.length === 0 ? {} : parts.length === 1 ? parts[0] : { $and: parts };
4668
4917
  }
4669
- async function readDocumentBody(event) {
4670
- return convertFields(decodeAnyObject(await readJson(event)));
4918
+ async function readScope(context, user, collection, filter, operation, options = {}) {
4919
+ return (await readScopeParts(context, user, collection, filter, operation, options)).filter;
4671
4920
  }
4672
-
4673
- class LuceneQueryError extends Error {
4674
- constructor(message) {
4675
- super(message);
4676
- this.name = "LuceneQueryError";
4921
+ async function readScopeParts(context, user, collection, filter, operation, options = {}) {
4922
+ if (!context.interceptors.has("document:beforeRead")) {
4923
+ return { filter, scope: {} };
4677
4924
  }
4678
- }
4679
- function describeQuery(query) {
4925
+ const databaseName = databaseOf(context.database, parseCollectionName(collection)).databaseName;
4926
+ const payload = await context.interceptors.run("document:beforeRead", { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, filter, operation, scopes: [], withDeleted: options.withDeleted === true });
4927
+ return { filter: combineScopes(filter, payload.scopes), scope: combineScopes({}, payload.scopes) };
4928
+ }
4929
+ function withDeletedOf(params, user, collection) {
4930
+ const value = params.get("withDeleted");
4931
+ if (value === null || value === "" || value === "false") {
4932
+ return {};
4933
+ }
4934
+ if (value !== "true") {
4935
+ throw MongocampError.decodeFailure("query parameter withDeleted", "true or false");
4936
+ }
4937
+ if (!user.canAdministrate(collection)) {
4938
+ throw MongocampError.forbidden("withDeleted needs the administrate grant of the collection");
4939
+ }
4940
+ return { withDeleted: true };
4941
+ }
4942
+
4943
+ const MaxOldValues = 1e4;
4944
+ function requireMatched(count) {
4945
+ if (count === 0) {
4946
+ throw MongocampError.notFound("could not find document");
4947
+ }
4948
+ }
4949
+ function updateResponse(result, pathId) {
4950
+ let ids = [];
4951
+ if (pathId !== void 0 && result.modifiedCount === 1 && (result.upsertedId === null || result.upsertedId === void 0)) {
4952
+ ids = [idToString(convertIdValue(pathId))];
4953
+ } else if (result.upsertedId !== null && result.upsertedId !== void 0) {
4954
+ ids = [idToString(result.upsertedId)];
4955
+ }
4956
+ return { wasAcknowledged: result.acknowledged, upsertedIds: ids, modifiedCount: result.modifiedCount, matchedCount: result.matchedCount };
4957
+ }
4958
+ function sameId(before, after) {
4959
+ if (before === after) {
4960
+ return true;
4961
+ }
4962
+ if (before === void 0 || after === void 0) {
4963
+ return false;
4964
+ }
4965
+ return BSON.EJSON.stringify({ id: before }, { relaxed: false }) === BSON.EJSON.stringify({ id: after }, { relaxed: false });
4966
+ }
4967
+ function writeErrorsOf(error) {
4968
+ const errors = error.writeErrors;
4969
+ return Array.isArray(errors) ? errors : errors ? [errors] : [];
4970
+ }
4971
+ function valueAt(document, path) {
4972
+ return path.split(".").reduce((value, key) => value !== null && typeof value === "object" && !Array.isArray(value) ? value[key] : void 0, document);
4973
+ }
4974
+ function withValueAt(document, path, value) {
4975
+ const [head, ...rest] = path.split(".");
4976
+ if (rest.length === 0) {
4977
+ return { ...document, [head]: value };
4978
+ }
4979
+ const inner = document[head];
4980
+ if (inner === null || typeof inner !== "object" || Array.isArray(inner)) {
4981
+ return document;
4982
+ }
4983
+ return { ...document, [head]: withValueAt(inner, rest.join("."), value) };
4984
+ }
4985
+ function idKey(id) {
4986
+ return BSON.EJSON.stringify({ id }, { relaxed: false });
4987
+ }
4988
+ class DocumentService {
4989
+ constructor(context) {
4990
+ this.context = context;
4991
+ }
4992
+ /** The collection of a name as the routes take it (`orders`, `otherdb:orders`). */
4993
+ collection(name) {
4994
+ return collectionOf(this.context.database, name);
4995
+ }
4996
+ /** The grant of the caller; `withDeleted` only for the administrators of the collection. */
4997
+ require(user, collection, right, options = {}) {
4998
+ this.context.auth.requireRight(user, collection, right);
4999
+ if (options.withDeleted === true && !user.canAdministrate(collection)) {
5000
+ throw MongocampError.forbidden("withDeleted needs the administrate grant of the collection");
5001
+ }
5002
+ }
5003
+ /** The filter with the read scope of the caller. */
5004
+ scope(user, collection, filter, operation, options = {}) {
5005
+ return readScope(this.context, user, collection, filter, operation, options);
5006
+ }
5007
+ /**
5008
+ * The declared references of `fields` (2.4.0); 400 for a name that is no reference of the collection and for more than `MaxExpands`.
5009
+ * Checked before anything is read.
5010
+ */
5011
+ refs(collection, fields) {
5012
+ const names = [...new Set((fields ?? []).map((field) => field.trim()).filter((field) => field !== ""))];
5013
+ if (names.length === 0) {
5014
+ return [];
5015
+ }
5016
+ if (names.length > MaxExpands) {
5017
+ throw MongocampError.badRequest(`expand takes at most ${MaxExpands} references, got ${names.length}`);
5018
+ }
5019
+ const declared = this.context.collections.resolve(this.context, collection)?.refs ?? [];
5020
+ return names.map((name) => {
5021
+ const ref = declared.find((entry) => entry.field === name);
5022
+ if (ref === void 0) {
5023
+ const known = declared.length > 0 ? `the references are ${declared.map((entry) => entry.field).join(", ")}` : "it declares no references (refs)";
5024
+ throw MongocampError.badRequest(`expand: ${name} is no reference of the collection ${collection}, ${known}`);
5025
+ }
5026
+ return ref;
5027
+ });
5028
+ }
5029
+ /**
5030
+ * 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
5031
+ * ids) with the grant and the read scope of the **target** for the same user, without its secret fields: a reference the user cannot
5032
+ * read directly becomes `null` (an array leaves it out), so an expansion never shows more than a direct read.
5033
+ */
5034
+ async expand(user, documents, refs) {
5035
+ let result = documents;
5036
+ for (const ref of refs) {
5037
+ if (result.length === 0) {
5038
+ break;
5039
+ }
5040
+ const ids = /* @__PURE__ */ new Map();
5041
+ for (const document of result) {
5042
+ const value = valueAt(document, ref.field);
5043
+ for (const id of Array.isArray(value) ? value : [value]) {
5044
+ if (id !== void 0 && id !== null) {
5045
+ ids.set(idKey(id), id);
5046
+ }
5047
+ }
5048
+ }
5049
+ const found = /* @__PURE__ */ new Map();
5050
+ if (ids.size > 0 && user.canRead(ref.collection)) {
5051
+ const filter = await this.scope(user, ref.collection, { _id: { $in: [...ids.values()] } }, "expand");
5052
+ const secrets = secretFieldsOf(this.context.database, ref.collection);
5053
+ for (const target of await this.collection(ref.collection).find(filter, readOptions$1).toArray()) {
5054
+ found.set(idKey(target._id), withoutSecrets(target, secrets));
5055
+ }
5056
+ }
5057
+ result = result.map((document) => {
5058
+ const value = valueAt(document, ref.field);
5059
+ if (value === void 0) {
5060
+ return document;
5061
+ }
5062
+ const expanded = Array.isArray(value) ? value.map((id) => found.get(idKey(id))).filter((target) => target !== void 0) : value === null ? null : found.get(idKey(value)) ?? null;
5063
+ return withValueAt(document, ref.field, expanded);
5064
+ });
5065
+ }
5066
+ return result;
5067
+ }
5068
+ /** A page of documents (list, find, search), with the references of `options.expand` expanded. */
5069
+ async page(user, collection, request, paging, count = "exact", options = {}) {
5070
+ this.require(user, collection, "read", options);
5071
+ const refs = this.refs(collection, options.expand);
5072
+ const filter = await this.scope(user, collection, request.filter, options.operation ?? "list", options);
5073
+ const page = await readPage(this.collection(collection), { ...request, filter }, paging, count);
5074
+ return refs.length > 0 ? { ...page, documents: await this.expand(user, page.documents, refs) } : page;
5075
+ }
5076
+ /** The number of documents of a filter. */
5077
+ async count(user, collection, filter, options = {}) {
5078
+ this.require(user, collection, "read", options);
5079
+ return this.collection(collection).countDocuments(await this.scope(user, collection, filter, "count", options));
5080
+ }
5081
+ /** 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. */
5082
+ async get(user, collection, id, options = {}) {
5083
+ this.require(user, collection, "read", options);
5084
+ const refs = this.refs(collection, options.expand);
5085
+ const document = await this.collection(collection).findOne(await this.scope(user, collection, pathIdFilter(id), "get", options), readOptions$1);
5086
+ return document !== null && refs.length > 0 ? (await this.expand(user, [document], refs))[0] : document;
5087
+ }
5088
+ /** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
5089
+ async exportFilter(user, collection, filter, options = {}) {
5090
+ this.require(user, collection, "read", options);
5091
+ return readScopeParts(this.context, user, collection, filter, "export", options);
5092
+ }
5093
+ /** The distinct values of a field, as aggregation results `{ _id, field }`. */
5094
+ async distinct(user, collection, field, paging, count = "exact", options = {}) {
5095
+ this.require(user, collection, "read", options);
5096
+ const scoped = await this.scope(user, collection, {}, "distinct", options);
5097
+ const path = `$${field}`;
5098
+ const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], { $group: { _id: path, field: { $first: path } } }];
5099
+ return paginatedAggregation(this.collection(collection), pipeline, true, paging, count);
5100
+ }
5101
+ /**
5102
+ * An aggregation: `prefix` (the client's filter, the unset of secrets) and the stages of the client, after the scope of the caller as
5103
+ * first `$match`. The checks of the pipeline (denied stages) are the route's.
5104
+ */
5105
+ async aggregate(user, collection, prefix, stages, allowDiskUse, paging, count = "exact", options = {}) {
5106
+ this.require(user, collection, "read", options);
5107
+ const scoped = await this.scope(user, collection, {}, "aggregate", options);
5108
+ const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], ...prefix, ...stages];
5109
+ return paginatedAggregation(this.collection(collection), pipeline, allowDiskUse, paging, count);
5110
+ }
5111
+ // ----- writes -----
5112
+ /**
5113
+ * 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
5114
+ * payload with their changes. A hook that refuses the write throws.
5115
+ */
5116
+ intercept(name, user, collection, fields) {
5117
+ const { interceptors, database } = this.context;
5118
+ if (!interceptors.has(name)) {
5119
+ return Promise.resolve({ user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName: "", ...fields });
5120
+ }
5121
+ const databaseName = databaseOf(database, parseCollectionName(collection)).databaseName;
5122
+ return interceptors.run(name, { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, ...fields });
5123
+ }
5124
+ /**
5125
+ * 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
5126
+ * their position). A hook that does not want a document refuses the write.
5127
+ */
5128
+ async interceptInsert(user, collection, documents, source, lines) {
5129
+ const count = documents.length;
5130
+ const payload = await this.intercept("document:beforeInsert", user, collection, lines !== void 0 ? { documents, source, lines } : { documents, source });
5131
+ if (payload.documents.length !== count) {
5132
+ throw new Error(`a document:beforeInsert interceptor changed the number of documents from ${count} to ${payload.documents.length}`);
5133
+ }
5134
+ return payload;
5135
+ }
5136
+ /** The documents before a change, read only when a listener waits for them; at most `MaxOldValues`. */
5137
+ async oldValues(name, collection, filter) {
5138
+ if (!this.context.events.has(name, collection)) {
5139
+ return [];
5140
+ }
5141
+ return this.collection(collection).find(filter).limit(MaxOldValues).toArray();
5142
+ }
5143
+ /** Deletes the documents of the filter, or applies the update of a before-hook instead (soft delete); answers the number of documents. */
5144
+ async deleteOrInstead(collection, filter, many, instead) {
5145
+ const target = this.collection(collection);
5146
+ if (instead !== void 0) {
5147
+ const result2 = many ? await target.updateMany(filter, instead.update) : await target.updateOne(filter, instead.update);
5148
+ return { acknowledged: result2.acknowledged, count: result2.matchedCount };
5149
+ }
5150
+ const result = many ? await target.deleteMany(filter) : await target.deleteOne(filter);
5151
+ return { acknowledged: result.acknowledged, count: result.deletedCount };
5152
+ }
5153
+ inserted(user, collection, response, documents) {
5154
+ this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
5155
+ return response;
5156
+ }
5157
+ updated(user, collection, response, old, source) {
5158
+ this.context.events.publish("document:update", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old, source });
5159
+ return response;
5160
+ }
5161
+ deleted(user, collection, response, old, softDeleted) {
5162
+ this.context.events.publish("document:delete", { user: user.user, collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
5163
+ return response;
5164
+ }
5165
+ /** Inserts one document (decoded). */
5166
+ async insert(user, collection, document) {
5167
+ this.require(user, collection, "write");
5168
+ const { documents } = await this.interceptInsert(user, collection, [document], "insert");
5169
+ const result = await this.collection(collection).insertOne(documents[0]);
5170
+ return this.inserted(user, collection, { wasAcknowledged: result.acknowledged, insertedIds: [idToString(result.insertedId)] }, documents);
5171
+ }
5172
+ /** Inserts documents; `ordered: false` stores the ones that can be stored and reports the others in `errors`. */
5173
+ async insertMany(user, collection, input, ordered = true) {
5174
+ this.require(user, collection, "write");
5175
+ const { documents } = await this.interceptInsert(user, collection, input, "insertMany");
5176
+ const target = this.collection(collection);
5177
+ if (ordered) {
5178
+ const result = await target.insertMany(documents);
5179
+ const ids = Object.keys(result.insertedIds).map(Number).sort((a, b) => a - b).map((index) => idToString(result.insertedIds[index]));
5180
+ return this.inserted(user, collection, { wasAcknowledged: result.acknowledged, insertedIds: ids, insertedCount: ids.length, errors: [] }, documents);
5181
+ }
5182
+ const withIds = documents.map((document) => "_id" in document ? document : { ...document, _id: new ObjectId() });
5183
+ try {
5184
+ await target.insertMany(withIds, { ordered: false });
5185
+ const ids = withIds.map((document) => idToString(document._id));
5186
+ return this.inserted(user, collection, { wasAcknowledged: true, insertedIds: ids, insertedCount: ids.length, errors: [] }, withIds);
5187
+ } catch (error) {
5188
+ if (!(error instanceof MongoBulkWriteError) || writeErrorsOf(error).length === 0) {
5189
+ throw error;
5190
+ }
5191
+ const errors = writeErrorsOf(error).map((writeError) => ({ index: Number(writeError.index), code: Number(writeError.code), message: removeInternalNames(writeError.errmsg ?? writeError.message ?? "") })).sort((a, b) => a.index - b.index);
5192
+ const failed = new Set(errors.map((entry) => entry.index));
5193
+ const ids = withIds.filter((_, index) => !failed.has(index)).map((document) => idToString(document._id));
5194
+ return this.inserted(user, collection, { wasAcknowledged: true, insertedIds: ids, insertedCount: ids.length, errors }, withIds.filter((_, index) => !failed.has(index)));
5195
+ }
5196
+ }
5197
+ /** Imports the lines of a body stream (all or nothing); the hooks see the valid documents of each batch. */
5198
+ async import(user, collection, body, maxBytes) {
5199
+ this.require(user, collection, "write");
5200
+ const beforeBatch = this.context.interceptors.has("document:beforeInsert") ? async (documents, lines) => (await this.interceptInsert(user, collection, documents, "import", lines)).documents : void 0;
5201
+ const state = await importStream(this.collection(collection), body, maxBytes, beforeBatch);
5202
+ if (state.storedIds.length > 0) {
5203
+ const insertedIds = state.storedIdTexts;
5204
+ this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
5205
+ }
5206
+ return state;
5207
+ }
5208
+ /** Replaces the document of the path id (decoded body); 404 when it is missing or not in the scope, 409 of a version check. */
5209
+ async replace(user, collection, id, body) {
5210
+ this.require(user, collection, "write");
5211
+ const bodyId = body._id;
5212
+ const { filter, document, onNoMatch } = await this.intercept("document:beforeReplace", user, collection, { filter: await this.scope(user, collection, pathIdFilter(id), "write"), document: body });
5213
+ if (!sameId(bodyId, document._id)) {
5214
+ throw MongocampError.badRequest("an interceptor must not change the _id of a replaced document");
5215
+ }
5216
+ const old = await this.oldValues("document:update", collection, filter);
5217
+ const result = await this.collection(collection).replaceOne(filter, document);
5218
+ if (result.matchedCount === 0) {
5219
+ await onNoMatch?.();
5220
+ }
5221
+ requireMatched(result.matchedCount);
5222
+ return this.updated(user, collection, updateResponse(result, id), old.slice(0, 1), "replace");
5223
+ }
5224
+ /** Changes the document of the path id with an operator update (`$set`, ...). */
5225
+ async update(user, collection, id, operators) {
5226
+ this.require(user, collection, "write");
5227
+ const { filter, update, onNoMatch } = await this.intercept("document:beforeUpdate", user, collection, { filter: await this.scope(user, collection, pathIdFilter(id), "write"), update: operators, many: false });
5228
+ const old = await this.oldValues("document:update", collection, filter);
5229
+ const result = await this.collection(collection).updateOne(filter, update);
5230
+ if (result.matchedCount === 0) {
5231
+ await onNoMatch?.();
5232
+ }
5233
+ requireMatched(result.matchedCount);
5234
+ return this.updated(user, collection, updateResponse(result, id), old.slice(0, 1), "update");
5235
+ }
5236
+ /** Changes the documents of a filter (checked by the caller: not empty unless intended). */
5237
+ async updateMany(user, collection, filter, operators) {
5238
+ this.require(user, collection, "write");
5239
+ const payload = await this.intercept("document:beforeUpdate", user, collection, { filter: await this.scope(user, collection, filter, "write"), update: operators, many: true });
5240
+ const old = await this.oldValues("document:update", collection, payload.filter);
5241
+ const result = await this.collection(collection).updateMany(payload.filter, payload.update);
5242
+ return this.updated(user, collection, updateResponse(result), old, "updateMany");
5243
+ }
5244
+ /** Deletes the document of the path id (or marks it, soft delete); 404 when it is missing or not in the scope. */
5245
+ async remove(user, collection, id) {
5246
+ this.require(user, collection, "write");
5247
+ const { filter, instead } = await this.intercept("document:beforeDelete", user, collection, { filter: await this.scope(user, collection, pathIdFilter(id), "write"), many: false });
5248
+ const old = await this.oldValues("document:delete", collection, filter);
5249
+ const result = await this.deleteOrInstead(collection, filter, false, instead);
5250
+ requireMatched(result.count);
5251
+ return this.deleted(user, collection, { wasAcknowledged: result.acknowledged, deletedCount: result.count }, old.slice(0, result.count), instead !== void 0);
5252
+ }
5253
+ /** Deletes the documents of a filter (checked by the caller). */
5254
+ async removeMany(user, collection, filter) {
5255
+ this.require(user, collection, "write");
5256
+ const { filter: scoped, instead } = await this.intercept("document:beforeDelete", user, collection, { filter: await this.scope(user, collection, filter, "write"), many: true });
5257
+ const old = await this.oldValues("document:delete", collection, scoped);
5258
+ const result = await this.deleteOrInstead(collection, scoped, true, instead);
5259
+ return this.deleted(user, collection, { wasAcknowledged: result.acknowledged, deletedCount: result.count }, old, instead !== void 0);
5260
+ }
5261
+ /** Brings a soft-deleted document back (collections declared with softDelete). */
5262
+ async restore(user, collection, id) {
5263
+ this.require(user, collection, "write");
5264
+ const declared = this.context.collections.resolve(this.context, collection);
5265
+ if (declared?.behaviours.softDelete === void 0) {
5266
+ throw MongocampError.notFound(`the collection ${collection} has no soft delete (declare it with softDelete: true)`);
5267
+ }
5268
+ const filter = await this.scope(user, collection, pathIdFilter(id), "restore");
5269
+ const old = this.context.events.has("document:restore", collection) ? await this.collection(collection).find(filter).limit(1).toArray() : [];
5270
+ const result = await this.collection(collection).updateOne(filter, restoreUpdate(declared.behaviours, { now: /* @__PURE__ */ new Date(), userId: user.user.userId }));
5271
+ if (result.matchedCount === 0) {
5272
+ throw MongocampError.notFound("could not find a deleted document with this id");
5273
+ }
5274
+ const response = updateResponse(result, id);
5275
+ this.context.events.publish("document:restore", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old });
5276
+ return response;
5277
+ }
5278
+ /** The audit records of a filter (a document or the collection), newest first. */
5279
+ async auditRecords(filter, paging, count = "exact") {
5280
+ return readPage(auditCollectionOf(this.context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, paging, count);
5281
+ }
5282
+ }
5283
+
5284
+ class LuceneQueryError extends Error {
5285
+ constructor(message) {
5286
+ super(message);
5287
+ this.name = "LuceneQueryError";
5288
+ }
5289
+ }
5290
+ function describeQuery(query) {
4680
5291
  switch (query.type) {
4681
5292
  case "boolean":
4682
5293
  return query.clauses.map((clause) => `${clause.occur === "MUST" ? "+" : clause.occur === "MUST_NOT" ? "-" : ""}${clause.query.type === "boolean" ? `(${describeQuery(clause.query)})` : describeQuery(clause.query)}`).join(" ");
@@ -5753,37 +6364,545 @@ class Parser {
5753
6364
  return { type: "term", field, text: text.includes("*") ? escapeChars(text, "\\*?") : text };
5754
6365
  }
5755
6366
  }
5756
- function parseLuceneQuery(input, defaultField) {
5757
- return new Parser(input, defaultField).parseTopLevel();
6367
+ function parseLuceneQuery(input, defaultField) {
6368
+ return new Parser(input, defaultField).parseTopLevel();
6369
+ }
6370
+
6371
+ const FilterDefaultField = "";
6372
+ function luceneToFilter(input, defaultField, options = {}) {
6373
+ return luceneQueryToFilter(parseLuceneQuery(input, defaultField), options);
6374
+ }
6375
+ function filterParameter(input, options = {}, parameter = "filter") {
6376
+ if (input === null || input === void 0 || input.trim() === "") {
6377
+ return {};
6378
+ }
6379
+ let query;
6380
+ try {
6381
+ query = parseLuceneQuery(input, FilterDefaultField);
6382
+ return luceneQueryToFilter(query, options);
6383
+ } catch (error) {
6384
+ const message = error instanceof LuceneQueryError || error instanceof Error ? error.message : "";
6385
+ const reason = message.split("\n").map((line) => line.trim()).find((line) => line !== "") ?? "the filter syntax is not supported";
6386
+ throw MongocampError.decodeFailure(`query parameter ${parameter}`, reason);
6387
+ }
6388
+ }
6389
+ function bodyFilter(input, options = {}) {
6390
+ if (input === null || input === void 0 || input.trim() === "") {
6391
+ return {};
6392
+ }
6393
+ try {
6394
+ return filterParameter(input, options);
6395
+ } catch (error) {
6396
+ throw new MongocampError("Invalid value for: filter", 400, 4001, error instanceof MongocampError ? error.additionalInfo : "");
6397
+ }
6398
+ }
6399
+
6400
+ const SystemUser = new AuthorizedUser({ userId: "system", password: "", apiKey: null, roles: ["system"] }, [{ name: "system", isAdmin: true, collectionGrants: [] }]);
6401
+ function idOf(target) {
6402
+ const id = isPlainObject(target) && "_id" in target ? target._id : target;
6403
+ return id instanceof ObjectId ? id.toHexString() : idToString(id);
6404
+ }
6405
+ function isDocument$1(target) {
6406
+ return isPlainObject(target) && "_id" in target;
6407
+ }
6408
+ function createServerCollection(context, name, options) {
6409
+ const service = context.documents;
6410
+ let resolved;
6411
+ const user = () => {
6412
+ resolved ??= (async () => {
6413
+ const given = options.user;
6414
+ if (given === "system") {
6415
+ return SystemUser;
6416
+ }
6417
+ if (given instanceof AuthorizedUser) {
6418
+ return given;
6419
+ }
6420
+ if (given instanceof Request) {
6421
+ return context.auth.authenticate(given);
6422
+ }
6423
+ if (typeof given === "string" && given !== "") {
6424
+ return context.auth.authorizedUser(given);
6425
+ }
6426
+ throw MongocampError.unauthorized("the server collection needs a user (an id, a request or 'system')");
6427
+ })();
6428
+ return resolved;
6429
+ };
6430
+ const filterOf = (filter) => {
6431
+ if (filter === void 0) {
6432
+ return {};
6433
+ }
6434
+ return typeof filter === "string" ? filterParameter(filter, { timeZone: context.config.string(ConfigKeys.FilterTimeZone) }) : filter;
6435
+ };
6436
+ const plain = (document) => plainNumbers(document);
6437
+ const decodedConflict = async (write) => {
6438
+ try {
6439
+ return await write;
6440
+ } catch (error) {
6441
+ if (error instanceof MongocampError && error.current !== void 0) {
6442
+ throw new MongocampError(error.message, error.status, error.code, error.additionalInfo, error.issues, BSON.EJSON.deserialize(error.current, { relaxed: true }));
6443
+ }
6444
+ throw error;
6445
+ }
6446
+ };
6447
+ const withVersion = (target, body) => {
6448
+ const versioned = context.collections.resolve(context, name)?.behaviours.versioned;
6449
+ if (versioned === void 0 || !isDocument$1(target)) {
6450
+ return body;
6451
+ }
6452
+ const version = versioned.field.split(".").reduce((value, key) => isPlainObject(value) ? value[key] : void 0, target);
6453
+ if (version === void 0) {
6454
+ return body;
6455
+ }
6456
+ const copy = { ...body };
6457
+ setPath(copy, versioned.field, version);
6458
+ return copy;
6459
+ };
6460
+ const page = async (find = {}) => {
6461
+ const request = {
6462
+ filter: filterOf(find.filter),
6463
+ sort: Array.isArray(find.sort) ? sortFromList(find.sort) : find.sort ?? {},
6464
+ projection: Array.isArray(find.projection) ? projectionFromList(find.projection) : find.projection ?? {}
6465
+ };
6466
+ const rowsPerPage = find.rowsPerPage ?? DefaultRowsPerPage;
6467
+ const pageNumber = find.page ?? 1;
6468
+ const result = await service.page(await user(), name, request, { rowsPerPage, page: pageNumber }, find.count ?? "exact", { operation: "list", withDeleted: find.withDeleted, expand: find.expand });
6469
+ return {
6470
+ documents: result.documents.map(plain),
6471
+ page: pageNumber,
6472
+ rowsPerPage,
6473
+ ...result.info.allCount !== void 0 ? { countRows: result.info.allCount } : {},
6474
+ ...result.info.pagesCount !== void 0 ? { countPages: result.info.pagesCount } : {}
6475
+ };
6476
+ };
6477
+ return {
6478
+ name,
6479
+ find: async (find = {}) => (await page(find)).documents,
6480
+ findPage: page,
6481
+ findById: async (id, read = {}) => {
6482
+ const document = await service.get(await user(), name, idOf(id), read);
6483
+ return document === null ? null : plain(document);
6484
+ },
6485
+ count: async (filter, read = {}) => service.count(await user(), name, filterOf(filter), read),
6486
+ insert: async (document) => service.insert(await user(), name, document),
6487
+ insertMany: async (documents, write = {}) => service.insertMany(await user(), name, documents, write.ordered ?? true),
6488
+ replace: async (target, document) => decodedConflict(service.replace(await user(), name, idOf(target), withVersion(target, document))),
6489
+ update: async (target, changes) => decodedConflict(service.update(await user(), name, idOf(target), convertToOperationMap(withVersion(target, changes)))),
6490
+ updateMany: async (filter, changes) => service.updateMany(await user(), name, filterOf(filter), convertToOperationMap(changes)),
6491
+ remove: async (target) => service.remove(await user(), name, idOf(target)),
6492
+ removeMany: async (filter) => service.removeMany(await user(), name, filterOf(filter)),
6493
+ restore: async (target) => service.restore(await user(), name, idOf(target)),
6494
+ history: async (target) => {
6495
+ const document = await service.get(await user(), name, idOf(target));
6496
+ const declared = context.collections.resolve(context, name);
6497
+ if (declared?.behaviours.audit === void 0) {
6498
+ throw MongocampError.notFound(`the collection ${name} has no audit (declare it with audit: true)`);
6499
+ }
6500
+ if (document === null && !(await user()).canAdministrate(name)) {
6501
+ throw MongocampError.notFound("could not find document");
6502
+ }
6503
+ const result = await service.auditRecords({ collection: declared.definition.name, database: declared.databaseName, documentId: document?._id ?? idOf(target) }, { rowsPerPage: 1e3, page: 1 }, "none");
6504
+ return result.documents.map((record) => plainNumbers(record));
6505
+ }
6506
+ };
6507
+ }
6508
+
6509
+ const allowedMethods = "OPTIONS, POST, PUT, PATCH, GET, DELETE";
6510
+ function requestOrigin(request) {
6511
+ const origin = request.headers.get("origin");
6512
+ if (origin) {
6513
+ return origin;
6514
+ }
6515
+ const referer = request.headers.get("referer");
6516
+ return referer ? referer.replace(/\/$/, "") : void 0;
6517
+ }
6518
+ function corsHeaders(config, origin) {
6519
+ const allowedOrigins = config.list(ConfigKeys.CorsOriginsAllowed).filter((entry) => entry !== "");
6520
+ let allowOrigin;
6521
+ if (origin !== void 0 && allowedOrigins.includes(origin)) {
6522
+ allowOrigin = origin;
6523
+ } else if (allowedOrigins.length === 0) {
6524
+ allowOrigin = "*";
6525
+ } else {
6526
+ allowOrigin = allowedOrigins[0];
6527
+ }
6528
+ return {
6529
+ "access-control-allow-origin": allowOrigin,
6530
+ "access-control-allow-credentials": "true",
6531
+ "access-control-allow-headers": config.list(ConfigKeys.CorsHeadersAllowed).join(","),
6532
+ "access-control-expose-headers": config.list(ConfigKeys.CorsHeadersExposed).join(",")
6533
+ };
6534
+ }
6535
+ function preflightResponse(request, config) {
6536
+ return new Response(null, {
6537
+ status: 200,
6538
+ headers: {
6539
+ ...corsHeaders(config, requestOrigin(request)),
6540
+ "access-control-allow-methods": allowedMethods
6541
+ }
6542
+ });
6543
+ }
6544
+ const requestIdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
6545
+ function newRequestId() {
6546
+ return Array.from(randomBytes(10), (byte) => requestIdAlphabet[byte % requestIdAlphabet.length]).join("");
6547
+ }
6548
+ function withCommonHeaders(response, request, config, version, requestId) {
6549
+ const headers = {
6550
+ ...corsHeaders(config, requestOrigin(request)),
6551
+ "server": `${version.name}/${version.version}`,
6552
+ "x-request-id": requestId
6553
+ };
6554
+ try {
6555
+ for (const [name, value] of Object.entries(headers)) {
6556
+ response.headers.set(name, value);
6557
+ }
6558
+ return response;
6559
+ } catch {
6560
+ const copy = new Response(response.body, response);
6561
+ for (const [name, value] of Object.entries(headers)) {
6562
+ copy.headers.set(name, value);
6563
+ }
6564
+ return copy;
6565
+ }
6566
+ }
6567
+
6568
+ const resourcePattern = /^\/mongodb\/(collections|buckets|databases)\/([^/]+)/;
6569
+ function decoded(segment) {
6570
+ try {
6571
+ return decodeURIComponent(segment);
6572
+ } catch {
6573
+ return segment;
6574
+ }
6575
+ }
6576
+ function requestFields(request, response, fields, user) {
6577
+ const result = { requestId: fields.requestId, operation: fields.methodName, controller: fields.controller };
6578
+ if (user) {
6579
+ result.user = user;
6580
+ }
6581
+ const match = resourcePattern.exec(new URL(request.url).pathname);
6582
+ if (match && match[2] !== "info") {
6583
+ const name = decoded(match[2]);
6584
+ if (match[1] === "collections") {
6585
+ result.collection = name;
6586
+ } else if (match[1] === "buckets") {
6587
+ result.bucket = name;
6588
+ } else if (match[2] !== "infos") {
6589
+ result.database = name;
6590
+ }
6591
+ }
6592
+ const rows = Number.parseInt(response.headers.get(PaginationHeaders.countRows) ?? "", 10);
6593
+ if (Number.isFinite(rows)) {
6594
+ result.rows = rows;
6595
+ }
6596
+ if (response.status >= 400) {
6597
+ const code = response.headers.get(ErrorHeaders.code);
6598
+ const message = response.headers.get(ErrorHeaders.message);
6599
+ if (code) {
6600
+ result.errorCode = code;
6601
+ }
6602
+ if (message) {
6603
+ result.errorMessage = message;
6604
+ }
6605
+ }
6606
+ return result;
6607
+ }
6608
+ function addRequestFields(log, request, response, fields, user) {
6609
+ try {
6610
+ log.set({ mongocamp: requestFields(request, response, fields, user) });
6611
+ } catch {
6612
+ }
6613
+ }
6614
+
6615
+ const operations = [
6616
+ ["POST", "/auth/login", "login", "Auth", "Login User"],
6617
+ ["POST", "/auth/logout", "logout", "Auth", "Logout User"],
6618
+ ["DELETE", "/auth/logout", "logoutByDelete", "Auth", "Logout User"],
6619
+ ["GET", "/auth/token/refresh", "refreshToken", "Auth", "Refresh User"],
6620
+ ["PATCH", "/auth/profile/password", "updatePassword", "Auth", "Update Password"],
6621
+ ["PATCH", "/auth/profile/apikey", "generateNewApiKey", "Auth", "Update ApiKey"],
6622
+ ["GET", "/auth/profile", "userProfile", "Auth", "User Profile"],
6623
+ ["GET", "/auth/permissions", "userPermissions", "Auth", "Collection permissions"],
6624
+ ["GET", "/auth/authenticated", "isAuthenticated", "Auth", "Check Authentication"],
6625
+ ["GET", "/admin/users", "listUsers", "Admin", "List Users"],
6626
+ ["PUT", "/admin/users", "addUser", "Admin", "Add User"],
6627
+ ["PATCH", "/admin/users/:userId/apikey", "gnerateNewApiKeyForUser", "Admin", "Update ApiKey"],
6628
+ ["PATCH", "/admin/users/:userId/password", "updatePasswordForUser", "Admin", "Update Password"],
6629
+ ["PATCH", "/admin/users/:userId/roles", "updateRolesForUser", "Admin", "Update User Roles"],
6630
+ ["GET", "/admin/users/:userId", "getUser", "Admin", "UserProfile for userId"],
6631
+ ["DELETE", "/admin/users/:userId", "deleteUser", "Admin", "Delete User"],
6632
+ ["GET", "/admin/roles", "listRoles", "Admin", "List Roles"],
6633
+ ["PUT", "/admin/roles", "addRole", "Admin", "Add Role"],
6634
+ ["GET", "/admin/roles/:roleName", "getRole", "Admin", "Get Role"],
6635
+ ["DELETE", "/admin/roles/:roleName", "deleteRole", "Admin", "Delete Role"],
6636
+ ["PATCH", "/admin/roles/:roleName", "updateRole", "Admin", "Update Role"],
6637
+ ["GET", "/mongodb/buckets/:bucketName/files", "listFiles", "File", "Files in Bucket"],
6638
+ ["PUT", "/mongodb/buckets/:bucketName/files", "insertFile", "File", "Insert File"],
6639
+ ["POST", "/mongodb/buckets/:bucketName/files", "findFiles", "File", "Files in Bucket"],
6640
+ ["GET", "/mongodb/buckets/:bucketName/files/:fileId", "getFileInformation", "File", "FileInformation from Bucket"],
6641
+ ["DELETE", "/mongodb/buckets/:bucketName/files/:fileId", "deleteFile", "File", "Delete File from Bucket"],
6642
+ ["PATCH", "/mongodb/buckets/:bucketName/files/:fileId", "updateFileInformation", "File", "Update FileInformation in Bucket"],
6643
+ ["GET", "/mongodb/buckets/:bucketName/files/:fileId/file", "getFile", "File", "File from Bucket"],
6644
+ ["GET", "/mongodb/buckets", "listBuckets", "Bucket", "List of Buckets"],
6645
+ ["GET", "/mongodb/buckets/:bucketName", "getBucket", "Bucket", "Bucket Information"],
6646
+ ["DELETE", "/mongodb/buckets/:bucketName", "deleteBucket", "Bucket", "Delete Bucket"],
6647
+ ["DELETE", "/mongodb/buckets/:bucketName/clear", "clearBucket", "Bucket", "Clear Bucket"],
6648
+ ["GET", "/mongodb/collections", "listCollections", "Collection", "List of Collections"],
6649
+ ["GET", "/mongodb/collections/info", "listCollectionInformation", "Collection", "Information of all Collections"],
6650
+ ["GET", "/mongodb/collections/:collectionName", "getCollectionInformation", "Collection", "Collection Information"],
6651
+ ["PUT", "/mongodb/collections/:collectionName", "createCollection", "Collection", "Create Collection"],
6652
+ ["DELETE", "/mongodb/collections/:collectionName", "deleteCollection", "Collection", "Delete Collection"],
6653
+ ["GET", "/mongodb/collections/:collectionName/fields", "getCollectionFields", "Collection", "Collection Fields"],
6654
+ ["GET", "/mongodb/collections/:collectionName/fields/detail", "getFieldDetails", "Collection", "Fields of a Collection with types"],
6655
+ ["GET", "/mongodb/collections/:collectionName/schema", "getJsonSchema", "Collection", "Collection Fields"],
6656
+ ["GET", "/mongodb/collections/:collectionName/schema/analysis", "getSchemaAnalysis", "Collection", "Collection Fields"],
6657
+ ["GET", "/mongodb/collections/:collectionName/schema/validator", "getSuggestedValidator", "Collection", "Suggested Validator"],
6658
+ ["POST", "/mongodb/collections/:collectionName/rename", "renameCollection", "Collection", "Rename Collection"],
6659
+ ["GET", "/mongodb/collections/:collectionName/options", "getCollectionOptions", "Collection", "Collection Options"],
6660
+ ["PATCH", "/mongodb/collections/:collectionName/options", "modifyCollectionOptions", "Collection", "Change the Validation of a Collection"],
6661
+ ["POST", "/mongodb/collections/:collectionName/copy", "copyCollection", "Collection", "Copy Collection"],
6662
+ ["DELETE", "/mongodb/collections/:collectionName/clear", "clearCollection", "Collection", "Clear Collection"],
6663
+ ["POST", "/mongodb/collections/:collectionName/aggregate", "aggregate", "Collection", "Aggregate in Collection"],
6664
+ ["POST", "/mongodb/collections/:collectionName/distinct/:field", "distinct", "Collection", "Distinct in Collection"],
6665
+ ["GET", "/system/settings", "settings", "Application", "System Settings"],
6666
+ ["GET", "/system/configurations", "listConfigurations", "Application", "List Configurations"],
6667
+ ["GET", "/system/configurations/:configurationKey", "getConfig", "Application", "Configuration for configurationKey"],
6668
+ ["PATCH", "/system/configurations/:configurationKey", "updateConfiguration", "Application", "Update Configuration"],
6669
+ ["DELETE", "/system", "shutdown", "Application", "Shutdown MongoCamp"],
6670
+ ["GET", "/mongodb/databases", "ListDatabases", "Database", "List of Databases"],
6671
+ ["GET", "/mongodb/databases/infos", "databaseInfos", "Database", "List of Database Infos"],
6672
+ ["GET", "/mongodb/databases/:databaseName", "getDatabaseInfo", "Database", "Database Infos of selected Database"],
6673
+ ["DELETE", "/mongodb/databases/:databaseName", "deleteDatabase", "Database", "Delete Database"],
6674
+ ["GET", "/mongodb/databases/:databaseName/collections", "listCollectionsByDatabase", "Database", "List of Collections"],
6675
+ ["GET", "/mongodb/collections/:collectionName/documents", "listDocuments", "Document", "Documents in Collection"],
6676
+ ["PUT", "/mongodb/collections/:collectionName/documents", "insert", "Document", "Insert Document"],
6677
+ ["POST", "/mongodb/collections/:collectionName/documents", "find", "Document", "Documents in Collection"],
6678
+ ["GET", "/mongodb/collections/:collectionName/documents/count", "countDocuments", "Document", "Count Documents in Collection"],
6679
+ ["POST", "/mongodb/collections/:collectionName/documents/count", "countDocumentsByBody", "Document", "Count Documents in Collection (filter in the body)"],
6680
+ ["POST", "/mongodb/collections/:collectionName/documents/search", "searchDocuments", "Document", "Search Documents in Collection"],
6681
+ ["GET", "/mongodb/collections/:collectionName/documents/export", "exportDocuments", "Document", "Export Documents of a Collection"],
6682
+ ["POST", "/mongodb/collections/:collectionName/documents/export", "exportDocumentsByBody", "Document", "Export Documents of a Collection (filter in the body)"],
6683
+ ["POST", "/mongodb/collections/:collectionName/documents/import", "importDocuments", "Document", "Import Documents into a Collection"],
6684
+ ["PUT", "/mongodb/collections/:collectionName/documents/many/insert", "insertMany", "Document", "Insert many Documents"],
6685
+ ["PATCH", "/mongodb/collections/:collectionName/documents/many/update", "updateMany", "Document", "Update many in Collection"],
6686
+ ["DELETE", "/mongodb/collections/:collectionName/documents/many/delete", "deleteMany", "Document", "Delete Many in Collection"],
6687
+ ["GET", "/mongodb/collections/:collectionName/documents/:documentId", "getDocument", "Document", "Document from Collection"],
6688
+ ["DELETE", "/mongodb/collections/:collectionName/documents/:documentId", "delete", "Document", "Delete Document from Collection"],
6689
+ ["PATCH", "/mongodb/collections/:collectionName/documents/:documentId", "update", "Document", "Update Document in Collection"],
6690
+ ["PATCH", "/mongodb/collections/:collectionName/documents/:documentId/partial", "updateDocumentPartial", "Document", "Update Document Parts in Collection"],
6691
+ ["POST", "/mongodb/collections/:collectionName/documents/:documentId/restore", "restoreDocument", "Document", "Restore a soft-deleted Document"],
6692
+ ["GET", "/mongodb/collections/:collectionName/documents/watch", "watchDocuments", "Document", "Live Updates of a Collection"],
6693
+ ["GET", "/mongodb/collections/:collectionName/documents/:documentId/history", "getDocumentHistory", "Document", "History of a Document"],
6694
+ ["GET", "/mongodb/collections/:collectionName/history", "getCollectionHistory", "Collection", "History of a Collection"],
6695
+ ["GET", "/mongodb/collections/:collectionName/declaration", "getCollectionDeclaration", "Collection", "Declaration of a Collection"],
6696
+ ["GET", "/mongodb/collections/:collectionName/index", "listIndices", "Index", "List Indices for Collection"],
6697
+ ["PUT", "/mongodb/collections/:collectionName/index", "createIndex", "Index", "Create Index for Collection"],
6698
+ ["GET", "/mongodb/collections/:collectionName/index/stats", "indexStats", "Index", "Index usage for Collection"],
6699
+ ["GET", "/mongodb/collections/:collectionName/index/details", "indexDetails", "Index", "Indices with details for Collection"],
6700
+ ["GET", "/mongodb/collections/:collectionName/index/:indexName", "index", "Index", "Index for Collection"],
6701
+ ["DELETE", "/mongodb/collections/:collectionName/index/:indexName", "deleteIndex", "Index", "Delete Index"],
6702
+ ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName", "createIndexForField", "Index", "Create Index by Field for Collection"],
6703
+ ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/unique", "createUniqueIndex", "Index", "Create Unique Index"],
6704
+ ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/:duration/expiring", "createExpiringIndex", "Index", "Create expiring Index by Field for Collection"],
6705
+ ["PUT", "/mongodb/collections/:collectionName/index/field/:fieldName/text", "createTextIndex", "Index", "Create text index by field for collection"],
6706
+ ["GET", "/version", "version", "System", "Version Information"],
6707
+ ["GET", "/system/jobs", "jobsList", "Jobs", "Registered Jobs"],
6708
+ ["PUT", "/system/jobs", "registerJob", "Jobs", "Register Job"],
6709
+ ["POST", "/system/jobs/:jobGroup/:jobName", "executeJob", "Jobs", "Execute Job"],
6710
+ ["DELETE", "/system/jobs/:jobGroup/:jobName", "deleteJob", "Jobs", "Delete Job"],
6711
+ ["PATCH", "/system/jobs/:jobGroup/:jobName", "updateJob", "Jobs", "Update Job"],
6712
+ ["GET", "/system/jobs/classes", "possibleJobsList", "Jobs", "Possible Jobs"],
6713
+ ["GET", "/system/cluster", "viewCluster", "System", "Registered Jobs"],
6714
+ ["GET", "/system/info", "systemInfo", "System", "System Information"],
6715
+ ["GET", "/system/stats", "systemStats", "System", "System Statistics"],
6716
+ ["GET", "/system/capabilities", "systemCapabilities", "System", "System Capabilities"]
6717
+ ];
6718
+
6719
+ const router = createRouter();
6720
+ for (const [method, path, operationId, tag, summary] of operations) {
6721
+ addRoute(router, method, path, { operationId, tag, summary });
6722
+ }
6723
+ function findOperation(method, path) {
6724
+ return findRoute(router, method.toUpperCase(), path)?.data;
6725
+ }
6726
+ function controllerName(tag) {
6727
+ return tag.replaceAll("/", "").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
6728
+ }
6729
+
6730
+ function remoteAddressOf(request) {
6731
+ const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
6732
+ return forwarded || request.headers.get("x-real-ip") || request.ip || "NOT_SET";
6733
+ }
6734
+ async function userIdOf(request, auth) {
6735
+ const credentials = readCredentials(request);
6736
+ const authorization = request.headers.get("authorization");
6737
+ if (authorization === null && credentials.apiKey === void 0) {
6738
+ return "";
6739
+ }
6740
+ try {
6741
+ return (await auth.authenticateUser(credentials)).userId;
6742
+ } catch {
6743
+ if (credentials.bearer !== void 0) {
6744
+ return "INVALID_TOKEN";
6745
+ }
6746
+ return authorization !== null ? "INVALID_AUTH" : "INVALID_APIKEY";
6747
+ }
6748
+ }
6749
+ class RequestEvents {
6750
+ constructor(events, auth) {
6751
+ this.events = events;
6752
+ this.auth = auth;
6753
+ }
6754
+ get needsUser() {
6755
+ return this.events.has("http:requestStart") || this.events.has("http:requestCompleted");
6756
+ }
6757
+ /** Publishes the start; the answer is the input of `completed`. */
6758
+ async started(request, requestId) {
6759
+ const startedAt = performance.now();
6760
+ const url = new URL(request.url);
6761
+ const operation = findOperation(request.method, url.pathname);
6762
+ const methodName = operation ? operation.operationId || operation.tag : "NOT_SET";
6763
+ const fields = {
6764
+ requestId,
6765
+ httpMethod: request.method,
6766
+ methodName,
6767
+ uri: request.url,
6768
+ remoteAddress: remoteAddressOf(request),
6769
+ userId: this.needsUser ? await userIdOf(request, this.auth) : "",
6770
+ controller: operation ? controllerName(operation.tag) : "NOT_SET",
6771
+ controllerMethod: methodName,
6772
+ comment: operation?.summary ?? "NOT_SET"
6773
+ };
6774
+ this.events.publish("http:requestStart", fields);
6775
+ return { fields, startedAt };
6776
+ }
6777
+ completed(start, response) {
6778
+ this.events.publish("http:requestCompleted", { ...start.fields, durationMillis: Math.round((performance.now() - start.startedAt) * 1e3) / 1e3, responseCode: response.status });
6779
+ }
6780
+ }
6781
+
6782
+ function fail(field) {
6783
+ throw MongocampError.decodeFailure("body", `field ${field}`);
6784
+ }
6785
+ function asObject(value, field = "body") {
6786
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
6787
+ fail(field);
6788
+ }
6789
+ return value;
6790
+ }
6791
+ function requiredString(body, field) {
6792
+ const value = body[field];
6793
+ if (typeof value !== "string") {
6794
+ fail(field);
6795
+ }
6796
+ return value;
6797
+ }
6798
+ function optionalString(body, field) {
6799
+ const value = body[field];
6800
+ if (value === void 0 || value === null) {
6801
+ return void 0;
6802
+ }
6803
+ if (typeof value !== "string") {
6804
+ fail(field);
6805
+ }
6806
+ return value;
6807
+ }
6808
+ function requiredBoolean(body, field) {
6809
+ const value = body[field];
6810
+ if (typeof value !== "boolean") {
6811
+ fail(field);
6812
+ }
6813
+ return value;
6814
+ }
6815
+ function optionalBoolean(body, field) {
6816
+ const value = body[field];
6817
+ if (value === void 0 || value === null) {
6818
+ return void 0;
6819
+ }
6820
+ if (typeof value !== "boolean") {
6821
+ fail(field);
6822
+ }
6823
+ return value;
6824
+ }
6825
+ function optionalInteger$1(body, field) {
6826
+ const value = body[field];
6827
+ if (value === void 0 || value === null) {
6828
+ return void 0;
6829
+ }
6830
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
6831
+ fail(field);
6832
+ }
6833
+ return value;
6834
+ }
6835
+ function stringList(value, field) {
6836
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
6837
+ fail(field);
6838
+ }
6839
+ return value;
6840
+ }
6841
+ function optionalList(body, field, map) {
6842
+ const value = body[field];
6843
+ if (value === void 0 || value === null) {
6844
+ return [];
6845
+ }
6846
+ if (!Array.isArray(value)) {
6847
+ fail(field);
6848
+ }
6849
+ return value.map(map);
6850
+ }
6851
+
6852
+ function readLogin(body) {
6853
+ const object = asObject(body);
6854
+ return { userId: requiredString(object, "userId"), password: requiredString(object, "password") };
6855
+ }
6856
+ function readPasswordUpdate(body) {
6857
+ return requiredString(asObject(body), "password");
6858
+ }
6859
+ function readUserInformation(body) {
6860
+ const object = asObject(body);
6861
+ return {
6862
+ userId: requiredString(object, "userId"),
6863
+ password: requiredString(object, "password"),
6864
+ apiKey: optionalString(object, "apiKey") ?? null,
6865
+ roles: object.roles === void 0 || object.roles === null ? [] : stringList(object.roles, "roles")
6866
+ };
6867
+ }
6868
+ function readGrant(value, index) {
6869
+ const object = asObject(value, `collectionGrants[${index}]`);
6870
+ return {
6871
+ name: requiredString(object, "name"),
6872
+ read: requiredBoolean(object, "read"),
6873
+ write: requiredBoolean(object, "write"),
6874
+ administrate: requiredBoolean(object, "administrate"),
6875
+ grantType: requiredString(object, "grantType")
6876
+ };
6877
+ }
6878
+ function readRole(body) {
6879
+ const object = asObject(body);
6880
+ return {
6881
+ name: requiredString(object, "name"),
6882
+ isAdmin: requiredBoolean(object, "isAdmin"),
6883
+ collectionGrants: optionalList(object, "collectionGrants", readGrant)
6884
+ };
6885
+ }
6886
+ function readUpdateRole(body) {
6887
+ const object = asObject(body);
6888
+ return {
6889
+ isAdmin: requiredBoolean(object, "isAdmin"),
6890
+ collectionGrants: optionalList(object, "collectionGrants", readGrant)
6891
+ };
6892
+ }
6893
+ function readRoleNames(body) {
6894
+ return stringList(body, "body");
5758
6895
  }
5759
6896
 
5760
- const FilterDefaultField = "";
5761
- function luceneToFilter(input, defaultField, options = {}) {
5762
- return luceneQueryToFilter(parseLuceneQuery(input, defaultField), options);
5763
- }
5764
- function filterParameter(input, options = {}, parameter = "filter") {
5765
- if (input === null || input === void 0 || input.trim() === "") {
5766
- return {};
5767
- }
5768
- let query;
5769
- try {
5770
- query = parseLuceneQuery(input, FilterDefaultField);
5771
- return luceneQueryToFilter(query, options);
5772
- } catch (error) {
5773
- const message = error instanceof LuceneQueryError || error instanceof Error ? error.message : "";
5774
- const reason = message.split("\n").map((line) => line.trim()).find((line) => line !== "") ?? "the filter syntax is not supported";
5775
- throw MongocampError.decodeFailure(`query parameter ${parameter}`, reason);
6897
+ async function readJson(event) {
6898
+ const text = await event.req.text();
6899
+ if (text.trim() === "") {
6900
+ throw MongocampError.decodeFailure("body");
5776
6901
  }
6902
+ return parseJsonBody(text);
5777
6903
  }
5778
- function bodyFilter(input, options = {}) {
5779
- if (input === null || input === void 0 || input.trim() === "") {
5780
- return {};
5781
- }
5782
- try {
5783
- return filterParameter(input, options);
5784
- } catch (error) {
5785
- throw new MongocampError("Invalid value for: filter", 400, 4001, error instanceof MongocampError ? error.additionalInfo : "");
5786
- }
6904
+ async function readDocumentBody(event) {
6905
+ return convertFields(decodeAnyObject(await readJson(event)));
5787
6906
  }
5788
6907
 
5789
6908
  function pathParam(event, name) {
@@ -5998,241 +7117,19 @@ function checkPipeline(user, collection, pipeline, deniedOperators) {
5998
7117
  if (!user.canRead(prefix + reference.name)) {
5999
7118
  throw MongocampError.forbidden(`the user is not allowed to read the collection ${reference.name} in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
6000
7119
  }
6001
- }
6002
- }
6003
- }
6004
- const firstStageOnly = /* @__PURE__ */ new Set(["$geoNear", "$search", "$searchMeta", "$vectorSearch", "$collStats", "$indexStats", "$documents"]);
6005
- function checkMatchBefore(pipeline) {
6006
- const first = pipeline[0];
6007
- if (first && firstStageOnly.has(normalizeStage(first.stage))) {
6008
- const stage = normalizeStage(first.stage);
6009
- throw MongocampError.badRequest(`the filter cannot be combined with a pipeline that starts with ${stage}, put the conditions in the stage itself`, ErrorCodes.filterNotSupported);
6010
- }
6011
- }
6012
- function toBsonPipeline(pipeline) {
6013
- return pipeline.map((stage) => ({ [normalizeStage(stage.stage)]: stage.value }));
6014
- }
6015
-
6016
- function cursorSort(sort) {
6017
- const keys = Object.entries(sort).map(([field, direction]) => [field, Number(direction) < 0 ? -1 : 1]);
6018
- return keys.some(([field]) => field === "_id") ? keys : [...keys, ["_id", 1]];
6019
- }
6020
- function valueAt(document, path) {
6021
- let current = document;
6022
- for (const segment of path.split(".")) {
6023
- if (current === null || typeof current !== "object") {
6024
- return null;
6025
- }
6026
- current = current[segment];
6027
- }
6028
- return current === void 0 ? null : current;
6029
- }
6030
- function encodeCursor(sort, document) {
6031
- const token = { s: sort, v: sort.map(([field]) => valueAt(document, field)) };
6032
- return Buffer.from(BSON.EJSON.stringify(token, { relaxed: false }), "utf8").toString("base64url");
6033
- }
6034
- function invalidCursor() {
6035
- return MongocampError.decodeFailure("query parameter after");
6036
- }
6037
- function decodeCursor(token, sort) {
6038
- let decoded;
6039
- try {
6040
- decoded = BSON.EJSON.parse(Buffer.from(token, "base64url").toString("utf8"), { relaxed: false });
6041
- } catch {
6042
- throw invalidCursor();
6043
- }
6044
- const { s, v } = decoded ?? {};
6045
- if (!Array.isArray(s) || !Array.isArray(v) || v.length !== sort.length || JSON.stringify(s) !== JSON.stringify(sort)) {
6046
- throw invalidCursor();
6047
- }
6048
- return v;
6049
- }
6050
- function afterValue(field, direction, value) {
6051
- if (value === null) {
6052
- return direction === 1 ? { [field]: { $ne: null } } : void 0;
6053
- }
6054
- return direction === 1 ? { [field]: { $gt: value } } : { $or: [{ [field]: { $lt: value } }, { [field]: null }] };
6055
- }
6056
- function afterFilter(sort, values) {
6057
- const branches = [];
6058
- for (let index = 0; index < sort.length; index++) {
6059
- const [field, direction] = sort[index];
6060
- const after = afterValue(field, direction, values[index]);
6061
- if (after) {
6062
- const equal = sort.slice(0, index).map(([previous], position) => ({ [previous]: values[position] }));
6063
- branches.push(equal.length === 0 ? after : { $and: [...equal, after] });
6064
- }
6065
- }
6066
- return branches.length === 0 ? { _id: { $exists: false } } : branches.length === 1 ? branches[0] : { $or: branches };
6067
- }
6068
- function isExclusion(projection) {
6069
- const values = Object.entries(projection).filter(([field]) => field !== "_id").map(([, value]) => value);
6070
- return values.length > 0 && values.every((value) => value === 0 || value === false);
6071
- }
6072
- function related(a, b) {
6073
- return a === b || a.startsWith(`${b}.`) || b.startsWith(`${a}.`);
6074
- }
6075
- function cursorProjection(projection, sort) {
6076
- if (Object.keys(projection).length === 0) {
6077
- return { projection, added: [] };
6078
- }
6079
- const result = { ...projection };
6080
- const added = [];
6081
- const exclusion = isExclusion(projection);
6082
- for (const [field] of sort) {
6083
- const value = projection[field];
6084
- if (field === "_id") {
6085
- if (value === 0 || value === false) {
6086
- delete result._id;
6087
- added.push("_id");
6088
- }
6089
- continue;
6090
- }
6091
- if (exclusion) {
6092
- for (const excluded of Object.keys(projection).filter((key) => related(key, field))) {
6093
- Reflect.deleteProperty(result, excluded);
6094
- added.push(excluded);
6095
- }
6096
- } else if (!Object.keys(projection).some((key) => key !== "_id" && (key === field || field.startsWith(`${key}.`)))) {
6097
- result[field] = 1;
6098
- added.push(field);
6099
- }
6100
- }
6101
- return { projection: result, added };
6102
- }
6103
- function stripAdded(document, added, projection) {
6104
- if (added.length === 0) {
6105
- return document;
6106
- }
6107
- const exclusion = isExclusion(projection);
6108
- const requested = Object.keys(projection).filter((key) => key !== "_id" && projection[key] !== 0 && projection[key] !== false);
6109
- for (const path of added) {
6110
- const segments = path.split(".");
6111
- const top = segments[0];
6112
- if (segments.length === 1 || !exclusion && !requested.some((key) => related(key, top))) {
6113
- Reflect.deleteProperty(document, top);
6114
- continue;
6115
- }
6116
- let parent = document;
6117
- for (const segment of segments.slice(0, -1)) {
6118
- parent = parent && typeof parent === "object" ? parent[segment] : void 0;
6119
- }
6120
- if (parent && typeof parent === "object") {
6121
- Reflect.deleteProperty(parent, segments.at(-1));
6122
- }
6123
- }
6124
- return document;
6125
- }
6126
-
6127
- const readOptions$1 = { promoteValues: false, bsonRegExp: true };
6128
- function plainNumbers(value) {
6129
- if (value instanceof Long || value instanceof Int32 || value instanceof Double) {
6130
- return Number(value.valueOf());
6131
- }
6132
- if (Array.isArray(value)) {
6133
- return value.map(plainNumbers);
6134
- }
6135
- if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
6136
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, plainNumbers(entry)]));
6137
- }
6138
- return value;
6139
- }
6140
- function sortFromList(fields) {
6141
- return Object.fromEntries(fields.map((field) => field.startsWith("-") ? [field.slice(1), -1] : [field, 1]));
6142
- }
6143
- function projectionFromList(fields) {
6144
- return Object.fromEntries(fields.map((field) => [field, 1]));
6145
- }
6146
- async function countMatching(collection, filter, count = "exact") {
6147
- if (count === "none") {
6148
- return void 0;
6149
- }
6150
- return Object.keys(filter).length === 0 ? collection.estimatedDocumentCount() : collection.countDocuments(filter);
6151
- }
6152
- async function readPage(collection, request, paging, count = "exact") {
6153
- const { rows, page, skip } = resolvePaging(paging);
6154
- const sort = plainNumbers(request.sort);
6155
- const projection = plainNumbers(request.projection);
6156
- const total = countMatching(collection, request.filter, count);
6157
- if (paging.after === void 0) {
6158
- let cursor2 = collection.find(request.filter, readOptions$1);
6159
- if (Object.keys(sort).length > 0) {
6160
- cursor2 = cursor2.sort(sort);
6161
- }
6162
- if (Object.keys(projection).length > 0) {
6163
- cursor2 = cursor2.project(projection);
6164
- }
6165
- const [allCount2, documents2] = await Promise.all([total, cursor2.skip(skip).limit(rows).toArray()]);
6166
- return { documents: documents2, info: paginationInfo(allCount2, rows, page) };
6167
- }
6168
- const sortKeys = cursorSort(sort);
6169
- const after = paging.after === "" ? void 0 : afterFilter(sortKeys, decodeCursor(paging.after, sortKeys));
6170
- const filter = after === void 0 ? request.filter : Object.keys(request.filter).length === 0 ? after : { $and: [request.filter, after] };
6171
- const read = cursorProjection(projection, sortKeys);
6172
- let cursor = collection.find(filter, readOptions$1).sort(sortKeys);
6173
- if (Object.keys(read.projection).length > 0) {
6174
- cursor = cursor.project(read.projection);
6175
- }
6176
- const [allCount, documents] = await Promise.all([total, cursor.limit(rows).toArray()]);
6177
- const next = documents.length === rows ? encodeCursor(sortKeys, documents.at(-1)) : void 0;
6178
- return { documents: documents.map((document) => stripAdded(document, read.added, projection)), info: paginationInfo(allCount, rows, void 0, next) };
6179
- }
6180
- async function paginatedFind(collection, request, paging, mode, count = "exact") {
6181
- const { documents, info } = await readPage(collection, request, paging, count);
6182
- return { items: documents.map((document) => documentToJson(document, mode)), info };
6183
- }
6184
- function numberOf$6(value) {
6185
- if (typeof value === "number") {
6186
- return value;
6187
- }
6188
- if (value && typeof value === "object" && "valueOf" in value) {
6189
- return Number(value.valueOf());
6190
- }
6191
- return 0;
6192
- }
6193
- async function paginatedAggregation(collection, pipeline, allowDiskUse, paging, count = "exact") {
6194
- const { rows, page, skip } = resolvePaging(paging);
6195
- if (count === "none") {
6196
- const documents = await collection.aggregate(pagedPipeline(pipeline, skip, rows), { allowDiskUse, ...readOptions$1 }).toArray();
6197
- return { documents, info: paginationInfo(void 0, rows, page) };
6198
- }
6199
- const facet = { $facet: { metadata: [{ $count: "total" }], data: [{ $skip: skip }, { $limit: rows }] } };
6200
- const [result] = await collection.aggregate([...pipeline, facet], { allowDiskUse, ...readOptions$1 }).toArray();
6201
- const metadata = Array.isArray(result?.metadata) ? result.metadata : [];
6202
- const total = metadata.length === 0 ? 0 : numberOf$6(metadata[0].total);
6203
- return { documents: Array.isArray(result?.data) ? result.data : [], info: paginationInfo(total, rows, page) };
6204
- }
6205
- function pagedPipeline(pipeline, skip, rows) {
6206
- return [...pipeline, ...skip > 0 ? [{ $skip: skip }] : [], { $limit: rows }];
6207
- }
6208
-
6209
- function combineScopes(filter, scopes) {
6210
- const parts = [filter, ...scopes].filter((part) => Object.keys(part).length > 0);
6211
- return parts.length === 0 ? {} : parts.length === 1 ? parts[0] : { $and: parts };
6212
- }
6213
- async function readScope(context, user, collection, filter, operation, options = {}) {
6214
- return (await readScopeParts(context, user, collection, filter, operation, options)).filter;
6215
- }
6216
- async function readScopeParts(context, user, collection, filter, operation, options = {}) {
6217
- if (!context.interceptors.has("document:beforeRead")) {
6218
- return { filter, scope: {} };
7120
+ }
6219
7121
  }
6220
- const databaseName = databaseOf(context.database, parseCollectionName(collection)).databaseName;
6221
- const payload = await context.interceptors.run("document:beforeRead", { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, filter, operation, scopes: [], withDeleted: options.withDeleted === true });
6222
- return { filter: combineScopes(filter, payload.scopes), scope: combineScopes({}, payload.scopes) };
6223
7122
  }
6224
- function withDeletedOf(params, user, collection) {
6225
- const value = params.get("withDeleted");
6226
- if (value === null || value === "" || value === "false") {
6227
- return {};
6228
- }
6229
- if (value !== "true") {
6230
- throw MongocampError.decodeFailure("query parameter withDeleted", "true or false");
6231
- }
6232
- if (!user.canAdministrate(collection)) {
6233
- throw MongocampError.forbidden("withDeleted needs the administrate grant of the collection");
7123
+ const firstStageOnly = /* @__PURE__ */ new Set(["$geoNear", "$search", "$searchMeta", "$vectorSearch", "$collStats", "$indexStats", "$documents"]);
7124
+ function checkMatchBefore(pipeline) {
7125
+ const first = pipeline[0];
7126
+ if (first && firstStageOnly.has(normalizeStage(first.stage))) {
7127
+ const stage = normalizeStage(first.stage);
7128
+ throw MongocampError.badRequest(`the filter cannot be combined with a pipeline that starts with ${stage}, put the conditions in the stage itself`, ErrorCodes.filterNotSupported);
6234
7129
  }
6235
- return { withDeleted: true };
7130
+ }
7131
+ function toBsonPipeline(pipeline) {
7132
+ return pipeline.map((stage) => ({ [normalizeStage(stage.stage)]: stage.value }));
6236
7133
  }
6237
7134
 
6238
7135
  function readAggregateRequest(body) {
@@ -6275,12 +7172,7 @@ function registerAggregationRoutes(app, context) {
6275
7172
  if (secrets.length > 0) {
6276
7173
  prefix.unshift({ $unset: [...secrets] });
6277
7174
  }
6278
- const scoped = await readScope(context, user, collection, {}, "aggregate", withDeletedOf(params, user, collection));
6279
- if (Object.keys(scoped).length > 0) {
6280
- prefix.unshift({ $match: scoped });
6281
- }
6282
- const pipeline = [...prefix, ...toBsonPipeline(request.pipeline)];
6283
- const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, request.allowDiskUse, paging, count);
7175
+ const { documents, info } = await context.documents.aggregate(user, collection, prefix, toBsonPipeline(request.pipeline), request.allowDiskUse, paging, count, withDeletedOf(params, user, collection));
6284
7176
  return jsonResponse(documents.map((document) => withoutSecrets(documentToJson(document, mode), secrets)), { headers: paginationHeaders(info) });
6285
7177
  });
6286
7178
  app.post("/mongodb/collections/:collectionName/distinct/:field", async (event) => {
@@ -6290,11 +7182,8 @@ function registerAggregationRoutes(app, context) {
6290
7182
  if (secretFieldsOf(database, collection).some((secret) => fieldName === secret || fieldName.startsWith(`${secret}.`))) {
6291
7183
  throw MongocampError.badRequest(`the field ${fieldName} of the users collection cannot be read`);
6292
7184
  }
6293
- const field = `$${fieldName}`;
6294
- const scoped = await readScope(context, user, collection, {}, "distinct", withDeletedOf(queryParams(event), user, collection));
6295
- const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], { $group: { _id: field, field: { $first: field } } }];
6296
7185
  const params = queryParams(event);
6297
- const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, true, readPaging(params), readCountMode(params));
7186
+ const { documents, info } = await context.documents.distinct(user, collection, fieldName, readPaging(params), readCountMode(params), withDeletedOf(params, user, collection));
6298
7187
  const mode = parseExtendedJsonMode(params.get("extendedJson"));
6299
7188
  return jsonResponse(documents.map((document) => mode === void 0 || mode === "plain" ? legacyValue(document.field) : documentToJson({ v: document.field }, mode).v), { headers: paginationHeaders(info) });
6300
7189
  });
@@ -10691,7 +11580,7 @@ paths:
10691
11580
  parameters:
10692
11581
  - name: withDeleted
10693
11582
  in: query
10694
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
11583
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
10695
11584
  required: false
10696
11585
  schema:
10697
11586
  default: false
@@ -10851,7 +11740,7 @@ paths:
10851
11740
  parameters:
10852
11741
  - name: withDeleted
10853
11742
  in: query
10854
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
11743
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
10855
11744
  required: false
10856
11745
  schema:
10857
11746
  default: false
@@ -11498,9 +12387,18 @@ paths:
11498
12387
  description: Get Documents paginated from given Collection
11499
12388
  operationId: listDocuments
11500
12389
  parameters:
12390
+ - name: expand
12391
+ in: query
12392
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
12393
+ required: false
12394
+ explode: true
12395
+ schema:
12396
+ type: array
12397
+ items:
12398
+ type: string
11501
12399
  - name: withDeleted
11502
12400
  in: query
11503
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
12401
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
11504
12402
  required: false
11505
12403
  schema:
11506
12404
  default: false
@@ -11751,9 +12649,18 @@ paths:
11751
12649
  Length
11752
12650
  operationId: find
11753
12651
  parameters:
12652
+ - name: expand
12653
+ in: query
12654
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
12655
+ required: false
12656
+ explode: true
12657
+ schema:
12658
+ type: array
12659
+ items:
12660
+ type: string
11754
12661
  - name: withDeleted
11755
12662
  in: query
11756
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
12663
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
11757
12664
  required: false
11758
12665
  schema:
11759
12666
  default: false
@@ -11919,7 +12826,7 @@ paths:
11919
12826
  parameters:
11920
12827
  - name: withDeleted
11921
12828
  in: query
11922
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
12829
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
11923
12830
  required: false
11924
12831
  schema:
11925
12832
  default: false
@@ -11993,7 +12900,7 @@ paths:
11993
12900
  parameters:
11994
12901
  - name: withDeleted
11995
12902
  in: query
11996
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
12903
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
11997
12904
  required: false
11998
12905
  schema:
11999
12906
  default: false
@@ -12070,9 +12977,18 @@ paths:
12070
12977
  headers are the same.'
12071
12978
  operationId: searchDocuments
12072
12979
  parameters:
12980
+ - name: expand
12981
+ in: query
12982
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
12983
+ required: false
12984
+ explode: true
12985
+ schema:
12986
+ type: array
12987
+ items:
12988
+ type: string
12073
12989
  - name: withDeleted
12074
12990
  in: query
12075
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
12991
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
12076
12992
  required: false
12077
12993
  schema:
12078
12994
  default: false
@@ -12250,9 +13166,18 @@ paths:
12250
13166
  for an end marker. POST takes the filter in the body (no URL limit).'
12251
13167
  operationId: exportDocuments
12252
13168
  parameters:
13169
+ - name: expand
13170
+ in: query
13171
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
13172
+ required: false
13173
+ explode: true
13174
+ schema:
13175
+ type: array
13176
+ items:
13177
+ type: string
12253
13178
  - name: withDeleted
12254
13179
  in: query
12255
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
13180
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
12256
13181
  required: false
12257
13182
  schema:
12258
13183
  default: false
@@ -12398,9 +13323,18 @@ paths:
12398
13323
  for an end marker. POST takes the filter in the body (no URL limit).'
12399
13324
  operationId: exportDocumentsByBody
12400
13325
  parameters:
13326
+ - name: expand
13327
+ in: query
13328
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
13329
+ required: false
13330
+ explode: true
13331
+ schema:
13332
+ type: array
13333
+ items:
13334
+ type: string
12401
13335
  - name: withDeleted
12402
13336
  in: query
12403
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
13337
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
12404
13338
  required: false
12405
13339
  schema:
12406
13340
  default: false
@@ -12844,9 +13778,18 @@ paths:
12844
13778
  description: Get one Document from given Collection
12845
13779
  operationId: getDocument
12846
13780
  parameters:
13781
+ - name: expand
13782
+ in: query
13783
+ description: 'References to expand (2.4.0): declared ref fields of the collection, repeated or comma separated, at most 5. Each becomes the referenced document, read with the grant and the read scope of its collection (null, or left out of an array, when the caller cannot read it). 400 for a field that is no reference.'
13784
+ required: false
13785
+ explode: true
13786
+ schema:
13787
+ type: array
13788
+ items:
13789
+ type: string
12847
13790
  - name: withDeleted
12848
13791
  in: query
12849
- description: 'Soft-deleted documents too (collections declared with softDelete, 2.4.0); needs the administrate grant of the collection, 403 otherwise.'
13792
+ description: 'Soft-deleted documents too (collections declared with softDelete, 2.3.0); needs the administrate grant of the collection, 403 otherwise.'
12850
13793
  required: false
12851
13794
  schema:
12852
13795
  default: false
@@ -13112,7 +14055,7 @@ paths:
13112
14055
  tags:
13113
14056
  - Document
13114
14057
  summary: Restore a soft-deleted Document
13115
- description: 'Removes the deleted mark of a document of a collection declared with softDelete (2.4.0). 404 for a collection without soft delete and for a document that is missing or not deleted.'
14058
+ description: 'Removes the deleted mark of a document of a collection declared with softDelete (2.3.0). 404 for a collection without soft delete and for a document that is missing or not deleted.'
13116
14059
  operationId: restoreDocument
13117
14060
  parameters:
13118
14061
  - name: collectionName
@@ -13175,9 +14118,18 @@ paths:
13175
14118
  tags:
13176
14119
  - Document
13177
14120
  summary: Live Updates of a Collection
13178
- description: 'The changes of the documents as Server-Sent Events (2.4.0), scoped like every read and by \`filter\`. Events: \`upsert\` (data \`{ id, document }\`, a document that is in the scope), \`remove\` (data \`{ id }\`, deleted or left the scope), \`reset\` (the client loads again). The \`id\` of an event is the resume token: send it as \`Last-Event-ID\` to resume. A comment every 25 seconds. Needs a replica set or a sharded cluster: 501 (code 5011) otherwise; at most \`WATCH_MAX_STREAMS\` streams per instance (503).'
14121
+ description: 'The changes of the documents as Server-Sent Events (2.3.0), scoped like every read and by \`filter\`. Events: \`upsert\` (data \`{ id, document }\`, a document that is in the scope), \`remove\` (data \`{ id }\`, deleted or left the scope), \`reset\` (the client loads again). The \`id\` of an event is the resume token: send it as \`Last-Event-ID\` to resume. A comment every 25 seconds. Needs a replica set or a sharded cluster: 501 (code 5011) otherwise; at most \`WATCH_MAX_STREAMS\` streams per instance (503).'
13179
14122
  operationId: watchDocuments
13180
14123
  parameters:
14124
+ - name: expand
14125
+ in: query
14126
+ description: 'References to expand in each upsert (2.4.0), like on the list of documents. A change of a referenced document sends no event.'
14127
+ required: false
14128
+ explode: true
14129
+ schema:
14130
+ type: array
14131
+ items:
14132
+ type: string
13181
14133
  - name: collectionName
13182
14134
  in: path
13183
14135
  description: The name of your MongoDb Collection
@@ -13213,7 +14165,7 @@ paths:
13213
14165
  tags:
13214
14166
  - Document
13215
14167
  summary: History of a Document
13216
- description: 'The audit records of a document of a collection declared with audit, newest first (2.4.0). For users who can read the document; administrators of the collection also get the history of deleted documents. 404 for a collection without audit.'
14168
+ description: 'The audit records of a document of a collection declared with audit, newest first (2.3.0). For users who can read the document; administrators of the collection also get the history of deleted documents. 404 for a collection without audit.'
13217
14169
  operationId: getDocumentHistory
13218
14170
  parameters:
13219
14171
  - name: collectionName
@@ -13300,7 +14252,7 @@ paths:
13300
14252
  tags:
13301
14253
  - Collection
13302
14254
  summary: History of a Collection
13303
- description: 'The audit records of a collection declared with audit, newest first (2.4.0); for the administrators of the collection. 404 for a collection without audit.'
14255
+ description: 'The audit records of a collection declared with audit, newest first (2.3.0); for the administrators of the collection. 404 for a collection without audit.'
13304
14256
  operationId: getCollectionHistory
13305
14257
  parameters:
13306
14258
  - name: collectionName
@@ -13400,7 +14352,7 @@ paths:
13400
14352
  tags:
13401
14353
  - Collection
13402
14354
  summary: Declaration of a Collection
13403
- description: 'What a client needs to know of a declared collection (2.4.0): fields it must not send, version and owner fields, behaviours. 404 for a collection that is not declared.'
14355
+ description: 'What a client needs to know of a declared collection (2.3.0): fields it must not send, version and owner fields, behaviours. 404 for a collection that is not declared.'
13404
14356
  operationId: getCollectionDeclaration
13405
14357
  parameters:
13406
14358
  - name: collectionName
@@ -15007,7 +15959,7 @@ components:
15007
15959
  items:
15008
15960
  $ref: '#/components/schemas/ValidationIssue'
15009
15961
  current:
15010
- description: 'The stored document of a version conflict (409, code 4092, 2.4.0), as Extended JSON: show it or merge with it, then send the change again with its version.'
15962
+ 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.'
15011
15963
  type: object
15012
15964
  additionalProperties: true
15013
15965
  ValidationIssue:
@@ -15504,6 +16456,11 @@ components:
15504
16456
  $ref: '#/components/schemas/Map_Any'
15505
16457
  projection:
15506
16458
  $ref: '#/components/schemas/Map_Any'
16459
+ expand:
16460
+ type: array
16461
+ description: 'References to expand (2.4.0), like the query parameter expand.'
16462
+ items:
16463
+ type: string
15507
16464
  MongoIndex:
15508
16465
  title: MongoIndex
15509
16466
  type: object
@@ -15726,6 +16683,8 @@ components:
15726
16683
  - validation
15727
16684
  - systemFields
15728
16685
  - protectedFields
16686
+ - indexes
16687
+ - refs
15729
16688
  properties:
15730
16689
  name:
15731
16690
  type: string
@@ -15746,6 +16705,40 @@ components:
15746
16705
  type: array
15747
16706
  items:
15748
16707
  type: string
16708
+ indexes:
16709
+ description: The indexes of the declaration and its behaviours (2.4.0), synced at the start.
16710
+ type: array
16711
+ items:
16712
+ type: object
16713
+ required:
16714
+ - name
16715
+ - key
16716
+ - unique
16717
+ properties:
16718
+ name:
16719
+ type: string
16720
+ key:
16721
+ type: object
16722
+ additionalProperties: true
16723
+ unique:
16724
+ type: boolean
16725
+ refs:
16726
+ description: The references of the declaration (2.4.0), the fields a read can expand (query parameter expand).
16727
+ type: array
16728
+ items:
16729
+ type: object
16730
+ required:
16731
+ - field
16732
+ - collection
16733
+ properties:
16734
+ field:
16735
+ type: string
16736
+ collection:
16737
+ description: The target collection (name or database:name).
16738
+ type: string
16739
+ many:
16740
+ description: Whether the field holds an array of ids (from the schema); missing when the schema does not tell.
16741
+ type: boolean
15749
16742
  timestamps:
15750
16743
  type: object
15751
16744
  properties:
@@ -15888,6 +16881,11 @@ components:
15888
16881
  limit:
15889
16882
  type: integer
15890
16883
  format: int32
16884
+ expand:
16885
+ type: array
16886
+ description: 'References to expand (2.4.0), like the query parameter expand.'
16887
+ items:
16888
+ type: string
15891
16889
  CountRequest:
15892
16890
  title: CountRequest
15893
16891
  type: object
@@ -15909,6 +16907,11 @@ components:
15909
16907
  type: array
15910
16908
  items:
15911
16909
  type: string
16910
+ expand:
16911
+ type: array
16912
+ description: 'References to expand (2.4.0), like the query parameter expand.'
16913
+ items:
16914
+ type: string
15912
16915
  SettingsResponse:
15913
16916
  title: SettingsResponse
15914
16917
  type: object
@@ -16115,6 +17118,8 @@ function declarationInfo(declared) {
16115
17118
  validation: declared.validation,
16116
17119
  systemFields: systemFields(behaviours).map((entry) => entry.path),
16117
17120
  protectedFields: [...behaviours.protectedFields],
17121
+ indexes: declared.indexes.map((index) => ({ name: index.name, key: { ...index.key }, unique: index.options.unique === true })),
17122
+ refs: declared.refs.map((ref) => ({ ...ref })),
16118
17123
  ...behaviours.timestamps !== void 0 ? { timestamps: { ...behaviours.timestamps } } : {},
16119
17124
  ...behaviours.owner !== void 0 ? { owner: { field: behaviours.owner.field, read: typeof behaviours.owner.read === "function" ? "custom" : behaviours.owner.read } } : {},
16120
17125
  ...behaviours.softDelete !== void 0 ? { softDelete: { ...behaviours.softDelete } } : {},
@@ -16170,271 +17175,116 @@ async function* renderExport(format, documents, columns) {
16170
17175
  yield "[";
16171
17176
  let first = true;
16172
17177
  for await (const document of documents) {
16173
- yield `${first ? "" : ","}${stringifyJson(document)}`;
16174
- first = false;
16175
- }
16176
- yield "]";
16177
- }
16178
- function exportCursor(collection, query) {
16179
- let cursor = collection.find(query.filter, { promoteValues: false, bsonRegExp: true });
16180
- if (Object.keys(query.sort).length > 0) {
16181
- cursor = cursor.sort(plainNumbers(query.sort));
16182
- }
16183
- if (Object.keys(query.projection).length > 0) {
16184
- cursor = cursor.project(plainNumbers(query.projection));
16185
- }
16186
- if (query.limit !== void 0) {
16187
- cursor = cursor.limit(query.limit);
16188
- }
16189
- return cursor;
16190
- }
16191
- async function* converted(cursor, mode, secrets = []) {
16192
- for await (const document of cursor) {
16193
- yield withoutSecrets(documentToJson(document, mode), secrets);
16194
- }
16195
- }
16196
- function endMarker(format, count) {
16197
- if (format === "ndjson") {
16198
- return `${stringifyJson({ $end: true, count })}
16199
- `;
16200
- }
16201
- return format === "csv" ? `# end ${count}\r
16202
- ` : "";
16203
- }
16204
- function errorMarker(format, error) {
16205
- const message = removeInternalNames(error instanceof Error ? error.message : String(error));
16206
- if (format === "ndjson") {
16207
- return `${stringifyJson({ $error: message })}
16208
- `;
16209
- }
16210
- return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
16211
- ` : "";
16212
- }
16213
- function exportStream(cursor, format, columns, options = {}) {
16214
- const encoder = new TextEncoder();
16215
- let count = 0;
16216
- async function* counted() {
16217
- for await (const document of converted(cursor, options.mode, options.secrets)) {
16218
- count++;
16219
- yield document;
16220
- }
16221
- }
16222
- const pieces = renderExport(format, counted(), columns);
16223
- return new ReadableStream({
16224
- async pull(controller) {
16225
- try {
16226
- const { value, done } = await pieces.next();
16227
- if (done) {
16228
- if (options.trailer) {
16229
- const marker = endMarker(format, count);
16230
- if (marker) {
16231
- controller.enqueue(encoder.encode(marker));
16232
- }
16233
- }
16234
- controller.close();
16235
- await cursor.close();
16236
- } else {
16237
- controller.enqueue(encoder.encode(value));
16238
- }
16239
- } catch (error) {
16240
- await cursor.close().catch(() => {
16241
- });
16242
- if (options.trailer) {
16243
- const marker = errorMarker(format, error);
16244
- if (marker) {
16245
- controller.enqueue(encoder.encode(marker));
16246
- }
16247
- controller.close();
16248
- } else {
16249
- controller.error(error);
16250
- }
16251
- }
16252
- },
16253
- async cancel() {
16254
- await pieces.return(void 0);
16255
- await cursor.close();
16256
- }
16257
- });
16258
- }
16259
- function exportFileName(collection, format) {
16260
- return `${collection.replace(/[^\w.-]/g, "_")}.${format}`;
16261
- }
16262
-
16263
- const BatchSize = 1e3;
16264
- const MaxReportedErrors = 1e3;
16265
- const MaxLineBytes = 17 * 1024 * 1024;
16266
- class ImportState {
16267
- read = 0;
16268
- inserted = 0;
16269
- failed = 0;
16270
- errors = [];
16271
- errorsTruncated = false;
16272
- /** The ids of the documents that were stored, as stored (for the compensation). */
16273
- storedIds = [];
16274
- /** The ids as text, for the events of the caller. */
16275
- get storedIdTexts() {
16276
- return this.storedIds.map(idToString);
16277
- }
16278
- addErrors(errors) {
16279
- const room = MaxReportedErrors - this.errors.length;
16280
- this.errors.push(...errors.slice(0, Math.max(room, 0)));
16281
- this.errorsTruncated ||= errors.length > room;
16282
- }
16283
- get response() {
16284
- return { read: this.read, inserted: this.inserted, failed: this.failed, errors: this.errors, errorsTruncated: this.errorsTruncated };
16285
- }
16286
- }
16287
- function lineError(number, message) {
16288
- return { index: number, code: ErrorCodes.invalidImportLine, message };
16289
- }
16290
- function parseLine(number, text) {
16291
- let json;
16292
- try {
16293
- json = parseJson(text);
16294
- } catch (error) {
16295
- const reason = (error instanceof Error ? error.message : String(error)).split("\n")[0].slice(0, 160);
16296
- return { error: lineError(number, `the line is not valid JSON: ${reason}`) };
16297
- }
16298
- if (!isPlainObject(json)) {
16299
- return { error: lineError(number, "the line has to be a JSON object") };
16300
- }
16301
- try {
16302
- const document = convertFields(decodeAny(json));
16303
- return { document: "_id" in document ? document : { _id: new ObjectId(), ...document } };
16304
- } catch (error) {
16305
- if (error instanceof MongocampError) {
16306
- return { error: lineError(number, error.message) };
16307
- }
16308
- throw error;
16309
- }
16310
- }
16311
- async function importBatch(collection, batch, state, beforeBatch) {
16312
- const parseErrors = batch.flatMap(([, entry]) => "error" in entry ? [entry.error] : []);
16313
- let valid = batch.flatMap(([number, entry]) => "document" in entry ? [[number, entry.document]] : []);
16314
- if (beforeBatch !== void 0 && valid.length > 0) {
16315
- const changed = await beforeBatch(valid.map(([, document]) => document), valid.map(([number]) => number));
16316
- valid = valid.map(([number], index) => [number, changed[index]]);
16317
- }
16318
- const databaseErrors = [];
16319
- if (valid.length > 0) {
16320
- try {
16321
- await collection.insertMany(valid.map(([, document]) => document), { ordered: false });
16322
- } catch (error) {
16323
- const writeErrors = error instanceof MongoBulkWriteError ? Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors] : [];
16324
- if (writeErrors.length === 0) {
16325
- throw error;
16326
- }
16327
- for (const writeError of writeErrors) {
16328
- const index = Number(writeError.index);
16329
- databaseErrors.push({ index: valid[index][0], code: Number(writeError.code), message: removeInternalNames(writeError.errmsg ?? "") });
16330
- }
16331
- }
16332
- }
16333
- const failedLines = new Set(databaseErrors.map((error) => error.index));
16334
- const stored = valid.filter(([number]) => !failedLines.has(number)).map(([, document]) => document._id);
16335
- const errors = [...parseErrors, ...databaseErrors].sort((a, b) => a.index - b.index);
16336
- state.read += batch.length;
16337
- state.inserted += stored.length;
16338
- state.failed += errors.length;
16339
- state.storedIds.push(...stored);
16340
- state.addErrors(errors);
16341
- }
16342
- async function compensate(collection, ids) {
16343
- let deleted = 0;
16344
- for (let start = 0; start < ids.length; start += BatchSize) {
16345
- deleted += (await collection.deleteMany({ _id: { $in: ids.slice(start, start + BatchSize) } })).deletedCount;
17178
+ yield `${first ? "" : ","}${stringifyJson(document)}`;
17179
+ first = false;
16346
17180
  }
16347
- return deleted;
17181
+ yield "]";
16348
17182
  }
16349
- function abortError(error, info) {
16350
- if (error instanceof MongocampError) {
16351
- return new MongocampError(error.message, error.status, error.code, [error.additionalInfo, info].filter((part) => part !== "").join("; "));
17183
+ function exportCursor(collection, query) {
17184
+ let cursor = collection.find(query.filter, { promoteValues: false, bsonRegExp: true });
17185
+ if (Object.keys(query.sort).length > 0) {
17186
+ cursor = cursor.sort(plainNumbers(query.sort));
16352
17187
  }
16353
- return error;
16354
- }
16355
- async function importStream(collection, body, maxBytes, beforeBatch) {
16356
- const state = new ImportState();
16357
- try {
16358
- await readLines(collection, body, maxBytes, state, beforeBatch);
16359
- return state;
16360
- } catch (error) {
16361
- if (state.storedIds.length === 0) {
16362
- throw error;
16363
- }
16364
- const stored = state.storedIds.length;
16365
- const deleted = await compensate(collection, state.storedIds).catch(() => -1);
16366
- throw abortError(error, deleted === stored ? `the import was rolled back, the ${stored} documents stored before were deleted` : `the import was aborted, deleting the ${stored} documents stored before failed (${Math.max(deleted, 0)} deleted)`);
17188
+ if (Object.keys(query.projection).length > 0) {
17189
+ cursor = cursor.project(plainNumbers(query.projection));
17190
+ }
17191
+ if (query.limit !== void 0) {
17192
+ cursor = cursor.limit(query.limit);
16367
17193
  }
17194
+ return cursor;
16368
17195
  }
16369
- async function readLines(collection, body, maxBytes, state, beforeBatch) {
16370
- if (!body) {
17196
+ const ExportExpandBatch = 100;
17197
+ async function* converted(cursor, mode, secrets = [], expand) {
17198
+ if (expand === void 0) {
17199
+ for await (const document of cursor) {
17200
+ yield withoutSecrets(documentToJson(document, mode), secrets);
17201
+ }
16371
17202
  return;
16372
17203
  }
16373
- const reader = body.getReader();
16374
- const decoder = new TextDecoder();
16375
- let pending = "";
16376
- let bytes = 0;
16377
- let lineNumber = 0;
16378
17204
  let batch = [];
16379
- const takeLine = async (rawLine) => {
16380
- lineNumber += 1;
16381
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
16382
- if (line.trim() === "") {
16383
- return;
16384
- }
16385
- batch.push([lineNumber, parseLine(lineNumber, line)]);
16386
- if (batch.length >= BatchSize) {
16387
- const full = batch;
16388
- batch = [];
16389
- await importBatch(collection, full, state, beforeBatch);
17205
+ const flush = async function* () {
17206
+ for (const document of await expand(batch)) {
17207
+ yield withoutSecrets(documentToJson(document, mode), secrets);
16390
17208
  }
17209
+ batch = [];
16391
17210
  };
16392
- let finished = false;
16393
- try {
16394
- for (; ; ) {
16395
- const { value, done } = await reader.read();
16396
- if (done) {
16397
- finished = true;
16398
- break;
16399
- }
16400
- bytes += value.byteLength;
16401
- if (bytes > maxBytes) {
16402
- throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
16403
- }
16404
- pending += decoder.decode(value, { stream: true });
16405
- let newline = pending.indexOf("\n");
16406
- while (newline >= 0) {
16407
- const line = pending.slice(0, newline);
16408
- pending = pending.slice(newline + 1);
16409
- await takeLine(line);
16410
- newline = pending.indexOf("\n");
16411
- }
16412
- if (Buffer.byteLength(pending) > MaxLineBytes) {
16413
- throw MongocampError.badRequest(`a line is longer than ${MaxLineBytes} bytes`);
16414
- }
16415
- }
16416
- pending += decoder.decode();
16417
- if (pending !== "") {
16418
- await takeLine(pending);
16419
- }
16420
- if (batch.length > 0) {
16421
- await importBatch(collection, batch, state, beforeBatch);
16422
- }
16423
- } finally {
16424
- if (!finished) {
16425
- await reader.cancel().catch(() => {
16426
- });
17211
+ for await (const document of cursor) {
17212
+ batch.push(document);
17213
+ if (batch.length >= ExportExpandBatch) {
17214
+ yield* flush();
16427
17215
  }
16428
- reader.releaseLock();
17216
+ }
17217
+ if (batch.length > 0) {
17218
+ yield* flush();
16429
17219
  }
16430
17220
  }
16431
-
16432
- const MaxOldValues = 1e4;
16433
- function requireMatched(count) {
16434
- if (count === 0) {
16435
- throw MongocampError.notFound("could not find document");
17221
+ function endMarker(format, count) {
17222
+ if (format === "ndjson") {
17223
+ return `${stringifyJson({ $end: true, count })}
17224
+ `;
17225
+ }
17226
+ return format === "csv" ? `# end ${count}\r
17227
+ ` : "";
17228
+ }
17229
+ function errorMarker(format, error) {
17230
+ const message = removeInternalNames(error instanceof Error ? error.message : String(error));
17231
+ if (format === "ndjson") {
17232
+ return `${stringifyJson({ $error: message })}
17233
+ `;
17234
+ }
17235
+ return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
17236
+ ` : "";
17237
+ }
17238
+ function exportStream(cursor, format, columns, options = {}) {
17239
+ const encoder = new TextEncoder();
17240
+ let count = 0;
17241
+ async function* counted() {
17242
+ for await (const document of converted(cursor, options.mode, options.secrets, options.expand)) {
17243
+ count++;
17244
+ yield document;
17245
+ }
16436
17246
  }
17247
+ const pieces = renderExport(format, counted(), columns);
17248
+ return new ReadableStream({
17249
+ async pull(controller) {
17250
+ try {
17251
+ const { value, done } = await pieces.next();
17252
+ if (done) {
17253
+ if (options.trailer) {
17254
+ const marker = endMarker(format, count);
17255
+ if (marker) {
17256
+ controller.enqueue(encoder.encode(marker));
17257
+ }
17258
+ }
17259
+ controller.close();
17260
+ await cursor.close();
17261
+ } else {
17262
+ controller.enqueue(encoder.encode(value));
17263
+ }
17264
+ } catch (error) {
17265
+ await cursor.close().catch(() => {
17266
+ });
17267
+ if (options.trailer) {
17268
+ const marker = errorMarker(format, error);
17269
+ if (marker) {
17270
+ controller.enqueue(encoder.encode(marker));
17271
+ }
17272
+ controller.close();
17273
+ } else {
17274
+ controller.error(error);
17275
+ }
17276
+ }
17277
+ },
17278
+ async cancel() {
17279
+ await pieces.return(void 0);
17280
+ await cursor.close();
17281
+ }
17282
+ });
17283
+ }
17284
+ function exportFileName(collection, format) {
17285
+ return `${collection.replace(/[^\w.-]/g, "_")}.${format}`;
16437
17286
  }
17287
+
16438
17288
  function pageResponse(page, secrets = []) {
16439
17289
  return jsonResponse(page.items.map((item) => withoutSecrets(item, secrets)), { headers: paginationHeaders(page.info) });
16440
17290
  }
@@ -16454,6 +17304,10 @@ function mapField(body, field, required = false) {
16454
17304
  }
16455
17305
  return decodeAny(value);
16456
17306
  }
17307
+ function expandOf(params, body) {
17308
+ const fromQuery = params.getAll("expand").flatMap((value) => value.split(","));
17309
+ return [...fromQuery, ...body !== void 0 ? stringListField(body, "expand") : []].map((value) => value.trim()).filter((value) => value !== "");
17310
+ }
16457
17311
  function stringListField(body, field) {
16458
17312
  const value = body[field];
16459
17313
  if (value === void 0 || value === null) {
@@ -16464,15 +17318,6 @@ function stringListField(body, field) {
16464
17318
  }
16465
17319
  return value;
16466
17320
  }
16467
- function updateResponse(result, pathId) {
16468
- let ids = [];
16469
- if (pathId !== void 0 && result.modifiedCount === 1 && (result.upsertedId === null || result.upsertedId === void 0)) {
16470
- ids = [idToString(convertIdValue(pathId))];
16471
- } else if (result.upsertedId !== null && result.upsertedId !== void 0) {
16472
- ids = [idToString(result.upsertedId)];
16473
- }
16474
- return { wasAcknowledged: result.acknowledged, upsertedIds: ids, modifiedCount: result.modifiedCount, matchedCount: result.matchedCount };
16475
- }
16476
17321
  function manyFilter(params, bodyFilterMap, options) {
16477
17322
  const lucene = params.get("filter");
16478
17323
  if (lucene !== null && Object.keys(bodyFilterMap).length > 0) {
@@ -16487,64 +17332,9 @@ function manyFilter(params, bodyFilterMap, options) {
16487
17332
  }
16488
17333
  return filter;
16489
17334
  }
16490
- function sameId(before, after) {
16491
- if (before === after) {
16492
- return true;
16493
- }
16494
- if (before === void 0 || after === void 0) {
16495
- return false;
16496
- }
16497
- return BSON.EJSON.stringify({ id: before }, { relaxed: false }) === BSON.EJSON.stringify({ id: after }, { relaxed: false });
16498
- }
16499
- function writeErrorsOf(error) {
16500
- const errors = error.writeErrors;
16501
- return Array.isArray(errors) ? errors : errors ? [errors] : [];
16502
- }
16503
17335
  function registerDocumentRoutes(app, context) {
16504
- const { auth, database, events, config, interceptors } = context;
16505
- const scope = (user, collection, filter, operation, options = {}) => readScope(context, user, collection, filter, operation, options);
16506
- const interceptInsert = async (user, collection, documents, source, lines) => {
16507
- const count = documents.length;
16508
- const payload = await intercept("document:beforeInsert", user, collection, lines !== void 0 ? { documents, source, lines } : { documents, source });
16509
- if (payload.documents.length !== count) {
16510
- throw new Error(`a document:beforeInsert interceptor changed the number of documents from ${count} to ${payload.documents.length}`);
16511
- }
16512
- return payload;
16513
- };
16514
- const intercept = (name, user, collection, fields) => {
16515
- if (!interceptors.has(name)) {
16516
- return Promise.resolve({ user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName: "", ...fields });
16517
- }
16518
- const databaseName = databaseOf(database, parseCollectionName(collection)).databaseName;
16519
- return interceptors.run(name, { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, ...fields });
16520
- };
16521
- const oldValues = async (name, collection, filter) => {
16522
- if (!events.has(name, collection)) {
16523
- return [];
16524
- }
16525
- return collectionOf(database, collection).find(filter).limit(MaxOldValues).toArray();
16526
- };
16527
- const inserted = (user, collection, response, documents) => {
16528
- events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
16529
- return jsonResponse(response);
16530
- };
16531
- const updated = (user, collection, response, old, source) => {
16532
- events.publish("document:update", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old, source });
16533
- return jsonResponse(response);
16534
- };
16535
- const deleted = (user, collection, response, old, softDeleted = false) => {
16536
- events.publish("document:delete", { user: user.user, collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
16537
- return jsonResponse(response);
16538
- };
16539
- const deleteOrInstead = async (collection, filter, many, instead) => {
16540
- const target = collectionOf(database, collection);
16541
- if (instead !== void 0) {
16542
- const result2 = many ? await target.updateMany(filter, instead.update) : await target.updateOne(filter, instead.update);
16543
- return { acknowledged: result2.acknowledged, count: result2.matchedCount };
16544
- }
16545
- const result = many ? await target.deleteMany(filter) : await target.deleteOne(filter);
16546
- return { acknowledged: result.acknowledged, count: result.deletedCount };
16547
- };
17336
+ const { auth, database, config, documents: service } = context;
17337
+ const pageOf = (collection, result, mode) => pageResponse({ items: result.documents.map((document) => documentToJson(document, mode)), info: result.info }, secretFieldsOf(database, collection));
16548
17338
  const base = "/mongodb/collections/:collectionName/documents";
16549
17339
  const collectionParam = (event) => pathParam(event, "collectionName");
16550
17340
  app.get(base, async (event) => {
@@ -16552,26 +17342,27 @@ function registerDocumentRoutes(app, context) {
16552
17342
  const user = await auth.requireCollection(event.req, collection, "read");
16553
17343
  const params = queryParams(event);
16554
17344
  const request = {
16555
- filter: await scope(user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "list", withDeletedOf(params, user, collection)),
17345
+ filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config))),
16556
17346
  sort: sortFromList(params.getAll("sort")),
16557
17347
  projection: projectionFromList(params.getAll("projection"))
16558
17348
  };
16559
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), extendedJsonMode(params), readCountMode(params)), secretFieldsOf(database, collection));
17349
+ const result = await service.page(user, collection, request, readPaging(params), readCountMode(params), { operation: "list", expand: expandOf(params), ...withDeletedOf(params, user, collection) });
17350
+ return pageOf(collection, result, extendedJsonMode(params));
16560
17351
  });
16561
17352
  app.get(`${base}/count`, async (event) => {
16562
17353
  const collection = collectionParam(event);
16563
17354
  const user = await auth.requireCollection(event.req, collection, "read");
16564
17355
  const params = queryParams(event);
16565
- const filter = await scope(user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "count", withDeletedOf(params, user, collection));
16566
- return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
17356
+ const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config)));
17357
+ return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
16567
17358
  });
16568
17359
  app.post(`${base}/count`, async (event) => {
16569
17360
  const collection = collectionParam(event);
16570
17361
  const user = await auth.requireCollection(event.req, collection, "read");
16571
17362
  const params = queryParams(event);
16572
17363
  const body = asObject(await readJson(event));
16573
- const filter = await scope(user, collection, convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config))), "count", withDeletedOf(params, user, collection));
16574
- return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
17364
+ const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config)));
17365
+ return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
16575
17366
  });
16576
17367
  app.post(`${base}/search`, async (event) => {
16577
17368
  const collection = collectionParam(event);
@@ -16580,11 +17371,11 @@ function registerDocumentRoutes(app, context) {
16580
17371
  const mode = extendedJsonMode(params);
16581
17372
  const body = asObject(await readJson(event));
16582
17373
  const request = {
16583
- filter: await scope(user, collection, convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config))), "search", withDeletedOf(params, user, collection)),
17374
+ filter: convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config))),
16584
17375
  sort: sortFromList(stringListField(body, "sort")),
16585
17376
  projection: projectionFromList(stringListField(body, "projection"))
16586
17377
  };
16587
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
17378
+ return pageOf(collection, await service.page(user, collection, request, readPaging(params), readCountMode(params), { operation: "search", expand: expandOf(params, body), ...withDeletedOf(params, user, collection) }), mode);
16588
17379
  });
16589
17380
  app.post(base, async (event) => {
16590
17381
  const collection = collectionParam(event);
@@ -16593,29 +17384,27 @@ function registerDocumentRoutes(app, context) {
16593
17384
  const mode = extendedJsonMode(params);
16594
17385
  const body = asObject(await readJson(event));
16595
17386
  const request = {
16596
- filter: await scope(user, collection, convertFields(mapField(body, "filter", true)), "search", withDeletedOf(params, user, collection)),
17387
+ filter: convertFields(mapField(body, "filter", true)),
16597
17388
  sort: mapField(body, "sort", true),
16598
17389
  projection: mapField(body, "projection", true)
16599
17390
  };
16600
17391
  if (referencesSecret(request.projection, secretFieldsOf(database, collection))) {
16601
17392
  throw MongocampError.badRequest("the projection must not read the password of the users collection");
16602
17393
  }
16603
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
17394
+ const options = withDeletedOf(params, user, collection);
17395
+ return pageOf(collection, await service.page(user, collection, request, readPaging(params), readCountMode(params), { operation: "search", expand: expandOf(params, body), ...options }), mode);
16604
17396
  });
16605
17397
  app.put(base, async (event) => {
16606
17398
  const collection = collectionParam(event);
16607
17399
  const user = await auth.requireCollection(event.req, collection, "write");
16608
- const { documents } = await interceptInsert(user, collection, [await readDocumentBody(event)], "insert");
16609
- const result = await collectionOf(database, collection).insertOne(documents[0]);
16610
- return inserted(user, collection, { wasAcknowledged: result.acknowledged, insertedIds: [idToString(result.insertedId)] }, documents);
17400
+ return jsonResponse(await service.insert(user, collection, await readDocumentBody(event)));
16611
17401
  });
16612
17402
  app.get(`${base}/:documentId`, async (event) => {
16613
17403
  const collection = collectionParam(event);
16614
17404
  const user = await auth.requireCollection(event.req, collection, "read");
16615
17405
  const params = queryParams(event);
16616
17406
  const mode = extendedJsonMode(params);
16617
- const filter = await scope(user, collection, pathIdFilter(pathParam(event, "documentId")), "get", withDeletedOf(params, user, collection));
16618
- const document = await collectionOf(database, collection).findOne(filter, readOptions$1);
17407
+ const document = await service.get(user, collection, pathParam(event, "documentId"), { expand: expandOf(params), ...withDeletedOf(params, user, collection) });
16619
17408
  if (!document) {
16620
17409
  throw MongocampError.notFound("could not find document");
16621
17410
  }
@@ -16624,50 +17413,31 @@ function registerDocumentRoutes(app, context) {
16624
17413
  app.delete(`${base}/:documentId`, async (event) => {
16625
17414
  const collection = collectionParam(event);
16626
17415
  const user = await auth.requireCollection(event.req, collection, "write");
16627
- const { filter, instead } = await intercept("document:beforeDelete", user, collection, { filter: await scope(user, collection, pathIdFilter(pathParam(event, "documentId")), "write"), many: false });
16628
- const old = await oldValues("document:delete", collection, filter);
16629
- const result = await deleteOrInstead(collection, filter, false, instead);
16630
- requireMatched(result.count);
16631
- return deleted(user, collection, { wasAcknowledged: result.acknowledged, deletedCount: result.count }, old.slice(0, result.count), instead !== void 0);
17416
+ return jsonResponse(await service.remove(user, collection, pathParam(event, "documentId")));
16632
17417
  });
16633
17418
  app.patch(`${base}/:documentId`, async (event) => {
16634
17419
  const collection = collectionParam(event);
16635
17420
  const user = await auth.requireCollection(event.req, collection, "write");
16636
17421
  const id = pathParam(event, "documentId");
16637
- const body = await readDocumentBody(event);
16638
- const bodyId = body._id;
16639
- const { filter, document, onNoMatch } = await intercept("document:beforeReplace", user, collection, { filter: await scope(user, collection, pathIdFilter(id), "write"), document: body });
16640
- if (!sameId(bodyId, document._id)) {
16641
- throw MongocampError.badRequest("an interceptor must not change the _id of a replaced document");
16642
- }
16643
- const old = await oldValues("document:update", collection, filter);
16644
- const result = await collectionOf(database, collection).replaceOne(filter, document);
16645
- if (result.matchedCount === 0) {
16646
- await onNoMatch?.();
16647
- }
16648
- requireMatched(result.matchedCount);
16649
- return updated(user, collection, updateResponse(result, id), old.slice(0, 1), "replace");
17422
+ return jsonResponse(await service.replace(user, collection, id, await readDocumentBody(event)));
16650
17423
  });
16651
17424
  app.patch(`${base}/:documentId/partial`, async (event) => {
16652
17425
  const collection = collectionParam(event);
16653
17426
  const user = await auth.requireCollection(event.req, collection, "write");
16654
17427
  const id = pathParam(event, "documentId");
16655
- const { filter, update, onNoMatch } = await intercept("document:beforeUpdate", user, collection, { filter: await scope(user, collection, pathIdFilter(id), "write"), update: convertToOperationMap(await readDocumentBody(event)), many: false });
16656
- const old = await oldValues("document:update", collection, filter);
16657
- const result = await collectionOf(database, collection).updateOne(filter, update);
16658
- if (result.matchedCount === 0) {
16659
- await onNoMatch?.();
16660
- }
16661
- requireMatched(result.matchedCount);
16662
- return updated(user, collection, updateResponse(result, id), old.slice(0, 1), "update");
17428
+ return jsonResponse(await service.update(user, collection, id, convertToOperationMap(await readDocumentBody(event))));
16663
17429
  });
16664
17430
  const exportResponse = async (user, collection, params, request) => {
16665
17431
  const format = parseExportFormat(params.get("format"));
17432
+ if (format === "csv" && request.expand.length > 0) {
17433
+ throw MongocampError.badRequest("expand is not possible for a csv export, use ndjson or json");
17434
+ }
17435
+ const refs = service.refs(collection, request.expand);
16666
17436
  const mode = parseExtendedJsonMode(params.get("extendedJson")) ?? (format === "csv" ? "plain" : DefaultExtendedJsonMode);
16667
17437
  if (request.limit !== void 0 && request.limit <= 0) {
16668
17438
  throw MongocampError.badRequest("limit has to be greater than 0");
16669
17439
  }
16670
- const scoped = await readScopeParts(context, user, collection, convertFields(request.filter), "export", withDeletedOf(params, user, collection));
17440
+ const scoped = await service.exportFilter(user, collection, convertFields(request.filter), withDeletedOf(params, user, collection));
16671
17441
  const query = {
16672
17442
  filter: scoped.filter,
16673
17443
  sort: sortFromList(request.sort),
@@ -16685,7 +17455,8 @@ function registerDocumentRoutes(app, context) {
16685
17455
  columns = columns.filter((column) => !secrets.includes(column));
16686
17456
  }
16687
17457
  const trailer = booleanQuery(params, "trailer", false);
16688
- return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer }), {
17458
+ const expand = refs.length > 0 ? (documents) => service.expand(user, documents, refs) : void 0;
17459
+ return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand }), {
16689
17460
  headers: {
16690
17461
  "content-type": "text/plain; charset=UTF-8",
16691
17462
  "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
@@ -16697,7 +17468,7 @@ function registerDocumentRoutes(app, context) {
16697
17468
  const user = await auth.requireCollection(event.req, collection, "read");
16698
17469
  const params = queryParams(event);
16699
17470
  const filter = filterParameter(params.get("filter"), filterOptions(params, config));
16700
- return exportResponse(user, collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit") });
17471
+ return exportResponse(user, collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit"), expand: expandOf(params) });
16701
17472
  });
16702
17473
  app.post(`${base}/export`, async (event) => {
16703
17474
  const collection = collectionParam(event);
@@ -16708,7 +17479,8 @@ function registerDocumentRoutes(app, context) {
16708
17479
  filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
16709
17480
  sort: stringListField(body, "sort"),
16710
17481
  projection: stringListField(body, "projection"),
16711
- limit: optionalInteger$1(body, "limit")
17482
+ limit: optionalInteger$1(body, "limit"),
17483
+ expand: expandOf(params, body)
16712
17484
  });
16713
17485
  });
16714
17486
  app.post(`${base}/import`, async (event) => {
@@ -16719,12 +17491,7 @@ function registerDocumentRoutes(app, context) {
16719
17491
  if (Number.isFinite(length) && length > maxBytes) {
16720
17492
  throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
16721
17493
  }
16722
- const beforeBatch = interceptors.has("document:beforeInsert") ? async (documents, lines) => (await interceptInsert(user, collection, documents, "import", lines)).documents : void 0;
16723
- const state = await importStream(collectionOf(database, collection), event.req.body, maxBytes, beforeBatch);
16724
- if (state.storedIds.length > 0) {
16725
- const insertedIds = state.storedIdTexts;
16726
- events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
16727
- }
17494
+ const state = await service.import(user, collection, event.req.body, maxBytes);
16728
17495
  return jsonResponse(state.response);
16729
17496
  });
16730
17497
  app.put(`${base}/many/insert`, async (event) => {
@@ -16738,27 +17505,7 @@ function registerDocumentRoutes(app, context) {
16738
17505
  if (body.length === 0) {
16739
17506
  throw MongocampError.badRequest("the list of documents to insert is empty", ErrorCodes.emptyBatch);
16740
17507
  }
16741
- const { documents } = await interceptInsert(user, collection, body.map((entry) => convertFields(decodeAnyObject(entry))), "insertMany");
16742
- const target = collectionOf(database, collection);
16743
- if (ordered) {
16744
- const result = await target.insertMany(documents);
16745
- const ids = Object.keys(result.insertedIds).map(Number).sort((a, b) => a - b).map((index) => idToString(result.insertedIds[index]));
16746
- return inserted(user, collection, { wasAcknowledged: result.acknowledged, insertedIds: ids, insertedCount: ids.length, errors: [] }, documents);
16747
- }
16748
- const withIds = documents.map((document) => "_id" in document ? document : { ...document, _id: new ObjectId() });
16749
- try {
16750
- await target.insertMany(withIds, { ordered: false });
16751
- const ids = withIds.map((document) => idToString(document._id));
16752
- return inserted(user, collection, { wasAcknowledged: true, insertedIds: ids, insertedCount: ids.length, errors: [] }, withIds);
16753
- } catch (error) {
16754
- if (!(error instanceof MongoBulkWriteError) || writeErrorsOf(error).length === 0) {
16755
- throw error;
16756
- }
16757
- const errors = writeErrorsOf(error).map((writeError) => ({ index: Number(writeError.index), code: Number(writeError.code), message: removeInternalNames(writeError.errmsg ?? writeError.message ?? "") })).sort((a, b) => a.index - b.index);
16758
- const failed = new Set(errors.map((entry) => entry.index));
16759
- const ids = withIds.filter((_, index) => !failed.has(index)).map((document) => idToString(document._id));
16760
- return inserted(user, collection, { wasAcknowledged: true, insertedIds: ids, insertedCount: ids.length, errors }, withIds.filter((_, index) => !failed.has(index)));
16761
- }
17508
+ return jsonResponse(await service.insertMany(user, collection, body.map((entry) => convertFields(decodeAnyObject(entry))), ordered));
16762
17509
  });
16763
17510
  app.patch(`${base}/many/update`, async (event) => {
16764
17511
  const collection = collectionParam(event);
@@ -16766,14 +17513,8 @@ function registerDocumentRoutes(app, context) {
16766
17513
  const body = asObject(await readJson(event));
16767
17514
  const document = mapField(body, "document", true);
16768
17515
  const params = queryParams(event);
16769
- const { filter, update } = await intercept("document:beforeUpdate", user, collection, {
16770
- filter: await scope(user, collection, manyFilter(params, mapField(body, "filter"), filterOptions(params, config)), "write"),
16771
- update: convertToOperationMap(convertFields(document)),
16772
- many: true
16773
- });
16774
- const old = await oldValues("document:update", collection, filter);
16775
- const result = await collectionOf(database, collection).updateMany(filter, update);
16776
- return updated(user, collection, updateResponse(result), old, "updateMany");
17516
+ const filter = manyFilter(params, mapField(body, "filter"), filterOptions(params, config));
17517
+ return jsonResponse(await service.updateMany(user, collection, filter, convertToOperationMap(convertFields(document))));
16777
17518
  });
16778
17519
  app.delete(`${base}/many/delete`, async (event) => {
16779
17520
  const collection = collectionParam(event);
@@ -16781,28 +17522,12 @@ function registerDocumentRoutes(app, context) {
16781
17522
  const text = await event.req.text();
16782
17523
  const bodyMap = text.trim() === "" ? {} : decodeAnyObject(parseJsonBody(text));
16783
17524
  const params = queryParams(event);
16784
- const { filter, instead } = await intercept("document:beforeDelete", user, collection, { filter: await scope(user, collection, manyFilter(params, bodyMap, filterOptions(params, config)), "write"), many: true });
16785
- const old = await oldValues("document:delete", collection, filter);
16786
- const result = await deleteOrInstead(collection, filter, true, instead);
16787
- return deleted(user, collection, { wasAcknowledged: result.acknowledged, deletedCount: result.count }, old, instead !== void 0);
17525
+ return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config))));
16788
17526
  });
16789
17527
  app.post(`${base}/:documentId/restore`, async (event) => {
16790
17528
  const collection = collectionParam(event);
16791
17529
  const user = await auth.requireCollection(event.req, collection, "write");
16792
- const declared = context.collections.resolve(context, collection);
16793
- if (declared?.behaviours.softDelete === void 0) {
16794
- throw MongocampError.notFound(`the collection ${collection} has no soft delete (declare it with softDelete: true)`);
16795
- }
16796
- const id = pathParam(event, "documentId");
16797
- const filter = await scope(user, collection, pathIdFilter(id), "restore");
16798
- const old = events.has("document:restore", collection) ? await collectionOf(database, collection).find(filter).limit(1).toArray() : [];
16799
- const result = await collectionOf(database, collection).updateOne(filter, restoreUpdate(declared.behaviours, { now: /* @__PURE__ */ new Date(), userId: user.user.userId }));
16800
- if (result.matchedCount === 0) {
16801
- throw MongocampError.notFound("could not find a deleted document with this id");
16802
- }
16803
- const response = updateResponse(result, id);
16804
- events.publish("document:restore", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old });
16805
- return jsonResponse(response);
17530
+ return jsonResponse(await service.restore(user, collection, pathParam(event, "documentId")));
16806
17531
  });
16807
17532
  app.get("/mongodb/collections/:collectionName/declaration", async (event) => {
16808
17533
  const collection = collectionParam(event);
@@ -16821,8 +17546,8 @@ function registerDocumentRoutes(app, context) {
16821
17546
  return declared;
16822
17547
  };
16823
17548
  const auditPage = async (params, filter) => {
16824
- const page = await paginatedFind(auditCollectionOf(context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, readPaging(params), extendedJsonMode(params), readCountMode(params));
16825
- return pageResponse(page);
17549
+ const result = await service.auditRecords(filter, readPaging(params), readCountMode(params));
17550
+ return pageResponse({ items: result.documents.map((document) => documentToJson(document, extendedJsonMode(params))), info: result.info });
16826
17551
  };
16827
17552
  app.get(`${base}/:documentId/history`, async (event) => {
16828
17553
  const collection = collectionParam(event);
@@ -16830,7 +17555,7 @@ function registerDocumentRoutes(app, context) {
16830
17555
  const declared = auditedOf(collection);
16831
17556
  const params = queryParams(event);
16832
17557
  const idFilter = pathIdFilter(pathParam(event, "documentId"));
16833
- const readable = await collectionOf(database, collection).findOne(await scope(user, collection, idFilter, "get"), { projection: { _id: 1 } });
17558
+ const readable = await service.get(user, collection, pathParam(event, "documentId"));
16834
17559
  if (readable === null && !user.canAdministrate(collection)) {
16835
17560
  throw MongocampError.notFound("could not find document");
16836
17561
  }
@@ -17682,6 +18407,7 @@ function registerWatchRoutes(app, context) {
17682
18407
  throw new MongocampError("too many live updates are open in this instance (WATCH_MAX_STREAMS)", 503);
17683
18408
  }
17684
18409
  const params = queryParams(event);
18410
+ const refs = context.documents.refs(collection, params.getAll("expand").flatMap((value) => value.split(",")));
17685
18411
  const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "watch");
17686
18412
  const target = collectionOf(database, collection);
17687
18413
  const secrets = secretFieldsOf(database, collection);
@@ -17716,7 +18442,11 @@ function registerWatchRoutes(app, context) {
17716
18442
  return { event: "remove", data: { id } };
17717
18443
  }
17718
18444
  const inScope = Object.keys(scope).length === 0 || await target.countDocuments({ $and: [{ _id: change.documentKey._id }, scope] }, { limit: 1 }) > 0;
17719
- return inScope ? { event: "upsert", data: { id, document: withoutSecrets(documentToJson(document), secrets) } } : { event: "remove", data: { id } };
18445
+ if (!inScope) {
18446
+ return { event: "remove", data: { id } };
18447
+ }
18448
+ const expanded = refs.length > 0 ? (await context.documents.expand(user, [document], refs))[0] : document;
18449
+ return { event: "upsert", data: { id, document: withoutSecrets(documentToJson(expanded), secrets) } };
17720
18450
  };
17721
18451
  const start = (resumeAfter) => {
17722
18452
  changes = target.watch([{ $match: { operationType: { $in: ["insert", "update", "replace", "delete"] } } }], {
@@ -18048,10 +18778,13 @@ async function createMongocampServer(options = {}) {
18048
18778
  events,
18049
18779
  interceptors,
18050
18780
  collections: new CollectionRegistry(),
18781
+ // set right below: the service needs the context
18782
+ documents: void 0,
18051
18783
  jobs,
18052
18784
  systemInfo: buildInfoCache(database.db()),
18053
18785
  shutdown: options.shutdown
18054
18786
  };
18787
+ context.documents = new DocumentService(context);
18055
18788
  const cleanups = [];
18056
18789
  const used = /* @__PURE__ */ new Set();
18057
18790
  const use = async (feature) => {
@@ -18105,6 +18838,7 @@ async function createMongocampServer(options = {}) {
18105
18838
  interceptors,
18106
18839
  registerJobHandler: (className, handler) => jobs.registerHandler(className, handler),
18107
18840
  use,
18841
+ collection: (name, collectionOptions) => createServerCollection(context, name, collectionOptions),
18108
18842
  routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
18109
18843
  close: async () => {
18110
18844
  await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
@@ -18142,4 +18876,4 @@ async function connectHooks(server, hooks) {
18142
18876
  };
18143
18877
  }
18144
18878
 
18145
- export { AuditCollection, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, SyncValidationLevel, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, requestFields, requestLogging, resolveBehaviours, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncPurgeIndex, syncValidator, systemFields, toMongoJsonSchema, validatorOf$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
18879
+ 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$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };