@sfxcode/nuxt-mongocamp-server 2.1.0 → 2.3.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 (80) hide show
  1. package/README.md +71 -19
  2. package/dist/module.d.mts +16 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +103 -11
  5. package/dist/runtime/api/.openapi-generator/FILES +24 -2
  6. package/dist/runtime/api/apis/CollectionApi.d.ts +137 -0
  7. package/dist/runtime/api/apis/CollectionApi.js +213 -0
  8. package/dist/runtime/api/apis/DocumentApi.d.ts +225 -8
  9. package/dist/runtime/api/apis/DocumentApi.js +364 -5
  10. package/dist/runtime/api/docs/AuditEntry.md +52 -0
  11. package/dist/runtime/api/docs/CollectionApi.md +272 -2
  12. package/dist/runtime/api/docs/CollectionDeclaration.md +52 -0
  13. package/dist/runtime/api/docs/CollectionDeclarationAudit.md +34 -0
  14. package/dist/runtime/api/docs/CollectionDeclarationOwner.md +36 -0
  15. package/dist/runtime/api/docs/CollectionDeclarationSoftDelete.md +36 -0
  16. package/dist/runtime/api/docs/CollectionDeclarationTimestamps.md +40 -0
  17. package/dist/runtime/api/docs/CollectionDeclarationVersioned.md +38 -0
  18. package/dist/runtime/api/docs/CountRequest.md +34 -0
  19. package/dist/runtime/api/docs/DocumentApi.md +467 -12
  20. package/dist/runtime/api/docs/ErrorDescription.md +4 -0
  21. package/dist/runtime/api/docs/ExportRequest.md +40 -0
  22. package/dist/runtime/api/docs/MongoAggregateRequest.md +2 -0
  23. package/dist/runtime/api/docs/SettingsResponse.md +0 -6
  24. package/dist/runtime/api/docs/SuggestedValidator.md +40 -0
  25. package/dist/runtime/api/docs/{UpdateRequest.md → UpdateManyRequest.md} +4 -4
  26. package/dist/runtime/api/docs/ValidationIssue.md +36 -0
  27. package/dist/runtime/api/models/AuditEntry.d.ts +88 -0
  28. package/dist/runtime/api/models/AuditEntry.js +56 -0
  29. package/dist/runtime/api/models/CollectionDeclaration.d.ts +80 -0
  30. package/dist/runtime/api/models/CollectionDeclaration.js +73 -0
  31. package/dist/runtime/api/models/CollectionDeclarationAudit.d.ts +30 -0
  32. package/dist/runtime/api/models/CollectionDeclarationAudit.js +26 -0
  33. package/dist/runtime/api/models/CollectionDeclarationOwner.d.ts +43 -0
  34. package/dist/runtime/api/models/CollectionDeclarationOwner.js +34 -0
  35. package/dist/runtime/api/models/CollectionDeclarationSoftDelete.d.ts +34 -0
  36. package/dist/runtime/api/models/CollectionDeclarationSoftDelete.js +28 -0
  37. package/dist/runtime/api/models/CollectionDeclarationTimestamps.d.ts +42 -0
  38. package/dist/runtime/api/models/CollectionDeclarationTimestamps.js +33 -0
  39. package/dist/runtime/api/models/CollectionDeclarationVersioned.d.ts +46 -0
  40. package/dist/runtime/api/models/CollectionDeclarationVersioned.js +36 -0
  41. package/dist/runtime/api/models/CountRequest.d.ts +30 -0
  42. package/dist/runtime/api/models/CountRequest.js +25 -0
  43. package/dist/runtime/api/models/ErrorDescription.d.ts +11 -0
  44. package/dist/runtime/api/models/ErrorDescription.js +10 -2
  45. package/dist/runtime/api/models/ExportRequest.d.ts +42 -0
  46. package/dist/runtime/api/models/ExportRequest.js +31 -0
  47. package/dist/runtime/api/models/Grant.d.ts +10 -1
  48. package/dist/runtime/api/models/Grant.js +5 -0
  49. package/dist/runtime/api/models/MongoAggregateRequest.d.ts +4 -0
  50. package/dist/runtime/api/models/MongoAggregateRequest.js +4 -2
  51. package/dist/runtime/api/models/SettingsResponse.d.ts +0 -14
  52. package/dist/runtime/api/models/SettingsResponse.js +0 -6
  53. package/dist/runtime/api/models/SuggestedValidator.d.ts +44 -0
  54. package/dist/runtime/api/models/SuggestedValidator.js +35 -0
  55. package/dist/runtime/api/models/UpdateManyRequest.d.ts +38 -0
  56. package/dist/runtime/api/models/{UpdateRequest.js → UpdateManyRequest.js} +7 -7
  57. package/dist/runtime/api/models/ValidationIssue.d.ts +34 -0
  58. package/dist/runtime/api/models/ValidationIssue.js +29 -0
  59. package/dist/runtime/api/models/index.d.ts +12 -1
  60. package/dist/runtime/api/models/index.js +12 -1
  61. package/dist/runtime/composables/mongocampApiCollection.d.ts +14 -15
  62. package/dist/runtime/composables/mongocampApiCollection.js +4 -1
  63. package/dist/runtime/composables/mongocampCollection.d.ts +106 -0
  64. package/dist/runtime/composables/mongocampCollection.js +200 -0
  65. package/dist/runtime/composables/mongocampLive.d.ts +33 -0
  66. package/dist/runtime/composables/mongocampLive.js +152 -0
  67. package/dist/runtime/composables/mongocampSearch.d.ts +12 -9
  68. package/dist/runtime/server/mongocamp/core.d.ts +2 -0
  69. package/dist/runtime/server/mongocamp/core.js +8 -1
  70. package/dist/runtime/server/mongocamp/plugin.d.ts +5 -1
  71. package/dist/runtime/server/mongocamp/plugin.js +21 -1
  72. package/dist/runtime/types/collections.d.ts +20 -0
  73. package/dist/runtime/types/collections.js +0 -0
  74. package/dist/runtime/utils/sse.d.ts +10 -0
  75. package/dist/runtime/utils/sse.js +33 -0
  76. package/dist/runtime/utils/toMongocampError.d.ts +7 -0
  77. package/dist/runtime/utils/toMongocampError.js +18 -1
  78. package/dist/types.d.mts +6 -0
  79. package/package.json +4 -3
  80. package/dist/runtime/api/models/UpdateRequest.d.ts +0 -38
