@sfxcode/mongocamp-server-core 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @sfxcode/mongocamp-server-core
2
2
 
3
3
  The MongoCamp REST API (`openapi/docs.yaml`) as a framework-neutral core: `createMongocampServer()` returns a web standard
4
- `fetch(Request): Promise<Response>` handler. It replaces the Scala `mongocamp-server` and is hosted by `apps/server` (Nitro 3,
5
- standalone) or embedded in a Nuxt application.
4
+ `fetch(Request): Promise<Response>` handler. It is hosted by `apps/server` (Nitro 3, standalone) or embedded in a Nuxt
5
+ application.
6
6
 
7
7
  ```ts
8
8
  import { createMongocampServer } from '@sfxcode/mongocamp-server-core'
@@ -17,19 +17,43 @@ await server.close()
17
17
 
18
18
  ## Configuration
19
19
 
20
- The keys are the env variables of the Scala server (`CONNECTION_*`, `AUTH_*`, `CORS_*`, ...). Persistent keys live in
21
- `<AUTH_PREFIX>configuration` and can be changed with `PATCH /system/configurations/{key}`; env and programmatic values win.
20
+ The keys are env variables (`CONNECTION_*`, `AUTH_*`, `CORS_*`, ...). Persistent keys live in `<AUTH_PREFIX>configuration` and can be
21
+ changed with `PATCH /system/configurations/{key}`; env and programmatic values win.
22
22
 
23
- | Plugin of the Scala server | Keys |
23
+ ## Features
24
+
25
+ Optional parts that a host switches on with `server.use(...)`, in Nitro from a plugin on `mongocamp:ready`:
26
+
27
+ | Feature | Content |
24
28
  | --- | --- |
25
- | request logging | `REQUESTLOGGING_ENABLED` — every request is a document of `<AUTH_PREFIX>request_logging` |
26
- | micrometer | `METRICS_ENABLED` — `GET /system/monitoring/{jvm,system,mongodb,events,prometheus}`; `METRICS_MONGODB_*` select the MongoDB metrics, `LOGGING_METRICS_MONGODB_*` write snapshots into `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` |
29
+ | `requestLogging()` | every request is a document of `<AUTH_PREFIX>request_logging` |
30
+ | `metrics()` | `GET /system/monitoring/{runtime,system,mongodb,events,prometheus}` (404 while off); `METRICS_MONGODB_*` select the MongoDB metrics, `LOGGING_METRICS_MONGODB_*` write snapshots into `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` |
31
+
32
+ `REQUESTLOGGING_ENABLED` / `METRICS_ENABLED` still switch them on in the core with a deprecation warning (removed in 3.0); `featureSwitches:
33
+ false` turns that off. `apps/server` reads the two settings in its own Nitro plugin.
27
34
 
28
- The category `jvm` holds the numbers of the Node runtime (`nodejs_*`).
35
+ The category `runtime` holds the numbers of the Node runtime (`nodejs_*`).
36
+
37
+ ## Logging
38
+
39
+ `logger` (`{ info, warn, error }`, default `console`) receives the messages of the server. `server.fetch(request, { log, requestId })`
40
+ adds the fields of the server under `mongocamp` to the wide event of the host (anything with `set(fields)`, e.g. evlog's request logger)
41
+ and uses the host's request id for `x-request-id` and the events. `apps/server` does both with `evlog/nitro/v3`; the Nuxt module passes
42
+ the event of `evlog/nuxt` when the application uses it.
29
43
 
30
44
  ## Extensions
31
45
 
32
- The dynamic JVM plugins of the Scala server are replaced by three things a host can use.
46
+ In Nitro, extensions are Nitro 3 plugins: `connectHooks(server, nitroApp.hooks)` (done by `apps/server` and the Nuxt module) calls
47
+ `mongocamp:ready` with the started server and forwards every event as a hook `mongocamp:<event>`:
48
+
49
+ ```ts
50
+ export default definePlugin((nitroApp) => {
51
+ nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
52
+ nitroApp.hooks.hook('mongocamp:document:update', event => audit(event))
53
+ })
54
+ ```
55
+
56
+ Expensive parts of an event are only read for hooks with a listener. Without Nitro, a host uses the server directly:
33
57
 
34
58
  ### Events
35
59
 
@@ -62,8 +86,14 @@ await createMongocampServer({
62
86
  enabled: true, // false: this instance does not run the jobs on their schedule (several instances of one application)
63
87
  },
64
88
  })
89
+
90
+ // later, e.g. in a Nuxt application through useMongocampCore(): schedules the stored jobs of the class right away
91
+ const remove = server.registerJobHandler('my.app.CleanupJob', async run => cleanup(run.config))
65
92
  ```