package/README.md CHANGED
@@ -8,7 +8,7 @@ Nuxt module wrapping a generated OpenAPI client for [MongoCamp](https://mongocam
8
8
 
9
9
  The module works in two modes:
10
10
 
11
- - **Embedded server** (`server.enabled`): the MongoCamp API runs inside the Nitro of your application (`@sfxcode/mongocamp-server-core`, a TypeScript replacement of the Scala server with the same OpenAPI contract). No second application is needed.
11
+ - **Embedded server** (`server.enabled`): the MongoCamp API runs inside the Nitro of your application (`@sfxcode/mongocamp-server-core`). No second application is needed.
12
12
  - **External server**: the module is a client for a running server at `url`.
13
13
 
14
14
  The module runs on **Nitro 3 / h3 2**. Nuxt 4.7 builds with Nitro 3 (`@nuxt/nitro-v3-server`) when the application declares `nitro`:
@@ -17,7 +17,7 @@ The module runs on **Nitro 3 / h3 2**. Nuxt 4.7 builds with Nitro 3 (`@nuxt/nitr
17
17
  pnpm add @sfxcode/nuxt-mongocamp-server nitro
18
18
  ```
19
19
 
20
- In external mode, this module is a client for [MongoCamp Server](https://github.com/MongoCamp/mongocamp-server), a REST API server for MongoDB that provides authentication, user/role management, and collection, document and index APIs. The OpenAPI client in this module is generated from the server's OpenAPI spec, so the module version should match a compatible server version. See the [server repository](https://github.com/MongoCamp/mongocamp-server) for installation, configuration and API documentation.
20
+ In external mode, this module is a client for a MongoCamp server: the [standalone server](#standalone-server) of this repository or another application that embeds it. It provides authentication, user/role management, and collection, document, index and file APIs. The OpenAPI client in this module is generated from the server's OpenAPI spec (`openapi/docs.yaml`), so module and server should have the same version.
21
21
 
22
22
  ## Nuxt UI MongoCamp
23
23
 
@@ -36,13 +36,14 @@ export default defineNuxtConfig({
36
36
  enabled: true,
37
37
  // prefix: '/api/mongocamp-server', the url of the clients defaults to it
38
38
  config: { CONNECTION_DATABASE: 'mongocamp' },
39
+ // requestLogging: true, metrics: true,
39
40
  },
40
41
  refreshToken: true,
41
42
  },
42
43
  })
43
44
  ```
44
45
 
45
- The connection and every other setting use the env variables of the Scala server, so existing deployments keep their environment:
46
+ The connection and every other setting are environment variables (all of them in the [configuration reference](https://mongocamp.github.io/nuxt-mongocamp-server/server/configuration)):
46
47
 
47
48
  | Env | Default | Description |
48
49
  | --- | --- | --- |
@@ -52,33 +53,77 @@ The connection and every other setting use the env variables of the Scala server
52
53
  | `AUTH_HANDLER` | `mongo` | users and roles in `mc_users` / `mc_roles` (`static`: `AUTH_USERS`, `AUTH_ROLES`) |
53
54
  | `AUTH_SECRET` | random, stored | secret of the tokens (stored in `mc_configuration`, shared by all instances) |
54
55
  | `AUTH_EXPIRING_DURATION` | `6h` | lifetime of a token |
55
- | `REQUESTLOGGING_ENABLED`, `METRICS_ENABLED` | `false` | request log and metrics (the former plugins) |
56
56
  | `JOBS_ENABLED` | `true` | `false`: this instance does not run the jobs on their schedule (several instances) |
57
57
 
58
- At the first start the user `admin` is created with a random password that is printed to the log (like the Scala server). Further settings
59
- and the extension points (events, job handlers registered with `core.registerJobHandler(...)`) are described in [`packages/server-core/README.md`](packages/server-core/README.md). In
60
- server code `useMongocampCore()` gives the embedded server, e.g. to listen to its events:
58
+ At the first start the user `admin` is created with a random password that is printed to the log.
59
+
60
+ Extensions are Nitro 3 plugins: every event of the server is a Nitro hook `mongocamp:<event>`, and `mongocamp:ready` hands over the
61
+ started server (features, job handlers, direct access). In server routes `useMongocampCore()` gives the same server.
61
62
 
62
63
  ```ts
63
64
  // server/plugins/audit.ts
64
65
  import { definePlugin } from 'nitro'
65
66
 
66
- export default definePlugin(async () => {
67
- const core = await useMongocampCore()
68
- core.events.on('document:delete', event => console.info(event.user.userId, event.collectionName, event.oldValues))
67
+ export default definePlugin((nitroApp) => {
68
+ nitroApp.hooks.hook('mongocamp:ready', server => server.registerJobHandler('my.app.ReportJob', sendReport))
69
+ nitroApp.hooks.hook('mongocamp:document:delete', event => console.info(event.user.userId, event.collectionName, event.oldValues))
70
+ })
71
+ ```
72
+
73
+ Before-hooks (`mongocamp:document:beforeInsert`, `…:beforeReplace`, `…:beforeUpdate`, `…:beforeDelete`) are awaited and can change a
74
+ write or refuse it by throwing a `MongocampError`.
75
+
76
+ ### Typed collections
77
+
78
+ A file in `server/mongocamp/` declares a collection with any Standard Schema library (Zod 4, Valibot, ArkType). The schema types the
79
+ documents on the client, validates the documents written through the API and becomes the `$jsonSchema` validator of the collection in
80
+ MongoDB ([docs](https://mongocamp.github.io/nuxt-mongocamp-server/server/declared-collections)):
81
+
82
+ ```ts
83
+ // server/mongocamp/orders.ts
84
+ import { z } from 'zod'
85
+
86
+ export default defineMongocampCollection({
87
+ name: 'orders',
88
+ schema: z.object({ customer: z.string().min(1), qty: z.int().min(1).default(1), createdAt: z.date() }),
89
+ validation: 'error', // 'warn' (default) logs invalid documents and writes them, 'off' does nothing
90
+ })
91
+ ```
92
+
93
+ ```ts
94
+ // in a component: typed, decoded documents; invalid writes throw with the fields in `issues`
95
+ const orders = useMongocampCollection('orders')
96
+ const open = await orders.find({ filter: 'qty:[2 TO *]' }) // { customer: string, qty: number, createdAt: Date }[]
97
+ await orders.insert({ customer: 'Ada', createdAt: new Date() })
98
+ ```
99
+
100
+ Since 2.4 a declaration also switches behaviours on, one flag each — what Mongoose users know from `{ timestamps: true }`, `__v` and
101
+ plugins, plus per-document ownership and live data in the browser ([behaviours](https://mongocamp.github.io/nuxt-mongocamp-server/server/declared-collections#behaviours),
102
+ [coming from Mongoose](https://mongocamp.github.io/nuxt-mongocamp-server/guide/coming-from-mongoose)):
103
+
104
+ ```ts
105
+ export default defineMongocampCollection({
106
+ name: 'orders',
107
+ schema,
108
+ timestamps: true, // createdAt, updatedAt (optionally createdBy, updatedBy, nested paths)
109
+ owner: true, // only the creator writes; reads 'own', 'all' or a function; others get 404
110
+ softDelete: true, // deletedAt, hidden everywhere, restore, withDeleted, purge
111
+ versioned: true, // an outdated write answers 409 with the stored document
112
+ audit: true, // before/after of every write, history(id)
69
113
  })
70
114
  ```
71
115
 
72
- **Migration to 2.0** (from 1.x or from the Scala server): every change and the checklist are in [`docs/migration/to-2.0.md`](docs/migration/to-2.0.md) — documents as Extended JSON, Lucene rules, 404 for missing resources, salted passwords, one start with `MIGRATION_DROP_SCALA_LEFTOVERS=true` on a database of the Scala server.
116
+ ```ts
117
+ // a live list: changes of other users appear (replica set: Server-Sent Events, else polling)
118
+ const { documents, status } = useMongocampLive('orders', { filter: 'status:open' })
119
+ ```
73
120
 
74
- **Migration from the Scala server** (details and all differences: [`docs/migration/from-scala.md`](docs/migration/from-scala.md)): point the embedded server at the same database (the same `CONNECTION_*` and `AUTH_PREFIX`); users,
75
- roles, tokens, the token secret and the stored configurations keep working. Jobs are read from `mc_jobs` with cron expressions in the
76
- syntax of [croner](https://croner.56k.guru) (`*/5` instead of `0/5`); the Quartz tables `mc_jobs_*` are not read.
121
+ **Upgrading** from an older MongoCamp server or a 1.x version of this module: see the migration guides ([`docs/migration/to-2.0.md`](docs/migration/to-2.0.md), [`docs/migration/from-scala.md`](docs/migration/from-scala.md)).
77
122
 
78
123
  ### Standalone server
79
124
 
80
125
  `apps/server` is the same server without Nuxt (Nitro 3), configured only by env and listening on `SERVER_INTERFACE:SERVER_PORT`
81
- (default `0.0.0.0:8080`) like the Scala image:
126
+ (default `0.0.0.0:8080`):
82
127
 
83
128
  ```bash
84
129
  docker build -f apps/server/Dockerfile -t mongocamp-nitro-server .
@@ -87,6 +132,8 @@ docker run -p 8080:8080 -e CONNECTION_HOST=host.docker.internal mongocamp-nitro-
87
132
 
88
133
  Every request is one JSON line on stdout ([evlog](https://www.evlog.dev) wide events with the fields of the server under `mongocamp`); a Nuxt application that uses `evlog/nuxt` gets the same fields for the embedded API.
89
134
 
135
+ `REQUESTLOGGING_ENABLED` and `METRICS_ENABLED` switch request logging and metrics on (a Nitro plugin of the app, `apps/server/plugins/features.ts`).
136
+
90
137
  The image (distroless Node 24, about 214 MB, the server itself 3 MB) stops cleanly on `docker stop` (SIGTERM) and on `DELETE /system`.
91
138
 
92
139
  The spec is served at `/docs/docs.yaml` (`DOCS_OPENAPI`, default on) and an API reference UI at `/docs` (`DOCS_SWAGGER`).
@@ -116,6 +163,9 @@ export default defineNuxtConfig({
116
163
  | `server.connectionUri` | `string` | — | MongoDB connection string; better by env `NUXT_MONGOCAMP_SERVER_CONNECTION_URI`. |
117
164
  | `server.config` | `object` | `{}` | Settings by key (`CONNECTION_DATABASE`, ...); the env variables win. |
118
165
  | `server.jobs` | `boolean` | `true` | Runs the jobs (token cleanup, ...) on their schedule in this instance. |
166
+ | `server.requestLogging` | `boolean` | `false` | Writes every request as a document of `mc_request_logging`. |
167
+ | `server.metrics` | `boolean` | `false` | Serves `/system/monitoring/*` (also Prometheus text) and writes the metric snapshots. |
168
+ | `server.collectionsDir` | `string` | `mongocamp` | Directory of the declared collections in `server/` (app and layers). With an external server: types only, when set. |
119
169
  | `apiKey` | `string` | — | Optional. Stored server-side only; picked up automatically by `useMongocampApi(event)`. |
120
170
  | `paginationSize` | `number` | `500` | Default rows per page for search/list composables. Values below 10 fall back to the default. |
121
171
  | `refreshToken` | `boolean` | `false` | Whether the client auto-refreshes the session token on an interval after login. |
@@ -133,9 +183,11 @@ A missing `url` throws during `nuxi dev`/`nuxi build`/`nuxi generate` (not durin
133
183
  | `useMongocampStorage()` | The session cookie (`{ token, profile }`) backing auth state; SSR-safe. |
134
184
  | `useMongocampUser()` | Reactive current user profile, derived from `useMongocampStorage()` (read-only). |
135
185
  | `useMongocampUrl()` | The configured base URL. |
136
- | `useMongocampSearch()` | `find`/`findAll`/`findByField` document search helpers. `find(..., filterCaseInsensitive)` makes wildcards of the filter ignore the case (case-sensitive by default since 2.0.0). |
186
+ | `useMongocampSearch()` | `find`/`findAll`/`findByField` document search helpers. `find(..., filterCaseInsensitive)` makes wildcards of the filter ignore the case (case-sensitive by default). |
137
187
  | `usePaginatedFind(collection, opts)`| Reactive pagination wrapper (`page`, `documents`, `pending`, `error`, `nextPage`/`previousPage`/`goToPage`); `opts.filterCaseInsensitive` as for `find`. |
138
- | `useMongocampApiCollection(name)` | Per-collection insert/update/delete/aggregate/schema helpers. |
188
+ | `useMongocampCollection(name)` | Typed and decoded documents of a declared collection (or `<T>(name)` for any other): `find`, `findPage`, `findById`, `insert`, `replace`, `update`, `remove`, `restore`, `history`, `isMine`, `paginated()`; versions sent automatically, errors with `status`, `issues`, `isConflict`, `current`. |
189
+ | `useMongocampLive(name, opts)` | A live list kept in sync with the server (Server-Sent Events on change streams, polling without a replica set). |
190
+ | `useMongocampApiCollection(name)` | Per-collection insert/update/delete/aggregate/schema helpers, `suggestValidator()`. |
139
191
  | `useMongocampApiCollections()` | List collections/databases, database info. |
140
192
  | `useMongocampApiFiles()` | Bucket and file upload/download/list helpers. |
141
193
  | `useMongocampApiJobs()` | List/register/update/execute/delete scheduled jobs. |
@@ -143,7 +195,7 @@ A missing `url` throws during `nuxi dev`/`nuxi build`/`nuxi generate` (not durin
143
195
 
144
196
  ### Documents as Extended JSON
145
197
 
146
- Since 2.0.0 the server returns documents as relaxed MongoDB Extended JSON: `{"_id": {"$oid": "…"}, "when": {"$date": "…"}}`. Send `extendedJson: 'plain'` for the 1.x format (ids and dates as strings). Auto-imported helpers:
198
+ The server returns documents as relaxed MongoDB Extended JSON: `{"_id": {"$oid": "…"}, "when": {"$date": "…"}}`. Send `extendedJson: 'plain'` for plain JSON (ids and dates as strings). Auto-imported helpers:
147
199
 
148
200
  | Helper | Purpose |
149
201
  | ---------------------------| --------------------------------------------------------------------------------------------------------|
@@ -156,7 +208,7 @@ Since 2.0.0 the server returns documents as relaxed MongoDB Extended JSON: `{"_i
156
208
  | Composable | Purpose |
157
209
  | -----------------------------------------------| -----------------------------------------------------------------------------------|
158
210
  | `useMongocampApi(event, token?)` | Builds authenticated API clients using the module's `apiKey`, or the given `token` as a fallback. With the embedded server the calls are answered in-process. |
159
- | `useMongocampCore()` | The embedded server (`server.enabled` only): events, configuration, direct access. |
211
+ | `useMongocampCore()` | The embedded server (`server.enabled` only) in server routes; plugins get it on the hook `mongocamp:ready`. |
160
212
  | `useMongocampServerApi(url, key?, token?)` | Lower-level factory when you need to authenticate against a different URL/credential explicitly. |
161
213
 
162
214
  ```ts
package/dist/module.d.mts CHANGED
@@ -1,5 +1,8 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
  export * from '../dist/runtime/api/index.js';
3
+ export { AuditEntry, CollectionFindOptions, CollectionPage, DocumentIdentity, MongocampRequestError, PaginatedCollection, TypedCollection } from '../dist/runtime/composables/mongocampCollection.js';
4
+ export { MongocampCollectionName, MongocampDocument, MongocampDocumentInput } from '../dist/runtime/types/collections.js';
5
+ export { LiveOptions, LiveState, LiveStatus } from '../dist/runtime/composables/mongocampLive.js';
3
6
 
4
7
  /** The option `server` of the module: the MongoCamp server embedded in the Nitro of the application. */
5
8
  interface ServerOptions {
@@ -13,6 +16,16 @@ interface ServerOptions {
13
16
  config?: Record<string, unknown>;
14
17
  /** Runs the jobs (token cleanup, ...) on their schedule in this instance (default true). */
15
18
  jobs?: boolean;
19
+ /** Writes every request as a document of `<AUTH_PREFIX>request_logging` (default false). */
20
+ requestLogging?: boolean;
21
+ /** Serves `/system/monitoring/*` and writes the metric snapshots of `LOGGING_METRICS_MONGODB_*` (default false). */
22
+ metrics?: boolean;
23
+ /**
24
+ * The directory of the declared collections in the server directory of the application and its layers (default `mongocamp`, i.e.
25
+ * `server/mongocamp/*.ts`). Registered in the embedded server and typed for the client; with an external server only typed, and only
26
+ * when this option is set.
27
+ */
28
+ collectionsDir?: string;
16
29
  }
17
30
  interface ResolvedServerOptions {
18
31
  enabled: boolean;
@@ -20,6 +33,9 @@ interface ResolvedServerOptions {
20
33
  connectionUri: string;
21
34
  config: Record<string, unknown>;
22
35
  jobs: boolean;
36
+ requestLogging: boolean;
37
+ metrics: boolean;
38
+ collectionsDir: string;
23
39
  }
24
40
 
25
41
  interface ModuleOptions {
package/dist/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-mongocamp-server",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "configKey": "mongocamp",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.7.0"
package/dist/module.mjs CHANGED
@@ -1,12 +1,14 @@
1
- import { defineNuxtModule, createResolver, addImportsDir, addImports, addServerImportsDir, addServerHandler, addServerPlugin, addServerImports } from '@nuxt/kit';
1
+ import { join, relative, basename, extname, isAbsolute, resolve } from 'node:path';
2
+ import { defineNuxtModule, createResolver, addImportsDir, addImports, addServerImportsDir, addServerHandler, addServerPlugin, addServerImports, addTypeTemplate, addServerTemplate, updateTemplates, resolveFiles } from '@nuxt/kit';
2
3
  import { defu } from 'defu';
3
4
  import { consola } from 'consola';
4
5
  export * from '../dist/runtime/api/index.js';
5
6
 
6
7
  const name = "@sfxcode/nuxt-mongocamp-server";
7
- const version = "2.1.0";
8
+ const version = "2.3.0";
8
9
 
9
10
  const DefaultServerPrefix = "/api/mongocamp-server";
11
+ const DefaultCollectionsDir = "mongocamp";
10
12
  function normalizePrefix(prefix) {
11
13
  const trimmed = (prefix ?? DefaultServerPrefix).trim().replace(/\/+$/, "");
12
14
  const path = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
@@ -21,7 +23,10 @@ function resolveServerOptions(options) {
21
23
  prefix: normalizePrefix(options?.prefix),
22
24
  connectionUri: options?.connectionUri ?? "",
23
25
  config: options?.config ?? {},
24
- jobs: options?.jobs ?? true
26
+ jobs: options?.jobs ?? true,
27
+ requestLogging: options?.requestLogging ?? false,
28
+ metrics: options?.metrics ?? false,
29
+ collectionsDir: options?.collectionsDir?.trim().replace(/^\/+|\/+$/g, "") || DefaultCollectionsDir
25
30
  };
26
31
  }
27
32
  function resolveClientUrl(url, server) {
@@ -31,6 +36,64 @@ function resolveClientUrl(url, server) {
31
36
  return server.enabled ? server.prefix : void 0;
32
37
  }
33
38
 
39
+ const CollectionsVirtualModule = "#mongocamp/collections";
40
+ const CollectionFilePattern = "*.{ts,mts,js,mjs}";
41
+ function collectionDirs(layers, collectionsDir) {
42
+ return [...new Set(layers.map(({ config }) => join(config.serverDir ?? join(config.srcDir ?? config.rootDir, "server"), collectionsDir)))];
43
+ }
44
+ async function scanCollections(dirs, resolve) {
45
+ const files = /* @__PURE__ */ new Map();
46
+ for (const dir of dirs) {
47
+ for (const path of (await resolve(dir)).sort()) {
48
+ if (path.endsWith(".d.ts")) {
49
+ continue;
50
+ }
51
+ const key = basename(path, extname(path));
52
+ if (!files.has(key)) {
53
+ files.set(key, { key, path });
54
+ }
55
+ }
56
+ }
57
+ return [...files.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
58
+ }
59
+ function importPath(from, path) {
60
+ const withoutExtension = /\.m?ts$/.test(path) ? path.replace(/\.m?ts$/, "") : path;
61
+ const relativePath = relative(from, withoutExtension).split("\\").join("/");
62
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
63
+ }
64
+ function collectionsServerTemplate(files, rootDir) {
65
+ const imports = files.map((file, index) => `import collection${index} from ${JSON.stringify(file.path)}`);
66
+ const entries = files.map((file, index) => ` { key: ${JSON.stringify(file.key)}, source: ${JSON.stringify(relative(rootDir, file.path).split("\\").join("/"))}, definition: collection${index} },`);
67
+ return [...imports, "", "export const declarations = [", ...entries, "]", ""].join("\n");
68
+ }
69
+ function collectionsTypeTemplate(files, typesDir) {
70
+ const entries = (type) => files.map((file) => ` ${JSON.stringify(file.key)}: ${type}<typeof import(${JSON.stringify(importPath(typesDir, file.path))}).default>`);
71
+ return [
72
+ "import type { InferDocument, InferDocumentInput } from '@sfxcode/mongocamp-server-core'",
73
+ "",
74
+ "declare global {",
75
+ " /** The documents of the declared collections (`server/mongocamp/<name>.ts`) as they are stored, by file name. */",
76
+ " interface MongocampCollections {",
77
+ ...entries("InferDocument"),
78
+ " }",
79
+ " /** The documents of the declared collections as they are written (before the defaults of the schema), by file name. */",
80
+ " interface MongocampCollectionInputs {",
81
+ ...entries("InferDocumentInput"),
82
+ " }",
83
+ "}",
84
+ "",
85
+ "export {}",
86
+ ""
87
+ ].join("\n");
88
+ }
89
+ const collectionsVirtualModuleTypes = [
90
+ `declare module '${CollectionsVirtualModule}' {`,
91
+ " import type { MongocampCollectionDefinition } from '@sfxcode/mongocamp-server-core'",
92
+ " export const declarations: Array<{ key: string, source: string, definition: MongocampCollectionDefinition }>",
93
+ "}",
94
+ ""
95
+ ].join("\n");
96
+
34
97
  const module$1 = defineNuxtModule({
35
98
  meta: {
36
99
  name,
@@ -77,18 +140,47 @@ const module$1 = defineNuxtModule({
77
140
  }
78
141
  );
79
142
  nuxt.options.runtimeConfig.mongocampApiKey = nuxt.options.runtimeConfig.mongocampApiKey ?? options.apiKey ?? "";
80
- const { resolve } = createResolver(import.meta.url);
81
- const runtimeDir = resolve("./runtime");
82
- addImportsDir(resolve(runtimeDir, "composables"));
83
- addImports(["fromExtendedJson", "toExtendedJson", "documentId"].map((name2) => ({ name: name2, from: resolve(runtimeDir, "utils/extendedJson") })));
84
- addServerImportsDir(resolve(runtimeDir, "server/composables"));
143
+ const { resolve: resolve$1 } = createResolver(import.meta.url);
144
+ const runtimeDir = resolve$1("./runtime");
145
+ addImportsDir(resolve$1(runtimeDir, "composables"));
146
+ addImports(["fromExtendedJson", "toExtendedJson", "documentId"].map((name2) => ({ name: name2, from: resolve$1(runtimeDir, "utils/extendedJson") })));
147
+ addServerImportsDir(resolve$1(runtimeDir, "server/composables"));
85
148
  nuxt.options.runtimeConfig.mongocampServer = defu(nuxt.options.runtimeConfig.mongocampServer, { ...server, version: { name: "mongocamp-nitro-server", version } });
86
149
  if (server.enabled) {
87
- addServerHandler({ route: `${server.prefix}/**`, handler: resolve(runtimeDir, "server/mongocamp/handler") });
88
- addServerPlugin(resolve(runtimeDir, "server/mongocamp/plugin"));
89
- addServerImports([{ name: "useMongocampCore", from: resolve(runtimeDir, "server/mongocamp/core") }]);
150
+ addServerHandler({ route: `${server.prefix}/**`, handler: resolve$1(runtimeDir, "server/mongocamp/handler") });
151
+ addServerPlugin(resolve$1(runtimeDir, "server/mongocamp/plugin"));
152
+ addServerImports([{ name: "useMongocampCore", from: resolve$1(runtimeDir, "server/mongocamp/core") }]);
153
+ addTypeTemplate({
154
+ filename: "types/mongocamp-hooks.d.ts",
155
+ getContents: () => [
156
+ "import type { MongocampHooks } from '@sfxcode/mongocamp-server-core'",
157
+ "declare module 'nitro/types' {",
158
+ " interface NitroRuntimeHooks extends MongocampHooks {}",
159
+ "}",
160
+ "export {}"
161
+ ].join("\n")
162
+ }, { nitro: true, nuxt: true });
90
163
  consola.info(`[mongocamp] embedded server at ${server.prefix}`);
91
164
  }
165
+ if (server.enabled || options.server?.collectionsDir !== void 0) {
166
+ const dirs = collectionDirs(nuxt.options._layers, server.collectionsDir);
167
+ const scan = () => scanCollections(dirs, (dir) => resolveFiles(dir, CollectionFilePattern));
168
+ if (server.enabled) {
169
+ addServerImports([{ name: "defineMongocampCollection", from: "@sfxcode/mongocamp-server-core" }]);
170
+ addServerTemplate({ filename: CollectionsVirtualModule, getContents: async () => collectionsServerTemplate(await scan(), nuxt.options.rootDir) });
171
+ addTypeTemplate({ filename: "types/mongocamp-collections-virtual.d.ts", getContents: () => collectionsVirtualModuleTypes }, { nitro: true });
172
+ }
173
+ addTypeTemplate({
174
+ filename: "types/mongocamp-collections.d.ts",
175
+ getContents: async () => collectionsTypeTemplate(await scan(), join(nuxt.options.buildDir, "types"))
176
+ }, { nitro: true, nuxt: true });
177
+ nuxt.hook("builder:watch", async (event, path) => {
178
+ const candidates = isAbsolute(path) ? [path] : [resolve(nuxt.options.srcDir, path), resolve(nuxt.options.rootDir, path)];
179
+ if ((event === "add" || event === "unlink") && candidates.some((candidate) => dirs.some((dir) => candidate.startsWith(`${dir}/`)))) {
180
+ await updateTemplates({ filter: (template) => template.filename === "types/mongocamp-collections.d.ts" });
181
+ }
182
+ });
183
+ }
92
184
  consola.success("mongocamp-nuxt available");
93
185
  }
94
186
  });
@@ -12,6 +12,7 @@ apis/SystemApi.ts
12
12
  apis/index.ts
13
13
  docs/AdminApi.md
14
14
  docs/ApplicationApi.md
15
+ docs/AuditEntry.md
15
16
  docs/AuthApi.md
16
17
  docs/BucketApi.md
17
18
  docs/BucketInformation.md
@@ -21,6 +22,12 @@ docs/ClusterInformation.md
21
22
  docs/ClusterMemberInformation.md
22
23
  docs/CollectionApi.md
23
24
  docs/CollectionCollation.md
25
+ docs/CollectionDeclaration.md
26
+ docs/CollectionDeclarationAudit.md
27
+ docs/CollectionDeclarationOwner.md
28
+ docs/CollectionDeclarationSoftDelete.md
29
+ docs/CollectionDeclarationTimestamps.md
30
+ docs/CollectionDeclarationVersioned.md
24
31
  docs/CollectionOptions.md
25
32
  docs/CollectionPermission.md
26
33
  docs/CollectionStatus.md
@@ -28,6 +35,7 @@ docs/CollectionSummary.md
28
35
  docs/ConnectionStats.md
29
36
  docs/CopyRequest.md
30
37
  docs/CopyResponse.md
38
+ docs/CountRequest.md
31
39
  docs/CountResponse.md
32
40
  docs/CreateCollectionResponse.md
33
41
  docs/DatabaseApi.md
@@ -35,6 +43,7 @@ docs/DatabaseInfo.md
35
43
  docs/DeleteResponse.md
36
44
  docs/DocumentApi.md
37
45
  docs/ErrorDescription.md
46
+ docs/ExportRequest.md
38
47
  docs/FieldInfo.md
39
48
  docs/FieldTypeCount.md
40
49
  docs/FileApi.md
@@ -77,23 +86,32 @@ docs/SchemaAnalysisField.md
77
86
  docs/SchemaAnalysisFieldType.md
78
87
  docs/SearchRequest.md
79
88
  docs/SettingsResponse.md
89
+ docs/SuggestedValidator.md
80
90
  docs/SystemApi.md
81
91
  docs/SystemInfo.md
82
92
  docs/SystemStats.md
83
93
  docs/UpdateFileInformationRequest.md
84
- docs/UpdateRequest.md
94
+ docs/UpdateManyRequest.md
85
95
  docs/UpdateResponse.md
86
96
  docs/UpdateRoleRequest.md
87
97
  docs/UserInformation.md
88
98
  docs/UserProfile.md
99
+ docs/ValidationIssue.md
89
100
  docs/Version.md
90
101
  index.ts
102
+ models/AuditEntry.ts
91
103
  models/BucketInformation.ts
92
104
  models/Capabilities.ts
93
105
  models/CapabilityLimits.ts
94
106
  models/ClusterInformation.ts
95
107
  models/ClusterMemberInformation.ts
96
108
  models/CollectionCollation.ts
109
+ models/CollectionDeclaration.ts
110
+ models/CollectionDeclarationAudit.ts
111
+ models/CollectionDeclarationOwner.ts
112
+ models/CollectionDeclarationSoftDelete.ts
113
+ models/CollectionDeclarationTimestamps.ts
114
+ models/CollectionDeclarationVersioned.ts
97
115
  models/CollectionOptions.ts
98
116
  models/CollectionPermission.ts
99
117
  models/CollectionStatus.ts
@@ -101,11 +119,13 @@ models/CollectionSummary.ts
101
119
  models/ConnectionStats.ts
102
120
  models/CopyRequest.ts
103
121
  models/CopyResponse.ts
122
+ models/CountRequest.ts
104
123
  models/CountResponse.ts
105
124
  models/CreateCollectionResponse.ts
106
125
  models/DatabaseInfo.ts
107
126
  models/DeleteResponse.ts
108
127
  models/ErrorDescription.ts
128
+ models/ExportRequest.ts
109
129
  models/FieldInfo.ts
110
130
  models/FieldTypeCount.ts
111
131
  models/FileInformation.ts
@@ -145,14 +165,16 @@ models/SchemaAnalysisField.ts
145
165
  models/SchemaAnalysisFieldType.ts
146
166
  models/SearchRequest.ts
147
167
  models/SettingsResponse.ts
168
+ models/SuggestedValidator.ts
148
169
  models/SystemInfo.ts
149
170
  models/SystemStats.ts
150
171
  models/UpdateFileInformationRequest.ts
151
- models/UpdateRequest.ts
172
+ models/UpdateManyRequest.ts
152
173
  models/UpdateResponse.ts
153
174
  models/UpdateRoleRequest.ts
154
175
  models/UserInformation.ts
155
176
  models/UserProfile.ts
177
+ models/ValidationIssue.ts
156
178
  models/Version.ts
157
179
  models/index.ts
158
180
  runtime.ts