66
93
 
94
+ `JOBS_ENABLED=false` (environment or `config`, never stored) switches the scheduler of an instance off as well, also for the standalone
95
+ server.
96
+
67
97
  ### Routes
68
98
 
69
99
  Routes of the host go in front of the core: answer them yourself and give every other request to `server.fetch`. In Nitro 3 a route
package/dist/index.d.mts CHANGED
@@ -21,12 +21,6 @@ declare const ConfigKeys: {
21
21
  readonly ServerInterface: "SERVER_INTERFACE";
22
22
  readonly ServerPort: "SERVER_PORT";
23
23
  readonly AggregationStagesDenied: "AGGREGATION_STAGES_DENIED";
24
- readonly PluginsIgnored: "PLUGINS_IGNORED";
25
- readonly PluginsDirectory: "PLUGINS_DIRECTORY";
26
- readonly PluginsUrls: "PLUGINS_URLS";
27
- readonly PluginsModules: "PLUGINS_MODULES";
28
- readonly PluginsMavenRepositories: "PLUGINS_MAVEN_REPOSITORIES";
29
- readonly HttpClientHeaders: "HTTP_CLIENT_HEADERS";
30
24
  readonly AuthHandler: "AUTH_HANDLER";
31
25
  readonly AuthSecret: "AUTH_SECRET";
32
26
  readonly AuthApiKeyLength: "AUTH_APIKEYLENGTH";
@@ -37,6 +31,7 @@ declare const ConfigKeys: {
37
31
  readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
38
32
  readonly FilterTimeZone: "FILTER_TIME_ZONE";
39
33
  readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
34
+ readonly JobsEnabled: "JOBS_ENABLED";
40
35
  readonly AuthPrefix: "AUTH_PREFIX";
41
36
  readonly AuthBearer: "AUTH_BEARER";
42
37
  readonly AuthBasic: "AUTH_BASIC";
@@ -67,6 +62,7 @@ declare const ConfigKeys: {
67
62
  readonly MetricsMongoDbCommand: "METRICS_MONGODB_COMMAND";
68
63
  readonly MetricsMongoDbConnectionPool: "METRICS_MONGODB_CONNECTIONPOOL";
69
64
  readonly LoggingMetricsStep: "LOGGING_METRICS_MONGODB_STEP";
65
+ readonly LoggingMetricsRuntime: "LOGGING_METRICS_MONGODB_RUNTIME";
70
66
  readonly LoggingMetricsJvm: "LOGGING_METRICS_MONGODB_JVM";
71
67
  readonly LoggingMetricsSystem: "LOGGING_METRICS_MONGODB_SYSTEM";
72
68
  readonly LoggingMetricsMongo: "LOGGING_METRICS_MONGODB_MONGO";
@@ -112,6 +108,24 @@ declare class ConfigStore {
112
108
  allDefinitions(): ConfigDefinition[];
113
109
  }
114
110
 
111
+ /**
112
+ * The log of the server: `console` by default, any structured logger (evlog, consola, pino) through the option `logger`. The core never
113
+ * depends on a logging library; a host adapts its logger to these three functions.
114
+ */
115
+ interface MongocampLogger {
116
+ info: (message: string) => void;
117
+ warn: (message: string) => void;
118
+ error: (message: string, error?: unknown) => void;
119
+ }
120
+ declare const consoleLogger: MongocampLogger;
121
+ /**
122
+ * The wide event of one request, e.g. the request logger of evlog (`useLogger(event)`): anything with `set`. The server adds its fields under
123
+ * the key `mongocamp` (`requestFields`), the host emits the event.
124
+ */
125
+ interface RequestLog {
126
+ set: (fields: Record<string, unknown>) => void;
127
+ }
128
+
115
129
  interface DatabaseOptions {
116
130
  /** A full MongoDB connection string. Takes precedence over the `CONNECTION_*` configurations. */
117
131
  connectionUri?: string;
@@ -265,7 +279,7 @@ declare class MongoAuthHolder implements AuthHolder {
265
279
  get users(): Collection;
266
280
  get rolesCollection(): Collection;
267
281
  /** Creates the indexes and, for an empty user collection, the user `admin` with a random password that is printed once. */
268
- createIndicesAndInitData(log?: (message: string) => void): Promise<void>;
282
+ createIndicesAndInitData(log?: (message: string) => void, warn?: (message: string) => void): Promise<void>;
269
283
  /**
270
284
  * Unique index for the api-key lookup, partial on string values (users without a key store `null`). A database in which two users share
271
285
  * a key (possible with the Scala server, which had no index) gets a non-unique index instead, so the start never fails on old data.
@@ -356,8 +370,10 @@ declare class AuthService {
356
370
  readonly tokens: TokenCache;
357
371
  /** Key: SHA-256 of user and password; value: the stored hash that was verified, valid while the user still has it. */
358
372
  private readonly basicCache;
373
+ /** The user of a request once it is authenticated, for the fields of its wide event (`userOf`). */
374
+ private readonly requestUsers;
359
375
  constructor(database: MongocampDatabase, config: ConfigStore, version: VersionInfo);
360
- initialize(): Promise<void>;
376
+ initialize(logger?: MongocampLogger): Promise<void>;
361
377
  /** The users and roles in the database, for the routes that change them (only with `AUTH_HANDLER=mongo`). */
362
378
  get mongoHolder(): MongoAuthHolder | undefined;
363
379
  get bearerEnabled(): boolean;
@@ -368,6 +384,8 @@ declare class AuthService {
368
384
  authenticateUser(credentials: Credentials): Promise<UserInformation>;
369
385
  /** The logged in user of a request with the current roles. */
370
386
  authenticate(request: Request): Promise<AuthorizedUser>;
387
+ /** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
388
+ userOf(request: Request): string | undefined;
371
389
  /** The error for a logged in user without the grant for a request; the status is `AUTH_GRANT_DENIED_STATUS` (403) or 401. */
372
390
  grantDenied(message: string): MongocampError;
373
391
  requireAdmin(request: Request): Promise<AuthorizedUser>;
@@ -601,7 +619,8 @@ interface components {
601
619
  read: boolean;
602
620
  write: boolean;
603
621
  administrate: boolean;
604
- grantType: string;
622
+ /** @enum {string} */
623
+ grantType: "COLLECTION" | "BUCKET" | "BUCKET_META";
605
624
  };
606
625
  /** ImportResponse */
607
626
  ImportResponse: {
@@ -780,6 +799,8 @@ interface components {
780
799
  MongoAggregateRequest: {
781
800
  pipeline?: components["schemas"]["PipelineStage"][];
782
801
  allowDiskUse: boolean;
802
+ /** @description 2.1.0: the Lucene filter of the list as first stage, like the query parameter filter (send one of both; no URL limit in the body) */
803
+ filter?: string;
783
804
  };
784
805
  /** MongoCampConfiguration */
785
806
  MongoCampConfiguration: {
@@ -890,6 +911,20 @@ interface components {
890
911
  /** Format: double */
891
912
  percentageOfParent: number;
892
913
  };
914
+ /** ExportRequest */
915
+ ExportRequest: {
916
+ /** @description Lucene filter like on the list of documents, by default all documents */
917
+ filter?: string;
918
+ sort?: string[];
919
+ projection?: string[];
920
+ /** Format: int32 */
921
+ limit?: number;
922
+ };
923
+ /** CountRequest */
924
+ CountRequest: {
925
+ /** @description Lucene filter like on the list of documents, by default all documents */
926
+ filter?: string;
927
+ };
893
928
  /** SearchRequest */
894
929
  SearchRequest: {
895
930
  filter?: string;
@@ -898,17 +933,6 @@ interface components {
898
933
  };
899
934
  /** SettingsResponse */
900
935
  SettingsResponse: {
901
- routesPlugins?: string[];
902
- /**
903
- * @deprecated
904
- * @description Deprecated: plugin system of the Scala server, always [GridFsFileAdapter]
905
- */
906
- filePlugins?: string[];
907
- /**
908
- * @deprecated
909
- * @description Deprecated: plugin system of the Scala server, the value of PLUGINS_IGNORED
910
- */
911
- ignoredPlugins?: string[];
912
936
  configurations: components["schemas"]["Map_Any"];
913
937
  };
914
938
  /** SystemInfo */
@@ -930,8 +954,8 @@ interface components {
930
954
  filename?: string;
931
955
  metadata?: components["schemas"]["Map_Any"];
932
956
  };
933
- /** UpdateRequest */
934
- UpdateRequest: {
957
+ /** UpdateManyRequest */
958
+ UpdateManyRequest: {
935
959
  document: components["schemas"]["Map_Any"];
936
960
  filter: components["schemas"]["Map_Any"];
937
961
  };
@@ -1140,16 +1164,28 @@ type HookMap = {
1140
1164
  };
1141
1165
  /** Sees every published event, also without a listener; it does not count as listener, so no expensive payload is read for it. */
1142
1166
  type EventObserver = (name: EventName, payload: MongocampEvents[EventName]) => void;
1167
+ /**
1168
+ * A hook system of the host that receives the events, e.g. the hooks of a Nitro app (`mongocamp:document:update`). `listens` tells whether
1169
+ * the host has a listener for an event, so that its expensive parts are only read when somebody waits for them.
1170
+ */
1171
+ interface EventTarget {
1172
+ listens: (name: EventName) => boolean;
1173
+ call: (name: EventName, event: MongocampEvent<EventName>) => unknown;
1174
+ }
1143
1175
  declare class EventBus {
1144
1176
  private readonly log;
1145
1177
  readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
1146
1178
  private readonly listeners;
1147
1179
  private readonly observers;
1180
+ private readonly targets;
1148
1181
  constructor(log?: (message: string, error: unknown) => void);
1149
1182
  /** Registers a listener; the returned function removes it. */
1150
1183
  on<N extends EventName>(name: N, listener: EventListener<N>): () => void;
1151
1184
  /** Registers an observer (metrics); the returned function removes it. */
1152
1185
  observe(observer: EventObserver): () => void;
1186
+ /** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
1187
+ forward(target: EventTarget): () => void;
1188
+ private targetsFor;
1153
1189
  /** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
1154
1190
  has(name: EventName): boolean;
1155
1191
  /** Sends an event without waiting for the listeners; a failure of a listener is logged. */
@@ -1228,9 +1264,10 @@ declare class JobScheduler {
1228
1264
  private readonly events;
1229
1265
  private readonly handlers;
1230
1266
  private readonly options;
1267
+ private readonly logger;
1231
1268
  private readonly entries;
1232
1269
  private timer;
1233
- constructor(database: MongocampDatabase, events: EventBus, handlers: Map<string, JobHandler>, options: SchedulerOptions);
1270
+ constructor(database: MongocampDatabase, events: EventBus, handlers: Map<string, JobHandler>, options: SchedulerOptions, logger?: MongocampLogger);
1234
1271
  get collection(): Collection;
1235
1272
  initialize(): Promise<void>;
1236
1273
  /** Reads the stored jobs and brings the schedules in line: new ones are added, changed ones rescheduled, removed ones stopped. */
@@ -1239,6 +1276,12 @@ declare class JobScheduler {
1239
1276
  private run;
1240
1277
  private information;
1241
1278
  list(): JobInformation[];
1279
+ /**
1280
+ * Adds the handler of a class name at runtime (a host that gets the server after its start, e.g. a Nuxt application through
1281
+ * `useMongocampCore()`). The stored jobs of that class are scheduled now; the returned function removes the handler again and stops them.
1282
+ */
1283
+ registerHandler(className: string, handler: JobHandler): () => void;
1284
+ private rescheduleClass;
1242
1285
  classes(): string[];
1243
1286
  /** Checks the class and the expression; an empty name is the simple name of the class (`addJob`). */
1244
1287
  private checked;
@@ -1253,12 +1296,13 @@ declare class JobScheduler {
1253
1296
 
1254
1297
  /**
1255
1298
  * `mongocamp-plugin-micrometer` on `@prometheus-io/client` (the successor of prom-client): four categories with the endpoints
1256
- * `/system/monitoring/{jvm,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1299
+ * `/system/monitoring/{runtime,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1257
1300
  * snapshots in the collections `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` (the document shape of micrometer-mongodb).
1258
1301
  *
1259
- * The category `jvm` keeps its name for the clients and holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles.
1302
+ * The category `runtime` holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles. Until 2.1.0 it was named `jvm`;
1303
+ * `/system/monitoring/jvm` and `LOGGING_METRICS_MONGODB_JVM` stay as deprecated aliases until 3.0.
1260
1304
  */
1261
- type MetricCategory = 'jvm' | 'system' | 'mongodb' | 'events';
1305
+ type MetricCategory = 'runtime' | 'system' | 'mongodb' | 'events';
1262
1306
  interface Measurement {
1263
1307
  statisticType: string;
1264
1308
  value: number;
@@ -1319,6 +1363,8 @@ interface VersionInfo {
1319
1363
  /** Everything a route needs. One instance per server. */
1320
1364
  interface MongocampContext {
1321
1365
  config: ConfigStore;
1366
+ /** The log of the server (option `logger`, `console` by default). */
1367
+ logger: MongocampLogger;
1322
1368
  database: MongocampDatabase;
1323
1369
  version: VersionInfo;
1324
1370
  auth: AuthService;
@@ -1331,10 +1377,21 @@ interface MongocampContext {
1331
1377
  systemInfo: InfoCache<SystemInfo>;
1332
1378
  /** Stops the process (`DELETE /system`); not set when the server is embedded in an application. */
1333
1379
  shutdown?: (force: boolean) => void | Promise<void>;
1334
- /** The names of the route groups (`SettingsResponse.routesPlugins`). */
1335
- routeGroups: string[];
1336
1380
  }
1337
1381
 
1382
+ /**
1383
+ * An optional part of the server that a host switches on with `server.use(...)`, typically from a Nitro plugin on the hook
1384
+ * `mongocamp:ready`. `setup` starts it and answers the function that stops it (called by `server.close()`).
1385
+ */
1386
+ interface MongocampFeature {
1387
+ name: string;
1388
+ setup: (context: MongocampContext) => Promise<() => void | Promise<void>> | (() => void | Promise<void>);
1389
+ }
1390
+ /** Every request as a document of `<AUTH_PREFIX>request_logging`. */
1391
+ declare function requestLogging(): MongocampFeature;
1392
+ /** `/system/monitoring/{runtime,system,mongodb,events,prometheus}` and the snapshots of `LOGGING_METRICS_MONGODB_*`. */
1393
+ declare function metrics(): MongocampFeature;
1394
+
1338
1395
  interface MongocampServerOptions extends DatabaseOptions {
1339
1396
  /** Environment variables, `process.env` when omitted. */
1340
1397
  env?: ConfigSources['env'];
@@ -1350,33 +1407,80 @@ interface MongocampServerOptions extends DatabaseOptions {
1350
1407
  /** Interval in milliseconds to read configuration changes of other instances, `false` for none. Default one minute. */
1351
1408
  configRefresh?: number | false;
1352
1409
  /**
1353
- * The jobs: `false` keeps the scheduler of this instance from running the jobs on their schedule (several instances of an application
1354
- * need only one that runs them); `handlers` adds job handlers by class name; `refresh` is the interval to read the job changes of other
1355
- * instances (default one minute, `false` for none).
1410
+ * Deprecated (removed in 3.0): switches request logging and metrics on from `REQUESTLOGGING_ENABLED` / `METRICS_ENABLED` (default true).
1411
+ * A host that adds them itself with `server.use(requestLogging())` / `server.use(metrics())` passes false.
1356
1412
  */
1413
+ featureSwitches?: boolean;
1414
+ /** The log of the server (start, failed jobs and writes, 5xx errors); `console` when omitted. */
1415
+ logger?: MongocampLogger;
1357
1416
  /** Listeners of the events, registered before the start (`server:started`); later ones with `server.events.on(...)`. */
1358
1417
  on?: {
1359
1418
  [N in EventName]?: EventListener<N>;
1360
1419
  };
1420
+ /**
1421
+ * The jobs: `false` keeps the scheduler of this instance from running the jobs on their schedule (several instances of an application
1422
+ * need only one that runs them; the configuration `JOBS_ENABLED=false` does the same); `handlers` adds job handlers by class name (later
1423
+ * ones with `server.registerJobHandler(...)`); `refresh` is the interval to read the job changes of other instances (default one minute,
1424
+ * `false` for none).
1425
+ */
1361
1426
  jobs?: boolean | {
1362
1427
  enabled?: boolean;
1363
1428
  handlers?: Record<string, JobHandler>;
1364
1429
  refresh?: number | false;
1365
1430
  };
1366
1431
  }
1432
+ /** Options of one request. */
1433
+ interface FetchOptions {
1434
+ /**
1435
+ * The wide event of the request in the host (e.g. `useLogger(event)` of evlog): the server adds its fields under `mongocamp` (operation,
1436
+ * user, collection or bucket, rows, error code), the host emits it.
1437
+ */
1438
+ log?: RequestLog;
1439
+ /** The id of the request in the host (e.g. the one of its wide event), used for `x-request-id` and the events; a new one without. */
1440
+ requestId?: string;
1441
+ }
1367
1442
  interface MongocampServer {
1368
1443
  /** Web standard handler; paths start at the API root (`/version`, `/auth/login`, ...). */
1369
- fetch: (request: Request) => Promise<Response>;
1444
+ fetch: (request: Request, options?: FetchOptions) => Promise<Response>;
1370
1445
  context: MongocampContext;
1371
1446
  /** The registered routes as `METHOD /path/:param`, for checks against the OpenAPI spec. */
1372
1447
  routes: () => string[];
1373
1448
  /** The events of the server (`hookable`): `server.events.on('document:create', event => ...)`. */
1374
1449
  events: EventBus;
1450
+ /**
1451
+ * Adds a job handler after the start: the stored jobs with this `className` are scheduled right away. Returns a function that removes the
1452
+ * handler again. A Nuxt application registers its handlers this way in a Nitro plugin (`(await useMongocampCore()).registerJobHandler(...)`).
1453
+ */
1454
+ registerJobHandler: (className: string, handler: JobHandler) => () => void;
1455
+ /**
1456
+ * Switches an optional part on (`requestLogging()`, `metrics()`), typically from a Nitro plugin on `mongocamp:ready`. A feature with the
1457
+ * same name is used once; it is stopped by `close`.
1458
+ */
1459
+ use: (feature: MongocampFeature) => Promise<void>;
1375
1460
  close: () => Promise<void>;
1376
1461
  }
1377
1462
  /** Creates and connects a MongoCamp server. */
1378
1463
  declare function createMongocampServer(options?: MongocampServerOptions): Promise<MongocampServer>;
1379
1464
 
1465
+ /** The fields of the server in the wide event of a request (key `mongocamp`). */
1466
+ interface MongocampRequestFields {
1467
+ requestId: string;
1468
+ /** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
1469
+ operation: string;
1470
+ controller: string;
1471
+ /** The user the request was authenticated as; missing for public routes and invalid credentials. */
1472
+ user?: string;
1473
+ database?: string;
1474
+ collection?: string;
1475
+ bucket?: string;
1476
+ /** All matching rows of a paged list (`x-pagination-count-rows`). */
1477
+ rows?: number;
1478
+ /** `x-error-code` and `x-error-message` of an error response. */
1479
+ errorCode?: string;
1480
+ errorMessage?: string;
1481
+ }
1482
+ declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
1483
+
1380
1484
  /** Error codes of the API (`mongocamp-library/.../exception/ErrorCodes.scala`), sent in `ErrorDescription.code` and `x-error-code`. */
1381
1485
  declare const ErrorCodes: {
1382
1486
  /** A request that could not be decoded (body, query or header with an invalid value). */
@@ -1474,6 +1578,7 @@ type LuceneQuery = {
1474
1578
  type: 'term';
1475
1579
  field: string;
1476
1580
  text: string;
1581
+ quoted?: boolean;
1477
1582
  } | {
1478
1583
  type: 'range';
1479
1584
  field: string;
@@ -1542,5 +1647,32 @@ declare function luceneToFilter(input: string, defaultField: string, options?: C
1542
1647
  */
1543
1648
  declare function filterParameter(input: string | null | undefined, options?: ConvertOptions, parameter?: string): Record<string, unknown>;
1544
1649
 
1545
- export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, stringifyJson };
1546
- export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, ExtendedJsonMode, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, VersionInfo };
1650
+ /**
1651
+ * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
1652
+ * the server once it is started. An extension of an application is then a plain Nitro plugin:
1653
+ *
1654
+ * export default definePlugin((nitroApp) => {
1655
+ * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
1656
+ * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
1657
+ * })
1658
+ */
1659
+ type MongocampHooks = {
1660
+ 'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
1661
+ } & {
1662
+ [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
1663
+ };
1664
+ /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
1665
+ interface HookSystem {
1666
+ callHook(name: string, ...args: unknown[]): unknown;
1667
+ }
1668
+ declare const HookPrefix = "mongocamp:";
1669
+ /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
1670
+ declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
1671
+ /**
1672
+ * Connects a started server with the hooks of its host: forwards the events and calls `mongocamp:ready` (awaited, so features that the
1673
+ * plugins switch on are active before the first request is answered).
1674
+ */
1675
+ declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
1676
+
1677
+ export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, forwardEventsToHooks, luceneQueryToFilter, luceneToFilter, metrics, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, requestLogging, stringifyJson };
1678
+ export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, EventTarget, ExtendedJsonMode, FetchOptions, HookSystem, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, RequestLog, VersionInfo };